code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import argparse
import copy
import logging
import os
import numpy as np
from astropy.wcs import Sip
from scipy import optimize as optimize
from CatalogMatcher import CatalogMatcher
from ReferenceCatalogProvider import refcat2
from wcsfitsdatabase import wcsfitdatabase
__author__ = '<EMAIL>'
log = logging.getLogger(__name__)
class SIPOptimizer:
""" Given a matched catalog, iteratively fit a WCS with SIP distortions up to second order.
"""
def __init__(self, newMatchedCatalog, maxorder=2):
self.matchedCatalog = newMatchedCatalog
if self.matchedCatalog.wcs is None:
log.error("Cannot proceed without a wcs in matched catalog. Aborting.")
return None
# bootstrap the initial SIP wcs
self.maxorder = maxorder
crval = self.matchedCatalog.wcs.wcs.crval
cd = self.matchedCatalog.wcs.wcs.cd
self.wcsfitparams = [crval[0], crval[1], cd[0][0], cd[0][1], cd[1][0], cd[1][1]]
# for the second order, we need 6 paramters, x^2, xy, and y^2 for each the x and y axis
if maxorder > 1:
self.wcsfitparams.extend([0, 0, 0, 0, 0, 0])
# for the third order, we need to add even more parameters. This is work in progress.
if maxorder > 2:
self.wcsfitparams.extend([0, 0, 0, 0])
# We calculate the inital merrit function before anything else to get a baseline.
merrit = SIPOptimizer.merritFunction(self.wcsfitparams, self.matchedCatalog)
# log.info("SIPOptimizer init: merrit function is %12.7f" % (merrit))
@staticmethod
def merritFunction(sipcoefficients, matchedCatalog):
""" Calculate a merrit function for a matched catalog based on current understadning of WCS.
This function is at the core of the optimizer, as it is the merrit function for the fitting function.
"""
# update the matched Catalog's WCS
matchedCatalog.wcs.wcs.crval[0] = sipcoefficients[0]
matchedCatalog.wcs.wcs.crval[1] = sipcoefficients[1]
matchedCatalog.wcs.wcs.cd[0][0] = sipcoefficients[2]
matchedCatalog.wcs.wcs.cd[0][1] = sipcoefficients[3]
matchedCatalog.wcs.wcs.cd[1][0] = sipcoefficients[4]
matchedCatalog.wcs.wcs.cd[1][1] = sipcoefficients[5]
m = 3
sip_a = np.zeros((m + 1, m + 1), np.double)
sip_b = np.zeros((m + 1, m + 1), np.double)
if len(sipcoefficients) > 6:
sip_a[1][1] = sipcoefficients[6]
sip_a[2][0] = sipcoefficients[7]
sip_a[0][2] = sipcoefficients[8]
sip_b[1][1] = sipcoefficients[9]
sip_b[2][0] = sipcoefficients[10]
sip_b[0][2] = sipcoefficients[11]
if len(sipcoefficients) > 12:
sip_a[3][0] = sipcoefficients[12]
sip_a[0][3] = sipcoefficients[13]
sip_b[3][0] = sipcoefficients[14]
sip_b[0][3] = sipcoefficients[15]
sip = Sip(sip_a, sip_b,
None, None, matchedCatalog.wcs.wcs.crpix)
matchedCatalog.wcs.sip = sip
matchedCatalog.wcs.wcs.ctype = ["RA---TAN", "DEC--TAN"]
matchedCatalog.wcs.wcs.set()
# Get the rms of the matched catalog.
merrit = matchedCatalog.updateWCSandUpdateRMS(matchedCatalog.wcs)
return merrit
def improveSIP(self):
bestfit = optimize.minimize(SIPOptimizer.merritFunction, self.wcsfitparams, args=(self.matchedCatalog))
merrit = SIPOptimizer.merritFunction(bestfit.x, self.matchedCatalog)
log.debug("Optimizer return {: 10.4f}".format(merrit))
def iterativelyFitWCSmany(images, args, refcat=None):
""" Wrapper to optimize the WCS for a set of images
"""
if refcat is None:
refcat = refcat2(args.refcat2)
if len(images) > 0:
for image in images:
iterativelyFitWCSsingle(image, args, searchradii=args.searchradii, refcat=refcat)
def iterativelyFitWCSsingle(image, args, searchradii, refcat=None):
""" Logistic to start optimizing WCS for a single image.
"""
log.info("Starting to process {}".format(image))
if refcat is None:
refcat = refcat2(args.refcat2)
pngbasename = os.path.basename(image)
if args.database:
wcsdb = wcsfitdatabase(args.database)
if wcsdb.checkifalreadyused(pngbasename) and not args.reprocess:
log.info("File already measured. Not doing the wame work twice; skipping")
wcsdb.close()
return
matchedCatalog = CatalogMatcher.createMatchedCatalogForLCO(
image,
refcat, searchradii[0], minobjects=args.minmatched, undistort=args.undistort)
if matchedCatalog is None:
log.info("returned empty catalog, not continuing.")
return
if args.makepng:
matchedCatalog.diagnosticPlots('{:s}_prefit'.format(pngbasename))
# Preserve the initial pointing
initialPointing = copy.deepcopy(matchedCatalog.wcs.wcs.crval)
# do a full fit
if (matchedCatalog.matchedCatalog is None) or (len(matchedCatalog.matchedCatalog['x']) < args.minmatched):
log.warning("Not enough stars in input catalog: %s found, %d are required to start. Giving up" % (
'None' if matchedCatalog.matchedCatalog is None else len(matchedCatalog.matchedCatalog['x']), args.minmatched))
return
opt = SIPOptimizer(matchedCatalog, maxorder=args.fitorder)
opt.improveSIP()
for searchradius in searchradii[1:]:
matchedCatalog.matchCatalogs(matchradius=searchradius)
opt = SIPOptimizer(matchedCatalog, maxorder=args.fitorder)
opt.improveSIP()
if args.makepng:
matchedCatalog.diagnosticPlots('{:s}_postfits'.format (pngbasename))
if (args.database):
wcsdb.addmeasurement(pngbasename, matchedCatalog.dateobs, matchedCatalog.camera, matchedCatalog.filter, None,
None, matchedCatalog.azimuth, matchedCatalog.altitude,
wcsdb.wcstojson(matchedCatalog.wcs))
log.info(matchedCatalog.wcs)
# Final report
finalPointing = matchedCatalog.wcs.wcs.crval
log.info('Fitting updated pointing at CRPIX by {}"'.format((finalPointing - initialPointing) * 3600.))
if (args.database):
wcsdb.close()
def parseCommandLine():
parser = argparse.ArgumentParser(
description='LCO WCS Tool')
parser.add_argument('--inputfiles', type=str, nargs='+', help="FITS file for which to derive the WCS function.")
parser.add_argument('--refcat2', type=str, default='/Catalogs/refcat2/refcat2.db',
help='Location of Atlas refcat2 catalog in slite forrmat')
parser.add_argument('--minmatched', type=int, default=50,
help='Minimum number of matched stars to accept solution or even proceed to fit.')
parser.add_argument('--fitorder', type=int, default=2)
parser.add_argument('--makepng', action='store_true', help="Create a png output of wcs before and after fit.")
parser.add_argument('--undistort', action='store_true',
help="Undistort input coordiante catalog before WCS fitting.")
parser.add_argument('--reprocess', action='store_true',
help="Reprocess even though file may have been processed already.")
parser.add_argument('--loglevel', dest='log_level', default='INFO', choices=['DEBUG', 'INFO', 'WARN'],
help='Set the debug level')
parser.add_argument('--searchradii', type=float, nargs='+', default=[10, 10, 5, 3, 2])
parser.add_argument('--database', default="wcsfits.sqlite")
args = parser.parse_args()
logging.basicConfig(level=getattr(logging, args.log_level.upper()),
format='%(asctime)s.%(msecs).03d %(levelname)7s: %(module)20s: %(message)s')
return args
if __name__ == '__main__':
args = parseCommandLine()
log.info("Processing %d input files" % len(args.inputfiles))
iterativelyFitWCSmany(args.inputfiles, args)
| [
"logging.getLogger",
"astropy.wcs.Sip",
"argparse.ArgumentParser",
"scipy.optimize.minimize",
"wcsfitsdatabase.wcsfitdatabase",
"ReferenceCatalogProvider.refcat2",
"numpy.zeros",
"os.path.basename",
"copy.deepcopy",
"CatalogMatcher.CatalogMatcher.createMatchedCatalogForLCO"
] | [((301, 328), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (318, 328), False, 'import logging\n'), ((4205, 4228), 'os.path.basename', 'os.path.basename', (['image'], {}), '(image)\n', (4221, 4228), False, 'import os\n'), ((4525, 4655), 'CatalogMatcher.CatalogMatcher.createMatchedCatalogForLCO', 'CatalogMatcher.createMatchedCatalogForLCO', (['image', 'refcat', 'searchradii[0]'], {'minobjects': 'args.minmatched', 'undistort': 'args.undistort'}), '(image, refcat, searchradii[0],\n minobjects=args.minmatched, undistort=args.undistort)\n', (4566, 4655), False, 'from CatalogMatcher import CatalogMatcher\n'), ((4931, 4974), 'copy.deepcopy', 'copy.deepcopy', (['matchedCatalog.wcs.wcs.crval'], {}), '(matchedCatalog.wcs.wcs.crval)\n', (4944, 4974), False, 'import copy\n'), ((6320, 6371), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""LCO WCS Tool"""'}), "(description='LCO WCS Tool')\n", (6343, 6371), False, 'import argparse\n'), ((2316, 2351), 'numpy.zeros', 'np.zeros', (['(m + 1, m + 1)', 'np.double'], {}), '((m + 1, m + 1), np.double)\n', (2324, 2351), True, 'import numpy as np\n'), ((2368, 2403), 'numpy.zeros', 'np.zeros', (['(m + 1, m + 1)', 'np.double'], {}), '((m + 1, m + 1), np.double)\n', (2376, 2403), True, 'import numpy as np\n'), ((2952, 3011), 'astropy.wcs.Sip', 'Sip', (['sip_a', 'sip_b', 'None', 'None', 'matchedCatalog.wcs.wcs.crpix'], {}), '(sip_a, sip_b, None, None, matchedCatalog.wcs.wcs.crpix)\n', (2955, 3011), False, 'from astropy.wcs import Sip\n'), ((3358, 3454), 'scipy.optimize.minimize', 'optimize.minimize', (['SIPOptimizer.merritFunction', 'self.wcsfitparams'], {'args': 'self.matchedCatalog'}), '(SIPOptimizer.merritFunction, self.wcsfitparams, args=self\n .matchedCatalog)\n', (3375, 3454), True, 'from scipy import optimize as optimize\n'), ((3760, 3781), 'ReferenceCatalogProvider.refcat2', 'refcat2', (['args.refcat2'], {}), '(args.refcat2)\n', (3767, 3781), False, 'from ReferenceCatalogProvider import refcat2\n'), ((4164, 4185), 'ReferenceCatalogProvider.refcat2', 'refcat2', (['args.refcat2'], {}), '(args.refcat2)\n', (4171, 4185), False, 'from ReferenceCatalogProvider import refcat2\n'), ((4268, 4297), 'wcsfitsdatabase.wcsfitdatabase', 'wcsfitdatabase', (['args.database'], {}), '(args.database)\n', (4282, 4297), False, 'from wcsfitsdatabase import wcsfitdatabase\n')] |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import numpy as np
import trimesh
# color palette for nyu40 labels
def create_color_palette():
return [
(0, 0, 0),
(174, 199, 232), # wall
(152, 223, 138), # floor
(31, 119, 180), # cabinet
(255, 187, 120), # bed
(188, 189, 34), # chair
(140, 86, 75), # sofa
(255, 152, 150), # table
(214, 39, 40), # door
(197, 176, 213), # window
(148, 103, 189), # bookshelf
(196, 156, 148), # picture
(23, 190, 207), # counter
(178, 76, 76),
(247, 182, 210), # desk
(66, 188, 102),
(219, 219, 141), # curtain
(140, 57, 197),
(202, 185, 52),
(51, 176, 203),
(200, 54, 131),
(92, 193, 61),
(78, 71, 183),
(172, 114, 82),
(255, 127, 14), # refrigerator
(91, 163, 138),
(153, 98, 156),
(140, 153, 101),
(158, 218, 229), # shower curtain
(100, 125, 154),
(178, 127, 135),
(120, 185, 128),
(146, 111, 194),
(44, 160, 44), # toilet
(112, 128, 144), # sink
(96, 207, 209),
(227, 119, 194), # bathtub
(213, 92, 176),
(94, 106, 211),
(82, 84, 163), # otherfurn
(100, 85, 144),
]
def write_triangle_mesh(vertices, colors, faces, outputFile):
mesh = trimesh.Trimesh(vertices=vertices, vertex_colors=colors, faces=faces, process=False)
mesh.export(outputFile)
def read_triangle_mesh(filename):
mesh = trimesh.load_mesh(filename, process=False)
if isinstance(mesh, trimesh.PointCloud):
vertices = mesh.vertices
colors = mesh.colors
faces = None
elif isinstance(mesh, trimesh.Trimesh):
vertices = mesh.vertices
colors = mesh.visual.vertex_colors
faces = mesh.faces
return vertices, colors, faces
def generate_bbox_mesh(bbox):
"""
bbox: np array (n, 7), last one is instance/label id
"""
def create_cylinder_mesh(radius, p0, p1, stacks=10, slices=10):
def compute_length_vec3(vec3):
return math.sqrt(vec3[0]*vec3[0] + vec3[1]*vec3[1] + vec3[2]*vec3[2])
def rotation(axis, angle):
rot = np.eye(4)
c = np.cos(-angle)
s = np.sin(-angle)
t = 1.0 - c
axis /= compute_length_vec3(axis)
x = axis[0]
y = axis[1]
z = axis[2]
rot[0,0] = 1 + t*(x*x-1)
rot[0,1] = z*s+t*x*y
rot[0,2] = -y*s+t*x*z
rot[1,0] = -z*s+t*x*y
rot[1,1] = 1+t*(y*y-1)
rot[1,2] = x*s+t*y*z
rot[2,0] = y*s+t*x*z
rot[2,1] = -x*s+t*y*z
rot[2,2] = 1+t*(z*z-1)
return rot
verts = []
indices = []
diff = (p1 - p0).astype(np.float32)
height = compute_length_vec3(diff)
for i in range(stacks+1):
for i2 in range(slices):
theta = i2 * 2.0 * math.pi / slices
pos = np.array([radius*math.cos(theta), radius*math.sin(theta), height*i/stacks])
verts.append(pos)
for i in range(stacks):
for i2 in range(slices):
i2p1 = math.fmod(i2 + 1, slices)
indices.append( np.array([(i + 1)*slices + i2, i*slices + i2, i*slices + i2p1], dtype=np.uint32) )
indices.append( np.array([(i + 1)*slices + i2, i*slices + i2p1, (i + 1)*slices + i2p1], dtype=np.uint32) )
transform = np.eye(4)
va = np.array([0, 0, 1], dtype=np.float32)
vb = diff
vb /= compute_length_vec3(vb)
axis = np.cross(vb, va)
angle = np.arccos(np.clip(np.dot(va, vb), -1, 1))
if angle != 0:
if compute_length_vec3(axis) == 0:
dotx = va[0]
if (math.fabs(dotx) != 1.0):
axis = np.array([1,0,0]) - dotx * va
else:
axis = np.array([0,1,0]) - va[1] * va
axis /= compute_length_vec3(axis)
transform = rotation(axis, -angle)
transform[:3,3] += p0
verts = [np.dot(transform, np.array([v[0], v[1], v[2], 1.0])) for v in verts]
verts = [np.array([v[0], v[1], v[2]]) / v[3] for v in verts]
return verts, indices
def get_bbox_edges(bbox_min, bbox_max):
def get_bbox_verts(bbox_min, bbox_max):
verts = [
np.array([bbox_min[0], bbox_min[1], bbox_min[2]]),
np.array([bbox_max[0], bbox_min[1], bbox_min[2]]),
np.array([bbox_max[0], bbox_max[1], bbox_min[2]]),
np.array([bbox_min[0], bbox_max[1], bbox_min[2]]),
np.array([bbox_min[0], bbox_min[1], bbox_max[2]]),
np.array([bbox_max[0], bbox_min[1], bbox_max[2]]),
np.array([bbox_max[0], bbox_max[1], bbox_max[2]]),
np.array([bbox_min[0], bbox_max[1], bbox_max[2]])
]
return verts
box_verts = get_bbox_verts(bbox_min, bbox_max)
edges = [
(box_verts[0], box_verts[1]),
(box_verts[1], box_verts[2]),
(box_verts[2], box_verts[3]),
(box_verts[3], box_verts[0]),
(box_verts[4], box_verts[5]),
(box_verts[5], box_verts[6]),
(box_verts[6], box_verts[7]),
(box_verts[7], box_verts[4]),
(box_verts[0], box_verts[4]),
(box_verts[1], box_verts[5]),
(box_verts[2], box_verts[6]),
(box_verts[3], box_verts[7])
]
return edges
radius = 0.02
offset = [0,0,0]
verts = []
indices = []
colors = []
for box in bbox:
box_min = np.array([box[0], box[1], box[2]])
box_max = np.array([box[3], box[4], box[5]])
r, g, b = create_color_palette()[int(box[6]%41)]
edges = get_bbox_edges(box_min, box_max)
for k in range(len(edges)):
cyl_verts, cyl_ind = create_cylinder_mesh(radius, edges[k][0], edges[k][1])
cur_num_verts = len(verts)
cyl_color = [[r/255.0,g/255.0,b/255.0] for _ in cyl_verts]
cyl_verts = [x + offset for x in cyl_verts]
cyl_ind = [x + cur_num_verts for x in cyl_ind]
verts.extend(cyl_verts)
indices.extend(cyl_ind)
colors.extend(cyl_color)
return verts, colors, indices | [
"numpy.eye",
"numpy.cross",
"trimesh.load_mesh",
"math.sqrt",
"math.cos",
"numpy.array",
"numpy.dot",
"math.fabs",
"numpy.cos",
"trimesh.Trimesh",
"numpy.sin",
"math.sin",
"math.fmod"
] | [((1567, 1655), 'trimesh.Trimesh', 'trimesh.Trimesh', ([], {'vertices': 'vertices', 'vertex_colors': 'colors', 'faces': 'faces', 'process': '(False)'}), '(vertices=vertices, vertex_colors=colors, faces=faces,\n process=False)\n', (1582, 1655), False, 'import trimesh\n'), ((1726, 1768), 'trimesh.load_mesh', 'trimesh.load_mesh', (['filename'], {'process': '(False)'}), '(filename, process=False)\n', (1743, 1768), False, 'import trimesh\n'), ((3742, 3751), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (3748, 3751), True, 'import numpy as np\n'), ((3765, 3802), 'numpy.array', 'np.array', (['[0, 0, 1]'], {'dtype': 'np.float32'}), '([0, 0, 1], dtype=np.float32)\n', (3773, 3802), True, 'import numpy as np\n'), ((3874, 3890), 'numpy.cross', 'np.cross', (['vb', 'va'], {}), '(vb, va)\n', (3882, 3890), True, 'import numpy as np\n'), ((5982, 6016), 'numpy.array', 'np.array', (['[box[0], box[1], box[2]]'], {}), '([box[0], box[1], box[2]])\n', (5990, 6016), True, 'import numpy as np\n'), ((6035, 6069), 'numpy.array', 'np.array', (['[box[3], box[4], box[5]]'], {}), '([box[3], box[4], box[5]])\n', (6043, 6069), True, 'import numpy as np\n'), ((2312, 2380), 'math.sqrt', 'math.sqrt', (['(vec3[0] * vec3[0] + vec3[1] * vec3[1] + vec3[2] * vec3[2])'], {}), '(vec3[0] * vec3[0] + vec3[1] * vec3[1] + vec3[2] * vec3[2])\n', (2321, 2380), False, 'import math\n'), ((2437, 2446), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2443, 2446), True, 'import numpy as np\n'), ((2463, 2477), 'numpy.cos', 'np.cos', (['(-angle)'], {}), '(-angle)\n', (2469, 2477), True, 'import numpy as np\n'), ((2494, 2508), 'numpy.sin', 'np.sin', (['(-angle)'], {}), '(-angle)\n', (2500, 2508), True, 'import numpy as np\n'), ((3458, 3483), 'math.fmod', 'math.fmod', (['(i2 + 1)', 'slices'], {}), '(i2 + 1, slices)\n', (3467, 3483), False, 'import math\n'), ((3925, 3939), 'numpy.dot', 'np.dot', (['va', 'vb'], {}), '(va, vb)\n', (3931, 3939), True, 'import numpy as np\n'), ((4392, 4425), 'numpy.array', 'np.array', (['[v[0], v[1], v[2], 1.0]'], {}), '([v[0], v[1], v[2], 1.0])\n', (4400, 4425), True, 'import numpy as np\n'), ((4460, 4488), 'numpy.array', 'np.array', (['[v[0], v[1], v[2]]'], {}), '([v[0], v[1], v[2]])\n', (4468, 4488), True, 'import numpy as np\n'), ((4686, 4735), 'numpy.array', 'np.array', (['[bbox_min[0], bbox_min[1], bbox_min[2]]'], {}), '([bbox_min[0], bbox_min[1], bbox_min[2]])\n', (4694, 4735), True, 'import numpy as np\n'), ((4753, 4802), 'numpy.array', 'np.array', (['[bbox_max[0], bbox_min[1], bbox_min[2]]'], {}), '([bbox_max[0], bbox_min[1], bbox_min[2]])\n', (4761, 4802), True, 'import numpy as np\n'), ((4820, 4869), 'numpy.array', 'np.array', (['[bbox_max[0], bbox_max[1], bbox_min[2]]'], {}), '([bbox_max[0], bbox_max[1], bbox_min[2]])\n', (4828, 4869), True, 'import numpy as np\n'), ((4887, 4936), 'numpy.array', 'np.array', (['[bbox_min[0], bbox_max[1], bbox_min[2]]'], {}), '([bbox_min[0], bbox_max[1], bbox_min[2]])\n', (4895, 4936), True, 'import numpy as np\n'), ((4955, 5004), 'numpy.array', 'np.array', (['[bbox_min[0], bbox_min[1], bbox_max[2]]'], {}), '([bbox_min[0], bbox_min[1], bbox_max[2]])\n', (4963, 5004), True, 'import numpy as np\n'), ((5022, 5071), 'numpy.array', 'np.array', (['[bbox_max[0], bbox_min[1], bbox_max[2]]'], {}), '([bbox_max[0], bbox_min[1], bbox_max[2]])\n', (5030, 5071), True, 'import numpy as np\n'), ((5089, 5138), 'numpy.array', 'np.array', (['[bbox_max[0], bbox_max[1], bbox_max[2]]'], {}), '([bbox_max[0], bbox_max[1], bbox_max[2]])\n', (5097, 5138), True, 'import numpy as np\n'), ((5156, 5205), 'numpy.array', 'np.array', (['[bbox_min[0], bbox_max[1], bbox_max[2]]'], {}), '([bbox_min[0], bbox_max[1], bbox_max[2]])\n', (5164, 5205), True, 'import numpy as np\n'), ((3516, 3607), 'numpy.array', 'np.array', (['[(i + 1) * slices + i2, i * slices + i2, i * slices + i2p1]'], {'dtype': 'np.uint32'}), '([(i + 1) * slices + i2, i * slices + i2, i * slices + i2p1], dtype\n =np.uint32)\n', (3524, 3607), True, 'import numpy as np\n'), ((3631, 3730), 'numpy.array', 'np.array', (['[(i + 1) * slices + i2, i * slices + i2p1, (i + 1) * slices + i2p1]'], {'dtype': 'np.uint32'}), '([(i + 1) * slices + i2, i * slices + i2p1, (i + 1) * slices + i2p1\n ], dtype=np.uint32)\n', (3639, 3730), True, 'import numpy as np\n'), ((4068, 4083), 'math.fabs', 'math.fabs', (['dotx'], {}), '(dotx)\n', (4077, 4083), False, 'import math\n'), ((4120, 4139), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (4128, 4139), True, 'import numpy as np\n'), ((4199, 4218), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (4207, 4218), True, 'import numpy as np\n'), ((3273, 3288), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (3281, 3288), False, 'import math\n'), ((3297, 3312), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (3305, 3312), False, 'import math\n')] |
import json
from collections import defaultdict
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt, patches
from dataset_utils.kitti_datum import KITTIDataset
from dataset_utils.mot_datum import MOTDataset
from trainer.dataset_info import kitti_classes_reverse
from vis_utils.vis_datum import ImageBoxes
def init_track_json(kind="KITTI",
path="/Users/kanchana/Documents/current/FYP/data/KITTI_tracking/data_tracking_image_2/training",
o_path="/Users/kanchana/Documents/current/FYP/data/KITTI_tracking/generate/tracks.json"):
if kind == "KITTI":
dataset = KITTIDataset(path)
elif kind == "MOT":
dataset = MOTDataset(path)
else:
dataset = None
tracks = defaultdict(dict)
for seq_id, sequence in enumerate(dataset.sequences):
t_id = 0
for datum in sequence.datums():
t_id += 1
i_w, i_h = datum.image.size
for obj in datum.objects:
x, y = (obj.x_min + obj.x_max) / (2 * i_w), (obj.y_min + obj.y_max) / (2 * i_h)
w = (obj.x_max - obj.x_min) / i_w
h = (obj.y_max - obj.y_min) / i_h
ar = h / w
if kind == "MOT":
category = 0
else:
category = kitti_classes_reverse[obj.category]
data = {'x': x, 'y': y, 'h': h, 'w': w, 'ar': ar, 'class': category, 'im': datum.im_path}
tracks["{}_{}".format(seq_id, obj.track)][str(t_id)] = data
with open(o_path.format("train"), 'w+') as fo:
json.dump(dict(list(tracks.items())[:-80]), fo)
with open(o_path.format("val"), 'w+') as fo:
json.dump(dict(list(tracks.items())[-80:]), fo)
def run_init():
base_path = "/Users/kanchana/Documents/current/FYP/"
init_track_json(
kind="KITTI",
path="{}/data/KITTI_tracking/data_tracking_image_2/training".format(base_path),
o_path="{}/fyp_2019/LSTM_Kanchana/data/kitti_tracks_{}.json".format(base_path, "{}")
)
init_track_json(
kind="MOT",
path="{}/data/MOT16/train".format(base_path),
o_path="{}/fyp_2019/LSTM_Kanchana/data/mot_tracks_{}.json".format(base_path, "{}")
)
def kitti_data_gen(path="/Users/kanchana/Documents/current/FYP/fyp_2019/LSTM_Kanchana/data/kitti_tracks_{}.json",
split="train", testing=False, one_hot_classes=False, anchors=False, num_classes=9):
"""
Args:
path:
split: train / val
testing:
one_hot_classes:
anchors:
num_classes:
Returns:
Tuple containing np.arrays of shape [10, 5] and [5,]
"""
assert split in ["train", "val"], "invalid split type: {}".format(split)
if isinstance(path, bytes):
path = path.decode()
tracks = json.load(tf.gfile.GFile(path.format(split), "r"))
valid_tracks = list(tracks.keys())
if split == "train":
np.random.shuffle(valid_tracks)
for track_id in valid_tracks:
track = tracks[track_id]
f_step = len(track.keys())
if f_step < 11:
continue
x = np.zeros(shape=(10, 5), dtype=np.float32)
if testing:
x_im = []
for start in range(0, f_step - 11):
l_step = int(sorted(list(track.keys()), key=lambda a: int(a))[start]) - 1
i = 0
for t_step, data in sorted(list(track.items())[start:start + 10], key=lambda vid: int(vid[0])):
assert int(t_step) > l_step, "order error; keys t-{} & l-{}".format(int(t_step), l_step)
l_step = int(t_step)
x[i] = np.array([data['x'], data['y'], data['h'], data['w'], data['class']])
if testing:
x_im.append(data['im'])
i += 1
_, data = list(track.items())[start + 10]
y = np.array([data['x'], data['y'], data['h'], data['w'], data['class']], dtype=np.float32)
if testing:
y_im = data["im"]
if one_hot_classes:
temp = np.zeros(shape=(x.shape[0], num_classes))
temp[np.array(range(len(x[:, 4]))), x[:, 4].astype(int)] = 1
x_ = np.concatenate([x[:, :4], temp.astype(float)], axis=-1)
assert x_.shape == (10, 4 + num_classes), "wrong shape for x"
if anchors:
y_x, y_y, y_h, y_w = (y[:4] - x[-1, :4])
y_x, y_y = make_anchors(y_x, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_y, (-0.5, 0, 0.1, 0.2, 0.5))
y_h, y_w = make_anchors(y_h, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_w, (-0.5, 0, 0.1, 0.2, 0.5))
y = np.array([y_x, y_y, y_h, y_w])
if testing:
if one_hot_classes:
yield (x_, y, x_im, y_im)
else:
yield (x, y, x_im, y_im)
else:
assert x.shape == (10, 5), "invalid shape"
yield (x, y)
def mot_data_gen(path="/Users/kanchana/Documents/current/FYP/fyp_2019/LSTM_Kanchana/data/mot_tracks_{}.json",
split="train", testing=False, one_hot_classes=False, anchors=False, num_classes=9):
"""
Args:
path:
split: train / val
testing: True to get image path
Returns:
Tuple containing np.arrays of shape [10, 5] and [5,]
"""
assert split in ["train", "val"], "invalid split type: {}".format(split)
if isinstance(path, bytes):
path = path.decode()
tracks = json.load(tf.gfile.GFile(path.format(split), "r"))
valid_tracks = list(tracks.keys())
if split == 'train':
np.random.shuffle(valid_tracks)
for track_id in valid_tracks:
track = tracks[track_id]
f_step = len(track.keys())
if f_step < 11:
continue
x = np.zeros(shape=(10, 5), dtype=np.float32)
if testing:
x_im = []
for start in range(0, f_step - 11):
l_step = int(sorted(list(track.keys()), key=lambda a: int(a))[start]) - 1
i = 0
for t_step, data in sorted(list(track.items())[start:start + 10], key=lambda vid: int(vid[0])):
assert int(t_step) > l_step, "order error; keys t-{} & l-{}".format(int(t_step), l_step)
l_step = int(t_step)
x[i] = np.array([data['x'], data['y'], data['h'], data['w'], data['class']])
if testing:
x_im.append(data['im'])
i += 1
_, data = list(track.items())[start + 10]
y = np.array([data['x'], data['y'], data['h'], data['w'], data['class']], dtype=np.float32)
if testing:
y_im = data["im"]
if one_hot_classes:
temp = np.zeros(shape=(x.shape[0], num_classes))
temp[np.array(range(len(x[:, 4]))), x[:, 4].astype(int)] = 1
x_ = np.concatenate([x[:, :4], temp.astype(float)], axis=-1)
assert x_.shape == (10, 4 + num_classes), "wrong shape for x"
if anchors:
y_x, y_y, y_h, y_w = (y[:4] - x[-1, :4])
y_x, y_y = make_anchors(y_x, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_y, (-0.5, 0, 0.1, 0.2, 0.5))
y_h, y_w = make_anchors(y_h, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_w, (-0.5, 0, 0.1, 0.2, 0.5))
y = np.array([y_x, y_y, y_h, y_w])
if testing:
if one_hot_classes:
yield (x_, y, x_im, y_im)
else:
yield (x, y, x_im, y_im)
else:
assert x.shape == (10, 5), "invalid shape"
yield (x, y)
def make_anchors(val, anchor_centres=(-0.5, 0, 0.1, 0.2, 0.5)):
"""
Args:
val: value to anchor
anchor_centres: tuple of anchor centres
Returns:
np.array of shape (6,) containing confidence and distance to anchor centre respectively.
output[:3] is confidence, and output[3:] is distance.
"""
idx = np.argmin(np.abs(val - np.array(anchor_centres)))
conf = np.zeros(shape=len(anchor_centres))
dist = np.zeros(shape=len(anchor_centres))
conf[idx] = 1
dist[idx] = val - anchor_centres[idx]
return np.concatenate((conf, dist), axis=0)
def joint_data_gen(paths=("/Users/kanchana/Documents/current/FYP/fyp_2019/LSTM_Kanchana/data/kitti_tracks_{}.json",
"/Users/kanchana/Documents/current/FYP/fyp_2019/LSTM_Kanchana/data/mot_tracks_{}.json"),
split="train", num_classes=9, anchors=True, one_hot_classes=True):
"""
Args:
paths: list/tuple of str to KITTI path, MOT path respectively
split: train / val
num_classes: number of classes
anchors: output y as anchors
one_hot_classes: output x with classes in one hot encoding
Returns:
generator with each iteration yielding a tuple containing (x,y), ie the ground truth and label for a track.
If anchors, output y is of shape (4, 6). 6 corresponds to 3 anchors confidence and distance respectively. Else,
shape is (4,) for [centre_x, centre_y, height, width].
If one_hot_classes, output x is of shape (10, 4 + num_classes). Else, shape is (10, 5). 10 corresponds to the
time steps in both cases.
"""
if isinstance(split, bytes):
split = split.decode()
assert split in ["train", "val"], "invalid split type: {}".format(split)
gens = (kitti_data_gen, mot_data_gen)
gens = [gen(path=path, split=split) for gen, path in zip(gens, paths)]
while True:
a = np.random.choice(range(4)) # MOT has over 3 times tracks as KITTI
if a < 1:
x, y = next(gens[1])
else:
x, y = next(gens[0])
if one_hot_classes:
temp = np.zeros(shape=(x.shape[0], num_classes))
temp[np.array(range(len(x[:, 4]))), x[:, 4].astype(int)] = 1
x = np.concatenate([x[:, :4], temp.astype(float)], axis=-1)
assert x.shape == (10, 4 + num_classes), "wrong shape for x"
if anchors:
y_x, y_y, y_h, y_w = (y[:4] - x[-1, :4])
y_x, y_y = make_anchors(y_x, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_y, (-0.5, 0, 0.1, 0.2, 0.5))
y_h, y_w = make_anchors(y_h, (-0.5, 0, 0.1, 0.2, 0.5)), make_anchors(y_w, (-0.5, 0, 0.1, 0.2, 0.5))
y = np.array([y_x, y_y, y_h, y_w])
else:
y = y[:4]
yield x, y
def val_data_gen(paths=("/Users/kanchana/Documents/current/FYP/data/KITTI_tracking/generate/tracks.json",
"/Users/kanchana/Documents/current/FYP/data/MOT16/generate/tracks.json"),
split="train", num_classes=9):
"""
Method to return images for validation data gen.
"""
gens = (kitti_data_gen, mot_data_gen)
gens = [gen(path=path, split=split, testing=True, one_hot_classes=True, anchors=True, num_classes=num_classes)
for gen, path in zip(gens, paths)]
while True:
a = np.random.choice(range(4)) # MOT has over 3 times tracks as KITTI
if a < 1:
x, y, x_im, y_im = next(gens[1])
else:
x, y, x_im, y_im = next(gens[0])
yield x, y
def to_bbox(x, y):
idx = np.argmax(y[:, :3], axis=-1)
dist = y[:, 3:][np.array(range(len(idx))), idx]
y = (dist + idx) * (x[-1, :4] - x[-2, :4] + 1e-5) + x[-1, :4]
return y
def vis_gen(auto_time=False):
gen = kitti_data_gen(testing=True)
# gen = mot_data_gen(testing=True)
while True:
x, y, x_im, y_im = next(gen)
fig, ax = plt.subplots(1)
image = ImageBoxes(path=y_im)
plt.axis("off")
for num, i in enumerate(x):
im = plt.imread(x_im[num])
ih, iw, _ = im.shape
cx, cy, h, w = i[:4]
image.add_box([cx, cy, w, h], color='blue')
for i in [y]:
im = plt.imread(y_im)
ih, iw, _ = im.shape
cx, cy, h, w = i[:4]
image.add_box([cx, cy, w, h])
ax.imshow(np.array(image.get_final()))
if auto_time:
plt.pause(0.1)
else:
plt.waitforbuttonpress()
plt.close()
| [
"dataset_utils.kitti_datum.KITTIDataset",
"matplotlib.pyplot.waitforbuttonpress",
"vis_utils.vis_datum.ImageBoxes",
"dataset_utils.mot_datum.MOTDataset",
"matplotlib.pyplot.imread",
"numpy.argmax",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.zeros",
"collections.defaultdict",
"numpy.concate... | [((765, 782), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (776, 782), False, 'from collections import defaultdict\n'), ((8451, 8487), 'numpy.concatenate', 'np.concatenate', (['(conf, dist)'], {'axis': '(0)'}), '((conf, dist), axis=0)\n', (8465, 8487), True, 'import numpy as np\n'), ((11542, 11570), 'numpy.argmax', 'np.argmax', (['y[:, :3]'], {'axis': '(-1)'}), '(y[:, :3], axis=-1)\n', (11551, 11570), True, 'import numpy as np\n'), ((640, 658), 'dataset_utils.kitti_datum.KITTIDataset', 'KITTIDataset', (['path'], {}), '(path)\n', (652, 658), False, 'from dataset_utils.kitti_datum import KITTIDataset\n'), ((2995, 3026), 'numpy.random.shuffle', 'np.random.shuffle', (['valid_tracks'], {}), '(valid_tracks)\n', (3012, 3026), True, 'import numpy as np\n'), ((3187, 3228), 'numpy.zeros', 'np.zeros', ([], {'shape': '(10, 5)', 'dtype': 'np.float32'}), '(shape=(10, 5), dtype=np.float32)\n', (3195, 3228), True, 'import numpy as np\n'), ((5770, 5801), 'numpy.random.shuffle', 'np.random.shuffle', (['valid_tracks'], {}), '(valid_tracks)\n', (5787, 5801), True, 'import numpy as np\n'), ((5962, 6003), 'numpy.zeros', 'np.zeros', ([], {'shape': '(10, 5)', 'dtype': 'np.float32'}), '(shape=(10, 5), dtype=np.float32)\n', (5970, 6003), True, 'import numpy as np\n'), ((11884, 11899), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (11896, 11899), True, 'from matplotlib import pyplot as plt, patches\n'), ((11916, 11937), 'vis_utils.vis_datum.ImageBoxes', 'ImageBoxes', ([], {'path': 'y_im'}), '(path=y_im)\n', (11926, 11937), False, 'from vis_utils.vis_datum import ImageBoxes\n'), ((11946, 11961), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (11954, 11961), True, 'from matplotlib import pyplot as plt, patches\n'), ((12478, 12489), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12487, 12489), True, 'from matplotlib import pyplot as plt, patches\n'), ((701, 717), 'dataset_utils.mot_datum.MOTDataset', 'MOTDataset', (['path'], {}), '(path)\n', (711, 717), False, 'from dataset_utils.mot_datum import MOTDataset\n'), ((3929, 4021), 'numpy.array', 'np.array', (["[data['x'], data['y'], data['h'], data['w'], data['class']]"], {'dtype': 'np.float32'}), "([data['x'], data['y'], data['h'], data['w'], data['class']], dtype\n =np.float32)\n", (3937, 4021), True, 'import numpy as np\n'), ((6703, 6795), 'numpy.array', 'np.array', (["[data['x'], data['y'], data['h'], data['w'], data['class']]"], {'dtype': 'np.float32'}), "([data['x'], data['y'], data['h'], data['w'], data['class']], dtype\n =np.float32)\n", (6711, 6795), True, 'import numpy as np\n'), ((10086, 10127), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x.shape[0], num_classes)'}), '(shape=(x.shape[0], num_classes))\n', (10094, 10127), True, 'import numpy as np\n'), ((10660, 10690), 'numpy.array', 'np.array', (['[y_x, y_y, y_h, y_w]'], {}), '([y_x, y_y, y_h, y_w])\n', (10668, 10690), True, 'import numpy as np\n'), ((12015, 12036), 'matplotlib.pyplot.imread', 'plt.imread', (['x_im[num]'], {}), '(x_im[num])\n', (12025, 12036), True, 'from matplotlib import pyplot as plt, patches\n'), ((12198, 12214), 'matplotlib.pyplot.imread', 'plt.imread', (['y_im'], {}), '(y_im)\n', (12208, 12214), True, 'from matplotlib import pyplot as plt, patches\n'), ((12404, 12418), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (12413, 12418), True, 'from matplotlib import pyplot as plt, patches\n'), ((12445, 12469), 'matplotlib.pyplot.waitforbuttonpress', 'plt.waitforbuttonpress', ([], {}), '()\n', (12467, 12469), True, 'from matplotlib import pyplot as plt, patches\n'), ((3693, 3762), 'numpy.array', 'np.array', (["[data['x'], data['y'], data['h'], data['w'], data['class']]"], {}), "([data['x'], data['y'], data['h'], data['w'], data['class']])\n", (3701, 3762), True, 'import numpy as np\n'), ((6467, 6536), 'numpy.array', 'np.array', (["[data['x'], data['y'], data['h'], data['w'], data['class']]"], {}), "([data['x'], data['y'], data['h'], data['w'], data['class']])\n", (6475, 6536), True, 'import numpy as np\n'), ((8258, 8282), 'numpy.array', 'np.array', (['anchor_centres'], {}), '(anchor_centres)\n', (8266, 8282), True, 'import numpy as np\n'), ((4138, 4179), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x.shape[0], num_classes)'}), '(shape=(x.shape[0], num_classes))\n', (4146, 4179), True, 'import numpy as np\n'), ((4778, 4808), 'numpy.array', 'np.array', (['[y_x, y_y, y_h, y_w]'], {}), '([y_x, y_y, y_h, y_w])\n', (4786, 4808), True, 'import numpy as np\n'), ((6912, 6953), 'numpy.zeros', 'np.zeros', ([], {'shape': '(x.shape[0], num_classes)'}), '(shape=(x.shape[0], num_classes))\n', (6920, 6953), True, 'import numpy as np\n'), ((7552, 7582), 'numpy.array', 'np.array', (['[y_x, y_y, y_h, y_w]'], {}), '([y_x, y_y, y_h, y_w])\n', (7560, 7582), True, 'import numpy as np\n')] |
__all__ = ['extract_ssi', 'extract_ssi_to_file',
'extract_eta', 'extract_eta_to_file',
'extract_Q_channel', 'extract_Q_down',
'extract_overland_volume', 'extract_overland_volume_to_file']
from datetime import timedelta
from configparser import SafeConfigParser
import h5py
import numpy as np
import numpy.ma as ma
# gzip compression flag
comp = 6
def extract_Q_down(control_fname):
"""Extract combined soil and overland out flow rates.
Read a PyTOPKAPI simulation file and return the combined overland
andsoil store outflows in a Numpy array.
Parameters
----------
control_fname : string
The file name of a PyTOPKAPI simulation control file. The name
should contain the full path relative to the current
directory.
Returns
-------
Qdown : Numpy array
A Numpy array containing the simulated outflow flow rates from
the overland and soil store of each cell.
"""
config = SafeConfigParser()
config.read(control_fname)
sim_fname = config.get('output_files', 'file_out')
tkpi_file = h5py.File(sim_fname, 'r')
Qdown = tkpi_file['/Q_down'][...]
tkpi_file.close()
return Qdown
def extract_Q_channel(control_fname):
"""Extract channel flow rates from a PyTOPKAPI simulation file.
Read a PyTOPKAPI simulation file and return the simulated channel
flows in a Numpy masked array.
Parameters
----------
control_fname : string
The file name of a PyTOPKAPI simulation control file. The name
should contain the full path relative to the current
directory.
Returns
-------
Qc : Numpy masked array
A Numpy masked array containing the simulated flow rates for
channel cells.
"""
config = SafeConfigParser()
config.read(control_fname)
param_fname = config.get('input_files', 'file_cell_param')
sim_fname = config.get('output_files', 'file_out')
params = np.loadtxt(param_fname)
tkpi_file = h5py.File(sim_fname, 'r')
Qc = tkpi_file['/Channel/Qc_out'][...]
tkpi_file.close()
channel_mask = params[:, 3]
cond = params[:, 3]*np.ones(Qc.shape, dtype=np.int) != 1
Qc = np.ma.masked_where(cond, Qc)
return Qc
def extract_overland_volume(control_fname):
"""Extract the volumes in the overland stores.
Read a PyTOPKAPI simulation file and return the combined overland
and store volumes in a Numpy array.
Parameters
----------
control_fname : string
The file name of a PyTOPKAPI simulation control file. The name
should contain the full path relative to the current directory
(or the root of the file system).
Returns
-------
Vo : Numpy array
A Numpy array containing the simulated storage volume in the
overland store of each cell.
"""
config = SafeConfigParser()
config.read(control_fname)
sim_fname = config.get('output_files', 'file_out')
tkpi_file = h5py.File(sim_fname, 'r')
Vo = tkpi_file['/Overland/V_o'][...]
tkpi_file.close()
return Vo
def extract_overland_volume_to_file(sim_fname, param_fname,
result_fname, start_dt, timestep):
"""Extract the volumes in the overland stores to a file.
Read a TOPKAPI simulation file and it's associated parameter file
and extract the overland store volumes for each timestep. Store
the results in a new HDF5 file, grouped by date and containing
datasets of latitude, longitude and storage volume.
Parameters
----------
sim_fname : string
The name of a PyTOPKAPI simulation file. This should include
the full or relative path.
param_fname : string
The name of a parameter file describing the catchment. This
should include the full or relative path.
result_fname : string
The name of an HDF5 file to store the output. This should
include the full or relative path.
start_dt : datetime.datetime
The starting date and time of the simulated results in
`sim_fname`.
timestep : int
The length of each model time-step in seconds.
Returns
-------
Nothing
"""
params = np.loadtxt(param_fname)
x = params[:, 1]
y = params[:, 2]
soil_depth = params[:, 8]
soil_depth = ma.masked_values(soil_depth, 0.0)
x = ma.array(x, mask=soil_depth.mask).compressed()
y = ma.array(y, mask=soil_depth.mask).compressed()
tkpi_file = h5py.File(sim_fname, 'r')
result_file = h5py.File(result_fname, 'w')
overland_vol = tkpi_file['/Overland/V_o'][...]
tkpi_file.close()
rows, cols = overland_vol.shape
# y
dset = result_file.require_dataset('y', shape=y.shape,
dtype=np.float32, compression=comp)
dset[...] = y
dset.attrs['name'] = 'y coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
# x
dset = result_file.require_dataset('x', shape=x.shape,
dtype=np.float32, compression=comp)
dset[...] = x
dset.attrs['name'] = 'x coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
curr_dt = start_dt
for k in range(rows):
print(curr_dt)
ov = ma.array(overland_vol[k], mask=soil_depth.mask).compressed()
dset = result_file.require_dataset(curr_dt.strftime('%Y%m%d%H00'),
shape=ov.shape,
dtype=np.float32, compression=comp)
dset[...] = ov
dset.attrs['name'] = 'TOPKAPI overland store volume'
dset.attrs['units'] = 'm^3'
curr_dt += timedelta(seconds=timestep)
tkpi_file.close()
result_file.close()
def extract_ssi(control_fname):
"""Extract SSI from a PyTOPKAPI simulation file.
Read a PyTOPKAPI simulation file and it's associated parameter
file and compute the Soil Saturation Index (SSI) for each model
cell and timestep. The results are returned as a Numpy array.
Parameters
----------
control_fname : string
The file name of a PyTOPKAPI simulation control file. The name
should contain the full path relative to the current
directory.
Returns
-------
ssi : Numpy ndarray
A Numpy array containing the calculated SSI values.
"""
config = SafeConfigParser()
config.read(control_fname)
global_param_fname = config.get('input_files', 'file_global_param')
param_fname = config.get('input_files', 'file_cell_param')
sim_fname = config.get('output_files', 'file_out')
fac_L = config.getfloat('calib_params', 'fac_L')
params = np.loadtxt(param_fname)
glob_params = np.genfromtxt(global_param_fname, names=True)
soil_depth = fac_L*params[:, 8]
factor = params[:, 11] - params[:, 10]
cell_area = glob_params['X']**2 # m^2
soil_depth = ma.masked_values(soil_depth, 0.0)
factor = ma.array(factor, mask=soil_depth.mask)
div = factor*soil_depth*cell_area
tkpi_file = h5py.File(sim_fname, 'r')
soil_vol = tkpi_file['/Soil/V_s'][...]
tkpi_file.close()
# ssi = (Vs/cell_vol)*100
# cell_vol = (theta_s - theta_r)*soil_depth*cell_area
sv = ma.array(soil_vol, mask=soil_depth.mask)
ssi = (sv/(div))*100.0
return ssi
def extract_ssi_to_file(sim_fname, param_fname,
result_fname, start_dt, timestep):
"""Extract percentage saturation to a file
Read a TOPKAPI simulation file and it's associated parameter file
and compute the SSI for each timestep. Store the results in a new
HDF5 file, grouped by date and containing datasets of latitude,
longitude and SSI value.
Parameters
----------
sim_fname : string
The name of a PyTOPKAPI simulation file. This should include
the full or relative path.
param_fname : string
The name of a parameter file describing the catchment. This
should include the full or relative path.
result_fname : string
The name of an HDF5 file to store the output. This should
include the full or relative path.
start_dt : datetime.datetime
The starting date and time of the simulated results in
`sim_fname`.
timestep : int
The length of each model time-step in seconds.
Returns
-------
Nothing
"""
params = np.loadtxt(param_fname)
x = params[:, 1]
y = params[:, 2]
soil_depth = params[:, 8]
factor = params[:, 11] - params[:, 10]
cell_area = 1000.0**2 # m^2
soil_depth = ma.masked_values(soil_depth, 0.0)
factor = ma.array(factor, mask=soil_depth.mask)
x = ma.array(x, mask=soil_depth.mask).compressed()
y = ma.array(y, mask=soil_depth.mask).compressed()
div = factor*soil_depth*cell_area
tkpi_file = h5py.File(sim_fname, 'r')
result_file = h5py.File(result_fname, 'w')
soil_vol = tkpi_file['/Soil/V_s'][...]
tkpi_file.close()
rows, cols = soil_vol.shape
# y
dset = result_file.require_dataset('y', shape=y.shape,
dtype=np.float32, compression=comp)
dset[...] = y
dset.attrs['name'] = 'y coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
# x
dset = result_file.require_dataset('x', shape=x.shape,
dtype=np.float32, compression=comp)
dset[...] = x
dset.attrs['name'] = 'x coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
curr_dt = start_dt
for k in range(rows):
print(curr_dt)
# ssi = (Vs/cell_vol)*100
# cell_vol = (theta_s - theta_r)*soil_depth*cell_area
sv = ma.array(soil_vol[k], mask=soil_depth.mask)
ssi = (sv/(div))*100.0
ssi = ssi.compressed()
# ssi
dset = result_file.require_dataset(curr_dt.strftime('%Y%m%d%H00'),
shape=ssi.shape,
dtype=np.float32, compression=comp)
dset[...] = ssi
dset.attrs['name'] = 'TOPKAPI soil saturation index'
dset.attrs['units'] = '% saturation'
curr_dt += timedelta(seconds=timestep)
tkpi_file.close()
result_file.close()
def extract_eta(control_fname):
"""Extract ETa from a PyTOPKAPI simulation file.
Read a PyTOPKAPI simulation file and it's associated parameter file
and extract the actual evapotranspiration for each model cell and
timestep. The results are returned as a Numpy array.
Parameters
----------
control_fname : string
The file name of a PyTOPKAPI simulation control file. The name
should contain the full path relative to the current
directory.
Returns
-------
eta : Numpy ndarray
A Numpy array containing the calculated ETa values.
"""
config = SafeConfigParser()
config.read(control_fname)
param_fname = config.get('input_files', 'file_cell_param')
sim_fname = config.get('output_files', 'file_out')
params = np.loadtxt(param_fname)
soil_depth = params[:, 8]
soil_depth = ma.masked_values(soil_depth, 0.0)
tkpi_file = h5py.File(sim_fname, 'r')
eta = tkpi_file['/ET_out'][...]
tkpi_file.close()
eta = ma.array(eta, mask=soil_depth.mask)
return eta
def extract_eta_to_file(sim_fname, param_fname,
result_fname, start_dt, timestep):
"""Extract actual evapotranspiration to a file
Read a PyTOPKAPI simulation file and it's associated parameter
file and extract the actual evapotranspiration for each
timestep. Store the results in a new HDF5 file, grouped by date
and containing datasets of latitude, longitude and ETa value.
Parameters
----------
sim_fname : string
The name of a PyTOPKAPI simulation file. This should include
the full or relative path.
param_fname : string
The name of a parameter file describing the catchment. This
should include the full or relative path.
result_fname : string
The name of an HDF5 file to store the output. This should
include the full or relative path.
start_dt : datetime.datetime
The starting date and time of the simulated results in
`sim_fname`.
timestep : int
The length of each model time-step in seconds.
Returns
-------
Nothing
"""
params = np.loadtxt(param_fname)
x = params[:, 1]
y = params[:, 2]
soil_depth = params[:, 8]
soil_depth = ma.masked_values(soil_depth, 0.0)
x = ma.array(x, mask=soil_depth.mask).compressed()
y = ma.array(y, mask=soil_depth.mask).compressed()
tkpi_file = h5py.File(sim_fname, 'r')
result_file = h5py.File(result_fname, 'w')
eta = tkpi_file['/ET_out'][...]
tkpi_file.close()
rows, cols = eta.shape
# y
dset = result_file.require_dataset('y', shape=y.shape,
dtype=np.float32, compression=comp)
dset[...] = y
dset.attrs['name'] = 'y coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
# x
dset = result_file.require_dataset('x', shape=x.shape,
dtype=np.float32, compression=comp)
dset[...] = x
dset.attrs['name'] = 'x coordinate'
dset.attrs['units'] = 'Projection dependent (Metres or Decimal degrees)'
curr_dt = start_dt
for k in range(rows):
print(curr_dt)
et = ma.array(eta[k], mask=soil_depth.mask)
et = et.compressed()
# ETa
dset = result_file.require_dataset(curr_dt.strftime('%Y%m%d%H00'),
shape=et.shape,
dtype=np.float32, compression=comp)
dset[...] = et
dset.attrs['name'] = 'PyTOPKAPI actual ET'
dset.attrs['units'] = 'mm'
curr_dt += timedelta(seconds=timestep)
result_file.close()
| [
"numpy.ma.masked_values",
"numpy.ones",
"numpy.ma.array",
"h5py.File",
"numpy.ma.masked_where",
"datetime.timedelta",
"numpy.loadtxt",
"numpy.genfromtxt",
"configparser.SafeConfigParser"
] | [((994, 1012), 'configparser.SafeConfigParser', 'SafeConfigParser', ([], {}), '()\n', (1010, 1012), False, 'from configparser import SafeConfigParser\n'), ((1117, 1142), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (1126, 1142), False, 'import h5py\n'), ((1810, 1828), 'configparser.SafeConfigParser', 'SafeConfigParser', ([], {}), '()\n', (1826, 1828), False, 'from configparser import SafeConfigParser\n'), ((1993, 2016), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (2003, 2016), True, 'import numpy as np\n'), ((2034, 2059), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (2043, 2059), False, 'import h5py\n'), ((2229, 2257), 'numpy.ma.masked_where', 'np.ma.masked_where', (['cond', 'Qc'], {}), '(cond, Qc)\n', (2247, 2257), True, 'import numpy as np\n'), ((2896, 2914), 'configparser.SafeConfigParser', 'SafeConfigParser', ([], {}), '()\n', (2912, 2914), False, 'from configparser import SafeConfigParser\n'), ((3019, 3044), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (3028, 3044), False, 'import h5py\n'), ((4264, 4287), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (4274, 4287), True, 'import numpy as np\n'), ((4378, 4411), 'numpy.ma.masked_values', 'ma.masked_values', (['soil_depth', '(0.0)'], {}), '(soil_depth, 0.0)\n', (4394, 4411), True, 'import numpy.ma as ma\n'), ((4539, 4564), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (4548, 4564), False, 'import h5py\n'), ((4583, 4611), 'h5py.File', 'h5py.File', (['result_fname', '"""w"""'], {}), "(result_fname, 'w')\n", (4592, 4611), False, 'import h5py\n'), ((6486, 6504), 'configparser.SafeConfigParser', 'SafeConfigParser', ([], {}), '()\n', (6502, 6504), False, 'from configparser import SafeConfigParser\n'), ((6794, 6817), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (6804, 6817), True, 'import numpy as np\n'), ((6836, 6881), 'numpy.genfromtxt', 'np.genfromtxt', (['global_param_fname'], {'names': '(True)'}), '(global_param_fname, names=True)\n', (6849, 6881), True, 'import numpy as np\n'), ((7022, 7055), 'numpy.ma.masked_values', 'ma.masked_values', (['soil_depth', '(0.0)'], {}), '(soil_depth, 0.0)\n', (7038, 7055), True, 'import numpy.ma as ma\n'), ((7069, 7107), 'numpy.ma.array', 'ma.array', (['factor'], {'mask': 'soil_depth.mask'}), '(factor, mask=soil_depth.mask)\n', (7077, 7107), True, 'import numpy.ma as ma\n'), ((7163, 7188), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (7172, 7188), False, 'import h5py\n'), ((7352, 7392), 'numpy.ma.array', 'ma.array', (['soil_vol'], {'mask': 'soil_depth.mask'}), '(soil_vol, mask=soil_depth.mask)\n', (7360, 7392), True, 'import numpy.ma as ma\n'), ((8515, 8538), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (8525, 8538), True, 'import numpy as np\n'), ((8705, 8738), 'numpy.ma.masked_values', 'ma.masked_values', (['soil_depth', '(0.0)'], {}), '(soil_depth, 0.0)\n', (8721, 8738), True, 'import numpy.ma as ma\n'), ((8752, 8790), 'numpy.ma.array', 'ma.array', (['factor'], {'mask': 'soil_depth.mask'}), '(factor, mask=soil_depth.mask)\n', (8760, 8790), True, 'import numpy.ma as ma\n'), ((8957, 8982), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (8966, 8982), False, 'import h5py\n'), ((9001, 9029), 'h5py.File', 'h5py.File', (['result_fname', '"""w"""'], {}), "(result_fname, 'w')\n", (9010, 9029), False, 'import h5py\n'), ((11056, 11074), 'configparser.SafeConfigParser', 'SafeConfigParser', ([], {}), '()\n', (11072, 11074), False, 'from configparser import SafeConfigParser\n'), ((11239, 11262), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (11249, 11262), True, 'import numpy as np\n'), ((11311, 11344), 'numpy.ma.masked_values', 'ma.masked_values', (['soil_depth', '(0.0)'], {}), '(soil_depth, 0.0)\n', (11327, 11344), True, 'import numpy.ma as ma\n'), ((11362, 11387), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (11371, 11387), False, 'import h5py\n'), ((11457, 11492), 'numpy.ma.array', 'ma.array', (['eta'], {'mask': 'soil_depth.mask'}), '(eta, mask=soil_depth.mask)\n', (11465, 11492), True, 'import numpy.ma as ma\n'), ((12616, 12639), 'numpy.loadtxt', 'np.loadtxt', (['param_fname'], {}), '(param_fname)\n', (12626, 12639), True, 'import numpy as np\n'), ((12730, 12763), 'numpy.ma.masked_values', 'ma.masked_values', (['soil_depth', '(0.0)'], {}), '(soil_depth, 0.0)\n', (12746, 12763), True, 'import numpy.ma as ma\n'), ((12892, 12917), 'h5py.File', 'h5py.File', (['sim_fname', '"""r"""'], {}), "(sim_fname, 'r')\n", (12901, 12917), False, 'import h5py\n'), ((12936, 12964), 'h5py.File', 'h5py.File', (['result_fname', '"""w"""'], {}), "(result_fname, 'w')\n", (12945, 12964), False, 'import h5py\n'), ((5783, 5810), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'timestep'}), '(seconds=timestep)\n', (5792, 5810), False, 'from datetime import timedelta\n'), ((9868, 9911), 'numpy.ma.array', 'ma.array', (['soil_vol[k]'], {'mask': 'soil_depth.mask'}), '(soil_vol[k], mask=soil_depth.mask)\n', (9876, 9911), True, 'import numpy.ma as ma\n'), ((10355, 10382), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'timestep'}), '(seconds=timestep)\n', (10364, 10382), False, 'from datetime import timedelta\n'), ((13697, 13735), 'numpy.ma.array', 'ma.array', (['eta[k]'], {'mask': 'soil_depth.mask'}), '(eta[k], mask=soil_depth.mask)\n', (13705, 13735), True, 'import numpy.ma as ma\n'), ((14123, 14150), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'timestep'}), '(seconds=timestep)\n', (14132, 14150), False, 'from datetime import timedelta\n'), ((2182, 2213), 'numpy.ones', 'np.ones', (['Qc.shape'], {'dtype': 'np.int'}), '(Qc.shape, dtype=np.int)\n', (2189, 2213), True, 'import numpy as np\n'), ((4420, 4453), 'numpy.ma.array', 'ma.array', (['x'], {'mask': 'soil_depth.mask'}), '(x, mask=soil_depth.mask)\n', (4428, 4453), True, 'import numpy.ma as ma\n'), ((4475, 4508), 'numpy.ma.array', 'ma.array', (['y'], {'mask': 'soil_depth.mask'}), '(y, mask=soil_depth.mask)\n', (4483, 4508), True, 'import numpy.ma as ma\n'), ((8799, 8832), 'numpy.ma.array', 'ma.array', (['x'], {'mask': 'soil_depth.mask'}), '(x, mask=soil_depth.mask)\n', (8807, 8832), True, 'import numpy.ma as ma\n'), ((8854, 8887), 'numpy.ma.array', 'ma.array', (['y'], {'mask': 'soil_depth.mask'}), '(y, mask=soil_depth.mask)\n', (8862, 8887), True, 'import numpy.ma as ma\n'), ((12773, 12806), 'numpy.ma.array', 'ma.array', (['x'], {'mask': 'soil_depth.mask'}), '(x, mask=soil_depth.mask)\n', (12781, 12806), True, 'import numpy.ma as ma\n'), ((12828, 12861), 'numpy.ma.array', 'ma.array', (['y'], {'mask': 'soil_depth.mask'}), '(y, mask=soil_depth.mask)\n', (12836, 12861), True, 'import numpy.ma as ma\n'), ((5367, 5414), 'numpy.ma.array', 'ma.array', (['overland_vol[k]'], {'mask': 'soil_depth.mask'}), '(overland_vol[k], mask=soil_depth.mask)\n', (5375, 5414), True, 'import numpy.ma as ma\n')] |
from __future__ import print_function
import torch
import numpy as np
import util
# getting started
def getting_started():
print(util.Section('Getting Started'))
# construction
print(util.SubSection('Construction'))
xa1 = torch.empty(5, 3) # uninitialized
xa2 = torch.rand(5, 3) # randomly initialized matrix
xa3 = torch.zeros(5, 3, dtype=torch.long) # filled zeros and of dtype long
xa4 = torch.tensor([5.5, 3]) # directly from data
xa5 = xa3.new_ones(5, 3, dtype=torch.double) # new_* method take in sizes
xa6 = torch.randn_like(xa5, dtype=torch.float) # override dtype with same size
print(f'x size = {xa6.size()}')
# operations
xb1 = torch.rand(5, 3)
yb1 = torch.rand(5, 3)
# operation: add
print(util.SubSection('Operations: Add'))
print(f'xb1 + yb1 = {xb1 + yb1}')
print(f'xb1 + yb1 = {torch.add(xb1, yb1)}')
# with output argument
rb1 = torch.empty(5, 3)
torch.add(xb1, yb1, out=rb1)
print(f'rb1 = {rb1}')
# add in place
yb1.add_(xb1)
print(f'yb1 = {yb1}')
# index
print(f'xb1[:,1] = {xb1[:, 1]}')
# operation: resize
print(util.SubSection('Operations: Resize'))
xb2 = torch.randn(4, 4)
yb2 = xb2.view(16)
zb2 = xb2.view(-1, 8)
print(f'xb2 = {xb2}')
print(f'yb2 = {yb2}')
print(f'zb2 = {zb2}')
print(f'xb2.size = {xb2.size()}, yb2.size = {yb2.size()}, zb2.size = {zb2.size()}')
# if only one element, can use .item() to get the values as a python number
xb3 = torch.randn(1)
print(f'xb3 = {xb3}')
print(f'xb3.item() = {xb3.item()}')
# numpy bridge, change one will change the other
print(util.SubSection('NumPy Bridge'))
# torch => numpy
xc1 = torch.ones(5)
print(f'xc1 = {xc1}')
yc1 = xc1.numpy()
print(f'yc1 = {yc1}')
# add, y will also changed
xc1.add_(1)
print(f'xc1 = {xc1}')
print(f'yc1 = {yc1}')
# numpy => torch
xc2 = np.ones(5)
yc2 = torch.from_numpy(xc2)
np.add(xc2, 1, out=xc2)
print(f'xc2 = {xc2}')
print(f'yc2 = {yc2}')
# CUDA tensors
print(util.SubSection('CUDA Tensors'))
xd1 = torch.rand((3, 2))
if torch.cuda.is_available():
print('use CUDA')
device = torch.device('cuda')
yd1 = torch.ones_like(xd1, device=device) # directly create a tensor on GPU
xd2 = xd1.to(device)
zd1 = xd2 + yd1
print(f'zd1 = {zd1}')
print(f'to CPU, zd1 = {zd1.to("cpu", torch.double)}') # "to" can also change dtype together
# autograd
def auto_grad():
print(util.Section('Auto Grad'))
# grad function
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
print('y = ', y)
print('y.grad_fn = ', y.grad_fn)
print('z = {0}, out = {1}'.format(z, out))
# requires grad setting
a = torch.randn(2, 2)
a = (a * 3) / (a - 1)
print('a.requires_grad = ', a.requires_grad)
a.requires_grad_(True)
print('a.requires_grad = ', a.requires_grad)
b = (a * a).sum()
print('b.grad_fn = ', b.grad_fn)
# gradients
out.backward()
print('x.grad = ', x.grad)
# do more crazy things with autograd
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
print('y = ', y)
gradients = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(gradients)
print('x.grad = ', x.grad)
# stop autograd
print(x.requires_grad)
print((x**2).requires_grad)
with torch.no_grad():
print((x**2).requires_grad)
if __name__ == '__main__':
print('pytorch version', torch.__version__)
getting_started()
auto_grad()
| [
"torch.ones_like",
"torch.ones",
"numpy.ones",
"numpy.add",
"util.SubSection",
"torch.device",
"torch.from_numpy",
"torch.tensor",
"torch.randn_like",
"torch.add",
"torch.cuda.is_available",
"util.Section",
"torch.no_grad",
"torch.empty",
"torch.zeros",
"torch.rand",
"torch.randn"
] | [((241, 258), 'torch.empty', 'torch.empty', (['(5)', '(3)'], {}), '(5, 3)\n', (252, 258), False, 'import torch\n'), ((286, 302), 'torch.rand', 'torch.rand', (['(5)', '(3)'], {}), '(5, 3)\n', (296, 302), False, 'import torch\n'), ((344, 379), 'torch.zeros', 'torch.zeros', (['(5)', '(3)'], {'dtype': 'torch.long'}), '(5, 3, dtype=torch.long)\n', (355, 379), False, 'import torch\n'), ((424, 446), 'torch.tensor', 'torch.tensor', (['[5.5, 3]'], {}), '([5.5, 3])\n', (436, 446), False, 'import torch\n'), ((558, 598), 'torch.randn_like', 'torch.randn_like', (['xa5'], {'dtype': 'torch.float'}), '(xa5, dtype=torch.float)\n', (574, 598), False, 'import torch\n'), ((696, 712), 'torch.rand', 'torch.rand', (['(5)', '(3)'], {}), '(5, 3)\n', (706, 712), False, 'import torch\n'), ((723, 739), 'torch.rand', 'torch.rand', (['(5)', '(3)'], {}), '(5, 3)\n', (733, 739), False, 'import torch\n'), ((931, 948), 'torch.empty', 'torch.empty', (['(5)', '(3)'], {}), '(5, 3)\n', (942, 948), False, 'import torch\n'), ((953, 981), 'torch.add', 'torch.add', (['xb1', 'yb1'], {'out': 'rb1'}), '(xb1, yb1, out=rb1)\n', (962, 981), False, 'import torch\n'), ((1204, 1221), 'torch.randn', 'torch.randn', (['(4)', '(4)'], {}), '(4, 4)\n', (1215, 1221), False, 'import torch\n'), ((1527, 1541), 'torch.randn', 'torch.randn', (['(1)'], {}), '(1)\n', (1538, 1541), False, 'import torch\n'), ((1736, 1749), 'torch.ones', 'torch.ones', (['(5)'], {}), '(5)\n', (1746, 1749), False, 'import torch\n'), ((1954, 1964), 'numpy.ones', 'np.ones', (['(5)'], {}), '(5)\n', (1961, 1964), True, 'import numpy as np\n'), ((1975, 1996), 'torch.from_numpy', 'torch.from_numpy', (['xc2'], {}), '(xc2)\n', (1991, 1996), False, 'import torch\n'), ((2001, 2024), 'numpy.add', 'np.add', (['xc2', '(1)'], {'out': 'xc2'}), '(xc2, 1, out=xc2)\n', (2007, 2024), True, 'import numpy as np\n'), ((2150, 2168), 'torch.rand', 'torch.rand', (['(3, 2)'], {}), '((3, 2))\n', (2160, 2168), False, 'import torch\n'), ((2176, 2201), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2199, 2201), False, 'import torch\n'), ((2631, 2667), 'torch.ones', 'torch.ones', (['(2)', '(2)'], {'requires_grad': '(True)'}), '(2, 2, requires_grad=True)\n', (2641, 2667), False, 'import torch\n'), ((2861, 2878), 'torch.randn', 'torch.randn', (['(2)', '(2)'], {}), '(2, 2)\n', (2872, 2878), False, 'import torch\n'), ((3206, 3240), 'torch.randn', 'torch.randn', (['(3)'], {'requires_grad': '(True)'}), '(3, requires_grad=True)\n', (3217, 3240), False, 'import torch\n'), ((3342, 3393), 'torch.tensor', 'torch.tensor', (['[0.1, 1.0, 0.0001]'], {'dtype': 'torch.float'}), '([0.1, 1.0, 0.0001], dtype=torch.float)\n', (3354, 3393), False, 'import torch\n'), ((135, 166), 'util.Section', 'util.Section', (['"""Getting Started"""'], {}), "('Getting Started')\n", (147, 166), False, 'import util\n'), ((198, 229), 'util.SubSection', 'util.SubSection', (['"""Construction"""'], {}), "('Construction')\n", (213, 229), False, 'import util\n'), ((772, 806), 'util.SubSection', 'util.SubSection', (['"""Operations: Add"""'], {}), "('Operations: Add')\n", (787, 806), False, 'import util\n'), ((1155, 1192), 'util.SubSection', 'util.SubSection', (['"""Operations: Resize"""'], {}), "('Operations: Resize')\n", (1170, 1192), False, 'import util\n'), ((1672, 1703), 'util.SubSection', 'util.SubSection', (['"""NumPy Bridge"""'], {}), "('NumPy Bridge')\n", (1687, 1703), False, 'import util\n'), ((2107, 2138), 'util.SubSection', 'util.SubSection', (['"""CUDA Tensors"""'], {}), "('CUDA Tensors')\n", (2122, 2138), False, 'import util\n'), ((2246, 2266), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (2258, 2266), False, 'import torch\n'), ((2281, 2316), 'torch.ones_like', 'torch.ones_like', (['xd1'], {'device': 'device'}), '(xd1, device=device)\n', (2296, 2316), False, 'import torch\n'), ((2576, 2601), 'util.Section', 'util.Section', (['"""Auto Grad"""'], {}), "('Auto Grad')\n", (2588, 2601), False, 'import util\n'), ((3540, 3555), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3553, 3555), False, 'import torch\n'), ((871, 890), 'torch.add', 'torch.add', (['xb1', 'yb1'], {}), '(xb1, yb1)\n', (880, 890), False, 'import torch\n')] |
#############################################################
# Copyright (C) 2015 <NAME>, <NAME>
#
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
##############################################################
import copy
import numpy as np
import pygp
from pygp.learning import optimization
import ei
import grid
import sobol_lib
import util
class GPSingle:
'''
GPSingle class for the optimization of a conditional hyperparameter space,
which models the whole joint space with a single GP, effectively ignoring
the information contained in the conditional space.
Appends an extra learner_choice parameter to the search_space given at
initialization time, and uses this parameter to optimize the learner
choice.
'''
def __init__(self, search_space, grid_size, gp_priors, optimist):
'''GPSingle constructor
Parameters:
-----------
search_space: list of subspaces representing conditional or independent
hyperparameters. For now only one level of subspaces is supported.
grid_size: total number of points to allow for the discretization
of the search space. Budget is spread evenly across subspaces
to the ratio of their dimensionalities.
gp_priors: priors to apply for the optimization of each GP's
hyperparameters.
optimist: if True, the GP will fix the prior mean to the maximum
possible value (e.g., 1 for 100% accuracy)
'''
self.__name__ = "gpsingle"
self.flat_search_space = [{"name": "learner_choice",
"min": 0,
"max": len(search_space)-1,
"type": "int"}]
self.learner_param_indexes = []
self.search_space = search_space
if optimist:
mu = 1
gp_priors["mu"] = None
else:
mu = 0
n_params = 1
for i in range(len(search_space)):
ss_i = search_space[i] # list of dicts
self.flat_search_space.extend(ss_i)
cur_indexes = []
for j in range(len(ss_i)):
cur_indexes.append(n_params)
n_params += 1
self.learner_param_indexes.append(cur_indexes)
# build grid
dims = len(self.flat_search_space)
self.map = grid.GridMap(self.flat_search_space)
self.space = np.transpose(sobol_lib.i4_sobol_generate(dims,
grid_size, 9001))
self.gp = pygp.BasicGP(sn=1, sf=1, ell=np.ones(dims), mu=mu,
kernel="matern5")
self.gp_priors = gp_priors
def next(self):
'''Return the next point to evaluate according to acquisition
function. Returns a subspace index, the index in the given subspace
and the corresponding learner parameters in a dict which is
directly unpackable. '''
if self.gp.ndata < 2:
# not enough points pick random parameters
grid_i = np.random.choice(len(self.space))
else:
# optimize the model
optimization.optimize_random_start(self.gp, self.gp_priors)
# pick the parameters maximizing the acquisition function
mu, var = self.gp.posterior(self.space)
acq = ei.expected_improvement(mu, var, self.gp.data[1])
grid_i = util.eq_rand_idx(acq, np.max(acq))
learner_i, learner_params = self.raw_to_learner_params(
self.space[grid_i])
return grid_i, learner_i, learner_params
def raw_to_learner_params(self, raw):
'''Return learning ID and its params from raw points (in search space
scaled to 0-1).
'''
params = self.map.get_params(raw)
learner_i = params[0]["val"]
l_param_i = self.learner_param_indexes[learner_i]
learner_params = {params[i]["name"]:params[i]["val"] for i in l_param_i}
return learner_i, learner_params
def update(self, learner_i, grid_i, score):
''' Update the model with the `score` obtained for `learner_i`
at index `grid_i` in the member's subspace.'''
self.gp.add_data(self.space[grid_i], score)
| [
"numpy.ones",
"sobol_lib.i4_sobol_generate",
"grid.GridMap",
"numpy.max",
"ei.expected_improvement",
"pygp.learning.optimization.optimize_random_start"
] | [((2471, 2507), 'grid.GridMap', 'grid.GridMap', (['self.flat_search_space'], {}), '(self.flat_search_space)\n', (2483, 2507), False, 'import grid\n'), ((2542, 2592), 'sobol_lib.i4_sobol_generate', 'sobol_lib.i4_sobol_generate', (['dims', 'grid_size', '(9001)'], {}), '(dims, grid_size, 9001)\n', (2569, 2592), False, 'import sobol_lib\n'), ((3259, 3318), 'pygp.learning.optimization.optimize_random_start', 'optimization.optimize_random_start', (['self.gp', 'self.gp_priors'], {}), '(self.gp, self.gp_priors)\n', (3293, 3318), False, 'from pygp.learning import optimization\n'), ((3459, 3508), 'ei.expected_improvement', 'ei.expected_improvement', (['mu', 'var', 'self.gp.data[1]'], {}), '(mu, var, self.gp.data[1])\n', (3482, 3508), False, 'import ei\n'), ((2654, 2667), 'numpy.ones', 'np.ones', (['dims'], {}), '(dims)\n', (2661, 2667), True, 'import numpy as np\n'), ((3552, 3563), 'numpy.max', 'np.max', (['acq'], {}), '(acq)\n', (3558, 3563), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
"""
Rescores words-as-classifier scores using sequence prediction
Uses data generated by "structural_model_weighting_trainer.py".
"""
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = "Copyright 2017 <NAME>"
__license__ = "Apache License, Version 2.0"
import argparse
import random
import sys
import keras.preprocessing.sequence
import numpy as np
import pandas as pd
from keras.models import Sequential
from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, \
group_seq_xy_by_len
def onehot_encodings(features: np.ndarray, onehot_encoder) -> np.ndarray:
"""
:param features: A 2D array of feature vectors, each of which starts with one-hot encoding features. Any other features follow those.
:param onehot_encoder: The instance used to encode the original values.
:return: A 2D numpy array consisting only of one-hot encoding features.
"""
feature_count = onehot_encoder.n_values_[0]
return features[:, :feature_count + 1]
def onehot_encoded_word(onehot_features: np.ndarray, label_encoder) -> str:
# Check if there are any non-zero values
if onehot_features.any():
word_label = onehot_features.argmax()
result = label_encoder.inverse_transform([word_label])[0]
else:
result = "(padding)"
return result
def word(features: np.ndarray, label_encoder, onehot_encoder) -> str:
feature_count = onehot_encoder.n_values_[0]
onehot = features[:feature_count + 1]
return onehot_encoded_word(onehot, label_encoder)
def word_seq(x: np.ndarray, label_encoder, onehot_encoder) -> np.ndarray:
word_features = onehot_encodings(x, onehot_encoder)
return np.apply_along_axis(lambda arr: onehot_encoded_word(arr, label_encoder), 1, word_features)
def score_entity(entity_utts: pd.DataFrame, seq_feature_extractor, model: Sequential):
sequence_groups = entity_utts.groupby(
("UTT_START_TIME", "UTT_END_TIME"), sort=False)
print("Generating data for {} entity token sequence(s).".format(len(sequence_groups)), file=sys.stderr)
# for time, tok_seq in sequence_groups:
# print(time)
# print(tok_seq)
seq_xy = sequence_groups.apply(seq_feature_extractor)
len_dict = group_seq_xy_by_len(seq_xy)
print("Created {} batches, one for each unique sequence length.".format(len(len_dict)), file=sys.stderr)
#for seq_len, seqs in sorted(len_dict.items(), key=lambda item: item[0]):
# print(seqs)
seq_batches_by_len = tuple(len_dict.values())
data_seq = TokenSequenceSequence(seq_batches_by_len)
#predictions = model.predict_generator(data_seq)
#print(predictions)
for seq_len, xy in len_dict.items():
print("Classifying {} inputs with length {}.".format(len(xy), seq_len), file=sys.stderr)
x_only = np.asarray(tuple(np.asarray(x) for x,y in xy))
for elem in x_only:
print(type(elem))
#print(x_only)
predictions = model.predict(x_only)
print(predictions)
#print(predictions)
#for xy in seq_batches_by_len:
# print(type(xy))
def test_round(round_group: pd.DataFrame, seq_feature_extractor, model: Sequential):
entity_utts = round_group.groupby(("ENTITY", "IS_TARGET"), as_index=False, sort=False)
entity_utts.apply(lambda group: score_entity(group, seq_feature_extractor, model))
def __create_argparser() -> argparse.ArgumentParser:
result = argparse.ArgumentParser(
description="Rescores words-as-classifier scores using sequence prediction.")
result.add_argument("indir", metavar="DIR", help="The directory with the model data to use for classification.")
return result
def __main(args):
indir = args.indir
print("Will read data from \"{}\".".format(indir),
file=sys.stderr)
random_seed = TrainingFile.RANDOM_SEED.value.read(indir)
print("Setting random seed to {}.".format(random_seed), file=sys.stderr)
# https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/
# fix random seed for reproducibility
random.seed(random_seed)
np.random.seed(random_seed)
label_encoder = TrainingFile.VOCAB_LABELS.value.read(indir)
onehot_encoder = TrainingFile.ONEHOT_ENCODINGS.value.read(indir)
# assert onehot_encoder.n_values_ == len(vocab_words)
# vocab_onehot_encoded = onehot_encoder.fit_transform(vocab_labels)
# print(vocab_onehot_encoded)
# invert first example
# inverted = label_encoder.inverse_transform([np.argmax(vocab_onehot_encoded[0, :])])
# print(inverted)
# training_df = TrainingFile.TRAINING_DATA.value.read(indir)
test_df = TrainingFile.TEST_DATA.value.read(indir)
seq_feature_extractor = SequenceFeatureExtractor(onehot_encoder)
# print("Generating training data token sequences.", file=sys.stderr)
# training_data_generator = data_generator_factory(training_df)
print("Generating validation data token sequences.", file=sys.stderr)
#validation_data_generator = data_generator_factory(find_target_ref_rows(test_df))
# https://stackoverflow.com/a/43472000/1391325
with keras.backend.get_session():
model = TrainingFile.MODEL.value.read(indir)
# create_loss_plot(training_history)
round_utts = test_df.groupby(
("CROSS_VALIDATION_ITER", "DYAD", "ROUND"),
as_index=False, sort=False)
print("Will test {} rounds.".format(len(round_utts)), file=sys.stderr)
test_results = round_utts.apply(
lambda group: test_round(group, seq_feature_extractor, model))
if __name__ == "__main__":
__main(__create_argparser().parse_args())
| [
"structural_model_weighting_trainer.TrainingFile.RANDOM_SEED.value.read",
"argparse.ArgumentParser",
"structural_model_weighting_trainer.TrainingFile.VOCAB_LABELS.value.read",
"structural_model_weighting_trainer.TrainingFile.ONEHOT_ENCODINGS.value.read",
"structural_model_weighting_trainer.TokenSequenceSequ... | [((2174, 2201), 'structural_model_weighting_trainer.group_seq_xy_by_len', 'group_seq_xy_by_len', (['seq_xy'], {}), '(seq_xy)\n', (2193, 2201), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((2457, 2498), 'structural_model_weighting_trainer.TokenSequenceSequence', 'TokenSequenceSequence', (['seq_batches_by_len'], {}), '(seq_batches_by_len)\n', (2478, 2498), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((3273, 3379), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Rescores words-as-classifier scores using sequence prediction."""'}), "(description=\n 'Rescores words-as-classifier scores using sequence prediction.')\n", (3296, 3379), False, 'import argparse\n'), ((3636, 3678), 'structural_model_weighting_trainer.TrainingFile.RANDOM_SEED.value.read', 'TrainingFile.RANDOM_SEED.value.read', (['indir'], {}), '(indir)\n', (3671, 3678), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((3899, 3923), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (3910, 3923), False, 'import random\n'), ((3925, 3952), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (3939, 3952), True, 'import numpy as np\n'), ((3971, 4014), 'structural_model_weighting_trainer.TrainingFile.VOCAB_LABELS.value.read', 'TrainingFile.VOCAB_LABELS.value.read', (['indir'], {}), '(indir)\n', (4007, 4014), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((4033, 4080), 'structural_model_weighting_trainer.TrainingFile.ONEHOT_ENCODINGS.value.read', 'TrainingFile.ONEHOT_ENCODINGS.value.read', (['indir'], {}), '(indir)\n', (4073, 4080), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((4440, 4480), 'structural_model_weighting_trainer.TrainingFile.TEST_DATA.value.read', 'TrainingFile.TEST_DATA.value.read', (['indir'], {}), '(indir)\n', (4473, 4480), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((4507, 4547), 'structural_model_weighting_trainer.SequenceFeatureExtractor', 'SequenceFeatureExtractor', (['onehot_encoder'], {}), '(onehot_encoder)\n', (4531, 4547), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((4933, 4969), 'structural_model_weighting_trainer.TrainingFile.MODEL.value.read', 'TrainingFile.MODEL.value.read', (['indir'], {}), '(indir)\n', (4962, 4969), False, 'from structural_model_weighting_trainer import SequenceFeatureExtractor, TokenSequenceSequence, TrainingFile, group_seq_xy_by_len\n'), ((2727, 2740), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (2737, 2740), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
"""
Contains a class to use an atlas to look up your location inside a brain.
Created 2/8/2021 by <NAME>.
"""
from pathlib import Path
from typing import Dict, Tuple
import templateflow.api
import pandas
import nibabel
import numpy
from functools import cached_property
from dataclasses import dataclass
@dataclass
class Atlas():
"""
Looks up atlas coordinates for you. All coordinates are in voxel space, NOT scanner space.
Your data MUST be aligned and resampled to the 1mm or 2mm MNI152NLin2009cAsym brain.
When constructing an Atlas object, you can set lower_resolution=True if you'd like the atlas to use 2mm resolution.
You may use the Atlas like a Python dictionary if you'd like. For example,
>>> coordinate_lookup = Atlas()
>>> print(coordinate_lookup[(100, 100, 100)])
prints the following:
'Right Cerebral White Matter'
"""
lower_resolution: bool=False
def __getitem__(self, thruple: Tuple[int, int, int]) -> str:
assert len(thruple) == 3, "You must pass a tuple with exactly 3 coordinates, i.e. (x, y, z)"
x, y, z = thruple
return self.translation_array[x, y, z]
@cached_property
def _image(self) -> nibabel.nifti1.Nifti1Image:
"""
Returns raw atlas image to be translated. If self.lower_resolution = True, raw atlas image will be 2mm resolution.
"""
nifti_path = self._MNI_dir / "tpl-MNI152NLin2009cAsym_res-01_desc-carpet_dseg.nii.gz"
if self.lower_resolution == True:
nifti_path = self._MNI_dir / "tpl-MNI152NLin2009cAsym_res-02_desc-carpet_dseg.nii.gz"
return nibabel.load(nifti_path)
@cached_property
def _translation_dictionary(self) -> Dict[int, str]:
"""
Returns a dict containing the code for each area of the brain recorded in
{MNI_dir}/"tpl-MNI152NLin2009cAsym_desc-carpet_dseg.tsv"
Each key is an index, and each value is a brain region.
"""
tsv_lookup = self._MNI_dir / "tpl-MNI152NLin2009cAsym_desc-carpet_dseg.tsv"
dataframe_lookup = pandas.read_csv(tsv_lookup, delimiter="\t")
return dict(zip(dataframe_lookup["index"], dataframe_lookup["name"]))
@cached_property
def _MNI_dir(self) -> Path:
"""
Uses templateflow to download MNI brain stuff. Returns directory in which it's downloaded.
"""
return templateflow.api.get("MNI152NLin2009cAsym")[0].parent
@cached_property
def translation_array(self) -> numpy.array:
"""
Returns an array. Contains an atlas location at each coordinate in the array.
"""
untranslated_array = numpy.asarray(self._image.dataobj).astype(int)
return self._replace_using_dict(untranslated_array, self._translation_dictionary)
def mask_image(self, image, region: str) -> numpy.ma.masked_array:
"""
Given a NiBabel image, returns a masked array for a region of interest.
Image must be in the same space as the atlas.
"""
image_array = image.get_fdata()
number_of_dimensions = image_array.ndim
assert number_of_dimensions == 3 or number_of_dimensions == 4, "Image must be 3-dimensional or 4-dimensional."
if number_of_dimensions == 3:
mask = self.get_3d_mask(region)
else:
fourth_dimension_length=image_array.shape[3]
mask = self.get_4d_mask(region, fourth_dimension_length)
masked_image = numpy.ma.masked_array(image_array, mask=mask)
return masked_image
def get_4d_mask(self, region: str, fourth_dimension_length: int) -> numpy.array:
"""
Returns a 4d array where each coordinate of the specified region equals False, and all other values are True.
Use this for atlasing EPI images or other 4d structures.
"""
third_dimensional_array = self.get_3d_mask(region)
fourth_dimensional_array = numpy.repeat(third_dimensional_array[..., numpy.newaxis], fourth_dimension_length, axis=-1)
return fourth_dimensional_array
def get_3d_mask(self, region: str) -> numpy.array:
"""
Returns a 3d array where each coordinate of the specified region is False, and all other values are True.
"""
mask = self.atlas_array != region
return mask
def _replace_using_dict(self, array: numpy.array, dictionary: Dict) -> numpy.array:
"""
Replace all keys in target array with their specified values.
"""
keys = numpy.array(list(dictionary.keys()))
values = numpy.array(list(dictionary.values()))
mapping_array = numpy.zeros(keys.max()+1, dtype=values.dtype)
mapping_array[keys] = values
return mapping_array[array]
| [
"numpy.repeat",
"pandas.read_csv",
"nibabel.load",
"numpy.asarray",
"numpy.ma.masked_array"
] | [((1649, 1673), 'nibabel.load', 'nibabel.load', (['nifti_path'], {}), '(nifti_path)\n', (1661, 1673), False, 'import nibabel\n'), ((2105, 2148), 'pandas.read_csv', 'pandas.read_csv', (['tsv_lookup'], {'delimiter': '"""\t"""'}), "(tsv_lookup, delimiter='\\t')\n", (2120, 2148), False, 'import pandas\n'), ((3513, 3558), 'numpy.ma.masked_array', 'numpy.ma.masked_array', (['image_array'], {'mask': 'mask'}), '(image_array, mask=mask)\n', (3534, 3558), False, 'import numpy\n'), ((3976, 4071), 'numpy.repeat', 'numpy.repeat', (['third_dimensional_array[..., numpy.newaxis]', 'fourth_dimension_length'], {'axis': '(-1)'}), '(third_dimensional_array[..., numpy.newaxis],\n fourth_dimension_length, axis=-1)\n', (3988, 4071), False, 'import numpy\n'), ((2682, 2716), 'numpy.asarray', 'numpy.asarray', (['self._image.dataobj'], {}), '(self._image.dataobj)\n', (2695, 2716), False, 'import numpy\n')] |
# Internal modules
from processing.data_management import load_excel, load_document
import processing.preprocessors as pp
from config import config
from graphs import graphs
# External libraries
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from utils import Header, make_dash_table
import pandas as pd
import numpy as np
import pathlib
from dash.dependencies import Input,Output
import json
import docx
df = load_excel(file_name=config.DATA_FILE)
########## TEMPORARY MAP DETAILS ######
mapbox_token = '<KEY>'
def create_layout(app):
# Page layouts
return html.Div(
[
#html.Div([Header(app)]),
Header(app),
# page 1
html.Div(
[
# Row 3
html.Div(
[
html.Div(
[
html.Div(html.H5("Housing Characteristics", style={"padding-left": "10px"}), className="inner-product2"),
html.Br([]),
html.P(load_document(config.TEXT_FILE),
style={"color": "#000000"},
className="row",
),
],
className="product2",
)
],
className="row",
),
# Row 4
html.Div(
[
html.Div(
[
html.H6(
["Poverty level"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-one',
figure = graphs.barchart(x1 = df['Target'].value_counts().index, y1 = df['Target'].value_counts().values))
],
className="six columns",
),
html.Div(
[
html.H6(
"Rent",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-two',
figure = graphs.linechart(df[(df['v2a1']>0) & (df['v2a1']<500000)]['v2a1']))
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "35px"},
),
# Row 5
html.Div(
[
html.Div(
[
html.H6(
["Number of rooms"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-four',
figure = graphs.barchart(x1 = df['rooms'].value_counts().index, y1 = df['rooms'].value_counts().values))
],
className="six columns",
),
html.Div(
[
html.H6(
"Level of overcrowding",
className="subtitle padded",
),
dcc.Graph(
id='hover-data2',
figure = graphs.linechart(np.sqrt(df['SQBovercrowding'])))
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "0px"},
)
],
className="sub_page"
)
],
className="page"
), html.Div(
[
#html.Div([Header(app)]), #################### PAGE TWO #######################
# page 1
html.Div(
[
# Row 3
html.Div(
[
html.Div(
[
html.Div(html.H5("Housing characteristics", style={"padding-left": "10px"}), className="inner-product2"),
html.Br([]),
html.P(load_document(config.TEXT_FILE),
style={"color": "#000000"},
className="row",
),
],
className="product2",
)
],
className="row",
),
# Row 4
html.Div(
[
html.Div(
[
html.H6(
["Quality of walls"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-seventeen',
figure = graphs.barchart(
x1 = df['walls'].value_counts().index,
y1 = df['walls'].value_counts().values)
)
],
className="six columns",
),
html.Div(
[
html.H6(
"Quality of ceiling",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-eighteen',
figure = graphs.barchart(
x1=df['cielorazo'].value_counts().index,
y1=df['cielorazo'].value_counts().values)
)
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "35px"},
),
# Row 5
html.Div(
[
html.Div(
[
html.H6(
["Quality of roof"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-nineteen',
figure = graphs.barchart(
x1=df['roof'].value_counts().index,
y1=df['roof'].value_counts().values)
)
],
className="six columns",
)
],
className="row",
style={"margin-bottom": "0px"},
),
],
className="sub_page",
),
],
className="page",
),html.Div(
[
#html.Div([Header(app)]), #################### PAGE THREE #######################
# page 1
html.Div(
[
# Row 3
html.Div(
[
html.Div(
[
html.Div(html.H5("Household characteristics", style={"padding-left": "10px"}), className="inner-product2"),
html.Br([]),
html.P(load_document(config.TEXT_FILE),
style={"color": "#000000"},
className="row",
),
],
className="product2",
)
],
className="row",
),
# Row 4
html.Div(
[
html.Div(
[
html.H6(
["Number of children aged 0-12"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-five',
figure = graphs.barchart(
x1 = df['r4t1'].value_counts().index,
y1 = df['r4t1'].value_counts().values)
)
],
className="six columns",
),
html.Div(
[
html.H6(
"Number of persons 0-19",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-six',
figure = graphs.barchart(
x1 = np.sqrt(df['SQBhogar_nin']).value_counts().index,
y1 = np.sqrt(df['SQBhogar_nin']).value_counts().values,
)
)
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "35px"},
),
# Row 5
html.Div(
[
html.Div(
[
html.H6(
["Dependency Ratio"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-seven',
figure = graphs.linechart(df['dependency'])
)
],
className="six columns",
),
html.Div(
[
html.H6(
"Minimum and Maximum Age",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-eight',
figure = graphs.linechart2(
x1 = df['age-min'].value_counts().sort_index().index,
y1 = df['age-min'].value_counts().sort_index().values,
x2 = df['age-max'].value_counts().sort_index().index,
y2 = df['age-max'].value_counts().sort_index().values)
)
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "0px"},
),
],
className="sub_page",
),
],
className="page",
), html.Div(
[
#html.Div([Header(app)]),
# page 1
html.Div(
[
# Row 3
html.Div(
[
html.Div(
[
html.Div(html.H5("Household characteristics", style={"padding-left": "10px"}), className="inner-product2"),
html.Br([]),
html.P(load_document(config.TEXT_FILE),
style={"color": "#000000"},
className="row",
),
],
className="product2",
)
],
className="row",
),
# Row 4
html.Div(
[
html.Div(
[
html.H6(
["Head of household education"], className="subtitle padded"
),
dcc.Graph(
id = 'graph-eleven',
figure = graphs.barchart(
x1 = np.sqrt(df['SQBedjefe']).value_counts().index,
y1 = np.sqrt(df['SQBedjefe']).value_counts().values,
x2 = df['edjefa'].value_counts().index,
y2 = df['edjefa'].value_counts().values)
)
],
className="six columns",
),
html.Div(
[
html.H6(
"Minimum and Maximum years of schooling",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-twelve',
figure = graphs.linechart2(
x1 = df['escolari-min'].value_counts().sort_index().index,
y1 = df['escolari-min'].value_counts().sort_index().values,
x2 = df['escolari-max'].value_counts().sort_index().index,
y2 = df['escolari-max'].value_counts().sort_index().values)
)
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "35px"},
),
# Row 5
html.Div(
[
html.Div(
[
html.H6(
"Highest level of completed education",
className="subtitle padded",
),
dcc.Graph(
id = 'graph-fourteen',
figure = graphs.barchart2(
x1 = df['instlevel1-sum'].value_counts().index,
y1 = df['instlevel1-sum'].value_counts().values,
x2 = df['instlevel2-sum'].value_counts().index,
y2 = df['instlevel2-sum'].value_counts().values,
x3 = df['instlevel8-sum'].value_counts().index,
y3 = df['instlevel8-sum'].value_counts().values)
)
],
className="six columns",
),
],
className="row",
style={"margin-bottom": "0px"},
),
#html.Div(
# [
# html.Div(
# [
# html.H6(
# ["Graph 15"], className="subtitle padded"
# ),
# dcc.Graph(
# id = 'graph-fifteen',
# figure = None
# )
# ],
# className="six columns",
# ),
# html.Div(
# [
# html.H6(
# "Graph 16",
# className="subtitle padded",
# ),
# dcc.Graph(
# id = 'graph-sixteen',
# figure = None
# )
# ],
# className="six columns",
# ),
# ],
# className="row",
# style={"margin-bottom": "0px"},
#),
],
className="sub_page",
),
],
className="page",
)
| [
"processing.data_management.load_excel",
"numpy.sqrt",
"utils.Header",
"dash_html_components.Br",
"dash_html_components.H5",
"dash_html_components.H6",
"graphs.graphs.linechart",
"processing.data_management.load_document"
] | [((470, 508), 'processing.data_management.load_excel', 'load_excel', ([], {'file_name': 'config.DATA_FILE'}), '(file_name=config.DATA_FILE)\n', (480, 508), False, 'from processing.data_management import load_excel, load_document\n'), ((700, 711), 'utils.Header', 'Header', (['app'], {}), '(app)\n', (706, 711), False, 'from utils import Header, make_dash_table\n'), ((1108, 1119), 'dash_html_components.Br', 'html.Br', (['[]'], {}), '([])\n', (1115, 1119), True, 'import dash_html_components as html\n'), ((1763, 1818), 'dash_html_components.H6', 'html.H6', (["['Poverty level']"], {'className': '"""subtitle padded"""'}), "(['Poverty level'], className='subtitle padded')\n", (1770, 1818), True, 'import dash_html_components as html\n'), ((2381, 2425), 'dash_html_components.H6', 'html.H6', (['"""Rent"""'], {'className': '"""subtitle padded"""'}), "('Rent', className='subtitle padded')\n", (2388, 2425), True, 'import dash_html_components as html\n'), ((3232, 3289), 'dash_html_components.H6', 'html.H6', (["['Number of rooms']"], {'className': '"""subtitle padded"""'}), "(['Number of rooms'], className='subtitle padded')\n", (3239, 3289), True, 'import dash_html_components as html\n'), ((3851, 3912), 'dash_html_components.H6', 'html.H6', (['"""Level of overcrowding"""'], {'className': '"""subtitle padded"""'}), "('Level of overcrowding', className='subtitle padded')\n", (3858, 3912), True, 'import dash_html_components as html\n'), ((5145, 5156), 'dash_html_components.Br', 'html.Br', (['[]'], {}), '([])\n', (5152, 5156), True, 'import dash_html_components as html\n'), ((5800, 5858), 'dash_html_components.H6', 'html.H6', (["['Quality of walls']"], {'className': '"""subtitle padded"""'}), "(['Quality of walls'], className='subtitle padded')\n", (5807, 5858), True, 'import dash_html_components as html\n'), ((6556, 6614), 'dash_html_components.H6', 'html.H6', (['"""Quality of ceiling"""'], {'className': '"""subtitle padded"""'}), "('Quality of ceiling', className='subtitle padded')\n", (6563, 6614), True, 'import dash_html_components as html\n'), ((7590, 7647), 'dash_html_components.H6', 'html.H6', (["['Quality of roof']"], {'className': '"""subtitle padded"""'}), "(['Quality of roof'], className='subtitle padded')\n", (7597, 7647), True, 'import dash_html_components as html\n'), ((9002, 9013), 'dash_html_components.Br', 'html.Br', (['[]'], {}), '([])\n', (9009, 9013), True, 'import dash_html_components as html\n'), ((9657, 9727), 'dash_html_components.H6', 'html.H6', (["['Number of children aged 0-12']"], {'className': '"""subtitle padded"""'}), "(['Number of children aged 0-12'], className='subtitle padded')\n", (9664, 9727), True, 'import dash_html_components as html\n'), ((10418, 10480), 'dash_html_components.H6', 'html.H6', (['"""Number of persons 0-19"""'], {'className': '"""subtitle padded"""'}), "('Number of persons 0-19', className='subtitle padded')\n", (10425, 10480), True, 'import dash_html_components as html\n'), ((11525, 11583), 'dash_html_components.H6', 'html.H6', (["['Dependency Ratio']"], {'className': '"""subtitle padded"""'}), "(['Dependency Ratio'], className='subtitle padded')\n", (11532, 11583), True, 'import dash_html_components as html\n'), ((12127, 12190), 'dash_html_components.H6', 'html.H6', (['"""Minimum and Maximum Age"""'], {'className': '"""subtitle padded"""'}), "('Minimum and Maximum Age', className='subtitle padded')\n", (12134, 12190), True, 'import dash_html_components as html\n'), ((13765, 13776), 'dash_html_components.Br', 'html.Br', (['[]'], {}), '([])\n', (13772, 13776), True, 'import dash_html_components as html\n'), ((14420, 14489), 'dash_html_components.H6', 'html.H6', (["['Head of household education']"], {'className': '"""subtitle padded"""'}), "(['Head of household education'], className='subtitle padded')\n", (14427, 14489), True, 'import dash_html_components as html\n'), ((15380, 15458), 'dash_html_components.H6', 'html.H6', (['"""Minimum and Maximum years of schooling"""'], {'className': '"""subtitle padded"""'}), "('Minimum and Maximum years of schooling', className='subtitle padded')\n", (15387, 15458), True, 'import dash_html_components as html\n'), ((16678, 16754), 'dash_html_components.H6', 'html.H6', (['"""Highest level of completed education"""'], {'className': '"""subtitle padded"""'}), "('Highest level of completed education', className='subtitle padded')\n", (16685, 16754), True, 'import dash_html_components as html\n'), ((975, 1041), 'dash_html_components.H5', 'html.H5', (['"""Housing Characteristics"""'], {'style': "{'padding-left': '10px'}"}), "('Housing Characteristics', style={'padding-left': '10px'})\n", (982, 1041), True, 'import dash_html_components as html\n'), ((1164, 1195), 'processing.data_management.load_document', 'load_document', (['config.TEXT_FILE'], {}), '(config.TEXT_FILE)\n', (1177, 1195), False, 'from processing.data_management import load_excel, load_document\n'), ((5012, 5078), 'dash_html_components.H5', 'html.H5', (['"""Housing characteristics"""'], {'style': "{'padding-left': '10px'}"}), "('Housing characteristics', style={'padding-left': '10px'})\n", (5019, 5078), True, 'import dash_html_components as html\n'), ((5201, 5232), 'processing.data_management.load_document', 'load_document', (['config.TEXT_FILE'], {}), '(config.TEXT_FILE)\n', (5214, 5232), False, 'from processing.data_management import load_excel, load_document\n'), ((8867, 8935), 'dash_html_components.H5', 'html.H5', (['"""Household characteristics"""'], {'style': "{'padding-left': '10px'}"}), "('Household characteristics', style={'padding-left': '10px'})\n", (8874, 8935), True, 'import dash_html_components as html\n'), ((9058, 9089), 'processing.data_management.load_document', 'load_document', (['config.TEXT_FILE'], {}), '(config.TEXT_FILE)\n', (9071, 9089), False, 'from processing.data_management import load_excel, load_document\n'), ((13630, 13698), 'dash_html_components.H5', 'html.H5', (['"""Household characteristics"""'], {'style': "{'padding-left': '10px'}"}), "('Household characteristics', style={'padding-left': '10px'})\n", (13637, 13698), True, 'import dash_html_components as html\n'), ((13821, 13852), 'processing.data_management.load_document', 'load_document', (['config.TEXT_FILE'], {}), '(config.TEXT_FILE)\n', (13834, 13852), False, 'from processing.data_management import load_excel, load_document\n'), ((2700, 2770), 'graphs.graphs.linechart', 'graphs.linechart', (["df[(df['v2a1'] > 0) & (df['v2a1'] < 500000)]['v2a1']"], {}), "(df[(df['v2a1'] > 0) & (df['v2a1'] < 500000)]['v2a1'])\n", (2716, 2770), False, 'from graphs import graphs\n'), ((11819, 11853), 'graphs.graphs.linechart', 'graphs.linechart', (["df['dependency']"], {}), "(df['dependency'])\n", (11835, 11853), False, 'from graphs import graphs\n'), ((4204, 4234), 'numpy.sqrt', 'np.sqrt', (["df['SQBovercrowding']"], {}), "(df['SQBovercrowding'])\n", (4211, 4234), True, 'import numpy as np\n'), ((10821, 10848), 'numpy.sqrt', 'np.sqrt', (["df['SQBhogar_nin']"], {}), "(df['SQBhogar_nin'])\n", (10828, 10848), True, 'import numpy as np\n'), ((10921, 10948), 'numpy.sqrt', 'np.sqrt', (["df['SQBhogar_nin']"], {}), "(df['SQBhogar_nin'])\n", (10928, 10948), True, 'import numpy as np\n'), ((14792, 14816), 'numpy.sqrt', 'np.sqrt', (["df['SQBedjefe']"], {}), "(df['SQBedjefe'])\n", (14799, 14816), True, 'import numpy as np\n'), ((14889, 14913), 'numpy.sqrt', 'np.sqrt', (["df['SQBedjefe']"], {}), "(df['SQBedjefe'])\n", (14896, 14913), True, 'import numpy as np\n')] |
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://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.
#
# When you publish or redistribute any data created with ScanCode or any ScanCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# ScanCode is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode-toolkit/ for support and download.
from __future__ import absolute_import, print_function
from os.path import join
from os.path import os
from unittest import skipIf
from unittest.case import skipUnless
from bitarray import bitarray
import commoncode
from commoncode.testcase import FileBasedTesting
from samecode import halohash
from samecode import hash as commoncode_hash
# un-comment to run perf tests
PERF_TEST_ENABLED = False
class TestHalohash(FileBasedTesting):
test_data_dir = os.path.join(os.path.dirname(__file__), 'data')
def test_BaseHaloHash(self):
class TestBaseHaloHash(halohash.BaseHaloHash):
def __init__(self):
halohash.BaseHaloHash.__init__(self)
def compute(self):
return bitarray([1] * len(self.hashes))
tbhh = TestBaseHaloHash()
assert [] == tbhh.hashes
tbhh.update('1')
assert ['1'] == tbhh.hashes
tbhh.update(['2', '3'])
assert ['1', '2', '3'] == tbhh.hashes
assert '111' == tbhh.hash().to01()
assert 7 == tbhh.intdigest()
assert '\xe0' == tbhh.digest()
assert 'e0' == tbhh.hexdigest()
assert 3 == tbhh.elements_count()
def test_BaseBucketHaloHash(self):
class BaseBucketHaloHashSubclass(halohash.BaseBucketHaloHash):
def __init__(self, size_in_bits):
halohash.BaseBucketHaloHash.__init__(self, size_in_bits=size_in_bits)
def compute(self):
return bitarray([1] * len(self.hashes))
tbbhh = BaseBucketHaloHashSubclass(size_in_bits=32)
assert commoncode_hash.get_hasher(160) == tbbhh.hashmodule
tbbhh.update(['1', '2', '3'])
buck = tbbhh.build_buckets()
expected = [
None, None, None, None, None, None,
[bitarray('1010110101000011001001010110111100100010011101'
'1000001001100010101000101011101001101000110001'
'1000010100011010100011011100110001110010101010'
'00010100010101011')],
None, None, None, None, None, None, None,
[bitarray('1111101111001101000110110101110110011011000001'
'0001110111010101110111011010110001110110110110'
'0011100100011100001010011010111000100000110111'
'01000001110111011')],
None, None, None, None, None, None, None,
None, None, None, None, None,
[bitarray('0100100101110010010001101111011101011001100110'
'0110111110001100111000000011101100000110010101'
'0110111101011101100010010101000001101011001000'
'00001000010110000')],
None, None, None, None]
assert expected == buck
hashsize = 2 ** 7
tbbhh = BaseBucketHaloHashSubclass(size_in_bits=hashsize)
tbbhh.update([ str(x) for x in range(1024)])
buck = tbbhh.build_buckets()
assert hashsize == len(buck)
def test_BucketAverageHaloHash_file_matching(self):
base = self.get_test_loc('halohash/neardupe1')
def geth(fn, size_in_bits=32):
f = open(join(base, fn)).read()
return halohash.BucketAverageHaloHash(f.split(), size_in_bits).hash()
h1 = geth('djc1')
h2 = geth('djc2')
h3 = geth('djc3')
h4 = geth('djc4')
h5 = geth('annotations.txt')
assert 0 == halohash.hamming_distance(h1, h1)
assert 0 == halohash.hamming_distance(h1, h2)
assert 5 == halohash.hamming_distance(h1, h3)
assert 5 == halohash.hamming_distance(h1, h4)
assert 5 == halohash.hamming_distance(h2, h3)
assert 17 == halohash.hamming_distance(h1, h5)
h1 = geth('djc1', size_in_bits=256)
h2 = geth('djc2', size_in_bits=256)
h3 = geth('djc3', size_in_bits=256)
h4 = geth('djc4', size_in_bits=256)
h5 = geth('annotations.txt', size_in_bits=256)
assert 0 == halohash.hamming_distance(h1, h1)
assert 0 == halohash.hamming_distance(h1, h2)
assert 5 == halohash.hamming_distance(h1, h3)
assert 17 == halohash.hamming_distance(h1, h4)
assert 5 == halohash.hamming_distance(h2, h3)
assert 78 == halohash.hamming_distance(h1, h5)
def test_BitAverageHaloHash_file_matching(self):
base = self.get_test_loc('halohash/neardupe1')
def geth(fn, size=32):
f = open(join(base, fn)).read()
return halohash.BitAverageHaloHash(f.split(), size).hash()
h1 = geth('djc1')
h2 = geth('djc2')
h3 = geth('djc3')
h4 = geth('djc4')
h5 = geth('annotations.txt')
assert 0 == halohash.hamming_distance(h1, h1)
assert 1 == halohash.hamming_distance(h1, h2)
assert 4 == halohash.hamming_distance(h1, h3)
assert 6 == halohash.hamming_distance(h1, h4)
assert 3 == halohash.hamming_distance(h2, h3)
assert 16 == halohash.hamming_distance(h1, h5)
def test_BitAverageHaloHash_simple(self):
a = halohash.BitAverageHaloHash(None, size_in_bits=512)
[a.update(str(x)) for x in xrange(4096)]
expected = 'e39effe5b9aeb2e4157b049a20f728e0d2ce7e51e5362981e40c746771a4d2915b4c1e4d33d09932f721813d96def3f16b0aae0e4bdad6ea8d40c776dec958e3'
assert expected == a.hexdigest()
def test_BitAverageHaloHash_elements_count_unicode(self):
a = halohash.BitAverageHaloHash(None, size_in_bits=512)
[a.update(unicode(x)) for x in xrange(4096)]
assert 4096 == a.elements_count()
def _random_HaloHash_test(self, module, size_in_bits, chunk_size):
"""
Using two files created with dd from a Linux /dev/urandom as an input,
this test split each file in chunks. A halohash is computed over the
chunks and the hamming distance is computed for each file. The second
files is progressively injected one chunk at a time from the first
file, mimicking a gradual buildup of similarity
"""
# the two random files are exactly 70000 bytes... use a chunk size that
# is a divider of it
assert 70000 % chunk_size == 0
base = self.get_test_loc('halohash/random')
def chunks(seq, n):
"""
Return a sequence of contiguous non-overlapping chunks of size n.
"""
return [seq[i : i + n] for i in range(len(seq))[::n]]
random1 = open(join(base, 'random1.txt'), 'rb').read()
random_chunks_1 = chunks(random1, chunk_size)
hash_on_random1 = module(size_in_bits=size_in_bits)
for x in random_chunks_1:
hash_on_random1.update(x)
hash1 = hash_on_random1.hash()
random2 = open(join(base, 'random2.txt'), 'rb').read()
random_chunks_2 = chunks(random2, chunk_size)
res = []
for i in range(len(random_chunks_1)):
# create a new halohash on the the second list
hash_on_random2 = module(size_in_bits=size_in_bits)
for y in random_chunks_2:
hash_on_random2.update(y)
hash2 = hash_on_random2.hash()
# compare with the original under bit hamming distance
res.append((i, halohash.hamming_distance(hash1, hash2)))
# replace one chunk to mimic similarity buildup
random_chunks_2[i] = random_chunks_1[i]
return res
def test_random_BitAverageHaloHash(self):
result = self._random_HaloHash_test(halohash.BitAverageHaloHash, 256, 1000)
expected = [(0, 140),
(1, 137), (2, 133), (3, 128), (4, 126), (5, 129), (6, 127), (7, 127), (8, 121),
(9, 117), (10, 116), (11, 114), (12, 116), (13, 116), (14, 109), (15, 114), (16,
110), (17, 110), (18, 112), (19, 105), (20, 111), (21, 107), (22, 102), (23,
104), (24, 100), (25, 102), (26, 100), (27, 96), (28, 93), (29, 98), (30, 97),
(31, 93), (32, 90), (33, 86), (34, 82), (35, 80), (36, 78), (37, 79), (38, 74),
(39, 76), (40, 80), (41, 76), (42, 72), (43, 69), (44, 71), (45, 73), (46, 65),
(47, 66), (48, 63), (49, 58), (50, 55), (51, 54), (52, 52), (53, 47), (54, 49),
(55, 47), (56, 44), (57, 45), (58, 44), (59, 44), (60, 47), (61, 42), (62, 32),
(63, 34), (64, 29), (65, 30), (66, 27), (67, 29), (68, 24), (69, 9)
]
assert expected == result
def test_random_BucketAverageHaloHash(self):
result = self._random_HaloHash_test(halohash.BucketAverageHaloHash, 256, 1000)
expected = [
(0, 54), (1, 52), (2, 51), (3, 50), (4, 49), (5, 47), (6, 46), (7, 47),
(8, 45), (9, 44), (10, 43), (11, 42), (12, 42), (13, 42), (14, 41), (15,
41), (16, 40), (17, 38), (18, 38), (19, 38), (20, 36), (21, 35), (22,
34), (23, 33), (24, 33), (25, 32), (26, 31), (27, 33), (28, 33), (29,
31), (30, 31), (31, 29), (32, 29), (33, 27), (34, 28), (35, 28), (36,
28), (37, 27), (38, 25), (39, 23), (40, 22), (41, 21), (42, 20), (43,
18), (44, 18), (45, 17), (46, 16), (47, 16), (48, 16), (49, 16), (50,
14), (51, 13), (52, 13), (53, 12), (54, 12), (55, 11), (56, 10), (57, 9),
(58, 9), (59, 7), (60, 5), (61, 4), (62, 4), (63, 4), (64, 3), (65, 2),
(66, 2), (67, 1), (68, 0), (69, 0)]
assert expected == result
if PERF_TEST_ENABLED:
try:
import numpy
except ImportError:
numpy = None
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
class TestBitAvgHaloHashPerformance(FileBasedTesting):
def check_perf_for_obj(self, a):
import cProfile as profile
import pstats
stats = 'profile_log_txt'
profile.runctx('''
for x in range(100000):
a.update("/project/path/test/a/" + str(x))
b = a.hexdigest()
''',
globals(), locals(), stats)
p = pstats.Stats(stats)
p.sort_stats('cumulative').print_stats(100)
os.remove(stats)
try:
from pympler import asizeof # @UnresolvedImport
print('Size of object:', asizeof.asizeof(a))
print()
except:
pass
expected = 'fe01e1389b43d115fb6b8f9a13eee937b599eebf4d4fac33866741bd33819466c38dc8c2cabdeb415179bb9fcff570d57d8ea80db21def5ebe7cc4b1b078c1e7'
assert expected == a.hexdigest()
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
def test_profile_bit_average_1(self):
# use the current implementation using numpy if present
# or the next best pure python if no numpy
a = halohash.BitAverageHaloHash(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
def test_optimization_hashup_using_map_no_numpy(self):
from operator import add
# NOTE: this twice slower than numpy
class OptimizedBitAvgHaloHashMap(halohash.BitAverageHaloHash):
def __hashup__(self, m):
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.hashes = map(add, self.hashes, ba)
self.hashed_elements += 1
a = OptimizedBitAvgHaloHashMap(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
def test_optimization_hashup_using_imap_and_bitarrayaccumulation(self):
# NOTE: this is as fast as numpy and uses only a tad more more memory
# because of the hashes accumulation
# we consume iterators now and then to keep the memory consumption low
from itertools import izip, imap
class OptimizedBitAvgHaloHashMapDelayed(halohash.BitAverageHaloHash):
def __init__(self, msg=None, size_in_bits=128):
halohash.BaseHaloHash.__init__(self)
self.size_in_bits = size_in_bits
self.digest_size = self.size_in_bits / 8
self.hashes = []
self.hashed_elements = 0
try:
self.hashmodule = commoncode.hash.get_hasher(size_in_bits)
except:
msg = ('No available hash module for the requested hash '
'size in bits: %(size_in_bits)d' % locals())
raise Exception(msg)
self.update(msg)
def __hashup__(self, m):
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.hashes.append(ba)
self.hashed_elements += 1
if self.hashed_elements % 50000 == 0:
# every now and then consume iterators to avoid memory
# exhaustion on large collections
self.sum_up()
def sum_up(self):
"""
Sum each bit column.
"""
self.hashes = [list(imap(sum, izip(*self.hashes)))]
def compute(self):
"""
Computes the bit average hash. The mean is global to a hash as
it depends on the number of hashed values.
# FIXME: this is not using FLOATs and therefore the division IS
# wrong, but only by one... this is however likely incorrectly
# introducing a BIAS but we cannot change this since we have
# fingerprints indexed and computed with this wrong algorithm
"""
mean = self.elements_count() / 2
self.sum_up()
averaged = [1 if s > mean else 0 for s in self.hashes[0]]
return bitarray(averaged)
a = OptimizedBitAvgHaloHashMapDelayed(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_1_numpy_bit_avg(self):
class OptimizedBitAvgHaloHash(halohash.BitAverageHaloHash):
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.hashes = (numpy.vstack(
(self.hashes,
numpy.asarray(ba.tolist())))
.sum(axis=0))
self.hashed_elements += 1
a = OptimizedBitAvgHaloHash(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_2_numpy_bit_avg(self):
class OptimizedBitAvgHaloHash2(halohash.BitAverageHaloHash):
vectors = []
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.vectors.append(numpy.array(ba.tolist()))
self.hashed_elements += 1
if self.hashed_elements % 100 == 0:
self.hashes = numpy.vstack((self.hashes, numpy.vstack(tuple(self.vectors)))).sum(axis=0)
self.vectors = []
a = OptimizedBitAvgHaloHash2(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_3_numpy_bit_avg(self):
class OptimizedBitAvgHaloHash3(halohash.BitAverageHaloHash):
vectors = []
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.vectors.append(ba.tolist())
self.hashed_elements += 1
if self.hashed_elements % 100 == 0:
s = numpy.cumsum(self.vectors, axis=0)
self.hashes = numpy.vstack((self.hashes, s)).sum(axis=0)
self.vectors = []
a = OptimizedBitAvgHaloHash3(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_4_numpy_bit_avg(self):
class OptimizedBitAvgHaloHash4(halohash.BitAverageHaloHash):
vectors = []
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.vectors.append(ba.tolist())
self.hashed_elements += 1
if self.hashed_elements % 10000 == 0:
self.hashes = numpy.vstack((self.hashes,
numpy.matrix(self.vectors)
.sum(axis=0))).sum(axis=0)
self.vectors = []
a = OptimizedBitAvgHaloHash4(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
def test_optimization_5_native_arrays(self):
class OptimizedBitAvgHaloHash5(halohash.BitAverageHaloHash):
vectors = []
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.vectors.append(ba)
self.hashed_elements += 1
if self.hashed_elements % 10000 == 0:
for v in self.vectors:
for i in range(self.size_in_bits):
self.hashes[i] += v[i]
self.vectors = []
a = OptimizedBitAvgHaloHash5(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_5_native_dicts(self):
class OptimizedBitAvgHaloHash5(halohash.BitAverageHaloHash):
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
self.hashes = (numpy.vstack((self.hashes,
numpy.array(ba.tolist())))
.sum(axis=0))
self.hashed_elements += 1
a = OptimizedBitAvgHaloHash5(None, size_in_bits=512)
self.check_perf_for_obj(a)
@skipUnless(PERF_TEST_ENABLED, 'Perf test disabled')
@skipIf(not numpy, 'Numpy is not installed')
def test_optimization_numpy_fast_array_conversion(self):
class OptimizedBitAvgHaloHash(halohash.BitAverageHaloHash):
def __hashup__(self, m):
if self.hashes == []:
self.hashes = [0] * self.size_in_bits
h = self.hashmodule(m)
ba = bitarray()
ba.fromstring(h.digest())
b = numpy.fromstring(ba.unpack(), dtype=bool)
self.hashes = numpy.vstack((self.hashes, b)).sum(axis=0)
self.hashed_elements += 1
a = OptimizedBitAvgHaloHash(None, size_in_bits=512)
self.check_perf_for_obj(a)
| [
"commoncode.hash.get_hasher",
"samecode.halohash.hamming_distance",
"unittest.case.skipUnless",
"unittest.skipIf",
"os.path.os.remove",
"os.path.join",
"pympler.asizeof.asizeof",
"pstats.Stats",
"numpy.vstack",
"itertools.izip",
"os.path.os.path.dirname",
"samecode.halohash.BaseBucketHaloHash.... | [((10925, 10976), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (10935, 10976), False, 'from unittest.case import skipUnless\n'), ((1833, 1858), 'os.path.os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1848, 1858), False, 'from os.path import os\n'), ((6441, 6492), 'samecode.halohash.BitAverageHaloHash', 'halohash.BitAverageHaloHash', (['None'], {'size_in_bits': '(512)'}), '(None, size_in_bits=512)\n', (6468, 6492), False, 'from samecode import halohash\n'), ((6808, 6859), 'samecode.halohash.BitAverageHaloHash', 'halohash.BitAverageHaloHash', (['None'], {'size_in_bits': '(512)'}), '(None, size_in_bits=512)\n', (6835, 6859), False, 'from samecode import halohash\n'), ((11913, 11964), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (11923, 11964), False, 'from unittest.case import skipUnless\n'), ((12251, 12302), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (12261, 12302), False, 'from unittest.case import skipUnless\n'), ((12916, 12967), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (12926, 12967), False, 'from unittest.case import skipUnless\n'), ((15661, 15712), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (15671, 15712), False, 'from unittest.case import skipUnless\n'), ((15722, 15765), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (15728, 15765), False, 'from unittest import skipIf\n'), ((16535, 16586), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (16545, 16586), False, 'from unittest.case import skipUnless\n'), ((16596, 16639), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (16602, 16639), False, 'from unittest import skipIf\n'), ((17506, 17557), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (17516, 17557), False, 'from unittest.case import skipUnless\n'), ((17567, 17610), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (17573, 17610), False, 'from unittest import skipIf\n'), ((18493, 18544), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (18503, 18544), False, 'from unittest.case import skipUnless\n'), ((18554, 18597), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (18560, 18597), False, 'from unittest import skipIf\n'), ((19563, 19614), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (19573, 19614), False, 'from unittest.case import skipUnless\n'), ((20511, 20562), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (20521, 20562), False, 'from unittest.case import skipUnless\n'), ((20572, 20615), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (20578, 20615), False, 'from unittest import skipIf\n'), ((21360, 21411), 'unittest.case.skipUnless', 'skipUnless', (['PERF_TEST_ENABLED', '"""Perf test disabled"""'], {}), "(PERF_TEST_ENABLED, 'Perf test disabled')\n", (21370, 21411), False, 'from unittest.case import skipUnless\n'), ((21421, 21464), 'unittest.skipIf', 'skipIf', (['(not numpy)', '"""Numpy is not installed"""'], {}), "(not numpy, 'Numpy is not installed')\n", (21427, 21464), False, 'from unittest import skipIf\n'), ((2947, 2978), 'samecode.hash.get_hasher', 'commoncode_hash.get_hasher', (['(160)'], {}), '(160)\n', (2973, 2978), True, 'from samecode import hash as commoncode_hash\n'), ((4796, 4829), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h1'], {}), '(h1, h1)\n', (4821, 4829), False, 'from samecode import halohash\n'), ((4850, 4883), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h2'], {}), '(h1, h2)\n', (4875, 4883), False, 'from samecode import halohash\n'), ((4904, 4937), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h3'], {}), '(h1, h3)\n', (4929, 4937), False, 'from samecode import halohash\n'), ((4958, 4991), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h4'], {}), '(h1, h4)\n', (4983, 4991), False, 'from samecode import halohash\n'), ((5012, 5045), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h2', 'h3'], {}), '(h2, h3)\n', (5037, 5045), False, 'from samecode import halohash\n'), ((5067, 5100), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h5'], {}), '(h1, h5)\n', (5092, 5100), False, 'from samecode import halohash\n'), ((5353, 5386), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h1'], {}), '(h1, h1)\n', (5378, 5386), False, 'from samecode import halohash\n'), ((5407, 5440), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h2'], {}), '(h1, h2)\n', (5432, 5440), False, 'from samecode import halohash\n'), ((5461, 5494), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h3'], {}), '(h1, h3)\n', (5486, 5494), False, 'from samecode import halohash\n'), ((5516, 5549), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h4'], {}), '(h1, h4)\n', (5541, 5549), False, 'from samecode import halohash\n'), ((5570, 5603), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h2', 'h3'], {}), '(h2, h3)\n', (5595, 5603), False, 'from samecode import halohash\n'), ((5625, 5658), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h5'], {}), '(h1, h5)\n', (5650, 5658), False, 'from samecode import halohash\n'), ((6077, 6110), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h1'], {}), '(h1, h1)\n', (6102, 6110), False, 'from samecode import halohash\n'), ((6131, 6164), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h2'], {}), '(h1, h2)\n', (6156, 6164), False, 'from samecode import halohash\n'), ((6185, 6218), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h3'], {}), '(h1, h3)\n', (6210, 6218), False, 'from samecode import halohash\n'), ((6239, 6272), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h4'], {}), '(h1, h4)\n', (6264, 6272), False, 'from samecode import halohash\n'), ((6293, 6326), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h2', 'h3'], {}), '(h2, h3)\n', (6318, 6326), False, 'from samecode import halohash\n'), ((6348, 6381), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['h1', 'h5'], {}), '(h1, h5)\n', (6373, 6381), False, 'from samecode import halohash\n'), ((11390, 11409), 'pstats.Stats', 'pstats.Stats', (['stats'], {}), '(stats)\n', (11402, 11409), False, 'import pstats\n'), ((11478, 11494), 'os.path.os.remove', 'os.remove', (['stats'], {}), '(stats)\n', (11487, 11494), False, 'from os.path import os\n'), ((12150, 12201), 'samecode.halohash.BitAverageHaloHash', 'halohash.BitAverageHaloHash', (['None'], {'size_in_bits': '(512)'}), '(None, size_in_bits=512)\n', (12177, 12201), False, 'from samecode import halohash\n'), ((2004, 2040), 'samecode.halohash.BaseHaloHash.__init__', 'halohash.BaseHaloHash.__init__', (['self'], {}), '(self)\n', (2034, 2040), False, 'from samecode import halohash\n'), ((2713, 2782), 'samecode.halohash.BaseBucketHaloHash.__init__', 'halohash.BaseBucketHaloHash.__init__', (['self'], {'size_in_bits': 'size_in_bits'}), '(self, size_in_bits=size_in_bits)\n', (2749, 2782), False, 'from samecode import halohash\n'), ((3157, 3334), 'bitarray.bitarray', 'bitarray', (['"""10101101010000110010010101101111001000100111011000001001100010101000101011101001101000110001100001010001101010001101110011000111001010101000010100010101011"""'], {}), "(\n '10101101010000110010010101101111001000100111011000001001100010101000101011101001101000110001100001010001101010001101110011000111001010101000010100010101011'\n )\n", (3165, 3334), False, 'from bitarray import bitarray\n'), ((3469, 3646), 'bitarray.bitarray', 'bitarray', (['"""11111011110011010001101101011101100110110000010001110111010101110111011010110001110110110110001110010001110000101001101011100010000011011101000001110111011"""'], {}), "(\n '11111011110011010001101101011101100110110000010001110111010101110111011010110001110110110110001110010001110000101001101011100010000011011101000001110111011'\n )\n", (3477, 3646), False, 'from bitarray import bitarray\n'), ((3823, 4000), 'bitarray.bitarray', 'bitarray', (['"""01001001011100100100011011110111010110011001100110111110001100111000000011101100000110010101011011110101110110001001010100000110101100100000001000010110000"""'], {}), "(\n '01001001011100100100011011110111010110011001100110111110001100111000000011101100000110010101011011110101110110001001010100000110101100100000001000010110000'\n )\n", (3831, 4000), False, 'from bitarray import bitarray\n'), ((7846, 7871), 'os.path.join', 'join', (['base', '"""random1.txt"""'], {}), "(base, 'random1.txt')\n", (7850, 7871), False, 'from os.path import join\n'), ((8136, 8161), 'os.path.join', 'join', (['base', '"""random2.txt"""'], {}), "(base, 'random2.txt')\n", (8140, 8161), False, 'from os.path import join\n'), ((8638, 8677), 'samecode.halohash.hamming_distance', 'halohash.hamming_distance', (['hash1', 'hash2'], {}), '(hash1, hash2)\n', (8663, 8677), False, 'from samecode import halohash\n'), ((11619, 11637), 'pympler.asizeof.asizeof', 'asizeof.asizeof', (['a'], {}), '(a)\n', (11634, 11637), False, 'from pympler import asizeof\n'), ((12636, 12646), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (12644, 12646), False, 'from bitarray import bitarray\n'), ((13473, 13509), 'samecode.halohash.BaseHaloHash.__init__', 'halohash.BaseHaloHash.__init__', (['self'], {}), '(self)\n', (13503, 13509), False, 'from samecode import halohash\n'), ((14190, 14200), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (14198, 14200), False, 'from bitarray import bitarray\n'), ((15518, 15536), 'bitarray.bitarray', 'bitarray', (['averaged'], {}), '(averaged)\n', (15526, 15536), False, 'from bitarray import bitarray\n'), ((16104, 16114), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (16112, 16114), False, 'from bitarray import bitarray\n'), ((17009, 17019), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (17017, 17019), False, 'from bitarray import bitarray\n'), ((17979, 17989), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (17987, 17989), False, 'from bitarray import bitarray\n'), ((18967, 18977), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (18975, 18977), False, 'from bitarray import bitarray\n'), ((19983, 19993), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (19991, 19993), False, 'from bitarray import bitarray\n'), ((20954, 20964), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (20962, 20964), False, 'from bitarray import bitarray\n'), ((21815, 21825), 'bitarray.bitarray', 'bitarray', ([], {}), '()\n', (21823, 21825), False, 'from bitarray import bitarray\n'), ((4529, 4543), 'os.path.join', 'join', (['base', 'fn'], {}), '(base, fn)\n', (4533, 4543), False, 'from os.path import join\n'), ((5821, 5835), 'os.path.join', 'join', (['base', 'fn'], {}), '(base, fn)\n', (5825, 5835), False, 'from os.path import join\n'), ((13773, 13813), 'commoncode.hash.get_hasher', 'commoncode.hash.get_hasher', (['size_in_bits'], {}), '(size_in_bits)\n', (13799, 13813), False, 'import commoncode\n'), ((18220, 18254), 'numpy.cumsum', 'numpy.cumsum', (['self.vectors'], {'axis': '(0)'}), '(self.vectors, axis=0)\n', (18232, 18254), False, 'import numpy\n'), ((21972, 22002), 'numpy.vstack', 'numpy.vstack', (['(self.hashes, b)'], {}), '((self.hashes, b))\n', (21984, 22002), False, 'import numpy\n'), ((14743, 14761), 'itertools.izip', 'izip', (['*self.hashes'], {}), '(*self.hashes)\n', (14747, 14761), False, 'from itertools import izip, imap\n'), ((18293, 18323), 'numpy.vstack', 'numpy.vstack', (['(self.hashes, s)'], {}), '((self.hashes, s))\n', (18305, 18323), False, 'import numpy\n'), ((19300, 19326), 'numpy.matrix', 'numpy.matrix', (['self.vectors'], {}), '(self.vectors)\n', (19312, 19326), False, 'import numpy\n')] |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
#
# pylint: disable=redefined-outer-name
#
"""Ensure correctness of the order parameters."""
import numpy as np
import pytest
from sdanalysis import order, read
INFILES = [
"test/data/dump-Trimer-13.50-0.40-p2.gsd",
"test/data/dump-Trimer-13.50-0.40-p2gg.gsd",
"test/data/dump-Trimer-13.50-0.40-pg.gsd",
]
@pytest.fixture(scope="module", params=INFILES)
def frame(request):
return next(read.open_trajectory(request.param))
def test_compute_neighbours(frame):
max_radius = 10
max_neighbours = 6
num_mols = len(frame)
neighs = order.compute_neighbours(
frame.box, frame.position, max_radius, max_neighbours
)
assert neighs.shape == (num_mols, max_neighbours)
assert np.all(neighs < num_mols)
def test_num_neighbours(frame):
max_radius = 3.5
neighs = order.num_neighbours(frame.box, frame.position, max_radius)
assert np.all(neighs == 6)
def test_voronoi_neighbours(frame):
neighs = order.compute_voronoi_neighs(frame.box, frame.position)
assert np.all(neighs == 6)
def test_create_neigh_ordering(frame):
order_func = order.create_neigh_ordering(6)
assert np.all(order_func(frame))
def test_orientational_order(frame):
max_radius = 3.5
orient_order = order.orientational_order(
frame.box, frame.position, frame.orientation, max_radius
)
assert np.all(orient_order > 0.60)
def test_create_orient_ordering(frame):
order_func = order.create_orient_ordering(0.60)
assert np.all(order_func(frame))
def test_relative_distance(frame):
print(frame.box)
distances = order.relative_distances(frame.box, frame.position)
assert np.all(np.isfinite(distances))
def test_relative_orientations(frame):
orientations = order.relative_orientations(
frame.box, frame.position, frame.orientation
)
assert np.all(np.isfinite(orientations))
| [
"sdanalysis.order.relative_distances",
"sdanalysis.order.compute_voronoi_neighs",
"sdanalysis.order.num_neighbours",
"sdanalysis.order.create_orient_ordering",
"sdanalysis.order.relative_orientations",
"sdanalysis.order.orientational_order",
"numpy.isfinite",
"pytest.fixture",
"sdanalysis.order.comp... | [((476, 522), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': 'INFILES'}), "(scope='module', params=INFILES)\n", (490, 522), False, 'import pytest\n'), ((716, 795), 'sdanalysis.order.compute_neighbours', 'order.compute_neighbours', (['frame.box', 'frame.position', 'max_radius', 'max_neighbours'], {}), '(frame.box, frame.position, max_radius, max_neighbours)\n', (740, 795), False, 'from sdanalysis import order, read\n'), ((875, 900), 'numpy.all', 'np.all', (['(neighs < num_mols)'], {}), '(neighs < num_mols)\n', (881, 900), True, 'import numpy as np\n'), ((969, 1028), 'sdanalysis.order.num_neighbours', 'order.num_neighbours', (['frame.box', 'frame.position', 'max_radius'], {}), '(frame.box, frame.position, max_radius)\n', (989, 1028), False, 'from sdanalysis import order, read\n'), ((1040, 1059), 'numpy.all', 'np.all', (['(neighs == 6)'], {}), '(neighs == 6)\n', (1046, 1059), True, 'import numpy as np\n'), ((1111, 1166), 'sdanalysis.order.compute_voronoi_neighs', 'order.compute_voronoi_neighs', (['frame.box', 'frame.position'], {}), '(frame.box, frame.position)\n', (1139, 1166), False, 'from sdanalysis import order, read\n'), ((1178, 1197), 'numpy.all', 'np.all', (['(neighs == 6)'], {}), '(neighs == 6)\n', (1184, 1197), True, 'import numpy as np\n'), ((1256, 1286), 'sdanalysis.order.create_neigh_ordering', 'order.create_neigh_ordering', (['(6)'], {}), '(6)\n', (1283, 1286), False, 'from sdanalysis import order, read\n'), ((1403, 1490), 'sdanalysis.order.orientational_order', 'order.orientational_order', (['frame.box', 'frame.position', 'frame.orientation', 'max_radius'], {}), '(frame.box, frame.position, frame.orientation,\n max_radius)\n', (1428, 1490), False, 'from sdanalysis import order, read\n'), ((1512, 1538), 'numpy.all', 'np.all', (['(orient_order > 0.6)'], {}), '(orient_order > 0.6)\n', (1518, 1538), True, 'import numpy as np\n'), ((1599, 1632), 'sdanalysis.order.create_orient_ordering', 'order.create_orient_ordering', (['(0.6)'], {}), '(0.6)\n', (1627, 1632), False, 'from sdanalysis import order, read\n'), ((1745, 1796), 'sdanalysis.order.relative_distances', 'order.relative_distances', (['frame.box', 'frame.position'], {}), '(frame.box, frame.position)\n', (1769, 1796), False, 'from sdanalysis import order, read\n'), ((1899, 1972), 'sdanalysis.order.relative_orientations', 'order.relative_orientations', (['frame.box', 'frame.position', 'frame.orientation'], {}), '(frame.box, frame.position, frame.orientation)\n', (1926, 1972), False, 'from sdanalysis import order, read\n'), ((559, 594), 'sdanalysis.read.open_trajectory', 'read.open_trajectory', (['request.param'], {}), '(request.param)\n', (579, 594), False, 'from sdanalysis import order, read\n'), ((1815, 1837), 'numpy.isfinite', 'np.isfinite', (['distances'], {}), '(distances)\n', (1826, 1837), True, 'import numpy as np\n'), ((2005, 2030), 'numpy.isfinite', 'np.isfinite', (['orientations'], {}), '(orientations)\n', (2016, 2030), True, 'import numpy as np\n')] |
from src.utils.words import GET_POLARTIY
from src.utils.utils import convert_dict_to_list
from sklearn import svm
from datetime import datetime
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score,recall_score
from tqdm import tqdm
from scipy.sparse import coo_matrix
import numpy as np
from sklearn.linear_model import SGDClassifier
def set_polarity(review, word_dictionary, negative, neutral):
final_sentence = list()
for sentence in (review):
sentence = sentence.split()
for i in range(0, len(sentence)):
if sentence[i] in word_dictionary:
score = word_dictionary[sentence[i]]
friend = False
if i+1 < len(sentence) and sentence[i + 1] in negative:
final_sentence.append((sentence[i] + "_" + sentence[i + 1], score * -1))
friend = True
if i +1 < len(sentence) and sentence[i + 1] in neutral:
final_sentence.append((sentence[i] + "_" + sentence[i + 1], score * 0))
friend = True
if i+2 < len(sentence) and sentence[i + 2] in negative:
final_sentence.append((sentence[i] + "_" + sentence[i + 2], score * -1))
friend = True
if i+2 < len(sentence) and sentence[i+2] in neutral:
final_sentence.append((sentence[i] + "_" + sentence[i + 2], score * 0))
friend = True
if not friend:
final_sentence.append((sentence[i], score))
return final_sentence
def score_word(sentence, word_dictionary, index, pad, score):
score_tup = 0
if word_dictionary[sentence[index + pad]]<0:
score_tup = score * -1
else:
score_tup = score
return sentence[index] + "_" + sentence[index + pad], score_tup
def run_model(training,testing, training_categories, testing_categories):
clf = SGDClassifier()
print('Fitting')
clf.fit(training, training_categories)
print(datetime.now())
print('Predicting')
predicted = clf.predict(testing)
print(datetime.now() )
print("Accuracy: " + str(accuracy_score(testing_categories, predicted)))
def sum_repeated(dataset):
final = dict()
list_without_repeat = list()
for review in dataset:
final.clear()
for pair in review:
if pair[0] in final:
final[pair[0]] = final[pair[0]] + pair[1]
else:
final[pair[0]] = pair[1]
list_without_repeat.append(convert_dict_to_list(final))
return list_without_repeat
def extract_unique_words(list_of_tuples):
unique_words = set()
for review in list_of_tuples:
for pair in review:
unique_words.add(pair[0])
return sorted(list(unique_words))
def create_sparse_matrix(unique_words, dataset):
columns = []
rows = []
data = []
dataset_size = len(dataset)
unique_words_size = len(unique_words)
for i in tqdm(range(0, dataset_size)):
for pair in dataset[i]:
index = unique_words.index(pair[0])
columns.append(index)
rows.append(i)
data.append(pair[1])
data = np.asarray(data)
rows = np.asarray(rows)
columns = np.asarray(columns)
matrix = coo_matrix((data, (rows, columns)),shape=(dataset_size, unique_words_size))
return matrix | [
"sklearn.linear_model.SGDClassifier",
"numpy.asarray",
"datetime.datetime.now",
"scipy.sparse.coo_matrix",
"src.utils.utils.convert_dict_to_list",
"sklearn.metrics.accuracy_score"
] | [((1959, 1974), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {}), '()\n', (1972, 1974), False, 'from sklearn.linear_model import SGDClassifier\n'), ((3241, 3257), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (3251, 3257), True, 'import numpy as np\n'), ((3269, 3285), 'numpy.asarray', 'np.asarray', (['rows'], {}), '(rows)\n', (3279, 3285), True, 'import numpy as np\n'), ((3300, 3319), 'numpy.asarray', 'np.asarray', (['columns'], {}), '(columns)\n', (3310, 3319), True, 'import numpy as np\n'), ((3333, 3409), 'scipy.sparse.coo_matrix', 'coo_matrix', (['(data, (rows, columns))'], {'shape': '(dataset_size, unique_words_size)'}), '((data, (rows, columns)), shape=(dataset_size, unique_words_size))\n', (3343, 3409), False, 'from scipy.sparse import coo_matrix\n'), ((2049, 2063), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2061, 2063), False, 'from datetime import datetime\n'), ((2136, 2150), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (2148, 2150), False, 'from datetime import datetime\n'), ((2575, 2602), 'src.utils.utils.convert_dict_to_list', 'convert_dict_to_list', (['final'], {}), '(final)\n', (2595, 2602), False, 'from src.utils.utils import convert_dict_to_list\n'), ((2182, 2227), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['testing_categories', 'predicted'], {}), '(testing_categories, predicted)\n', (2196, 2227), False, 'from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score\n')] |
import numpy as np
import matplotlib.pyplot as plt
import torch
from modules.distributions import NormalDistribution, BernoulliDistribution
from modules.models import HierarchicalModel
from modules.networks import TriResNet
K = 30
mean_sigma = 1.
scale_mu = 0.1
scale_sigma = 0.1
n_children = 10
emission_sigma_list = [0.5 for _ in range(n_children)]
d_x = 3*K
mean_dist = NormalDistribution()
scale_dist = NormalDistribution()
children_dist= NormalDistribution()
mean_link = lambda x: x
scale_link = lambda x: torch.exp(x)
def emission(x,r):
N = x.shape[0]
b1 = x[:,:K]
W1 = x[:,K:2*K].view((N,K,1))
W2 = x[:, 2*K:].view((N,1,K))
return torch.matmul(W2, torch.relu(torch.matmul(W1,r) + b1))
emission_distribution = NormalDistribution()
M = 100
regressors = [torch.tensor(np.random.normal(0.,2.,(1,1,M)).astype("float32"))
for _ in range(n_children)]
model = HierarchicalModel(n_children, d_x, mean_sigma, scale_mu, scale_sigma, emission_sigma_list, mean_dist, scale_dist,
children_dist, mean_link, scale_link, emission, emission_distribution, regressors)
N = 40
_, y = model.sample_hierarchical_observations(N, M)
for n in range(n_children):
plt.scatter(regressors[n].detach().numpy().flatten(), y[n][0,:].detach().numpy().flatten(), 25, alpha=0.5)
plt.show()
transformations = [TriResNet(d_x=d_x, d_epsilon=10, epsilon_nu=0.1, in_pre_lambda=1.) for _ in range(2 + n_children)]
tr_model = HierarchicalModel(n_children, d_x, mean_sigma, scale_mu, scale_sigma, emission_sigma_list, mean_dist, scale_dist,
children_dist, mean_link, scale_link, emission, emission_distribution, regressors,
transformations=transformations)
_, tr_y = tr_model.sample_hierarchical_observations(N, M)
for n in range(n_children):
plt.scatter(regressors[n].detach().numpy().flatten(), tr_y[n][0,:].detach().numpy().flatten(), 25, alpha=0.5)
plt.show()
#X_true, Y, mu = bm.sample_observations(N) | [
"numpy.random.normal",
"modules.networks.TriResNet",
"modules.models.HierarchicalModel",
"modules.distributions.NormalDistribution",
"torch.exp",
"torch.matmul",
"matplotlib.pyplot.show"
] | [((376, 396), 'modules.distributions.NormalDistribution', 'NormalDistribution', ([], {}), '()\n', (394, 396), False, 'from modules.distributions import NormalDistribution, BernoulliDistribution\n'), ((410, 430), 'modules.distributions.NormalDistribution', 'NormalDistribution', ([], {}), '()\n', (428, 430), False, 'from modules.distributions import NormalDistribution, BernoulliDistribution\n'), ((446, 466), 'modules.distributions.NormalDistribution', 'NormalDistribution', ([], {}), '()\n', (464, 466), False, 'from modules.distributions import NormalDistribution, BernoulliDistribution\n'), ((741, 761), 'modules.distributions.NormalDistribution', 'NormalDistribution', ([], {}), '()\n', (759, 761), False, 'from modules.distributions import NormalDistribution, BernoulliDistribution\n'), ((899, 1103), 'modules.models.HierarchicalModel', 'HierarchicalModel', (['n_children', 'd_x', 'mean_sigma', 'scale_mu', 'scale_sigma', 'emission_sigma_list', 'mean_dist', 'scale_dist', 'children_dist', 'mean_link', 'scale_link', 'emission', 'emission_distribution', 'regressors'], {}), '(n_children, d_x, mean_sigma, scale_mu, scale_sigma,\n emission_sigma_list, mean_dist, scale_dist, children_dist, mean_link,\n scale_link, emission, emission_distribution, regressors)\n', (916, 1103), False, 'from modules.models import HierarchicalModel\n'), ((1323, 1333), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1331, 1333), True, 'import matplotlib.pyplot as plt\n'), ((1465, 1706), 'modules.models.HierarchicalModel', 'HierarchicalModel', (['n_children', 'd_x', 'mean_sigma', 'scale_mu', 'scale_sigma', 'emission_sigma_list', 'mean_dist', 'scale_dist', 'children_dist', 'mean_link', 'scale_link', 'emission', 'emission_distribution', 'regressors'], {'transformations': 'transformations'}), '(n_children, d_x, mean_sigma, scale_mu, scale_sigma,\n emission_sigma_list, mean_dist, scale_dist, children_dist, mean_link,\n scale_link, emission, emission_distribution, regressors,\n transformations=transformations)\n', (1482, 1706), False, 'from modules.models import HierarchicalModel\n'), ((1956, 1966), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1964, 1966), True, 'import matplotlib.pyplot as plt\n'), ((514, 526), 'torch.exp', 'torch.exp', (['x'], {}), '(x)\n', (523, 526), False, 'import torch\n'), ((1354, 1421), 'modules.networks.TriResNet', 'TriResNet', ([], {'d_x': 'd_x', 'd_epsilon': '(10)', 'epsilon_nu': '(0.1)', 'in_pre_lambda': '(1.0)'}), '(d_x=d_x, d_epsilon=10, epsilon_nu=0.1, in_pre_lambda=1.0)\n', (1363, 1421), False, 'from modules.networks import TriResNet\n'), ((690, 709), 'torch.matmul', 'torch.matmul', (['W1', 'r'], {}), '(W1, r)\n', (702, 709), False, 'import torch\n'), ((797, 834), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(2.0)', '(1, 1, M)'], {}), '(0.0, 2.0, (1, 1, M))\n', (813, 834), True, 'import numpy as np\n')] |
"""calc_metrics module for calculating metrics
Module contains functions for calculating metrics
TODO
"""
import numpy as np
from stonesoup.types.track import Track
from stonesoup.types.groundtruth import GroundTruthPath
from stonesoup.types.state import State
from stonesoup.types.groundtruth import GroundTruthState
import scipy.linalg as la
def calc_nees(tracks: Track, ground_truths: GroundTruthPath):
"""
Calculates NEES. Assumes that tracks and ground_truths are of same length, and that the elements on the same
index correlates.
:param tracks:
:param ground_truths:
:return:
"""
nees = []
for (state, ground_truth) in zip(tracks, ground_truths):
chol_cov = la.cholesky(state.covar, lower=True)
mean_diff = state.state_vector - ground_truth.state_vector
inv_chol_cov_diff = la.solve_triangular(chol_cov, mean_diff, lower=True)
nees.append((inv_chol_cov_diff ** 2).sum())
return nees
def calc_anees(nees):
"""
Calculates anees
:param nees:
:return: np.array containing the anees value
"""
return np.array(nees).mean()
def calc_rmse(tracks: Track, ground_truths: GroundTruthPath):
"""
Calculates the root mean square error
:param tracks:
:param ground_truths:
:return: the scalar rmse
"""
errors = [gt.state_vector - track.state_vector for track, gt in zip(tracks, ground_truths)]
squared_errors = np.array([err.T @ err for err in errors]).flatten()[:, None]
mean_squared_error = squared_errors.mean()
rmse = np.sqrt(mean_squared_error)
return rmse.flatten()[0]
def calc_percentage_nees_within_ci(nees, ci):
"""
Calculates the percentage of NEES within the confidence interval
"""
within_ci = [ind_nees < ci[1] and ind_nees > ci[0] for ind_nees in nees]
return sum(within_ci) / len(nees)
| [
"numpy.array",
"scipy.linalg.cholesky",
"scipy.linalg.solve_triangular",
"numpy.sqrt"
] | [((1558, 1585), 'numpy.sqrt', 'np.sqrt', (['mean_squared_error'], {}), '(mean_squared_error)\n', (1565, 1585), True, 'import numpy as np\n'), ((713, 749), 'scipy.linalg.cholesky', 'la.cholesky', (['state.covar'], {'lower': '(True)'}), '(state.covar, lower=True)\n', (724, 749), True, 'import scipy.linalg as la\n'), ((845, 897), 'scipy.linalg.solve_triangular', 'la.solve_triangular', (['chol_cov', 'mean_diff'], {'lower': '(True)'}), '(chol_cov, mean_diff, lower=True)\n', (864, 897), True, 'import scipy.linalg as la\n'), ((1104, 1118), 'numpy.array', 'np.array', (['nees'], {}), '(nees)\n', (1112, 1118), True, 'import numpy as np\n'), ((1439, 1482), 'numpy.array', 'np.array', (['[(err.T @ err) for err in errors]'], {}), '([(err.T @ err) for err in errors])\n', (1447, 1482), True, 'import numpy as np\n')] |
# Data here: https://www.kaggle.com/c/instant-gratification/data
# Original source here: https://www.kaggle.com/prashantkikani/ig-pca-nusvc-knn-lr-stack
import argparse
import pickle
import time
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from instant_utils import *
from willump.evaluation.willump_executor import willump_execute
base_path = "tests/test_resources/instant_gratification/"
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--cascades", action="store_true", help="Cascades?")
parser.add_argument("-k", "--top_k", type=int, help="Top-K to return", required=True)
parser.add_argument("-d", "--disable", help="Disable Willump", action="store_true")
args = parser.parse_args()
if args.cascades:
cascades = pickle.load(open(base_path + "cascades.pk", "rb"))
else:
cascades = None
top_K = args.top_k
@willump_execute(disable=args.disable, eval_cascades=cascades, top_k=top_K)
def predict_stacked_model(X, model, clf_svnu, clf_knn, clf_lr, clf_mlp, clf_svc):
pred_svnu = model_prediction(X, clf_svnu)
# pred_knn = model_prediction(X, clf_knn)
pred_lr = model_prediction(X, clf_lr)
pred_mlp = model_prediction(X, clf_mlp)
pred_svc = model_prediction(X, clf_svc)
combined_pred = np.hstack([pred_svnu, pred_lr, pred_mlp, pred_svc])
preds = willump_predict_proba_function(model, combined_pred)
return preds
if __name__ == "__main__":
data = pd.read_csv(base_path + "train.csv")
_, valid_data = train_test_split(data, test_size=0.1, random_state=42)
valid_data = valid_data[valid_data['wheezy-copper-turtle-magic'] < NUM_PARTITIONS].reset_index(drop=True)
print("Validation Data Length: %d" % len(valid_data))
valid_y = valid_data.pop('target')
partition_column = valid_data.pop('wheezy-copper-turtle-magic').values.reshape(-1, 1)
del data
cols = [c for c in valid_data.columns if c not in ['id', 'wheezy-copper-turtle-magic']]
pca_scaler, standard_scaler = pickle.load(open(base_path + "scaler.pk", "rb"))
valid_data = standard_scaler.transform(pca_scaler.transform(valid_data[cols]))
valid_data = np.append(valid_data, partition_column, 1)
clf_svnu, clf_knn, clf_lr, clf_mlp, clf_svc = pickle.load(open(base_path + "clf.pk", "rb"))
model = pickle.load(open(base_path + "model.pk", "rb"))
mini_data = valid_data[:3]
orig_preds = predict_stacked_model(valid_data, model, clf_svnu, clf_knn, clf_lr, clf_mlp, clf_svc)
predict_stacked_model(mini_data, model, clf_svnu, clf_knn, clf_lr, clf_mlp, clf_svc)
t0 = time.time()
preds = predict_stacked_model(valid_data, model, clf_svnu, clf_knn, clf_lr, clf_mlp, clf_svc)
time_elapsed = time.time() - t0
orig_model_top_k_idx = np.argsort(orig_preds)[-1 * top_K:]
actual_model_top_k_idx = np.argsort(preds)[-1 * top_K:]
precision = len(np.intersect1d(orig_model_top_k_idx, actual_model_top_k_idx)) / top_K
orig_model_sum = sum(orig_preds[orig_model_top_k_idx])
actual_model_sum = sum(preds[actual_model_top_k_idx])
set_size = len(valid_data)
print("Title Processing Time %fs Num Rows %d Throughput %f rows/sec" %
(time_elapsed, set_size, set_size / time_elapsed))
print("Precision: %f Orig Model Sum: %f Actual Model Sum: %f" % (precision, orig_model_sum, actual_model_sum))
| [
"numpy.intersect1d",
"pandas.read_csv",
"numpy.hstack",
"sklearn.model_selection.train_test_split",
"argparse.ArgumentParser",
"numpy.append",
"numpy.argsort",
"time.time",
"willump.evaluation.willump_executor.willump_execute"
] | [((451, 476), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (474, 476), False, 'import argparse\n'), ((886, 960), 'willump.evaluation.willump_executor.willump_execute', 'willump_execute', ([], {'disable': 'args.disable', 'eval_cascades': 'cascades', 'top_k': 'top_K'}), '(disable=args.disable, eval_cascades=cascades, top_k=top_K)\n', (901, 960), False, 'from willump.evaluation.willump_executor import willump_execute\n'), ((1285, 1336), 'numpy.hstack', 'np.hstack', (['[pred_svnu, pred_lr, pred_mlp, pred_svc]'], {}), '([pred_svnu, pred_lr, pred_mlp, pred_svc])\n', (1294, 1336), True, 'import numpy as np\n'), ((1459, 1495), 'pandas.read_csv', 'pd.read_csv', (["(base_path + 'train.csv')"], {}), "(base_path + 'train.csv')\n", (1470, 1495), True, 'import pandas as pd\n'), ((1516, 1570), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data'], {'test_size': '(0.1)', 'random_state': '(42)'}), '(data, test_size=0.1, random_state=42)\n', (1532, 1570), False, 'from sklearn.model_selection import train_test_split\n'), ((2159, 2201), 'numpy.append', 'np.append', (['valid_data', 'partition_column', '(1)'], {}), '(valid_data, partition_column, 1)\n', (2168, 2201), True, 'import numpy as np\n'), ((2594, 2605), 'time.time', 'time.time', ([], {}), '()\n', (2603, 2605), False, 'import time\n'), ((2723, 2734), 'time.time', 'time.time', ([], {}), '()\n', (2732, 2734), False, 'import time\n'), ((2768, 2790), 'numpy.argsort', 'np.argsort', (['orig_preds'], {}), '(orig_preds)\n', (2778, 2790), True, 'import numpy as np\n'), ((2833, 2850), 'numpy.argsort', 'np.argsort', (['preds'], {}), '(preds)\n', (2843, 2850), True, 'import numpy as np\n'), ((2884, 2944), 'numpy.intersect1d', 'np.intersect1d', (['orig_model_top_k_idx', 'actual_model_top_k_idx'], {}), '(orig_model_top_k_idx, actual_model_top_k_idx)\n', (2898, 2944), True, 'import numpy as np\n')] |
import numpy as np
import pytest
from ndcube.tests.helpers import assert_cubes_equal
from ndcube.utils.wcs import WCS
import astropy.units as u
from astropy.time import Time, TimeDelta
from sunraster import SpectrogramCube
import sunraster.spectrogram
# Define a sample wcs object
H0 = {
'CTYPE1': 'WAVE ', 'CUNIT1': 'Angstrom', 'CDELT1': 0.2, 'CRPIX1': 0, 'CRVAL1': 10,
'NAXIS1': 3,
'CTYPE2': 'HPLT-TAN', 'CUNIT2': 'deg', 'CDELT2': 0.5, 'CRPIX2': 2, 'CRVAL2': 0.5, 'NAXIS2': 2,
'CTYPE3': 'HPLN-TAN', 'CUNIT3': 'deg', 'CDELT3': 0.4, 'CRPIX3': 2, 'CRVAL3': 1, 'NAXIS3': 2,
}
WCS0 = WCS(header=H0, naxis=3)
H_NO_COORDS = {
'CTYPE1': 'PIX ', 'CUNIT1': '', 'CDELT1': 1, 'CRPIX1': 0, 'CRVAL1': 0, 'NAXIS1': 3,
'CTYPE2': 'PIX ', 'CUNIT2': '', 'CDELT2': 1, 'CRPIX2': 0, 'CRVAL2': 0, 'NAXIS2': 3,
'CTYPE3': 'PIX ', 'CUNIT3': '', 'CDELT3': 1, 'CRPIX3': 0, 'CRVAL3': 0, 'NAXIS3': 3,
}
WCS_NO_COORDS = WCS(header=H_NO_COORDS, naxis=3)
SOURCE_DATA_DN = np.array([[[0.563, 1.132, -1.343], [-0.719, 1.441, 1.566]],
[[0.563, 1.132, -1.343], [-0.719, 1.441, 1.566]]])
SOURCE_UNCERTAINTY_DN = np.sqrt(SOURCE_DATA_DN)
TIME_DIM_LEN = SOURCE_DATA_DN.shape[0]
SINGLES_EXPOSURE_TIME = 2.
EXPOSURE_TIME = u.Quantity(np.zeros(TIME_DIM_LEN) + SINGLES_EXPOSURE_TIME, unit=u.s)
# Define sample extra coords
EXTRA_COORDS0 = [("time", 0,
Time('2017-01-01') + TimeDelta(np.arange(TIME_DIM_LEN), format='sec')),
("exposure time", 0, EXPOSURE_TIME)]
EXTRA_COORDS1 = [("time", 0,
(Time('2017-01-01') +
TimeDelta(np.arange(TIME_DIM_LEN, TIME_DIM_LEN * 2), format='sec'))),
("exposure time", 0, EXPOSURE_TIME)]
# Define SpectrogramCubes in various units.
spectrogram_DN0 = SpectrogramCube(
SOURCE_DATA_DN, WCS0, EXTRA_COORDS0, u.ct, SOURCE_UNCERTAINTY_DN)
spectrogram_DN_per_s0 = SpectrogramCube(
SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS0, u.ct / u.s,
SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)
spectrogram_DN_per_s_per_s0 = SpectrogramCube(
SOURCE_DATA_DN /
SINGLES_EXPOSURE_TIME /
SINGLES_EXPOSURE_TIME,
WCS0,
EXTRA_COORDS0,
u.ct /
u.s /
u.s,
SOURCE_UNCERTAINTY_DN /
SINGLES_EXPOSURE_TIME /
SINGLES_EXPOSURE_TIME)
spectrogram_DN_s0 = SpectrogramCube(
SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS0, u.ct * u.s,
SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)
spectrogram_DN1 = SpectrogramCube(
SOURCE_DATA_DN, WCS0, EXTRA_COORDS1, u.ct, SOURCE_UNCERTAINTY_DN)
spectrogram_DN_per_s1 = SpectrogramCube(
SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS1, u.ct / u.s,
SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)
spectrogram_DN_per_s_per_s1 = SpectrogramCube(
SOURCE_DATA_DN /
SINGLES_EXPOSURE_TIME /
SINGLES_EXPOSURE_TIME,
WCS0,
EXTRA_COORDS1,
u.ct /
u.s /
u.s,
SOURCE_UNCERTAINTY_DN /
SINGLES_EXPOSURE_TIME /
SINGLES_EXPOSURE_TIME)
spectrogram_DN_s1 = SpectrogramCube(
SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS1, u.ct * u.s,
SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)
spectrogram_NO_COORDS = SpectrogramCube(SOURCE_DATA_DN, WCS_NO_COORDS)
spectrogram_instrument_axes = SpectrogramCube(
SOURCE_DATA_DN, WCS0, EXTRA_COORDS0, u.ct, SOURCE_UNCERTAINTY_DN, instrument_axes=("a", "b", "c"))
def test_spectral_axis():
assert all(spectrogram_DN0.spectral_axis == spectrogram_DN0.axis_world_coords("em.wl"))
def test_spectral_axis_error():
with pytest.raises(ValueError):
spectrogram_NO_COORDS.spectral_axis
def test_time():
assert (spectrogram_DN0.time == EXTRA_COORDS0[0][2]).all()
def test_time_error():
with pytest.raises(ValueError):
spectrogram_NO_COORDS.time
def test_exposure_time():
assert (spectrogram_DN0.exposure_time == EXTRA_COORDS0[1][2]).all()
def test_exposure_time_error():
with pytest.raises(ValueError):
spectrogram_NO_COORDS.exposure_time
def test_lon():
assert (spectrogram_DN0.lon == spectrogram_DN0.axis_world_coords("lon")).all()
def test_lon_error():
with pytest.raises(ValueError):
spectrogram_NO_COORDS.lon
def test_lat():
assert (spectrogram_DN0.lat == spectrogram_DN0.axis_world_coords("lat")).all()
def test_lat_error():
with pytest.raises(ValueError):
spectrogram_NO_COORDS.lat
@pytest.mark.parametrize("input_cube, undo, force, expected_cube", [
(spectrogram_DN0, False, False, spectrogram_DN_per_s0),
(spectrogram_DN_per_s0, True, False, spectrogram_DN0),
(spectrogram_DN_per_s0, False, True, spectrogram_DN_per_s_per_s0),
(spectrogram_DN0, True, True, spectrogram_DN_s0)
])
def test_apply_exposure_time_correction(input_cube, undo, force, expected_cube):
output_cube = input_cube.apply_exposure_time_correction(undo=undo, force=force)
assert_cubes_equal(output_cube, expected_cube)
def test_calculate_exposure_time_correction_error():
with pytest.raises(ValueError):
sunraster.spectrogram._calculate_exposure_time_correction(SOURCE_DATA_DN, None, u.s,
EXTRA_COORDS0[1][2])
def test_uncalculate_exposure_time_correction_error():
with pytest.raises(ValueError):
sunraster.spectrogram._uncalculate_exposure_time_correction(SOURCE_DATA_DN, None, u.ct,
EXTRA_COORDS0[1][2])
@pytest.mark.parametrize("item,expected", [
(0, np.array(["b", "c"])),
(slice(0, 1), np.array(["a", "b", "c"])),
((slice(None), 0), np.array(["a", "c"])),
((slice(None), slice(None), slice(0, 1)), np.array(["a", "b", "c"])),
])
def test_instrument_axes_slicing(item, expected):
sliced_cube = spectrogram_instrument_axes[item]
output = sliced_cube.instrument_axes
print(output, output.shape, expected, expected.shape)
assert all(output == expected)
| [
"numpy.sqrt",
"ndcube.utils.wcs.WCS",
"numpy.array",
"pytest.mark.parametrize",
"numpy.zeros",
"ndcube.tests.helpers.assert_cubes_equal",
"pytest.raises",
"sunraster.SpectrogramCube",
"astropy.time.Time",
"numpy.arange"
] | [((604, 627), 'ndcube.utils.wcs.WCS', 'WCS', ([], {'header': 'H0', 'naxis': '(3)'}), '(header=H0, naxis=3)\n', (607, 627), False, 'from ndcube.utils.wcs import WCS\n'), ((939, 971), 'ndcube.utils.wcs.WCS', 'WCS', ([], {'header': 'H_NO_COORDS', 'naxis': '(3)'}), '(header=H_NO_COORDS, naxis=3)\n', (942, 971), False, 'from ndcube.utils.wcs import WCS\n'), ((990, 1104), 'numpy.array', 'np.array', (['[[[0.563, 1.132, -1.343], [-0.719, 1.441, 1.566]], [[0.563, 1.132, -1.343],\n [-0.719, 1.441, 1.566]]]'], {}), '([[[0.563, 1.132, -1.343], [-0.719, 1.441, 1.566]], [[0.563, 1.132,\n -1.343], [-0.719, 1.441, 1.566]]])\n', (998, 1104), True, 'import numpy as np\n'), ((1152, 1175), 'numpy.sqrt', 'np.sqrt', (['SOURCE_DATA_DN'], {}), '(SOURCE_DATA_DN)\n', (1159, 1175), True, 'import numpy as np\n'), ((1806, 1891), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['SOURCE_DATA_DN', 'WCS0', 'EXTRA_COORDS0', 'u.ct', 'SOURCE_UNCERTAINTY_DN'], {}), '(SOURCE_DATA_DN, WCS0, EXTRA_COORDS0, u.ct,\n SOURCE_UNCERTAINTY_DN)\n', (1821, 1891), False, 'from sunraster import SpectrogramCube\n'), ((1917, 2056), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS0', '(u.ct / u.s)', '(SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS0,\n u.ct / u.s, SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)\n', (1932, 2056), False, 'from sunraster import SpectrogramCube\n'), ((2092, 2290), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS0', '(u.ct / u.s / u.s)', '(SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME /\n SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS0, u.ct / u.s / u.s, \n SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)\n', (2107, 2290), False, 'from sunraster import SpectrogramCube\n'), ((2347, 2486), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS0', '(u.ct * u.s)', '(SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS0,\n u.ct * u.s, SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)\n', (2362, 2486), False, 'from sunraster import SpectrogramCube\n'), ((2510, 2595), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['SOURCE_DATA_DN', 'WCS0', 'EXTRA_COORDS1', 'u.ct', 'SOURCE_UNCERTAINTY_DN'], {}), '(SOURCE_DATA_DN, WCS0, EXTRA_COORDS1, u.ct,\n SOURCE_UNCERTAINTY_DN)\n', (2525, 2595), False, 'from sunraster import SpectrogramCube\n'), ((2621, 2760), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS1', '(u.ct / u.s)', '(SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS1,\n u.ct / u.s, SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME)\n', (2636, 2760), False, 'from sunraster import SpectrogramCube\n'), ((2796, 2994), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS1', '(u.ct / u.s / u.s)', '(SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN / SINGLES_EXPOSURE_TIME /\n SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS1, u.ct / u.s / u.s, \n SOURCE_UNCERTAINTY_DN / SINGLES_EXPOSURE_TIME / SINGLES_EXPOSURE_TIME)\n', (2811, 2994), False, 'from sunraster import SpectrogramCube\n'), ((3051, 3190), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['(SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME)', 'WCS0', 'EXTRA_COORDS1', '(u.ct * u.s)', '(SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)'], {}), '(SOURCE_DATA_DN * SINGLES_EXPOSURE_TIME, WCS0, EXTRA_COORDS1,\n u.ct * u.s, SOURCE_UNCERTAINTY_DN * SINGLES_EXPOSURE_TIME)\n', (3066, 3190), False, 'from sunraster import SpectrogramCube\n'), ((3220, 3266), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['SOURCE_DATA_DN', 'WCS_NO_COORDS'], {}), '(SOURCE_DATA_DN, WCS_NO_COORDS)\n', (3235, 3266), False, 'from sunraster import SpectrogramCube\n'), ((3297, 3415), 'sunraster.SpectrogramCube', 'SpectrogramCube', (['SOURCE_DATA_DN', 'WCS0', 'EXTRA_COORDS0', 'u.ct', 'SOURCE_UNCERTAINTY_DN'], {'instrument_axes': "('a', 'b', 'c')"}), "(SOURCE_DATA_DN, WCS0, EXTRA_COORDS0, u.ct,\n SOURCE_UNCERTAINTY_DN, instrument_axes=('a', 'b', 'c'))\n", (3312, 3415), False, 'from sunraster import SpectrogramCube\n'), ((4435, 4750), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_cube, undo, force, expected_cube"""', '[(spectrogram_DN0, False, False, spectrogram_DN_per_s0), (\n spectrogram_DN_per_s0, True, False, spectrogram_DN0), (\n spectrogram_DN_per_s0, False, True, spectrogram_DN_per_s_per_s0), (\n spectrogram_DN0, True, True, spectrogram_DN_s0)]'], {}), "('input_cube, undo, force, expected_cube', [(\n spectrogram_DN0, False, False, spectrogram_DN_per_s0), (\n spectrogram_DN_per_s0, True, False, spectrogram_DN0), (\n spectrogram_DN_per_s0, False, True, spectrogram_DN_per_s_per_s0), (\n spectrogram_DN0, True, True, spectrogram_DN_s0)])\n", (4458, 4750), False, 'import pytest\n'), ((4918, 4964), 'ndcube.tests.helpers.assert_cubes_equal', 'assert_cubes_equal', (['output_cube', 'expected_cube'], {}), '(output_cube, expected_cube)\n', (4936, 4964), False, 'from ndcube.tests.helpers import assert_cubes_equal\n'), ((1270, 1292), 'numpy.zeros', 'np.zeros', (['TIME_DIM_LEN'], {}), '(TIME_DIM_LEN)\n', (1278, 1292), True, 'import numpy as np\n'), ((3579, 3604), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3592, 3604), False, 'import pytest\n'), ((3766, 3791), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3779, 3791), False, 'import pytest\n'), ((3971, 3996), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3984, 3996), False, 'import pytest\n'), ((4176, 4201), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4189, 4201), False, 'import pytest\n'), ((4371, 4396), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (4384, 4396), False, 'import pytest\n'), ((5029, 5054), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5042, 5054), False, 'import pytest\n'), ((5302, 5327), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5315, 5327), False, 'import pytest\n'), ((1405, 1423), 'astropy.time.Time', 'Time', (['"""2017-01-01"""'], {}), "('2017-01-01')\n", (1409, 1423), False, 'from astropy.time import Time, TimeDelta\n'), ((1579, 1597), 'astropy.time.Time', 'Time', (['"""2017-01-01"""'], {}), "('2017-01-01')\n", (1583, 1597), False, 'from astropy.time import Time, TimeDelta\n'), ((5571, 5591), 'numpy.array', 'np.array', (["['b', 'c']"], {}), "(['b', 'c'])\n", (5579, 5591), True, 'import numpy as np\n'), ((5616, 5641), 'numpy.array', 'np.array', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (5624, 5641), True, 'import numpy as np\n'), ((5671, 5691), 'numpy.array', 'np.array', (["['a', 'c']"], {}), "(['a', 'c'])\n", (5679, 5691), True, 'import numpy as np\n'), ((5744, 5769), 'numpy.array', 'np.array', (["['a', 'b', 'c']"], {}), "(['a', 'b', 'c'])\n", (5752, 5769), True, 'import numpy as np\n'), ((1436, 1459), 'numpy.arange', 'np.arange', (['TIME_DIM_LEN'], {}), '(TIME_DIM_LEN)\n', (1445, 1459), True, 'import numpy as np\n'), ((1629, 1670), 'numpy.arange', 'np.arange', (['TIME_DIM_LEN', '(TIME_DIM_LEN * 2)'], {}), '(TIME_DIM_LEN, TIME_DIM_LEN * 2)\n', (1638, 1670), True, 'import numpy as np\n')] |
'''
this is EMU^r (recursive computation of expected marginal utility) algorithm of Bhattacharjee et.al
REFERENCES:
<NAME>., <NAME>., <NAME>., <NAME>.: Bridging the gap: Manyobjective optimization and informed decision-making. IEEE Trans. Evolutionary
Computation 21(5), 813{820 (2017)
'''
import numpy as np
import math as m
import copy
from sklearn.cluster import AffinityPropagation
class solution(object):
def __init__(self):
self.index = None
self.objective = None
self.original_objective = None
self.type = None
self.marginalU = 0
self.front = 0
self.pick = 0
self.re_vector = None
class reference_point(object):
def __init__(self):
self.direction = None
self.neighbor = []
self.associate = []
self.identify = None
def compute_emu(p, w):
for i in range(len(p)):
p[i].index = i
obj_mat = np.asarray([i.objective for i in p]).T
w_mat = np.asarray([i.direction for i in w])
u_mat = np.dot(w_mat, obj_mat)
for i in range(len(u_mat)):
temp_index = np.argsort(u_mat[i, :])
for j in p:
if j.index == temp_index[0]:
k = 1
eta = u_mat[i, temp_index[k]] - u_mat[i, temp_index[0]]
while eta == 0.0:
k = k + 1
if k >= len(temp_index):
eta = 0
break
eta = u_mat[i, temp_index[k]] - u_mat[i, temp_index[0]]
j.marginalU += eta
else:
j.marginalU += 0
return p
def Compute(p, w):
front_current = 0
current_array = p
while len(current_array) > 1:
current_array = compute_emu(current_array, w)
front_current += 1
next_array = []
for i in current_array:
if i.marginalU != 0:
i.front = front_current
else:
next_array.append(i)
current_array = next_array
if len(current_array) == 1:
front_current += 1
current_array[0].front = front_current
else:
pass
for i in range(front_current):
front_now = front_current - i
if front_now != 1:
temp_front_array = [j.marginalU for j in p if j.front == front_now]
temp_max_emu = max(temp_front_array)
for k in p:
if k.front == front_now-1:
k.marginalU += temp_max_emu
else:
pass
else:
pass
return p
def Associate(p, w):
obj_mat = np.asarray([i.objective for i in p]).T
w_mat = np.asarray([i.direction for i in w])
d_mat = np.dot(w_mat, obj_mat)
for i in range(len(w_mat)):
d_mat[i, :] = d_mat[i, :] / np.sqrt(sum(w_mat[i, :]**2))
for i in range(len(obj_mat[0, :])):
length2 = sum(obj_mat[:, i]**2)
for j in range(len(d_mat[:, i])):
d_2 = length2-d_mat[j, i]**2
if d_2 < 0:
d_mat[j, i] = 0
else:
d_mat[j, i] = d_2
w[np.argmin(d_mat[:, i])].associate.append(p[i])
p[i].repoints = w[np.argmin(d_mat[:, i])]
return p, w
def Identify(w):
for i in w:
if len(i.associate) >= 1:
temp_max = -1
for k in i.associate:
if k.marginalU > temp_max:
temp_max = k.marginalU
i.identify = k
k.re_vector = i
else:
pass
else:
pass
return w
def Select(w):
select_set = []
for i in w:
if i.identify:
mark = 1
for j in i.neighbor:
if j.identify:
if i.identify.marginalU >= j.identify.marginalU:
pass
else:
mark = 0
else:
pass
if mark == 1:
select_set.append(i.identify)
else:
pass
else:
pass
return select_set
def Initializaiton(p, w):
for i in p:
i.type = None
i.index = None
i.marginalU = 0
i.front = 0
i.pick = 0
i.re_vector = None
for i in w:
i.associate = []
i.identify = None
return p, w
def main_function(data, K):
points = copy.copy(data)
dim = len(points[0])
popsize = len(points)
for i in range(dim):
temp1 = max(points[:, i])
temp2 = min(points[:, i])
points[:, i] = (points[:, i] - temp2) / (temp1 - temp2)
solutions = [solution() for i in range(popsize)]
# reference_points
div = 0
H = 0
factor = 400 / 1600 * popsize
while H <= factor:
div += 1
H = m.factorial(div + dim - 1) / (m.factorial(div) * m.factorial(dim - 1))
div -= 1
list_range = [i / div for i in range(div + 1)]
direction = []
def w_generator(now_dim, now_sum, now_array):
if now_dim == 1:
for i in list_range:
temp_array = copy.copy(now_array)
if round(i + now_sum - 1, 5) == 0:
temp_array.append(i)
direction.append(temp_array)
else:
for i in list_range:
temp_array = copy.copy(now_array)
if round(i + now_sum - 1, 5) <= 0:
temp_array.append(i)
w_generator(now_dim - 1, now_sum + i, temp_array)
w_generator(dim, 0, [])
direction = np.asarray(direction)
Repoints = [reference_point() for i in range(len(direction))]
for i in range(len(direction)):
Repoints[i].direction = direction[i, :]
distance_list = np.sum((direction - direction[i, :] * np.ones(direction.shape)) ** 2, axis = 1)
distance_sort = np.argsort(distance_list)
temp_min_d = distance_list[distance_sort[1]]
current_index = 1
while round(temp_min_d - distance_list[distance_sort[current_index]], 5) == 0:
Repoints[i].neighbor.append(Repoints[distance_sort[current_index]])
current_index += 1
SOI_A = []
SOI = []
# initialization
for i in range(popsize):
SOI_A.append(solutions[i])
solutions[i].objective = points[i, :]
solutions[i].original_objective = data[i, :]
# outer loop
while len(SOI) < K:
# inner loop
while len(SOI_A) > 0:
SOI_A, Repoints = Initializaiton(SOI_A, Repoints)
SOI_A = Compute(SOI_A, Repoints)
SOI_A, Repoints = Associate(SOI_A, Repoints)
Repoints = Identify(Repoints)
S = Select(Repoints)
if len(S) <= K or len(S) == len(SOI_A):
break
else:
SOI_A = S
SOI = SOI + S
temp = []
for j in solutions:
if j not in SOI:
temp.append(j)
else:
pass
SOI_A = temp
SOI.sort(key=lambda x: x.marginalU, reverse=True)
SOIf = []
if len(SOI) > K:
# classify
minimun_value = []
PeripheralE = []
Peripheral = []
Internal = []
for i in range(dim):
minimun_value.append(min(points[:, i]))
for i in SOI:
for j in range(dim):
if i.objective[j] == minimun_value[j]:
i.type = 'PeripheralE'
PeripheralE.append(i)
else:
pass
if i.type != 'PeripheralE':
if min(i.re_vector.direction) == 0:
i.type = 'Peripheral'
Peripheral.append(i)
else:
i.type = 'Internal'
Internal.append(i)
else:
pass
if len(Internal) > K:
X = np.asarray([j.objective for j in Internal])
clustering = AffinityPropagation().fit(X)
center_points = clustering.cluster_centers_
for j in Internal:
for k in center_points:
if (j.objective == k).all():
if len(SOIf) < K:
SOIf.append(j)
else:
pass
else:
pass
if len(SOIf) < K:
for j in Internal:
if j not in SOIf:
SOIf.append(j)
else:
pass
if len(SOIf) == K:
break
else:
pass
elif len(Internal) < K:
for j in Internal:
SOIf.append(j)
temp_array = Peripheral + PeripheralE
X = np.asarray([j.objective for j in temp_array])
clustering = AffinityPropagation().fit(X)
center_points = clustering.cluster_centers_
for j in temp_array:
for k in center_points:
if (j.objective == k).all():
if len(SOIf) < K:
SOIf.append(j)
else:
pass
else:
pass
if len(SOIf) < K:
for j in temp_array:
if j not in SOIf:
SOIf.append(j)
else:
pass
if len(SOIf) == K:
break
else:
pass
else:
SOIf = Internal
elif len(SOI) == K:
SOIf = SOI
else:
pass
knee_points = np.asarray([j.original_objective for j in SOIf])
return knee_points
if __name__ == '__main__':
points = np.loadtxt(sys.path[0]+'/data/points1/PMOP1_M2_A2.out')
main_function(points, 1)
| [
"numpy.ones",
"math.factorial",
"numpy.asarray",
"sklearn.cluster.AffinityPropagation",
"copy.copy",
"numpy.argsort",
"numpy.dot",
"numpy.argmin",
"numpy.loadtxt"
] | [((973, 1009), 'numpy.asarray', 'np.asarray', (['[i.direction for i in w]'], {}), '([i.direction for i in w])\n', (983, 1009), True, 'import numpy as np\n'), ((1022, 1044), 'numpy.dot', 'np.dot', (['w_mat', 'obj_mat'], {}), '(w_mat, obj_mat)\n', (1028, 1044), True, 'import numpy as np\n'), ((2674, 2710), 'numpy.asarray', 'np.asarray', (['[i.direction for i in w]'], {}), '([i.direction for i in w])\n', (2684, 2710), True, 'import numpy as np\n'), ((2723, 2745), 'numpy.dot', 'np.dot', (['w_mat', 'obj_mat'], {}), '(w_mat, obj_mat)\n', (2729, 2745), True, 'import numpy as np\n'), ((4448, 4463), 'copy.copy', 'copy.copy', (['data'], {}), '(data)\n', (4457, 4463), False, 'import copy\n'), ((5616, 5637), 'numpy.asarray', 'np.asarray', (['direction'], {}), '(direction)\n', (5626, 5637), True, 'import numpy as np\n'), ((9847, 9895), 'numpy.asarray', 'np.asarray', (['[j.original_objective for j in SOIf]'], {}), '([j.original_objective for j in SOIf])\n', (9857, 9895), True, 'import numpy as np\n'), ((9957, 10014), 'numpy.loadtxt', 'np.loadtxt', (["(sys.path[0] + '/data/points1/PMOP1_M2_A2.out')"], {}), "(sys.path[0] + '/data/points1/PMOP1_M2_A2.out')\n", (9967, 10014), True, 'import numpy as np\n'), ((922, 958), 'numpy.asarray', 'np.asarray', (['[i.objective for i in p]'], {}), '([i.objective for i in p])\n', (932, 958), True, 'import numpy as np\n'), ((1098, 1121), 'numpy.argsort', 'np.argsort', (['u_mat[i, :]'], {}), '(u_mat[i, :])\n', (1108, 1121), True, 'import numpy as np\n'), ((2623, 2659), 'numpy.asarray', 'np.asarray', (['[i.objective for i in p]'], {}), '([i.objective for i in p])\n', (2633, 2659), True, 'import numpy as np\n'), ((5916, 5941), 'numpy.argsort', 'np.argsort', (['distance_list'], {}), '(distance_list)\n', (5926, 5941), True, 'import numpy as np\n'), ((3197, 3219), 'numpy.argmin', 'np.argmin', (['d_mat[:, i]'], {}), '(d_mat[:, i])\n', (3206, 3219), True, 'import numpy as np\n'), ((4858, 4884), 'math.factorial', 'm.factorial', (['(div + dim - 1)'], {}), '(div + dim - 1)\n', (4869, 4884), True, 'import math as m\n'), ((7959, 8002), 'numpy.asarray', 'np.asarray', (['[j.objective for j in Internal]'], {}), '([j.objective for j in Internal])\n', (7969, 8002), True, 'import numpy as np\n'), ((4888, 4904), 'math.factorial', 'm.factorial', (['div'], {}), '(div)\n', (4899, 4904), True, 'import math as m\n'), ((4907, 4927), 'math.factorial', 'm.factorial', (['(dim - 1)'], {}), '(dim - 1)\n', (4918, 4927), True, 'import math as m\n'), ((5150, 5170), 'copy.copy', 'copy.copy', (['now_array'], {}), '(now_array)\n', (5159, 5170), False, 'import copy\n'), ((5388, 5408), 'copy.copy', 'copy.copy', (['now_array'], {}), '(now_array)\n', (5397, 5408), False, 'import copy\n'), ((8917, 8962), 'numpy.asarray', 'np.asarray', (['[j.objective for j in temp_array]'], {}), '([j.objective for j in temp_array])\n', (8927, 8962), True, 'import numpy as np\n'), ((8028, 8049), 'sklearn.cluster.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (8047, 8049), False, 'from sklearn.cluster import AffinityPropagation\n'), ((3124, 3146), 'numpy.argmin', 'np.argmin', (['d_mat[:, i]'], {}), '(d_mat[:, i])\n', (3133, 3146), True, 'import numpy as np\n'), ((5850, 5874), 'numpy.ones', 'np.ones', (['direction.shape'], {}), '(direction.shape)\n', (5857, 5874), True, 'import numpy as np\n'), ((8988, 9009), 'sklearn.cluster.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (9007, 9009), False, 'from sklearn.cluster import AffinityPropagation\n')] |
"""
PhaseShift operator
====================
This example shows how to use the :class:`pylops.waveeqprocessing.PhaseShift`
operator to perform frequency-wavenumber shift of an input multi-dimensional
signal. Such a procedure is applied in a variety of disciplines including
geophysics, medical imaging and non-destructive testing.
"""
import numpy as np
import matplotlib.pyplot as plt
import pylops
plt.close('all')
############################################
# Let's first create a synthetic dataset composed of a number of hyperbolas
par = {'ox':-300, 'dx':20, 'nx':31,
'oy':-200, 'dy':20, 'ny':21,
'ot':0, 'dt':0.004, 'nt':201,
'f0': 20, 'nfmax': 210}
# Create axis
t, t2, x, y = pylops.utils.seismicevents.makeaxis(par)
# Create wavelet
wav = pylops.utils.wavelets.ricker(np.arange(41) * par['dt'],
f0=par['f0'])[0]
vrms = [900, 1300, 1800]
t0 = [0.2, 0.3, 0.6]
amp = [1., 0.6, -2.]
_, m = \
pylops.utils.seismicevents.hyperbolic2d(x, t, t0, vrms, amp, wav)
############################################
# We can now apply a taper at the edges and also pad the input to avoid
# artifacts during the phase shift
pad = 11
taper = pylops.utils.tapers.taper2d(par['nt'], par['nx'], 5)
mpad = np.pad(m*taper, ((pad, pad), (0, 0)), mode='constant')
############################################
# We perform now forward propagation in a constant velocity :math:`v=2000` for
# a depth of :math:`z_{prop} = 100 m`. We should expect the hyperbolas to move
# forward in time and become flatter.
vel = 1500.
zprop = 100
freq = np.fft.rfftfreq(par['nt'], par['dt'])
kx = np.fft.fftshift(np.fft.fftfreq(par['nx'] + 2*pad, par['dx']))
Pop = pylops.waveeqprocessing.PhaseShift(vel, zprop, par['nt'], freq, kx)
mdown = Pop * mpad.T.ravel()
############################################
# We now take the forward propagated wavefield and apply backward propagation,
# which is in this case simply the adjoint of our operator.
# We should expect the hyperbolas to move backward in time and show the same
# traveltime as the original dataset. Of course, as we are only performing the
# adjoint operation we should expect some small differences between this
# wavefield and the input dataset.
mup = Pop.H * mdown.ravel()
mdown = np.real(mdown.reshape(par['nt'], par['nx'] + 2*pad)[:, pad:-pad])
mup = np.real(mup.reshape(par['nt'], par['nx'] + 2*pad)[:, pad:-pad])
fig, axs = plt.subplots(1, 3, figsize=(10, 6), sharey=True)
fig.suptitle('2D Phase shift', fontsize=12,
fontweight='bold')
axs[0].imshow(m.T, aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[0].set_xlabel(r'$x(m)$')
axs[0].set_ylabel(r'$t(s)$')
axs[0].set_title('Original data')
axs[1].imshow(mdown, aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[1].set_xlabel(r'$x(m)$')
axs[1].set_title('Forward propagation')
axs[2].imshow(mup, aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[2].set_xlabel(r'$x(m)$')
axs[2].set_title('Backward propagation')
############################################
# Finally we perform the same for a 3-dimensional signal
_, m = \
pylops.utils.seismicevents.hyperbolic3d(x, y, t, t0, vrms, vrms, amp, wav)
pad = 11
taper = pylops.utils.tapers.taper3d(par['nt'], (par['ny'], par['nx']), (3, 3))
mpad = np.pad(m*taper, ((pad, pad), (pad, pad), (0, 0)), mode='constant')
kx = np.fft.fftshift(np.fft.fftfreq(par['nx'] + 2*pad, par['dx']))
ky = np.fft.fftshift(np.fft.fftfreq(par['ny'] + 2*pad, par['dy']))
Pop = pylops.waveeqprocessing.PhaseShift(vel, zprop, par['nt'], freq, kx, ky)
mdown = Pop * mpad.transpose(2, 1, 0).ravel()
mup = Pop.H * mdown.ravel()
mdown = np.real(mdown.reshape(par['nt'],
par['nx'] + 2 * pad,
par['ny'] + 2 * pad)[:, pad:-pad, pad:-pad])
mup = np.real(mup.reshape(par['nt'],
par['nx'] + 2 * pad,
par['ny'] + 2 * pad)[:, pad:-pad, pad:-pad])
fig, axs = plt.subplots(2, 3, figsize=(10, 12), sharey=True)
fig.suptitle('3D Phase shift', fontsize=12,
fontweight='bold')
axs[0][0].imshow(m[:, par['nx']//2].T, aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[0][0].set_xlabel(r'$y(m)$')
axs[0][0].set_ylabel(r'$t(s)$')
axs[0][0].set_title('Original data')
axs[0][1].imshow(mdown[:, par['nx']//2], aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[0][1].set_xlabel(r'$y(m)$')
axs[0][1].set_title('Forward propagation')
axs[0][2].imshow(mup[:, par['nx']//2], aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[0][2].set_xlabel(r'$y(m)$')
axs[0][2].set_title('Backward propagation')
axs[1][0].imshow(m[par['ny'] // 2].T, aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[1][0].set_xlabel(r'$x(m)$')
axs[1][0].set_ylabel(r'$t(s)$')
axs[1][0].set_title('Original data')
axs[1][1].imshow(mdown[:, :, par['ny'] // 2], aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[1][1].set_xlabel(r'$x(m)$')
axs[1][1].set_title('Forward propagation')
axs[1][2].imshow(mup[:, :, par['ny'] // 2], aspect='auto',
interpolation='nearest', vmin=-2, vmax=2,
cmap='gray', extent=(x.min(), x.max(), t.max(), t.min()))
axs[1][2].set_xlabel(r'$x(m)$')
axs[1][2].set_title('Backward propagation')
| [
"numpy.fft.rfftfreq",
"pylops.waveeqprocessing.PhaseShift",
"pylops.utils.seismicevents.hyperbolic2d",
"numpy.fft.fftfreq",
"pylops.utils.tapers.taper3d",
"matplotlib.pyplot.close",
"pylops.utils.seismicevents.makeaxis",
"pylops.utils.seismicevents.hyperbolic3d",
"numpy.pad",
"pylops.utils.tapers.... | [((403, 419), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (412, 419), True, 'import matplotlib.pyplot as plt\n'), ((711, 751), 'pylops.utils.seismicevents.makeaxis', 'pylops.utils.seismicevents.makeaxis', (['par'], {}), '(par)\n', (746, 751), False, 'import pylops\n'), ((966, 1031), 'pylops.utils.seismicevents.hyperbolic2d', 'pylops.utils.seismicevents.hyperbolic2d', (['x', 't', 't0', 'vrms', 'amp', 'wav'], {}), '(x, t, t0, vrms, amp, wav)\n', (1005, 1031), False, 'import pylops\n'), ((1202, 1254), 'pylops.utils.tapers.taper2d', 'pylops.utils.tapers.taper2d', (["par['nt']", "par['nx']", '(5)'], {}), "(par['nt'], par['nx'], 5)\n", (1229, 1254), False, 'import pylops\n'), ((1262, 1318), 'numpy.pad', 'np.pad', (['(m * taper)', '((pad, pad), (0, 0))'], {'mode': '"""constant"""'}), "(m * taper, ((pad, pad), (0, 0)), mode='constant')\n", (1268, 1318), True, 'import numpy as np\n'), ((1590, 1627), 'numpy.fft.rfftfreq', 'np.fft.rfftfreq', (["par['nt']", "par['dt']"], {}), "(par['nt'], par['dt'])\n", (1605, 1627), True, 'import numpy as np\n'), ((1701, 1768), 'pylops.waveeqprocessing.PhaseShift', 'pylops.waveeqprocessing.PhaseShift', (['vel', 'zprop', "par['nt']", 'freq', 'kx'], {}), "(vel, zprop, par['nt'], freq, kx)\n", (1735, 1768), False, 'import pylops\n'), ((2433, 2481), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {'figsize': '(10, 6)', 'sharey': '(True)'}), '(1, 3, figsize=(10, 6), sharey=True)\n', (2445, 2481), True, 'import matplotlib.pyplot as plt\n'), ((3394, 3468), 'pylops.utils.seismicevents.hyperbolic3d', 'pylops.utils.seismicevents.hyperbolic3d', (['x', 'y', 't', 't0', 'vrms', 'vrms', 'amp', 'wav'], {}), '(x, y, t, t0, vrms, vrms, amp, wav)\n', (3433, 3468), False, 'import pylops\n'), ((3487, 3557), 'pylops.utils.tapers.taper3d', 'pylops.utils.tapers.taper3d', (["par['nt']", "(par['ny'], par['nx'])", '(3, 3)'], {}), "(par['nt'], (par['ny'], par['nx']), (3, 3))\n", (3514, 3557), False, 'import pylops\n'), ((3565, 3633), 'numpy.pad', 'np.pad', (['(m * taper)', '((pad, pad), (pad, pad), (0, 0))'], {'mode': '"""constant"""'}), "(m * taper, ((pad, pad), (pad, pad), (0, 0)), mode='constant')\n", (3571, 3633), True, 'import numpy as np\n'), ((3773, 3844), 'pylops.waveeqprocessing.PhaseShift', 'pylops.waveeqprocessing.PhaseShift', (['vel', 'zprop', "par['nt']", 'freq', 'kx', 'ky'], {}), "(vel, zprop, par['nt'], freq, kx, ky)\n", (3807, 3844), False, 'import pylops\n'), ((4256, 4305), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(3)'], {'figsize': '(10, 12)', 'sharey': '(True)'}), '(2, 3, figsize=(10, 12), sharey=True)\n', (4268, 4305), True, 'import matplotlib.pyplot as plt\n'), ((1649, 1695), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (["(par['nx'] + 2 * pad)", "par['dx']"], {}), "(par['nx'] + 2 * pad, par['dx'])\n", (1663, 1695), True, 'import numpy as np\n'), ((3654, 3700), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (["(par['nx'] + 2 * pad)", "par['dx']"], {}), "(par['nx'] + 2 * pad, par['dx'])\n", (3668, 3700), True, 'import numpy as np\n'), ((3721, 3767), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (["(par['ny'] + 2 * pad)", "par['dy']"], {}), "(par['ny'] + 2 * pad, par['dy'])\n", (3735, 3767), True, 'import numpy as np\n'), ((805, 818), 'numpy.arange', 'np.arange', (['(41)'], {}), '(41)\n', (814, 818), True, 'import numpy as np\n')] |
import numpy as np
import scipy.signal
import tensorflow as tf
import imageio
import os
from ACNetwork import ACNetwork
class Trainer():
def __init__(self, settings, sess, number, coord, globalEpisodes):
self.settings = settings
self.coord = coord
self.sess = sess
self.name = 'trainer{}'.format(number)
self.number = number
self.globalEpisodes = globalEpisodes
self.incrementGE = self.globalEpisodes.assign_add(1)
self.localEpisodes = tf.Variable(0, dtype=tf.int32, name='local_episodes', trainable=False)
self.incrementLE = self.localEpisodes.assign_add(1)
self.localSteps = tf.Variable(0, dtype=tf.int32, name='{}_episodes'.format(self.name), trainable=False)
self.writer = tf.summary.FileWriter(settings.tbPath + self.name)
self.summaryData = {}
self.localAC = ACNetwork(settings, self.name, step=self.localSteps)
globalNetwork = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'global')
localNetwork = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)
self.updateLocalVars = []
for gnVars, lnVars in zip(globalNetwork, localNetwork):
self.updateLocalVars.append(lnVars.assign(gnVars))
def discount(self, x, gamma):
return scipy.signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]
def train(self, trainingData):
episodeData = trainingData["episodeData"]
values = trainingData["values"]
bootStrapValue = trainingData["bootStrapValue"]
score = trainingData["score"]
worker = trainingData["worker"]
print("{} is training with worker{}s data!".format(self.name, worker))
frames = episodeData[:, 0]
actions = episodeData[:, 1]
rewards = episodeData[:, 2]
frames = np.asarray(frames.tolist())
size = len(episodeData)
gamma = self.settings.gamma
rewardsPlus = np.asarray(rewards.tolist() + [bootStrapValue])
discountedRewards = self.discount(rewardsPlus, gamma)[:-1]
valuePlus = np.asarray(values + [bootStrapValue])
# Calculates the generalized advantage estimate
advantages = rewards + gamma * valuePlus[1:] - valuePlus[:-1]
advantages = self.discount(advantages, gamma)
# Update the global network using gradients from loss
# Generate network statistics to periodically save
self.sess.run(self.updateLocalVars)
feedDict = {self.localAC.targetV: discountedRewards,
self.localAC.frame: frames,
self.localAC.actions: actions,
self.localAC.advantages: advantages}
vl, pl, e, gn, vn, _ = self.sess.run([self.localAC.valueLoss,
self.localAC.policyLoss,
self.localAC.entropy,
self.localAC.gradNorms,
self.localAC.varNorms,
self.localAC.applyGradsGlobal],
feed_dict=feedDict)
#if (e/size < 0.01):
# print("Model collapses, entropy: {}".format(e/size))
# self.coord.request_stop()
if (not worker in self.summaryData):
self.summaryData[worker] = SummaryData(self.writer)
self.summaryData[worker].extend(size, vl, pl, e, gn, vn, score)
if bootStrapValue == 0: # This means that a worker has finished an episode
self.sess.run(self.incrementGE)
self.sess.run(self.incrementLE)
if self.sess.run(self.localEpisodes) % self.settings.logFreq == 0:
self.summaryData[worker].write(self.sess.run(self.localAC.lr), self.sess.run(self.localEpisodes))
self.summaryData[worker].clear()
if (self.sess.run(self.localEpisodes) % 100 == 0):
self.writeFramesToDisk(frames)
def writeFramesToDisk(self, frames):
print("{} is saving frames to disk".format(self.name))
path = "{}/{}/{}/".format(self.settings.imagePath, self.name, self.sess.run(self.localEpisodes))
if not os.path.exists(path):
print("{} is making path: {}".format(self.name, path))
os.makedirs(path)
framePick = np.random.randint(0, len(frames))
frameSeq = frames[framePick]
for i in range(self.settings.frameSequenceLen):
imageio.imwrite(path + "{}.png".format(i), frameSeq[i])
class SummaryData:
def __init__(self, writer):
self.clear()
self.writer = writer
def extend(self, size, vl, pl, e, gn, vn, score):
self.size += size
self.valueLoss += vl
self.policyLoss += pl
self.entropy += e
self.gradientNorm += gn
self.variableNorm += vn
self.score += score
self.bootStrapCount += 1
def clear(self):
self.size = 0
self.valueLoss = 0
self.policyLoss = 0
self.entropy = 0
self.gradientNorm = 0
self.variableNorm = 0
self.score = 0
self.bootStrapCount = 0
def write(self, lr, episode):
summary = tf.Summary()
summary.value.add(tag="Performance/Score", simple_value=self.score)
summary.value.add(tag="Performance/BootStrapCount", simple_value=self.bootStrapCount)
summary.value.add(tag='Losses/Value Loss', simple_value=float(self.valueLoss/self.size))
summary.value.add(tag='Losses/Policy Loss', simple_value=float(self.policyLoss/self.size))
summary.value.add(tag='Losses/Entropy', simple_value=float(self.entropy/self.size))
summary.value.add(tag='Losses/Grad Norm', simple_value=float(self.gradientNorm / self.bootStrapCount))
summary.value.add(tag='Losses/Var Norm', simple_value=float(self.variableNorm / self.bootStrapCount))
summary.value.add(tag='Losses/Learning rate',
simple_value=float(lr))
self.writer.add_summary(summary, episode)
self.writer.flush() | [
"os.path.exists",
"ACNetwork.ACNetwork",
"tensorflow.Summary",
"os.makedirs",
"tensorflow.Variable",
"numpy.asarray",
"tensorflow.summary.FileWriter",
"tensorflow.get_collection"
] | [((508, 578), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'dtype': 'tf.int32', 'name': '"""local_episodes"""', 'trainable': '(False)'}), "(0, dtype=tf.int32, name='local_episodes', trainable=False)\n", (519, 578), True, 'import tensorflow as tf\n'), ((774, 824), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['(settings.tbPath + self.name)'], {}), '(settings.tbPath + self.name)\n', (795, 824), True, 'import tensorflow as tf\n'), ((879, 931), 'ACNetwork.ACNetwork', 'ACNetwork', (['settings', 'self.name'], {'step': 'self.localSteps'}), '(settings, self.name, step=self.localSteps)\n', (888, 931), False, 'from ACNetwork import ACNetwork\n'), ((956, 1017), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES', '"""global"""'], {}), "(tf.GraphKeys.TRAINABLE_VARIABLES, 'global')\n", (973, 1017), True, 'import tensorflow as tf\n'), ((1041, 1103), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES', 'self.name'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)\n', (1058, 1103), True, 'import tensorflow as tf\n'), ((2096, 2133), 'numpy.asarray', 'np.asarray', (['(values + [bootStrapValue])'], {}), '(values + [bootStrapValue])\n', (2106, 2133), True, 'import numpy as np\n'), ((5264, 5276), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (5274, 5276), True, 'import tensorflow as tf\n'), ((4245, 4265), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (4259, 4265), False, 'import os\n'), ((4346, 4363), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (4357, 4363), False, 'import os\n')] |
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import *
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, ZeroPadding2D
from keras.layers import BatchNormalization
from keras import initializers
from keras import regularizers
from keras.layers.advanced_activations import LeakyReLU
import pandas as pd
import numpy as np
import os
import keras
import matplotlib.pyplot as plt
from keras.layers import Dense,GlobalAveragePooling2D
from keras.applications import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.optimizers import Adam
from keras.models import load_model
from sklearn.metrics import classification_report, confusion_matrix
ROOT_PATH = "../../"
train_directory_path = ROOT_PATH + 'TRAIN_FINAL/'
test_directory_path = ROOT_PATH + 'TEST_FINAL/'
width = 224
height = 224
batch_size = 20
test_datagen = ImageDataGenerator()
validation_generator = test_datagen.flow_from_directory(
test_directory_path,
target_size=(width, height),
batch_size=batch_size,
class_mode='categorical',
seed=42)
gen = pred_generator = test_datagen.flow_from_directory(
test_directory_path,
target_size=(width, height),
batch_size=batch_size,
class_mode='categorical',
shuffle = False,
seed=42)
step_size_validate = validation_generator.n // validation_generator.batch_size
# Define Top2 and Top3 Accuracy
from keras.metrics import categorical_accuracy, top_k_categorical_accuracy
def top_3_accuracy(y_true, y_pred):
return top_k_categorical_accuracy(y_true, y_pred, k=3)
def top_2_accuracy(y_true, y_pred):
return top_k_categorical_accuracy(y_true, y_pred, k=2)
model = load_model('FINAL.h5', custom_objects={'top_3_accuracy': top_3_accuracy, 'top_2_accuracy': top_2_accuracy})
labels = (validation_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
print(labels)
# eval = model.evaluate_generator(validation_generator, step_size_validate, verbose=1)
# print(eval)
#print(pred_generator.classes)
ground_truth = pred_generator.classes
true_labels = [labels[k] for k in ground_truth]
print(true_labels)
pred = model.predict_generator(pred_generator, step_size_validate, verbose=1)
y_pred = np.argmax(pred, axis=1)
#print(y_pred)
predicted_class_indices=np.argmax(pred,axis=1)
predictions = [labels[k] for k in predicted_class_indices]
print(predictions)
true_benign = 0
true_malignant = 0
false_benign = 0
false_malignant = 0
malignant = ['MEL', 'BCC', 'AKIEC']
benign = ['NV', 'BKL', 'VASC', 'DF']
label_names = ['AKIEC', 'BCC', 'BKL', 'DF', 'MEL', 'NV', 'VASC']
# print(labels)
# print('evaluation:')
# print(model.metrics_names)
# print(evaluated)
for predicted, true in zip(predictions, true_labels):
if predicted in malignant:
if true in malignant:
true_malignant += 1
else:
false_malignant += 1
else:
if true in benign:
true_benign += 1
else:
false_benign += 1
total = true_malignant + true_benign + false_benign + false_malignant
print("num of pictures:")
print(total)
# print("accuracy in 7 classes:")
# print(correct / (incorrect + correct))
print('Confusion Matrix for 7 classes')
print(confusion_matrix(ground_truth, predicted_class_indices))
print('Classification Report for 7 classes')
print(classification_report(ground_truth, predicted_class_indices, target_names=label_names))
print('Confusion matrix for 2 classes')
print('predicted [ BEN MAL ]')
print('actual BEN [ {} {} ]', true_benign, false_malignant)
print('actual MAL [ {} {} ]', false_benign, true_malignant)
print('')
print('Accuracy: {}', ((true_malignant+true_benign)/total) )
precision = true_malignant/(true_malignant+false_malignant)
recall = true_malignant/(true_malignant+false_benign)
print('Precision: {}', precision)
print('Recall: {}', recall)
print('F1: {}', 2*precision*recall/(precision+recall))
| [
"keras.models.load_model",
"sklearn.metrics.classification_report",
"numpy.argmax",
"keras.preprocessing.image.ImageDataGenerator",
"keras.metrics.top_k_categorical_accuracy",
"sklearn.metrics.confusion_matrix"
] | [((1111, 1131), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {}), '()\n', (1129, 1131), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((1915, 2026), 'keras.models.load_model', 'load_model', (['"""FINAL.h5"""'], {'custom_objects': "{'top_3_accuracy': top_3_accuracy, 'top_2_accuracy': top_2_accuracy}"}), "('FINAL.h5', custom_objects={'top_3_accuracy': top_3_accuracy,\n 'top_2_accuracy': top_2_accuracy})\n", (1925, 2026), False, 'from keras.models import load_model\n'), ((2458, 2481), 'numpy.argmax', 'np.argmax', (['pred'], {'axis': '(1)'}), '(pred, axis=1)\n', (2467, 2481), True, 'import numpy as np\n'), ((2522, 2545), 'numpy.argmax', 'np.argmax', (['pred'], {'axis': '(1)'}), '(pred, axis=1)\n', (2531, 2545), True, 'import numpy as np\n'), ((1760, 1807), 'keras.metrics.top_k_categorical_accuracy', 'top_k_categorical_accuracy', (['y_true', 'y_pred'], {'k': '(3)'}), '(y_true, y_pred, k=3)\n', (1786, 1807), False, 'from keras.metrics import categorical_accuracy, top_k_categorical_accuracy\n'), ((1856, 1903), 'keras.metrics.top_k_categorical_accuracy', 'top_k_categorical_accuracy', (['y_true', 'y_pred'], {'k': '(2)'}), '(y_true, y_pred, k=2)\n', (1882, 1903), False, 'from keras.metrics import categorical_accuracy, top_k_categorical_accuracy\n'), ((3463, 3518), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['ground_truth', 'predicted_class_indices'], {}), '(ground_truth, predicted_class_indices)\n', (3479, 3518), False, 'from sklearn.metrics import classification_report, confusion_matrix\n'), ((3571, 3662), 'sklearn.metrics.classification_report', 'classification_report', (['ground_truth', 'predicted_class_indices'], {'target_names': 'label_names'}), '(ground_truth, predicted_class_indices, target_names=\n label_names)\n', (3592, 3662), False, 'from sklearn.metrics import classification_report, confusion_matrix\n')] |
import pytest
import sys
sys.path.append('..')
from app.src.mnist import train_mnist
deterministic_training = True
if deterministic_training:
# Code snippet for reproducibility in Keras (https://stackoverflow.com/questions/48631576/reproducible-results-using-keras-with-tensorflow-backend)
# Note: Perfect reproducibility is not guaranteed when using GPUs for training (see link above)
# =================================================================================================================================================
# Seed value (can actually be different for each attribution step)
seed_value= 0
# 1. Set `PYTHONHASHSEED` environment variable at a fixed value
import os
os.environ['PYTHONHASHSEED']=str(seed_value)
# 2. Set `python` built-in pseudo-random generator at a fixed value
import random
random.seed(seed_value)
# 3. Set `numpy` pseudo-random generator at a fixed value
import numpy as np
np.random.seed(seed_value)
# 4. Set `tensorflow` pseudo-random generator at a fixed value
import tensorflow as tf
tf.set_random_seed(seed_value)
# 5. Configure a new global `tensorflow` session
from keras import backend as K
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)
# =================================================================================================================================================
def test_training_mnist():
test_accuracy = train_mnist()
assert test_accuracy == pytest.approx(0.9738, 0.01)
| [
"pytest.approx",
"keras.backend.set_session",
"app.src.mnist.train_mnist",
"random.seed",
"numpy.random.seed",
"tensorflow.ConfigProto",
"tensorflow.set_random_seed",
"sys.path.append",
"tensorflow.get_default_graph"
] | [((27, 48), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (42, 48), False, 'import sys\n'), ((844, 867), 'random.seed', 'random.seed', (['seed_value'], {}), '(seed_value)\n', (855, 867), False, 'import random\n'), ((952, 978), 'numpy.random.seed', 'np.random.seed', (['seed_value'], {}), '(seed_value)\n', (966, 978), True, 'import numpy as np\n'), ((1073, 1103), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed_value'], {}), '(seed_value)\n', (1091, 1103), True, 'import tensorflow as tf\n'), ((1206, 1284), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'intra_op_parallelism_threads': '(1)', 'inter_op_parallelism_threads': '(1)'}), '(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n', (1220, 1284), True, 'import tensorflow as tf\n'), ((1358, 1377), 'keras.backend.set_session', 'K.set_session', (['sess'], {}), '(sess)\n', (1371, 1377), True, 'from keras import backend as K\n'), ((1577, 1590), 'app.src.mnist.train_mnist', 'train_mnist', ([], {}), '()\n', (1588, 1590), False, 'from app.src.mnist import train_mnist\n'), ((1619, 1646), 'pytest.approx', 'pytest.approx', (['(0.9738)', '(0.01)'], {}), '(0.9738, 0.01)\n', (1632, 1646), False, 'import pytest\n'), ((1311, 1333), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1331, 1333), True, 'import tensorflow as tf\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import gzip
import six
import numpy as np
from scipy.special import expit
def _maybe_download(target_dir):
target_path = os.path.join(target_dir, "mnist.pkl.gz")
if not os.path.exists(target_dir):
os.system(" ".join([
"wget -P",
target_dir,
"http://deeplearning.net/data/mnist/mnist.pkl.gz"
]))
def load_mnist(target_dir):
_maybe_download(target_dir)
target_path = os.path.join(target_dir, "mnist.pkl.gz")
file_in = gzip.open(target_path, "rb")
if six.PY2:
import cPickle
train, valid, test = cPickle.load(file_in)
elif six.PY3:
import pickle
u = pickle._Unpickler(file_in)
u.encoding = 'latin1'
train, valid, test = u.load()
images = np.vstack([train[0], valid[0], test[0]])
n_vis = 784
return images, n_vis
def calc_update(data, b, c, w, n_samp=1):
m_vis = data
m_hid = expit(np.dot(data, w) + c)
s_vis = m_vis
for i in range(n_samp):
sm_hid = expit(np.dot(s_vis, w) + c)
s_hid = np.random.binomial(1, sm_hid)
sm_vis = expit(np.dot(s_hid, w.T) + b)
s_vis = np.random.binomial(1, sm_vis)
ub = np.mean(m_vis - s_vis, axis=0)
uc = np.mean(m_hid - s_hid, axis=0)
uw = (np.dot(m_vis.T, m_hid) - np.dot(s_vis.T, s_hid)) / len(data)
return ub, uc, uw
def _reconst(data, b, c, w):
m_h = expit(np.dot(data, w) + c)
return expit(np.dot(w, m_h.T).T + b)
def calc_xentropy(data, b, c, w):
m_vis = _reconst(data, b, c, w)
m_vis = np.clip(m_vis, 1e-8, 1 - 1e-8)
xentropy = - np.mean(
np.sum(
data * np.log(m_vis) +
(1-data) * np.log(1-m_vis),
axis=1)
)
return xentropy
| [
"numpy.clip",
"numpy.mean",
"os.path.exists",
"gzip.open",
"numpy.log",
"os.path.join",
"numpy.dot",
"numpy.vstack",
"pickle._Unpickler",
"cPickle.load",
"numpy.random.binomial"
] | [((244, 284), 'os.path.join', 'os.path.join', (['target_dir', '"""mnist.pkl.gz"""'], {}), "(target_dir, 'mnist.pkl.gz')\n", (256, 284), False, 'import os\n'), ((527, 567), 'os.path.join', 'os.path.join', (['target_dir', '"""mnist.pkl.gz"""'], {}), "(target_dir, 'mnist.pkl.gz')\n", (539, 567), False, 'import os\n'), ((580, 608), 'gzip.open', 'gzip.open', (['target_path', '"""rb"""'], {}), "(target_path, 'rb')\n", (589, 608), False, 'import gzip\n'), ((829, 869), 'numpy.vstack', 'np.vstack', (['[train[0], valid[0], test[0]]'], {}), '([train[0], valid[0], test[0]])\n', (838, 869), True, 'import numpy as np\n'), ((1219, 1249), 'numpy.mean', 'np.mean', (['(m_vis - s_vis)'], {'axis': '(0)'}), '(m_vis - s_vis, axis=0)\n', (1226, 1249), True, 'import numpy as np\n'), ((1257, 1287), 'numpy.mean', 'np.mean', (['(m_hid - s_hid)'], {'axis': '(0)'}), '(m_hid - s_hid, axis=0)\n', (1264, 1287), True, 'import numpy as np\n'), ((1560, 1592), 'numpy.clip', 'np.clip', (['m_vis', '(1e-08)', '(1 - 1e-08)'], {}), '(m_vis, 1e-08, 1 - 1e-08)\n', (1567, 1592), True, 'import numpy as np\n'), ((294, 320), 'os.path.exists', 'os.path.exists', (['target_dir'], {}), '(target_dir)\n', (308, 320), False, 'import os\n'), ((667, 688), 'cPickle.load', 'cPickle.load', (['file_in'], {}), '(file_in)\n', (679, 688), False, 'import cPickle\n'), ((1097, 1126), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'sm_hid'], {}), '(1, sm_hid)\n', (1115, 1126), True, 'import numpy as np\n'), ((1182, 1211), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'sm_vis'], {}), '(1, sm_vis)\n', (1200, 1211), True, 'import numpy as np\n'), ((731, 757), 'pickle._Unpickler', 'pickle._Unpickler', (['file_in'], {}), '(file_in)\n', (748, 757), False, 'import pickle\n'), ((981, 996), 'numpy.dot', 'np.dot', (['data', 'w'], {}), '(data, w)\n', (987, 996), True, 'import numpy as np\n'), ((1296, 1318), 'numpy.dot', 'np.dot', (['m_vis.T', 'm_hid'], {}), '(m_vis.T, m_hid)\n', (1302, 1318), True, 'import numpy as np\n'), ((1321, 1343), 'numpy.dot', 'np.dot', (['s_vis.T', 's_hid'], {}), '(s_vis.T, s_hid)\n', (1327, 1343), True, 'import numpy as np\n'), ((1421, 1436), 'numpy.dot', 'np.dot', (['data', 'w'], {}), '(data, w)\n', (1427, 1436), True, 'import numpy as np\n'), ((1063, 1079), 'numpy.dot', 'np.dot', (['s_vis', 'w'], {}), '(s_vis, w)\n', (1069, 1079), True, 'import numpy as np\n'), ((1146, 1164), 'numpy.dot', 'np.dot', (['s_hid', 'w.T'], {}), '(s_hid, w.T)\n', (1152, 1164), True, 'import numpy as np\n'), ((1457, 1473), 'numpy.dot', 'np.dot', (['w', 'm_h.T'], {}), '(w, m_h.T)\n', (1463, 1473), True, 'import numpy as np\n'), ((1640, 1653), 'numpy.log', 'np.log', (['m_vis'], {}), '(m_vis)\n', (1646, 1653), True, 'import numpy as np\n'), ((1673, 1690), 'numpy.log', 'np.log', (['(1 - m_vis)'], {}), '(1 - m_vis)\n', (1679, 1690), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import time
import datetime
from dateutil.parser import parse
from btcTrans import ordered
from pytrends.request import TrendReq
def graphTwo(x, y, yaxis, xaxis):
meanx = np.mean(x)
meany = np.mean(y)
varx = np.var(x)
vary = np.var(y)
covxy = np.mean((x - meanx) * (y - meany))
rho = covxy / (np.sqrt(varx * vary))
bestY = (meany + rho * (np.sqrt(vary)/np.sqrt(varx))*(x - meanx))
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
plt.ylim(min(y)-10,max(y)+10)
plt.plot(x, y, 'o')
plt.plot(x, bestY)
plt.xlabel(xaxis)
plt.ylabel(yaxis)
plt.grid()
# Find all the unique points and those shall be the x values, for y it will be th
plt.show()
print("------------------------------------")
print("covxy: ", covxy)
print("------------------------------------")
print("Rho: ", rho) | [
"numpy.mean",
"matplotlib.pyplot.grid",
"numpy.sqrt",
"numpy.unique",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.var",
"matplotlib.pyplot.show"
] | [((265, 275), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (272, 275), True, 'import numpy as np\n'), ((288, 298), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (295, 298), True, 'import numpy as np\n'), ((310, 319), 'numpy.var', 'np.var', (['x'], {}), '(x)\n', (316, 319), True, 'import numpy as np\n'), ((331, 340), 'numpy.var', 'np.var', (['y'], {}), '(y)\n', (337, 340), True, 'import numpy as np\n'), ((353, 387), 'numpy.mean', 'np.mean', (['((x - meanx) * (y - meany))'], {}), '((x - meanx) * (y - meany))\n', (360, 387), True, 'import numpy as np\n'), ((611, 630), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o"""'], {}), "(x, y, 'o')\n", (619, 630), True, 'import matplotlib.pyplot as plt\n'), ((635, 653), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'bestY'], {}), '(x, bestY)\n', (643, 653), True, 'import matplotlib.pyplot as plt\n'), ((658, 675), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xaxis'], {}), '(xaxis)\n', (668, 675), True, 'import matplotlib.pyplot as plt\n'), ((680, 697), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['yaxis'], {}), '(yaxis)\n', (690, 697), True, 'import matplotlib.pyplot as plt\n'), ((702, 712), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (710, 712), True, 'import matplotlib.pyplot as plt\n'), ((804, 814), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (812, 814), True, 'import matplotlib.pyplot as plt\n'), ((407, 427), 'numpy.sqrt', 'np.sqrt', (['(varx * vary)'], {}), '(varx * vary)\n', (414, 427), True, 'import numpy as np\n'), ((513, 525), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (522, 525), True, 'import numpy as np\n'), ((558, 570), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (567, 570), True, 'import numpy as np\n'), ((537, 556), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (547, 556), True, 'import numpy as np\n'), ((458, 471), 'numpy.sqrt', 'np.sqrt', (['vary'], {}), '(vary)\n', (465, 471), True, 'import numpy as np\n'), ((472, 485), 'numpy.sqrt', 'np.sqrt', (['varx'], {}), '(varx)\n', (479, 485), True, 'import numpy as np\n')] |
import os
import numpy as np
import pandas as pd
import pytest
from terra.utils import ensure_dir_exists
from terra.io import Artifact, json_dump, rm_nested_artifacts, json_load
import terra.database as tdb
from .testbed import BaseTestBed
@pytest.fixture()
def testbed(request, tmpdir):
testbed_class, config = request.param
return testbed_class(**config, tmpdir=tmpdir)
@BaseTestBed.parametrize()
def test_artifact_dump_and_load(testbed: BaseTestBed):
run_dir = os.path.join(testbed.tmpdir, str(1))
ensure_dir_exists(run_dir)
x = np.random.rand(100)
artifact = Artifact.dump(value=x, run_dir=run_dir)
x_loaded = artifact.load(run_id=1)
assert np.allclose(x, x_loaded)
# test row added to artifact tableƒ
df = tdb.get_artifact_dumps()
assert len(df) == 1
assert df.iloc[0].type == "<class 'numpy.ndarray'>"
# test row added to artifact table
df = tdb.get_artifact_loads()
assert len(df) == 1
@BaseTestBed.parametrize()
def test_artifact_rm(testbed: BaseTestBed):
run_dir = os.path.join(testbed.tmpdir, str(1))
ensure_dir_exists(run_dir)
x = np.random.rand(100)
artifact = Artifact.dump(value=x, run_dir=run_dir)
artifact.rm()
assert not os.path.isfile(artifact._get_abs_path())
# check that artifact is reflected as removed in the daabase
df = tdb.get_artifact_dumps(run_ids=1)
assert df.iloc[0].rm
@BaseTestBed.parametrize()
def test_rm_nested_artifacts(testbed: BaseTestBed):
run_dir = os.path.join(testbed.tmpdir, str(1))
ensure_dir_exists(run_dir)
json_dump(
{
"a": [1, 3, np.random.rand(10)],
"b": pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}),
"c": [1, 2, 3, {"a": np.random.rand(10)}],
},
run_dir=run_dir,
path=os.path.join(run_dir, "out.json"),
)
out = json_load(os.path.join(run_dir, "out.json"))
rm_nested_artifacts(out)
# check that artifacts are reflected as removed in the daabase
df = tdb.get_artifact_dumps(run_ids=1)
assert df.rm.all()
| [
"terra.database.get_artifact_loads",
"numpy.allclose",
"numpy.random.rand",
"pandas.DataFrame",
"terra.utils.ensure_dir_exists",
"os.path.join",
"terra.io.Artifact.dump",
"terra.database.get_artifact_dumps",
"terra.io.rm_nested_artifacts",
"pytest.fixture"
] | [((244, 260), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (258, 260), False, 'import pytest\n'), ((523, 549), 'terra.utils.ensure_dir_exists', 'ensure_dir_exists', (['run_dir'], {}), '(run_dir)\n', (540, 549), False, 'from terra.utils import ensure_dir_exists\n'), ((558, 577), 'numpy.random.rand', 'np.random.rand', (['(100)'], {}), '(100)\n', (572, 577), True, 'import numpy as np\n'), ((593, 632), 'terra.io.Artifact.dump', 'Artifact.dump', ([], {'value': 'x', 'run_dir': 'run_dir'}), '(value=x, run_dir=run_dir)\n', (606, 632), False, 'from terra.io import Artifact, json_dump, rm_nested_artifacts, json_load\n'), ((684, 708), 'numpy.allclose', 'np.allclose', (['x', 'x_loaded'], {}), '(x, x_loaded)\n', (695, 708), True, 'import numpy as np\n'), ((759, 783), 'terra.database.get_artifact_dumps', 'tdb.get_artifact_dumps', ([], {}), '()\n', (781, 783), True, 'import terra.database as tdb\n'), ((913, 937), 'terra.database.get_artifact_loads', 'tdb.get_artifact_loads', ([], {}), '()\n', (935, 937), True, 'import terra.database as tdb\n'), ((1091, 1117), 'terra.utils.ensure_dir_exists', 'ensure_dir_exists', (['run_dir'], {}), '(run_dir)\n', (1108, 1117), False, 'from terra.utils import ensure_dir_exists\n'), ((1126, 1145), 'numpy.random.rand', 'np.random.rand', (['(100)'], {}), '(100)\n', (1140, 1145), True, 'import numpy as np\n'), ((1161, 1200), 'terra.io.Artifact.dump', 'Artifact.dump', ([], {'value': 'x', 'run_dir': 'run_dir'}), '(value=x, run_dir=run_dir)\n', (1174, 1200), False, 'from terra.io import Artifact, json_dump, rm_nested_artifacts, json_load\n'), ((1351, 1384), 'terra.database.get_artifact_dumps', 'tdb.get_artifact_dumps', ([], {'run_ids': '(1)'}), '(run_ids=1)\n', (1373, 1384), True, 'import terra.database as tdb\n'), ((1547, 1573), 'terra.utils.ensure_dir_exists', 'ensure_dir_exists', (['run_dir'], {}), '(run_dir)\n', (1564, 1573), False, 'from terra.utils import ensure_dir_exists\n'), ((1914, 1938), 'terra.io.rm_nested_artifacts', 'rm_nested_artifacts', (['out'], {}), '(out)\n', (1933, 1938), False, 'from terra.io import Artifact, json_dump, rm_nested_artifacts, json_load\n'), ((2016, 2049), 'terra.database.get_artifact_dumps', 'tdb.get_artifact_dumps', ([], {'run_ids': '(1)'}), '(run_ids=1)\n', (2038, 2049), True, 'import terra.database as tdb\n'), ((1875, 1908), 'os.path.join', 'os.path.join', (['run_dir', '"""out.json"""'], {}), "(run_dir, 'out.json')\n", (1887, 1908), False, 'import os\n'), ((1661, 1707), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [1, 2, 3], 'b': [4, 5, 6]}"], {}), "({'a': [1, 2, 3], 'b': [4, 5, 6]})\n", (1673, 1707), True, 'import pandas as pd\n'), ((1813, 1846), 'os.path.join', 'os.path.join', (['run_dir', '"""out.json"""'], {}), "(run_dir, 'out.json')\n", (1825, 1846), False, 'import os\n'), ((1623, 1641), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (1637, 1641), True, 'import numpy as np\n'), ((1742, 1760), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (1756, 1760), True, 'import numpy as np\n')] |
#----------------------------
# Author: <NAME>
#----------------------------
from collections import namedtuple
import numpy as np
import math
FILE_TYPE = "P2" # to verify the file type
PGMFile = namedtuple('PGMFile', ['max_shade', 'data']) # named tuple
# This function receives the name of a file, reads it in, verifies that
# the type is P2, and returns the corresponding PGMFile
def read_pgm(filename):
rows = 0
cols = 0
max_shade = 0
pixel_array = []
line_no = 1
try:
f = open(filename)
except:
print(f"\nError: The file named \'{filename}\' does not exist!")
else:
try:
for line in f: # reading one line at a time from the file
if line != "\n": # checking for blank lines
end_index = line.find("\n")
line = line[0:end_index]
if line.find("#") != -1: # checking for annoying cooments
end_index = line.find("#")
line = line[0:end_index]
line = line.strip()
if len(line) != 0:
if line_no == 1: # checking for file type in line 1
if line == FILE_TYPE:
line_no += 1
else:
print("Error: The input file is not a P2 image!")
elif line_no == 2: # getting the width and height of the image from line 2
dimensions = line.split()
rows = int(dimensions[1]) # rows = height
cols = int(dimensions[0]) # columns = width
line_no += 1
elif line_no == 3: # getting the maximum shade value from line 3
max_shade = int(line)
line_no += 1
else:
line_array = line.split() # storing all the numbers into a list after removing all the white spaces
for i in range(len(line_array)):
pixel_array.append(int(line_array[i]))
except:
print("\nError: The input file could not be read properly!")
else:
data = np.array(pixel_array).reshape(rows, cols) # creating a 2D numpy array
return PGMFile(max_shade, data) # returning the corresponding PGMFile
# This function receives a file name and a PGMFile, and creates the corresponding image file
def create_image(filename, pgm):
with open(filename, "w") as f:
print(f"{FILE_TYPE}\n{pgm.data.shape[1]} {pgm.data.shape[0]}\n{pgm.max_shade}\n", file=f)
for row in pgm.data:
for i in range(0, len(row)):
print(str(row[i]), end=" ", file=f)
print("", file=f)
# This function reflects a pgm image from left to right
def reflect_left_to_right(pgm_file):
matrix = np.flip(pgm_file.data, axis=1)
return PGMFile(pgm_file.max_shade, matrix)
# This function reflects a pgm image from top to bottom
def reflect_top_to_bottom(pgm_file):
matrix = np.flip(pgm_file.data, axis=0)
return PGMFile(pgm_file.max_shade, matrix)
# This function inverts the black and white pixels in a pgm image
def invert_black_white(pgm_file):
matrix = np.subtract(pgm_file.max_shade, pgm_file.data)
return PGMFile(pgm_file.max_shade, matrix)
# This function brightens a pgm image by 10%
def brighten(pgm_file, increase_by):
brightness = int((increase_by/100) * (np.sum(pgm_file.data, dtype=np.uint64) / pgm_file.data.size))
matrix = np.add(brightness, pgm_file.data) # adding the brightness value to each pixel of the image
matrix = np.clip(matrix, 0, pgm_file.max_shade) # some pixels will be > 255, so bringing those values down to 255
return PGMFile(pgm_file.max_shade, matrix)
# A function that receives a standard deviation σ and number of neighbors r, and returns the corresponding
# 1D dimensional Gaussian kernel of length 2r+ 1, normalized so that its entries sum to 1
def one_d_gaussian_kernel(sigma, r):
size = (2*r)+1
gaussian_kernel = []
for i in range(size):
x = i-r
p_x = 1/(sigma*math.sqrt(2*math.pi)) * (math.pow(math.e, (-1/2)*(math.pow(x, 2)/math.pow(sigma, 2))))
gaussian_kernel.append(p_x)
gaussian_kernel = np.array(gaussian_kernel)
gaussian_kernel = np.divide(gaussian_kernel, np.sum(gaussian_kernel))
return gaussian_kernel
# A helper function to truncate and normalize the 1D Gaussian kernel
def truncate_normalize_1d_gaussian(kernel, left, right):
highest_col_index = kernel.size-1
new_kernel = np.copy(kernel)
if left != 0:
col_nums = [y for y in range(left)] # storing the column numbers to be deleted from the left, in a list
new_kernel = np.delete(new_kernel, col_nums)
highest_col_index = new_kernel.size - 1
if right != 0:
col_nums = [highest_col_index-y for y in range(right)] # storing the column numbers to be deleted from the right, in a list
new_kernel = np.delete(new_kernel, col_nums)
new_kernel = np.divide(new_kernel, np.sum(new_kernel)) # normalizing the kernel
return new_kernel
def convolve_1dkernel_hrzntl(kernel, image_matrix):
r = kernel.size // 2
num_rows, num_cols = image_matrix.shape
# traversing through the image matrix
for row in range(num_rows):
for col in range(num_cols):
left = col # num of cols to the left of current pixel
right = (num_cols-1) - col # num of cols to the right of current pixel
trunc_left = 0
trunc_right = 0
if left < r:
trunc_left = r - left # num of cols to truncate from left of 1D Gaussian
if right < r:
trunc_right = r - right # num of cols to truncate from left of 1D Gaussian
new_kernel = truncate_normalize_1d_gaussian(kernel, trunc_left, trunc_right)
curr_pixel_value = 0
if left > r:
for x in range(new_kernel.size):
curr_pixel_value += new_kernel[x] * image_matrix[row][x+(left-r)]
else:
for x in range(new_kernel.size):
curr_pixel_value += new_kernel[x] * image_matrix[row][x]
image_matrix[row][col] = curr_pixel_value # updating the current pixel value
return image_matrix
# A function that convolves a 2D image with a 1D kernel twice in succession: first horizontally, then vertically
def convolve_1dkernel(kernel, pgm_file):
img_matrix = np.copy(pgm_file.data)
img_matrix = convolve_1dkernel_hrzntl(kernel, img_matrix) # convolving horizontally
img_matrix = np.transpose(img_matrix) # changing the orientation of the image
img_matrix = convolve_1dkernel_hrzntl(kernel, img_matrix) # convolving vertically
img_matrix = np.transpose(img_matrix) # changing the orientation of the image
max_pixel = np.amax(img_matrix)
return PGMFile(max_pixel, img_matrix)
# A helper function to build the gradient vector matrix
def get_gradient_vector(smooth_image):
img_matrix = smooth_image.data
num_rows, num_cols = img_matrix.shape
gradient_vector = []
cd_j = 0 # in j direction - horizontal
cd_k = 0 # in k direction - vertical
for row in range(num_rows):
top = row
bottom = (num_rows-1)-row
cols = []
for col in range(num_cols):
left = col
right = (num_cols-1)-col
if left >= 1 and right >= 1:
cd_j = (img_matrix[row][col+1] - img_matrix[row][col-1])/2
elif left < 1 and right >= 1:
cd_j = img_matrix[row][col+1] - img_matrix[row][col]
elif left >= 1 and right < 1:
cd_j = img_matrix[row][col] - img_matrix[row][col-1]
if top >= 1 and bottom >= 1:
cd_k = (img_matrix[row+1][col] - img_matrix[row-1][col])/2
elif top < 1 and bottom >= 1:
cd_k = img_matrix[row+1][col] - img_matrix[row][col]
elif top >= 1 and bottom < 1:
cd_k = img_matrix[row][col] - img_matrix[row-1][col]
cols.append((cd_j, cd_k))
gradient_vector.append(cols)
return gradient_vector # returns gradient vector matrix as a matrix of tuples
# a helper function to get the theta of the gradient vector
def get_angle(gradient_vector):
result = 0
angle = np.arctan2(gradient_vector[1], gradient_vector[0]) * 180 / np.pi
if angle > 337.5 or angle <= 22.5 or (angle > 157.5 and angle <= 202.5):
result = 0
elif (angle > 22.5 and angle <= 67.5) or (angle > 202.5 and angle <= 247.5):
result = 45
elif (angle > 67.5 and angle <= 112.5) or (angle > 247.5 and angle <= 292.5):
result = 90
elif (angle > 112.5 and angle <= 157.5) or (angle > 292.5 and angle <= 337.5):
result = 135
return result
# A function to detect edges in the image
def edge_detection(pgm_file, gradient_vector_matrix):
img_matrix = pgm_file.data
num_rows, num_cols = img_matrix.shape
temp_matrix = np.copy(pgm_file.data)
for row in range(num_rows):
for col in range(num_cols):
gradient_vector = gradient_vector_matrix[row][col]
mag_grad_vector = math.sqrt(math.pow(gradient_vector[0], 2) + math.pow(gradient_vector[1], 2))
temp_matrix[row][col] = mag_grad_vector
max_pixel = np.amax(temp_matrix)
return PGMFile(max_pixel, temp_matrix)
# A function to thin the edges in the image
def edge_thinning(pgm_file, gradient_vector_matrix):
img_matrix = pgm_file.data
num_rows, num_cols = img_matrix.shape
temp_matrix = np.copy(pgm_file.data)
for row in range(num_rows):
top = row
bottom = (num_rows-1)-row
for col in range(num_cols):
left = col
right = (num_cols-1)-col
gradient_vector = gradient_vector_matrix[row][col]
angle = get_angle(gradient_vector)
curr_pixel = img_matrix[row][col]
if angle == 0:
if left >= 1 and right >= 1:
if curr_pixel < img_matrix[row][col-1] or curr_pixel < img_matrix[row][col+1]:
temp_matrix[row][col] = 0
elif left < 1 and right >= 1:
if curr_pixel < img_matrix[row][col+1]:
temp_matrix[row][col] = 0
elif left >= 1 and right < 1:
if curr_pixel < img_matrix[row][col-1]:
temp_matrix[row][col] = 0
elif angle == 45:
if left >= 1 and right >= 1 and top >= 1 and bottom >= 1:
if curr_pixel < img_matrix[row-1][col+1] or curr_pixel < img_matrix[row+1][col-1]:
temp_matrix[row][col] = 0
elif left >= 1 and bottom >= 1:
if curr_pixel < img_matrix[row+1][col-1]:
temp_matrix[row][col] = 0
elif right >= 1 and top >= 1:
if curr_pixel < img_matrix[row-1][col+1]:
temp_matrix[row][col] = 0
elif angle == 90:
if top >= 1 and bottom >= 1:
if curr_pixel < img_matrix[row-1][col] or curr_pixel < img_matrix[row+1][col]:
temp_matrix[row][col] = 0
elif top < 1 and bottom >= 1:
if curr_pixel < img_matrix[row+1][col]:
temp_matrix[row][col] = 0
elif top >= 1 and bottom < 1:
if curr_pixel < img_matrix[row-1][col]:
temp_matrix[row][col] = 0
elif angle == 135:
if left >= 1 and right >= 1 and top >= 1 and bottom >= 1:
if curr_pixel < img_matrix[row-1][col-1] or curr_pixel < img_matrix[row+1][col+1]:
temp_matrix[row][col] = 0
elif left >= 1 and top >= 1:
if curr_pixel < img_matrix[row-1][col-1]:
temp_matrix[row][col] = 0
elif right >= 1 and bottom >= 1:
if curr_pixel < img_matrix[row+1][col+1]:
temp_matrix[row][col] = 0
max_pixel = np.amax(temp_matrix)
return PGMFile(max_pixel, temp_matrix)
# A function tosuppress the noise in the image
def noise_suppress(pgm_file, low_thresh, high_thresh):
img_matrix = pgm_file.data
num_rows, num_cols = img_matrix.shape
temp_matrix = np.copy(pgm_file.data)
max_pixel = np.amax(img_matrix)
low_thresh = low_thresh * max_pixel
high_thresh = high_thresh * max_pixel
for row in range(num_rows):
top = row
bottom = (num_rows-1)-row
for col in range(num_cols):
left = col
right = (num_cols-1)-col
curr_pixel = img_matrix[row][col]
if left >= 1 and right >= 1 and top >= 1 and bottom >= 1:
if curr_pixel < low_thresh:
temp_matrix[row][col] = 0
elif low_thresh <= curr_pixel < high_thresh:
if img_matrix[row][col-1] <= high_thresh:
if img_matrix[row-1][col-1] <= high_thresh:
if img_matrix[row-1][col] <= high_thresh:
if img_matrix[row-1][col+1] <= high_thresh:
if img_matrix[row][col+1] <= high_thresh:
if img_matrix[row+1][col+1] <= high_thresh:
if img_matrix[row+1][col] <= high_thresh:
if img_matrix[row+1][col-1] <= high_thresh:
temp_matrix[row][col] = 0
max_pixel = np.amax(temp_matrix)
return PGMFile(max_pixel, temp_matrix)
| [
"numpy.clip",
"numpy.flip",
"numpy.copy",
"collections.namedtuple",
"numpy.add",
"math.pow",
"numpy.delete",
"math.sqrt",
"numpy.subtract",
"numpy.array",
"numpy.sum",
"numpy.arctan2",
"numpy.transpose",
"numpy.amax"
] | [((199, 243), 'collections.namedtuple', 'namedtuple', (['"""PGMFile"""', "['max_shade', 'data']"], {}), "('PGMFile', ['max_shade', 'data'])\n", (209, 243), False, 'from collections import namedtuple\n'), ((3029, 3059), 'numpy.flip', 'np.flip', (['pgm_file.data'], {'axis': '(1)'}), '(pgm_file.data, axis=1)\n', (3036, 3059), True, 'import numpy as np\n'), ((3215, 3245), 'numpy.flip', 'np.flip', (['pgm_file.data'], {'axis': '(0)'}), '(pgm_file.data, axis=0)\n', (3222, 3245), True, 'import numpy as np\n'), ((3408, 3454), 'numpy.subtract', 'np.subtract', (['pgm_file.max_shade', 'pgm_file.data'], {}), '(pgm_file.max_shade, pgm_file.data)\n', (3419, 3454), True, 'import numpy as np\n'), ((3703, 3736), 'numpy.add', 'np.add', (['brightness', 'pgm_file.data'], {}), '(brightness, pgm_file.data)\n', (3709, 3736), True, 'import numpy as np\n'), ((3808, 3846), 'numpy.clip', 'np.clip', (['matrix', '(0)', 'pgm_file.max_shade'], {}), '(matrix, 0, pgm_file.max_shade)\n', (3815, 3846), True, 'import numpy as np\n'), ((4451, 4476), 'numpy.array', 'np.array', (['gaussian_kernel'], {}), '(gaussian_kernel)\n', (4459, 4476), True, 'import numpy as np\n'), ((4761, 4776), 'numpy.copy', 'np.copy', (['kernel'], {}), '(kernel)\n', (4768, 4776), True, 'import numpy as np\n'), ((6715, 6737), 'numpy.copy', 'np.copy', (['pgm_file.data'], {}), '(pgm_file.data)\n', (6722, 6737), True, 'import numpy as np\n'), ((6845, 6869), 'numpy.transpose', 'np.transpose', (['img_matrix'], {}), '(img_matrix)\n', (6857, 6869), True, 'import numpy as np\n'), ((7017, 7041), 'numpy.transpose', 'np.transpose', (['img_matrix'], {}), '(img_matrix)\n', (7029, 7041), True, 'import numpy as np\n'), ((7100, 7119), 'numpy.amax', 'np.amax', (['img_matrix'], {}), '(img_matrix)\n', (7107, 7119), True, 'import numpy as np\n'), ((9277, 9299), 'numpy.copy', 'np.copy', (['pgm_file.data'], {}), '(pgm_file.data)\n', (9284, 9299), True, 'import numpy as np\n'), ((9608, 9628), 'numpy.amax', 'np.amax', (['temp_matrix'], {}), '(temp_matrix)\n', (9615, 9628), True, 'import numpy as np\n'), ((9862, 9884), 'numpy.copy', 'np.copy', (['pgm_file.data'], {}), '(pgm_file.data)\n', (9869, 9884), True, 'import numpy as np\n'), ((12463, 12483), 'numpy.amax', 'np.amax', (['temp_matrix'], {}), '(temp_matrix)\n', (12470, 12483), True, 'import numpy as np\n'), ((12722, 12744), 'numpy.copy', 'np.copy', (['pgm_file.data'], {}), '(pgm_file.data)\n', (12729, 12744), True, 'import numpy as np\n'), ((12761, 12780), 'numpy.amax', 'np.amax', (['img_matrix'], {}), '(img_matrix)\n', (12768, 12780), True, 'import numpy as np\n'), ((14022, 14042), 'numpy.amax', 'np.amax', (['temp_matrix'], {}), '(temp_matrix)\n', (14029, 14042), True, 'import numpy as np\n'), ((4526, 4549), 'numpy.sum', 'np.sum', (['gaussian_kernel'], {}), '(gaussian_kernel)\n', (4532, 4549), True, 'import numpy as np\n'), ((4930, 4961), 'numpy.delete', 'np.delete', (['new_kernel', 'col_nums'], {}), '(new_kernel, col_nums)\n', (4939, 4961), True, 'import numpy as np\n'), ((5183, 5214), 'numpy.delete', 'np.delete', (['new_kernel', 'col_nums'], {}), '(new_kernel, col_nums)\n', (5192, 5214), True, 'import numpy as np\n'), ((5255, 5273), 'numpy.sum', 'np.sum', (['new_kernel'], {}), '(new_kernel)\n', (5261, 5273), True, 'import numpy as np\n'), ((8602, 8652), 'numpy.arctan2', 'np.arctan2', (['gradient_vector[1]', 'gradient_vector[0]'], {}), '(gradient_vector[1], gradient_vector[0])\n', (8612, 8652), True, 'import numpy as np\n'), ((3628, 3666), 'numpy.sum', 'np.sum', (['pgm_file.data'], {'dtype': 'np.uint64'}), '(pgm_file.data, dtype=np.uint64)\n', (3634, 3666), True, 'import numpy as np\n'), ((2343, 2364), 'numpy.array', 'np.array', (['pixel_array'], {}), '(pixel_array)\n', (2351, 2364), True, 'import numpy as np\n'), ((4306, 4328), 'math.sqrt', 'math.sqrt', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', (4315, 4328), False, 'import math\n'), ((9472, 9503), 'math.pow', 'math.pow', (['gradient_vector[0]', '(2)'], {}), '(gradient_vector[0], 2)\n', (9480, 9503), False, 'import math\n'), ((9506, 9537), 'math.pow', 'math.pow', (['gradient_vector[1]', '(2)'], {}), '(gradient_vector[1], 2)\n', (9514, 9537), False, 'import math\n'), ((4356, 4370), 'math.pow', 'math.pow', (['x', '(2)'], {}), '(x, 2)\n', (4364, 4370), False, 'import math\n'), ((4371, 4389), 'math.pow', 'math.pow', (['sigma', '(2)'], {}), '(sigma, 2)\n', (4379, 4389), False, 'import math\n')] |
from PyCommon.modules.Motion import ysBipedAnalysis as yba
from PyCommon.modules.Math import mmMath as mm
from PyCommon.modules.Math import ysFunctionGraph as yfg
from PyCommon.modules.Motion import ysMotionAnalysis as yma
import numpy as np
stitch_func = lambda xx : 1. - yfg.hermite2nd(xx)
#TODO:
if False:
stf_stabilize_func = yfg.concatenate([yfg.hermite2nd, yfg.one], [c_landing_duration])
match_stl_func = yfg.hermite2nd
swf_placement_func = yfg.hermite2nd
# swf_placement_func = yfg.identity
swf_height_func = yfg.hermite2nd
swf_height_sine_func = yfg.sine
# stf_balancing_func = yfg.concatenate([yfg.hermite2nd, yfg.one], [c_landing_duration])
stf_balancing_func = yfg.hermite2nd
# stf_balancing_func = yfg.hermite5th
class HpBipedFeedback():
def __init__(self, phys_model, motion_ori, seginfo):
self.prev_R_swp = []
self.phys_model = phys_model
self.seginfo = seginfo
self.motion_ori = motion_ori
def refresh_frame_fbpar_information(self,
Kt,
Dt,
Ks,
Ds,
mu,
c_min_contact_vel,
c_min_contact_time,
c_landing_duration,
c_taking_duration,
c_swf_mid_offset,
c_locking_vel,
c_swf_offset,
K_stp_pos,
c5,
c6,
K_stb_vel,
K_stb_pos,
K_swp_vel_sag,
K_swp_vel_cor,
K_swp_pos_sag,
K_swp_pos_cor,
K_swp_pos_sag_faster
):
self.Kt=Kt
self.Dt=Dt
self.Ks=Ks
self.Ds=Ds
self.mu=mu
self.c_min_contact_vel=c_min_contact_vel
self.c_min_contact_time=c_min_contact_time
self.c_landing_duration=c_landing_duration
self.c_taking_duration=c_taking_duration
self.c_swf_mid_offset=c_swf_mid_offset
self.c_locking_vel=c_locking_vel
self.c_swf_offset=c_swf_offset
self.K_stp_pos=K_stp_pos
self.c5=c5
self.c6=c6
self.K_stb_vel=K_stb_vel
self.K_stb_pos=K_stb_pos
self.K_swp_vel_sag=K_swp_vel_sag
self.K_swp_vel_cor=K_swp_vel_cor
self.K_swp_pos_sag=K_swp_pos_sag
self.K_swp_pos_cor=K_swp_pos_cor
self.K_swp_pos_sag_faster=K_swp_pos_sag_faster
def refresh_frame_seg_information(self, seginfo, seg_index, acc_offset):
self.cur_state = seginfo[seg_index]['state']
self.cur_interval = yma.offsetInterval(acc_offset, seginfo[seg_index]['interval'])
self.stance_legs = seginfo[seg_index]['stanceHips']
self.swing_legs = seginfo[seg_index]['swingHips']
self.stance_foots = seginfo[seg_index]['stanceFoots']
self.swing_foots = seginfo[seg_index]['swingFoots']
self.swing_knees = seginfo[seg_index]['swingKnees']
self.ground_height = seginfo[seg_index]['ground_height']
self.max_stf_push_frame = seginfo[seg_index]['max_stf_push_frame']
def refresh_frame_dyn_information(self, motion_seg, frame, avg_dCM):
self.frame = frame
prev_frame = frame-1 if frame>0 else 0
# information
dCM_tar = motion_seg.getJointVelocityGlobal(0, prev_frame)
CM_tar = motion_seg.getJointPositionGlobal(0, prev_frame)
stf_tar = motion_seg.getJointPositionGlobal(stanceFoots[0], prev_frame)
CMr_tar = CM_tar - stf_tar
# dCM : average velocity of root of controlModel over 1 frame
dCM = avg_dCM
CM = self.phys_model.getBody("Hips").com()
CMreal = self.phys_model.getCOM()
stf = self.phys_model.getJointPositionGlobal(stanceFoots[0])
CMr = CM - stf
# diff_dCM : diff of velocity of COM between current and desired
diff_dCM = mm.projectionOnPlane(dCM-dCM_tar, (1,0,0), (0,0,1))
# diff_dCM_axis : perpendicular of diff_dCM
diff_dCM_axis = np.cross((0,1,0), diff_dCM)
rd_vec1[0] = diff_dCM
rd_vecori1[0] = CM_tar
diff_CMr = mm.projectionOnPlane(CMr-CMr_tar, (1,0,0), (0,0,1))
diff_CMr_axis = np.cross((0,1,0), diff_CMr)
direction = mm.normalize2(mm.projectionOnPlane(dCM_tar, (1,0,0), (0,0,1)))
directionAxis = np.cross((0,1,0), direction)
diff_dCM_sag, diff_dCM_cor = mm.projectionOnVector2(diff_dCM, direction)
diff_dCM_sag_axis = np.cross((0,1,0), diff_dCM_sag)
diff_dCM_cor_axis = np.cross((0,1,0), diff_dCM_cor)
diff_CMr_sag, diff_CMr_cor = mm.projectionOnVector2(diff_CMr, direction)
diff_CMr_sag_axis = np.cross((0,1,0), diff_CMr_sag)
diff_CMr_cor_axis = np.cross((0,1,0), diff_CMr_cor)
self.t = max((frame-self.cur_interval[0])/float(self.cur_interval[1]-self.cur_interval[0]), 1.)
t_raw = self.t
# match stance leg
def match_stance_leg(self, motion_edit, cur_gait_state, stanceLegs):
if cur_gait_state != yba.GaitState.STOP:
for stanceLegIdx in range(len(stanceLegs)):
stanceLeg = stanceLegs[stanceLegIdx]
# stanceFoot = stanceFoots[stanceLegIdx]
# motion stance leg -> character stance leg as time goes
R_motion = motion_edit[self.frame].getJointOrientationGlobal(stanceLeg)
R_character = self.phys_model.getJointOrientationGlobal(stanceLeg)
motion_edit[self.frame].setJointOrientationGlobal(stanceLeg,
mm.slerp(R_motion, R_character, match_stl_func(t)))
def swing_foot_placement(self, phys_model, motion_edit, frame, is_extended):
global prev_R_swp
t_swing_foot_placement = swf_placement_func(t)
if is_extended:
R_swp_sag = prev_R_swp[0][0]
R_swp_cor = prev_R_swp[0][1]
else:
R_swp_sag = mm.I_SO3()
R_swp_cor = mm.I_SO3()
# R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement))
# R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement))
# if np.dot(direction, diff_CMr_sag) < 0:
# R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement))
# else:
# R_swp_sag = np.dot(R_swp_sag, mm.exp(diff_CMr_sag_axis * K_swp_pos_sag_faster * -t_swing_foot_placement))
# R_swp_cor = np.dot(R_swp_cor, mm.exp(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement))
R_swp_sag = np.dot(R_swp_sag, mm.clampExp(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement, math.pi/12.))
R_swp_cor = np.dot(R_swp_cor, mm.clampExp(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement, math.pi/12.))
if np.dot(direction, diff_CMr_sag) < 0:
R_swp_sag = np.dot(R_swp_sag, mm.clampExp(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement, math.pi/12.))
else:
R_swp_sag = np.dot(R_swp_sag, mm.clampExp(diff_CMr_sag_axis * K_swp_pos_sag_faster * -t_swing_foot_placement, math.pi/12.))
R_swp_cor = np.dot(R_swp_cor, mm.clampExp(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement, math.pi/12.))
for i in range(len(swingLegs)):
swingLeg = swingLegs[i]
swingFoot = swingFoots[i]
# save swing foot global orientation
R_swf = motion_swf_placement[frame].getJointOrientationGlobal(swingFoot)
# rotate swing leg
motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_sag)
motion_swf_placement[frame].mulJointOrientationGlobal(swingLeg, R_swp_cor)
# restore swing foot global orientation
motion_swf_placement[frame].setJointOrientationGlobal(swingFoot, R_swf)
# motion_swf_placement[frame].setJointOrientationGlobal(swingFoot, )
# hwangpil
# temporal code.... for heel strike and ankle pushup
# motion_swf_placement[frame].mulJointOrientationGlobal(swingFoot, mm.exp([0., 0., -0.17*t_swing_foot_placement]))
# motion_swf_placement[frame].mulJointOrientationGlobal(swingFoot, mm.exp([0.2*t_swing_foot_placement, 0., 0.]))
# hwangpil
# foot placement based on difference
# # CM = dartModel.getBody("Hips").com()
# swf = dartModel.getJointPositionGlobal(swingFoot)
# CMr_swf = CM - swf
#
# # CM_tar = motion_seg.getJointPositionGlobal(0, prev_frame)
# swf_tar = motion_seg.getJointPositionGlobal(swingFoot, prev_frame)
# CMr_swf_tar = CM_tar - swf_tar
#
# diff_CMr_swf = mm.projectionOnPlane(CMr_swf-CMr_swf_tar, (1,0,0), (0,0,1))
#
# newPosition = motion_swf_placement[frame].getJointPositionGlobal(swingFoot)
# # newPosition += (diff_CMr_swf + diff_dCM)*t_swing_foot_placement
# newPosition += 0.1*diff_CMr_swf * t_swing_foot_placement
# aik.ik_analytic(motion_swf_placement[frame], swingFoot, newPosition)
prev_R_swp[0] = (R_swp_sag, R_swp_cor)
| [
"PyCommon.modules.Math.ysFunctionGraph.hermite2nd",
"PyCommon.modules.Math.mmMath.projectionOnPlane",
"numpy.cross",
"PyCommon.modules.Motion.ysMotionAnalysis.offsetInterval",
"PyCommon.modules.Math.mmMath.projectionOnVector2",
"numpy.dot",
"PyCommon.modules.Math.mmMath.clampExp",
"PyCommon.modules.Ma... | [((336, 400), 'PyCommon.modules.Math.ysFunctionGraph.concatenate', 'yfg.concatenate', (['[yfg.hermite2nd, yfg.one]', '[c_landing_duration]'], {}), '([yfg.hermite2nd, yfg.one], [c_landing_duration])\n', (351, 400), True, 'from PyCommon.modules.Math import ysFunctionGraph as yfg\n'), ((275, 293), 'PyCommon.modules.Math.ysFunctionGraph.hermite2nd', 'yfg.hermite2nd', (['xx'], {}), '(xx)\n', (289, 293), True, 'from PyCommon.modules.Math import ysFunctionGraph as yfg\n'), ((3082, 3144), 'PyCommon.modules.Motion.ysMotionAnalysis.offsetInterval', 'yma.offsetInterval', (['acc_offset', "seginfo[seg_index]['interval']"], {}), "(acc_offset, seginfo[seg_index]['interval'])\n", (3100, 3144), True, 'from PyCommon.modules.Motion import ysMotionAnalysis as yma\n'), ((4375, 4432), 'PyCommon.modules.Math.mmMath.projectionOnPlane', 'mm.projectionOnPlane', (['(dCM - dCM_tar)', '(1, 0, 0)', '(0, 0, 1)'], {}), '(dCM - dCM_tar, (1, 0, 0), (0, 0, 1))\n', (4395, 4432), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((4503, 4532), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_dCM'], {}), '((0, 1, 0), diff_dCM)\n', (4511, 4532), True, 'import numpy as np\n'), ((4612, 4669), 'PyCommon.modules.Math.mmMath.projectionOnPlane', 'mm.projectionOnPlane', (['(CMr - CMr_tar)', '(1, 0, 0)', '(0, 0, 1)'], {}), '(CMr - CMr_tar, (1, 0, 0), (0, 0, 1))\n', (4632, 4669), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((4688, 4717), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_CMr'], {}), '((0, 1, 0), diff_CMr)\n', (4696, 4717), True, 'import numpy as np\n'), ((4824, 4854), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'direction'], {}), '((0, 1, 0), direction)\n', (4832, 4854), True, 'import numpy as np\n'), ((4891, 4934), 'PyCommon.modules.Math.mmMath.projectionOnVector2', 'mm.projectionOnVector2', (['diff_dCM', 'direction'], {}), '(diff_dCM, direction)\n', (4913, 4934), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((4963, 4996), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_dCM_sag'], {}), '((0, 1, 0), diff_dCM_sag)\n', (4971, 4996), True, 'import numpy as np\n'), ((5023, 5056), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_dCM_cor'], {}), '((0, 1, 0), diff_dCM_cor)\n', (5031, 5056), True, 'import numpy as np\n'), ((5093, 5136), 'PyCommon.modules.Math.mmMath.projectionOnVector2', 'mm.projectionOnVector2', (['diff_CMr', 'direction'], {}), '(diff_CMr, direction)\n', (5115, 5136), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((5165, 5198), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_CMr_sag'], {}), '((0, 1, 0), diff_CMr_sag)\n', (5173, 5198), True, 'import numpy as np\n'), ((5225, 5258), 'numpy.cross', 'np.cross', (['(0, 1, 0)', 'diff_CMr_cor'], {}), '((0, 1, 0), diff_CMr_cor)\n', (5233, 5258), True, 'import numpy as np\n'), ((4751, 4802), 'PyCommon.modules.Math.mmMath.projectionOnPlane', 'mm.projectionOnPlane', (['dCM_tar', '(1, 0, 0)', '(0, 0, 1)'], {}), '(dCM_tar, (1, 0, 0), (0, 0, 1))\n', (4771, 4802), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((6442, 6452), 'PyCommon.modules.Math.mmMath.I_SO3', 'mm.I_SO3', ([], {}), '()\n', (6450, 6452), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((6477, 6487), 'PyCommon.modules.Math.mmMath.I_SO3', 'mm.I_SO3', ([], {}), '()\n', (6485, 6487), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((7184, 7277), 'PyCommon.modules.Math.mmMath.clampExp', 'mm.clampExp', (['(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement)', '(math.pi / 12.0)'], {}), '(diff_dCM_sag_axis * K_swp_vel_sag * -t_swing_foot_placement, \n math.pi / 12.0)\n', (7195, 7277), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((7313, 7406), 'PyCommon.modules.Math.mmMath.clampExp', 'mm.clampExp', (['(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement)', '(math.pi / 12.0)'], {}), '(diff_dCM_cor_axis * K_swp_vel_cor * -t_swing_foot_placement, \n math.pi / 12.0)\n', (7324, 7406), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((7415, 7446), 'numpy.dot', 'np.dot', (['direction', 'diff_CMr_sag'], {}), '(direction, diff_CMr_sag)\n', (7421, 7446), True, 'import numpy as np\n'), ((7785, 7878), 'PyCommon.modules.Math.mmMath.clampExp', 'mm.clampExp', (['(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement)', '(math.pi / 12.0)'], {}), '(diff_CMr_cor_axis * K_swp_pos_cor * -t_swing_foot_placement, \n math.pi / 12.0)\n', (7796, 7878), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((7498, 7591), 'PyCommon.modules.Math.mmMath.clampExp', 'mm.clampExp', (['(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement)', '(math.pi / 12.0)'], {}), '(diff_CMr_sag_axis * K_swp_pos_sag * -t_swing_foot_placement, \n math.pi / 12.0)\n', (7509, 7591), True, 'from PyCommon.modules.Math import mmMath as mm\n'), ((7649, 7749), 'PyCommon.modules.Math.mmMath.clampExp', 'mm.clampExp', (['(diff_CMr_sag_axis * K_swp_pos_sag_faster * -t_swing_foot_placement)', '(math.pi / 12.0)'], {}), '(diff_CMr_sag_axis * K_swp_pos_sag_faster * -\n t_swing_foot_placement, math.pi / 12.0)\n', (7660, 7749), True, 'from PyCommon.modules.Math import mmMath as mm\n')] |
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
x = np.linspace(-10, 10, 300)
plt.plot(x, np.sin(x), 'r-', label="Sinus")
plt.plot(x, -0.7 * np.cos(x), 'b-', label='- Cosinus')
plt.xlim(-10, 10)
plt.ylim(-2.5,2.5)
plt.xlabel(r"$x$")
plt.ylabel(r"$f(x)$")
plt.legend(loc='upper right')
plt.grid()
plt.tight_layout()
plt.savefig("build/integration2.pdf")
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.linspace",
"numpy.cos",
"matplotlib.pyplot.tight_layout",
"numpy.sin",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.legend"
] | [((92, 117), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(300)'], {}), '(-10, 10, 300)\n', (103, 117), True, 'import numpy as np\n'), ((217, 234), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-10)', '(10)'], {}), '(-10, 10)\n', (225, 234), True, 'import matplotlib.pyplot as plt\n'), ((235, 254), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-2.5)', '(2.5)'], {}), '(-2.5, 2.5)\n', (243, 254), True, 'import matplotlib.pyplot as plt\n'), ((254, 271), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x$"""'], {}), "('$x$')\n", (264, 271), True, 'import matplotlib.pyplot as plt\n'), ((273, 293), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$f(x)$"""'], {}), "('$f(x)$')\n", (283, 293), True, 'import matplotlib.pyplot as plt\n'), ((295, 324), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (305, 324), True, 'import matplotlib.pyplot as plt\n'), ((325, 335), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (333, 335), True, 'import matplotlib.pyplot as plt\n'), ((336, 354), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (352, 354), True, 'import matplotlib.pyplot as plt\n'), ((355, 392), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""build/integration2.pdf"""'], {}), "('build/integration2.pdf')\n", (366, 392), True, 'import matplotlib.pyplot as plt\n'), ((130, 139), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (136, 139), True, 'import numpy as np\n'), ((181, 190), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (187, 190), True, 'import numpy as np\n')] |
import os
from abc import ABC, abstractmethod
from queue import PriorityQueue
import numpy as np
import pickle
import torch
class AgentBase(ABC):
def __init__(self, CONFIG, CONFIG_ENV):
super().__init__(CONFIG, CONFIG_ENV)
self.config = CONFIG
self.rng = np.random.default_rng(seed=CONFIG.SEED)
self.device = CONFIG.DEVICE
self.image_device = CONFIG.IMAGE_DEVICE
# Mode
self.eval = CONFIG.EVAL
# Vectorized envs
self.n_envs = CONFIG.NUM_CPUS
self.action_dim = CONFIG_ENV.ACTION_DIM
self.use_append = CONFIG_ENV.USE_APPEND
self.max_train_steps = CONFIG_ENV.MAX_TRAIN_STEPS
self.max_eval_steps = CONFIG_ENV.MAX_EVAL_STEPS
self.env_step_cnt = [0 for _ in range(self.n_envs)]
# Save
self.out_folder = CONFIG.OUT_FOLDER
self.save_top_k = CONFIG.SAVE_TOP_K
self.pq_top_k = PriorityQueue()
self.save_metric = CONFIG.SAVE_METRIC
self.use_wandb = CONFIG.USE_WANDB
# Figure folder
# figure_folder = os.path.join(out_folder, 'figure')
# os.makedirs(figure_folder, exist_ok=True)
# Save loss and eval info, key is step number
self.loss_record = {}
self.eval_record = {}
# Load tasks
dataset = CONFIG_ENV.DATASET
print("= Loading tasks from", dataset)
with open(dataset, 'rb') as f:
self.task_all = pickle.load(f)
self.num_task = len(self.task_all)
print(self.num_task, "tasks are loaded")
# Mode
if self.eval:
self.set_eval_mode()
else:
self.set_train_mode()
# Set starting step
if CONFIG.CURRENT_STEP is None:
self.cnt_step = 0
else:
self.cnt_step = CONFIG.CURRENT_STEP
print("starting from {:d} steps".format(self.cnt_step))
@abstractmethod
def learn(self):
raise NotImplementedError
# @abstractmethod
# def finish_eval(self):
# raise NotImplementedError
def set_train_mode(self):
self.num_eval_episode = 0
self.eval_mode = False
self.max_env_step = self.max_train_steps
def set_eval_mode(self):
self.num_eval_episode = 0
self.num_eval_success = 0 # for calculating expected success rate
self.num_eval_safe = 0 # for calculating expected safety rate
self.eval_reward_cumulative = [0 for _ in range(self.n_envs)
] # for calculating cumulative reward
self.eval_reward_best = [0 for _ in range(self.n_envs)]
self.eval_reward_cumulative_all = 0
self.eval_reward_best_all = 0
self.env_step_cnt = [0 for _ in range(self.n_envs)]
self.eval_mode = True
self.max_env_step = self.max_eval_steps
# === Venv ===
def step(self, action):
return self.venv.step(action)
def reset_sim(self):
self.venv.env_method('close_pb')
def reset_env_all(self, task_ids=None, verbose=False):
if task_ids is None:
task_ids = self.rng.integers(low=0,
high=self.num_task,
size=(self.n_envs, ))
tasks = [self.task_all[id] for id in task_ids]
s = self.venv.reset(tasks)
if verbose:
for index in range(self.n_envs):
print("<-- Reset environment {} with task {}:".format(
index, task_ids[index]))
self.env_step_cnt = [0 for _ in range(self.n_envs)]
return s, task_ids
def reset_env(self, env_ind, task_id=None, verbose=False):
if task_id is None:
task_id = self.rng.integers(low=0, high=self.num_task)
s = self.venv.reset_one(env_ind, self.task_all[task_id])
if verbose:
print("<-- Reset environment {} with task {}:".format(
env_ind, task_id))
self.env_step_cnt[env_ind] = 0
return s, task_id
# === Models ===
def save(self, metric=None, force_save=False):
assert metric is not None or force_save, \
"should provide metric of force save"
save_current = False
if force_save:
save_current = True
elif self.pq_top_k.qsize() < self.save_top_k:
self.pq_top_k.put((metric, self.cnt_step))
save_current = True
elif metric > self.pq_top_k.queue[0][0]: # overwrite
# Remove old one
_, step_remove = self.pq_top_k.get()
for module, module_folder in zip(self.module_all,
self.module_folder_all):
module.remove(int(step_remove), module_folder)
self.pq_top_k.put((metric, self.cnt_step))
save_current = True
if save_current:
print()
print('Saving current model...')
for module, module_folder in zip(self.module_all,
self.module_folder_all):
module.save(self.cnt_step, module_folder)
print(self.pq_top_k.queue)
# TODO
def restore(self, step, logs_path, agent_type, actor_path=None):
"""Restore the weights of the neural network.
Args:
step (int): #updates trained.
logs_path (str): the path of the directory, under this folder there
should be critic/ and agent/ folders.
"""
model_folder = path_c = os.path.join(logs_path, agent_type)
path_c = os.path.join(model_folder, 'critic',
'critic-{}.pth'.format(step))
if actor_path is not None:
path_a = actor_path
else:
path_a = os.path.join(model_folder, 'actor',
'actor-{}.pth'.format(step))
self.learner.critic.load_state_dict(
torch.load(path_c, map_location=self.device))
self.learner.critic_target.load_state_dict(
torch.load(path_c, map_location=self.device))
self.learner.actor.load_state_dict(
torch.load(path_a, map_location=self.device))
print(' <= Restore {} with {} updates from {}.'.format(
agent_type, step, model_folder))
| [
"numpy.random.default_rng",
"torch.load",
"pickle.load",
"os.path.join",
"queue.PriorityQueue"
] | [((286, 325), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'CONFIG.SEED'}), '(seed=CONFIG.SEED)\n', (307, 325), True, 'import numpy as np\n'), ((921, 936), 'queue.PriorityQueue', 'PriorityQueue', ([], {}), '()\n', (934, 936), False, 'from queue import PriorityQueue\n'), ((5551, 5586), 'os.path.join', 'os.path.join', (['logs_path', 'agent_type'], {}), '(logs_path, agent_type)\n', (5563, 5586), False, 'import os\n'), ((1450, 1464), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1461, 1464), False, 'import pickle\n'), ((5959, 6003), 'torch.load', 'torch.load', (['path_c'], {'map_location': 'self.device'}), '(path_c, map_location=self.device)\n', (5969, 6003), False, 'import torch\n'), ((6069, 6113), 'torch.load', 'torch.load', (['path_c'], {'map_location': 'self.device'}), '(path_c, map_location=self.device)\n', (6079, 6113), False, 'import torch\n'), ((6171, 6215), 'torch.load', 'torch.load', (['path_a'], {'map_location': 'self.device'}), '(path_a, map_location=self.device)\n', (6181, 6215), False, 'import torch\n')] |
import random
import numpy as np
from math import pow,sqrt
from utils.vocab import Vocab
class NEG:
def __init__(self, vocab: Vocab, alpha: float=0.75, size: int=20, subsampling: bool=False, subsample_thr:float = 1e-3):
random.seed(42)
np.random.seed(42)
self.alpha = alpha
self.vocab = vocab
self.size = size
self.subsample_thr = subsample_thr
self.table_size = int(1e6)
self.subsampling = subsampling
self.sample_table = self.build_sampler(self.vocab,self.alpha,self.subsampling)
def build_sampler(self,vocab: Vocab,alpha: float,subsampling: bool=False):
if subsampling:
freq = np.array(list(map(lambda x: x[1], vocab.token_freq)))
selection = list(map(lambda x: sqrt(self.subsample_thr / x) + self.subsample_thr / x, freq))
sifter = []
for i, t in enumerate(selection):
shaizi = random.random()
if shaizi > t:
sifter.append(0)
else:
sifter.append(1)
sifter = np.array(sifter)
freq = freq * sifter
sampler = np.array(list(map(lambda x: pow(x, alpha), freq)))
else:
sampler = np.array(list(map(lambda x: pow(x[1], alpha), vocab.token_freq)))
dominator = np.sum(sampler)
sampler[:] /= dominator
sampler[:] = np.cumsum(sampler)
sampler[-1] = 1.0
table = []
st = 0; step = 1.0/self.table_size
table.append(st)
for i in range(1,self.table_size+1):
while i*step>sampler[st]:
st+=1
table.append(st)
return table
def sample(self,target_id:int):
sample = []
for i in range(self.size):
random_number = random.randint(0,self.table_size-1)
id = self.sample_table[random_number]
if id != target_id:
sample.append(id)
if len(sample)==0:
sample.append((target_id+1)%len(self.vocab))
return np.array(sample)
| [
"math.pow",
"math.sqrt",
"random.seed",
"numpy.sum",
"numpy.array",
"numpy.random.seed",
"numpy.cumsum",
"random.random",
"random.randint"
] | [((234, 249), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (245, 249), False, 'import random\n'), ((258, 276), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (272, 276), True, 'import numpy as np\n'), ((1346, 1361), 'numpy.sum', 'np.sum', (['sampler'], {}), '(sampler)\n', (1352, 1361), True, 'import numpy as np\n'), ((1415, 1433), 'numpy.cumsum', 'np.cumsum', (['sampler'], {}), '(sampler)\n', (1424, 1433), True, 'import numpy as np\n'), ((2072, 2088), 'numpy.array', 'np.array', (['sample'], {}), '(sample)\n', (2080, 2088), True, 'import numpy as np\n'), ((1101, 1117), 'numpy.array', 'np.array', (['sifter'], {}), '(sifter)\n', (1109, 1117), True, 'import numpy as np\n'), ((1822, 1860), 'random.randint', 'random.randint', (['(0)', '(self.table_size - 1)'], {}), '(0, self.table_size - 1)\n', (1836, 1860), False, 'import random\n'), ((937, 952), 'random.random', 'random.random', ([], {}), '()\n', (950, 952), False, 'import random\n'), ((780, 808), 'math.sqrt', 'sqrt', (['(self.subsample_thr / x)'], {}), '(self.subsample_thr / x)\n', (784, 808), False, 'from math import pow, sqrt\n'), ((1201, 1214), 'math.pow', 'pow', (['x', 'alpha'], {}), '(x, alpha)\n', (1204, 1214), False, 'from math import pow, sqrt\n'), ((1288, 1304), 'math.pow', 'pow', (['x[1]', 'alpha'], {}), '(x[1], alpha)\n', (1291, 1304), False, 'from math import pow, sqrt\n')] |
import os
import shutil
import unittest
import matrix_io
import numpy
import scipy
import scipy.io
class TestMatrixIO(unittest.TestCase):
TEMP_DIR_NAME = 'tmp'
@classmethod
def setUpClass(cls):
shutil.rmtree(cls.TEMP_DIR_NAME, ignore_errors=True)
os.makedirs(cls.TEMP_DIR_NAME)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.TEMP_DIR_NAME, ignore_errors=True)
def test_dense_float64(self):
matrix_filename = "test_dense_float64.ddm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_dense_float64(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_dense_float64(matrix_relative_path)
self.assertTrue(numpy.array_equal(actual_matrix, expected_matrix))
def test_sparse_float64(self):
matrix_filename = "test_sparse_float64.sdm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = scipy.sparse.rand(10, 20, 0.5)
matrix_io.write_sparse_float64(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_sparse_float64(matrix_relative_path)
self.assertTrue((expected_matrix != actual_matrix).nnz == 0)
def test_sparse_binary_matrix(self):
matrix_filename = "test_sparse_binary_matrix.sbm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_dense_matrix = numpy.random.randint(0, 2, size=(10, 20))
expected_sparse_matrix = scipy.sparse.coo_matrix(expected_dense_matrix)
matrix_io.write_sparse_binary_matrix(matrix_relative_path, expected_sparse_matrix)
actual_matrix = matrix_io.read_sparse_binary_matrix(matrix_relative_path)
self.assertTrue((expected_sparse_matrix != actual_matrix).nnz == 0)
def test_dense_float64_matrix_as_tensor(self):
matrix_filename = "test_dense_float64_matrix_as_tensor.ddt"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_dense_float64_matrix_as_tensor(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_dense_float64_tensor_as_matrix(matrix_relative_path)
self.assertTrue(numpy.array_equal(actual_matrix, expected_matrix))
def test_sparse_float64_matrix_as_tensor(self):
matrix_filename = "test_sparse_float64_matrix_as_tensor.sdt"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = scipy.sparse.rand(10, 20, 0.5)
matrix_io.write_sparse_float64_matrix_as_tensor(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_sparse_float64_tensor_as_matrix(matrix_relative_path)
self.assertTrue((expected_matrix != actual_matrix).nnz == 0)
def test_csv(self):
matrix_filename = "test_csv.csv"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_csv(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_csv(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_dense_mtx(self):
matrix_filename = "test_dense_mtx.mtx"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.my_mmwrite(matrix_relative_path, expected_matrix)
actual_matrix = scipy.io.mmread(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_sparse_mtx(self):
matrix_filename = "test_sparse_mtx.mtx"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = scipy.sparse.rand(10, 20, 0.5)
matrix_io.my_mmwrite(matrix_relative_path, expected_matrix)
actual_matrix = scipy.io.mmread(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix.todense(), expected_matrix.todense()))
def test_matrix_ddm(self):
matrix_filename = "test_matrix_ddt.ddm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_matrix(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.array_equal(actual_matrix, expected_matrix))
def test_matrix_sdm(self):
matrix_filename = "test_matrix_sdm.sdm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = scipy.sparse.rand(10, 20, 0.5)
matrix_io.write_matrix(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue((expected_matrix != actual_matrix).nnz == 0)
def test_matrix_sbm(self):
matrix_filename = "test_matrix_sbm.sbm"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_dense_matrix = numpy.random.randint(0, 2, size=(10, 20))
expected_sparse_matrix = scipy.sparse.coo_matrix(expected_dense_matrix)
matrix_io.write_matrix(matrix_relative_path, expected_sparse_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue((expected_sparse_matrix != actual_matrix).nnz == 0)
def test_dense_matrix_mtx(self):
matrix_filename = "test_dense_matrix_mtx.mtx"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_matrix(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_matrix_sparse_mtx(self):
matrix_filename = "test_matrix_sparse_mtx.mtx"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = scipy.sparse.rand(10, 20, 0.5)
matrix_io.write_matrix(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix.todense(), expected_matrix.todense()))
def test_dense_matrix_csv(self):
matrix_filename = "test_dense_matrix_csv.csv"
matrix_relative_path = "{}/{}".format(self.TEMP_DIR_NAME, matrix_filename)
expected_matrix = numpy.random.randn(10, 20)
matrix_io.write_matrix(matrix_relative_path, expected_matrix)
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_read_cpp_generated_dense_matrix_ddm(self):
matrix_relative_path = "test_data/cpp_generated_dense_matrix.ddm"
expected_matrix = numpy.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_read_cpp_generated_dense_matrix_mtx(self):
matrix_relative_path = "test_data/cpp_generated_dense_matrix.mtx"
expected_matrix = numpy.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_read_cpp_generated_dense_matrix_csv(self):
matrix_relative_path = "test_data/cpp_generated_dense_matrix.csv"
expected_matrix = numpy.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix, expected_matrix))
def test_read_cpp_generated_sparse_matrix_sdm(self):
matrix_relative_path = "test_data/cpp_generated_sparse_matrix.sdm"
expected_matrix_rows = numpy.array([0, 0, 0, 0, 2, 2, 2, 2])
expected_matrix_cols = numpy.array([0, 1, 2, 3, 0, 1, 2, 3])
expected_matrix_vals = numpy.array([1, 2, 3, 4, 9, 10, 11, 12])
expected_matrix = scipy.sparse.coo_matrix((expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols)), shape=(3, 4))
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix.todense(), expected_matrix.todense()))
def test_read_cpp_generated_sparse_matrix_sbm(self):
matrix_relative_path = "test_data/cpp_generated_sparse_matrix.sbm"
expected_matrix_rows = numpy.array([0, 0, 0, 0, 2, 2, 2, 2])
expected_matrix_cols = numpy.array([0, 1, 2, 3, 0, 1, 2, 3])
expected_matrix_vals = numpy.array([1, 1, 1, 1, 1, 1, 1, 1])
expected_matrix = scipy.sparse.coo_matrix((expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols)), shape=(3, 4))
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix.todense(), expected_matrix.todense()))
def test_read_cpp_generated_sparse_matrix_mtx(self):
matrix_relative_path = "test_data/cpp_generated_sparse_matrix.mtx"
expected_matrix_rows = numpy.array([0, 0, 0, 0, 2, 2, 2, 2])
expected_matrix_cols = numpy.array([0, 1, 2, 3, 0, 1, 2, 3])
expected_matrix_vals = numpy.array([1, 2, 3, 4, 9, 10, 11, 12])
expected_matrix = scipy.sparse.coo_matrix((expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols)), shape=(3, 4))
actual_matrix = matrix_io.read_matrix(matrix_relative_path)
self.assertTrue(numpy.allclose(actual_matrix.todense(), expected_matrix.todense()))
if __name__ == '__main__':
unittest.main()
| [
"matrix_io.write_csv",
"scipy.sparse.rand",
"matrix_io.write_sparse_binary_matrix",
"matrix_io.write_matrix",
"matrix_io.read_matrix",
"numpy.array",
"unittest.main",
"matrix_io.read_dense_float64",
"matrix_io.write_dense_float64_matrix_as_tensor",
"matrix_io.read_csv",
"matrix_io.read_dense_flo... | [((10217, 10232), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10230, 10232), False, 'import unittest\n'), ((217, 269), 'shutil.rmtree', 'shutil.rmtree', (['cls.TEMP_DIR_NAME'], {'ignore_errors': '(True)'}), '(cls.TEMP_DIR_NAME, ignore_errors=True)\n', (230, 269), False, 'import shutil\n'), ((278, 308), 'os.makedirs', 'os.makedirs', (['cls.TEMP_DIR_NAME'], {}), '(cls.TEMP_DIR_NAME)\n', (289, 308), False, 'import os\n'), ((363, 415), 'shutil.rmtree', 'shutil.rmtree', (['cls.TEMP_DIR_NAME'], {'ignore_errors': '(True)'}), '(cls.TEMP_DIR_NAME, ignore_errors=True)\n', (376, 415), False, 'import shutil\n'), ((611, 637), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (629, 637), False, 'import numpy\n'), ((646, 714), 'matrix_io.write_dense_float64', 'matrix_io.write_dense_float64', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (675, 714), False, 'import matrix_io\n'), ((739, 789), 'matrix_io.read_dense_float64', 'matrix_io.read_dense_float64', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (767, 789), False, 'import matrix_io\n'), ((1062, 1092), 'scipy.sparse.rand', 'scipy.sparse.rand', (['(10)', '(20)', '(0.5)'], {}), '(10, 20, 0.5)\n', (1079, 1092), False, 'import scipy\n'), ((1101, 1170), 'matrix_io.write_sparse_float64', 'matrix_io.write_sparse_float64', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (1131, 1170), False, 'import matrix_io\n'), ((1195, 1246), 'matrix_io.read_sparse_float64', 'matrix_io.read_sparse_float64', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (1224, 1246), False, 'import matrix_io\n'), ((1531, 1572), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(2)'], {'size': '(10, 20)'}), '(0, 2, size=(10, 20))\n', (1551, 1572), False, 'import numpy\n'), ((1606, 1652), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['expected_dense_matrix'], {}), '(expected_dense_matrix)\n', (1629, 1652), False, 'import scipy\n'), ((1661, 1747), 'matrix_io.write_sparse_binary_matrix', 'matrix_io.write_sparse_binary_matrix', (['matrix_relative_path', 'expected_sparse_matrix'], {}), '(matrix_relative_path,\n expected_sparse_matrix)\n', (1697, 1747), False, 'import matrix_io\n'), ((1768, 1825), 'matrix_io.read_sparse_binary_matrix', 'matrix_io.read_sparse_binary_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (1803, 1825), False, 'import matrix_io\n'), ((2131, 2157), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (2149, 2157), False, 'import numpy\n'), ((2166, 2255), 'matrix_io.write_dense_float64_matrix_as_tensor', 'matrix_io.write_dense_float64_matrix_as_tensor', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path,\n expected_matrix)\n', (2212, 2255), False, 'import matrix_io\n'), ((2276, 2343), 'matrix_io.read_dense_float64_tensor_as_matrix', 'matrix_io.read_dense_float64_tensor_as_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (2321, 2343), False, 'import matrix_io\n'), ((2650, 2680), 'scipy.sparse.rand', 'scipy.sparse.rand', (['(10)', '(20)', '(0.5)'], {}), '(10, 20, 0.5)\n', (2667, 2680), False, 'import scipy\n'), ((2689, 2779), 'matrix_io.write_sparse_float64_matrix_as_tensor', 'matrix_io.write_sparse_float64_matrix_as_tensor', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path,\n expected_matrix)\n', (2736, 2779), False, 'import matrix_io\n'), ((2800, 2868), 'matrix_io.read_sparse_float64_tensor_as_matrix', 'matrix_io.read_sparse_float64_tensor_as_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (2846, 2868), False, 'import matrix_io\n'), ((3113, 3139), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (3131, 3139), False, 'import numpy\n'), ((3148, 3206), 'matrix_io.write_csv', 'matrix_io.write_csv', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (3167, 3206), False, 'import matrix_io\n'), ((3231, 3271), 'matrix_io.read_csv', 'matrix_io.read_csv', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (3249, 3271), False, 'import matrix_io\n'), ((3531, 3557), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (3549, 3557), False, 'import numpy\n'), ((3566, 3625), 'matrix_io.my_mmwrite', 'matrix_io.my_mmwrite', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (3586, 3625), False, 'import matrix_io\n'), ((3650, 3687), 'scipy.io.mmread', 'scipy.io.mmread', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (3665, 3687), False, 'import scipy\n'), ((3949, 3979), 'scipy.sparse.rand', 'scipy.sparse.rand', (['(10)', '(20)', '(0.5)'], {}), '(10, 20, 0.5)\n', (3966, 3979), False, 'import scipy\n'), ((3988, 4047), 'matrix_io.my_mmwrite', 'matrix_io.my_mmwrite', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (4008, 4047), False, 'import matrix_io\n'), ((4072, 4109), 'scipy.io.mmread', 'scipy.io.mmread', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (4087, 4109), False, 'import scipy\n'), ((4391, 4417), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (4409, 4417), False, 'import numpy\n'), ((4426, 4487), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (4448, 4487), False, 'import matrix_io\n'), ((4512, 4555), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (4533, 4555), False, 'import matrix_io\n'), ((4820, 4850), 'scipy.sparse.rand', 'scipy.sparse.rand', (['(10)', '(20)', '(0.5)'], {}), '(10, 20, 0.5)\n', (4837, 4850), False, 'import scipy\n'), ((4859, 4920), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (4881, 4920), False, 'import matrix_io\n'), ((4945, 4988), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (4966, 4988), False, 'import matrix_io\n'), ((5253, 5294), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(2)'], {'size': '(10, 20)'}), '(0, 2, size=(10, 20))\n', (5273, 5294), False, 'import numpy\n'), ((5328, 5374), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['expected_dense_matrix'], {}), '(expected_dense_matrix)\n', (5351, 5374), False, 'import scipy\n'), ((5383, 5451), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_sparse_matrix'], {}), '(matrix_relative_path, expected_sparse_matrix)\n', (5405, 5451), False, 'import matrix_io\n'), ((5476, 5519), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (5497, 5519), False, 'import matrix_io\n'), ((5797, 5823), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (5815, 5823), False, 'import numpy\n'), ((5832, 5893), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (5854, 5893), False, 'import matrix_io\n'), ((5918, 5961), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (5939, 5961), False, 'import matrix_io\n'), ((6237, 6267), 'scipy.sparse.rand', 'scipy.sparse.rand', (['(10)', '(20)', '(0.5)'], {}), '(10, 20, 0.5)\n', (6254, 6267), False, 'import scipy\n'), ((6276, 6337), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (6298, 6337), False, 'import matrix_io\n'), ((6362, 6405), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (6383, 6405), False, 'import matrix_io\n'), ((6699, 6725), 'numpy.random.randn', 'numpy.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (6717, 6725), False, 'import numpy\n'), ((6734, 6795), 'matrix_io.write_matrix', 'matrix_io.write_matrix', (['matrix_relative_path', 'expected_matrix'], {}), '(matrix_relative_path, expected_matrix)\n', (6756, 6795), False, 'import matrix_io\n'), ((6820, 6863), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (6841, 6863), False, 'import matrix_io\n'), ((7093, 7151), 'numpy.array', 'numpy.array', (['[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]'], {}), '([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n', (7104, 7151), False, 'import numpy\n'), ((7260, 7303), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (7281, 7303), False, 'import matrix_io\n'), ((7533, 7591), 'numpy.array', 'numpy.array', (['[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]'], {}), '([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n', (7544, 7591), False, 'import numpy\n'), ((7700, 7743), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (7721, 7743), False, 'import matrix_io\n'), ((7973, 8031), 'numpy.array', 'numpy.array', (['[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]'], {}), '([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n', (7984, 8031), False, 'import numpy\n'), ((8140, 8183), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (8161, 8183), False, 'import matrix_io\n'), ((8421, 8458), 'numpy.array', 'numpy.array', (['[0, 0, 0, 0, 2, 2, 2, 2]'], {}), '([0, 0, 0, 0, 2, 2, 2, 2])\n', (8432, 8458), False, 'import numpy\n'), ((8494, 8531), 'numpy.array', 'numpy.array', (['[0, 1, 2, 3, 0, 1, 2, 3]'], {}), '([0, 1, 2, 3, 0, 1, 2, 3])\n', (8505, 8531), False, 'import numpy\n'), ((8567, 8607), 'numpy.array', 'numpy.array', (['[1, 2, 3, 4, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 9, 10, 11, 12])\n', (8578, 8607), False, 'import numpy\n'), ((8634, 8745), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['(expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols))'], {'shape': '(3, 4)'}), '((expected_matrix_vals, (expected_matrix_rows,\n expected_matrix_cols)), shape=(3, 4))\n', (8657, 8745), False, 'import scipy\n'), ((8766, 8809), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (8787, 8809), False, 'import matrix_io\n'), ((9067, 9104), 'numpy.array', 'numpy.array', (['[0, 0, 0, 0, 2, 2, 2, 2]'], {}), '([0, 0, 0, 0, 2, 2, 2, 2])\n', (9078, 9104), False, 'import numpy\n'), ((9137, 9174), 'numpy.array', 'numpy.array', (['[0, 1, 2, 3, 0, 1, 2, 3]'], {}), '([0, 1, 2, 3, 0, 1, 2, 3])\n', (9148, 9174), False, 'import numpy\n'), ((9207, 9244), 'numpy.array', 'numpy.array', (['[1, 1, 1, 1, 1, 1, 1, 1]'], {}), '([1, 1, 1, 1, 1, 1, 1, 1])\n', (9218, 9244), False, 'import numpy\n'), ((9271, 9382), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['(expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols))'], {'shape': '(3, 4)'}), '((expected_matrix_vals, (expected_matrix_rows,\n expected_matrix_cols)), shape=(3, 4))\n', (9294, 9382), False, 'import scipy\n'), ((9403, 9446), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (9424, 9446), False, 'import matrix_io\n'), ((9704, 9741), 'numpy.array', 'numpy.array', (['[0, 0, 0, 0, 2, 2, 2, 2]'], {}), '([0, 0, 0, 0, 2, 2, 2, 2])\n', (9715, 9741), False, 'import numpy\n'), ((9777, 9814), 'numpy.array', 'numpy.array', (['[0, 1, 2, 3, 0, 1, 2, 3]'], {}), '([0, 1, 2, 3, 0, 1, 2, 3])\n', (9788, 9814), False, 'import numpy\n'), ((9850, 9890), 'numpy.array', 'numpy.array', (['[1, 2, 3, 4, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 9, 10, 11, 12])\n', (9861, 9890), False, 'import numpy\n'), ((9917, 10028), 'scipy.sparse.coo_matrix', 'scipy.sparse.coo_matrix', (['(expected_matrix_vals, (expected_matrix_rows, expected_matrix_cols))'], {'shape': '(3, 4)'}), '((expected_matrix_vals, (expected_matrix_rows,\n expected_matrix_cols)), shape=(3, 4))\n', (9940, 10028), False, 'import scipy\n'), ((10049, 10092), 'matrix_io.read_matrix', 'matrix_io.read_matrix', (['matrix_relative_path'], {}), '(matrix_relative_path)\n', (10070, 10092), False, 'import matrix_io\n'), ((814, 863), 'numpy.array_equal', 'numpy.array_equal', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (831, 863), False, 'import numpy\n'), ((2368, 2417), 'numpy.array_equal', 'numpy.array_equal', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (2385, 2417), False, 'import numpy\n'), ((3296, 3342), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (3310, 3342), False, 'import numpy\n'), ((3712, 3758), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (3726, 3758), False, 'import numpy\n'), ((4580, 4629), 'numpy.array_equal', 'numpy.array_equal', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (4597, 4629), False, 'import numpy\n'), ((5986, 6032), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (6000, 6032), False, 'import numpy\n'), ((6888, 6934), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (6902, 6934), False, 'import numpy\n'), ((7328, 7374), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (7342, 7374), False, 'import numpy\n'), ((7768, 7814), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (7782, 7814), False, 'import numpy\n'), ((8208, 8254), 'numpy.allclose', 'numpy.allclose', (['actual_matrix', 'expected_matrix'], {}), '(actual_matrix, expected_matrix)\n', (8222, 8254), False, 'import numpy\n')] |
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
from matplotlib import rc
rc('font',**{'family':'serif','serif':'Computer Modern Roman','size':12})
rc('text', usetex=True)
import numpy as np
import os as os
import pylab as plt
def drawblock(x, y, size, label):
px = x + size * np.array([0., 1., 1., 0., 0.])
py = y + size * np.array([0., 0., 1., 1., 0.])
plt.plot(px, py, 'k-', lw=3.)
plt.text(x + 0.5 * size, y + 0.5 * size, label,
horizontalalignment='center',
verticalalignment='center')
return None
def stringblocks(fn):
plt.figure(figsize=(4, 0.75))
xo, yo = 0.15, 0.20
plt.axes([0., 0., 1., 1.])
tiny = -0.06
plt.plot([-1., 7.], [tiny, tiny], 'k-', lw=3.)
drawblock(0., 0., 1., '$m_1$')
drawblock(4., 0., 1., '$m_2$')
plt.plot([1., 4.], [0.5, 0.5], 'k-', lw=2.)
plt.text(2.5, 0.6, '$T$', ha='center')
plt.gca().add_patch(plt.Arrow(5., 0.5, 1., 0., facecolor='k',
edgecolor='none', alpha=0.5))
plt.text(6.1, 0.5, '$F$', ha='left', va='center')
plt.axis('equal')
plt.axis('off')
plt.savefig(fn)
return None
if __name__ == '__main__':
fn = 'stringblocks.pdf'
stringblocks(fn)
| [
"pylab.axis",
"pylab.axes",
"matplotlib.use",
"pylab.plot",
"pylab.savefig",
"pylab.figure",
"numpy.array",
"matplotlib.rc",
"pylab.text",
"pylab.Arrow",
"pylab.gca"
] | [((53, 74), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (67, 74), False, 'import matplotlib\n'), ((109, 188), 'matplotlib.rc', 'rc', (['"""font"""'], {}), "('font', **{'family': 'serif', 'serif': 'Computer Modern Roman', 'size': 12})\n", (111, 188), False, 'from matplotlib import rc\n'), ((187, 210), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (189, 210), False, 'from matplotlib import rc\n'), ((407, 437), 'pylab.plot', 'plt.plot', (['px', 'py', '"""k-"""'], {'lw': '(3.0)'}), "(px, py, 'k-', lw=3.0)\n", (415, 437), True, 'import pylab as plt\n'), ((441, 551), 'pylab.text', 'plt.text', (['(x + 0.5 * size)', '(y + 0.5 * size)', 'label'], {'horizontalalignment': '"""center"""', 'verticalalignment': '"""center"""'}), "(x + 0.5 * size, y + 0.5 * size, label, horizontalalignment=\n 'center', verticalalignment='center')\n", (449, 551), True, 'import pylab as plt\n'), ((616, 645), 'pylab.figure', 'plt.figure', ([], {'figsize': '(4, 0.75)'}), '(figsize=(4, 0.75))\n', (626, 645), True, 'import pylab as plt\n'), ((674, 704), 'pylab.axes', 'plt.axes', (['[0.0, 0.0, 1.0, 1.0]'], {}), '([0.0, 0.0, 1.0, 1.0])\n', (682, 704), True, 'import pylab as plt\n'), ((722, 771), 'pylab.plot', 'plt.plot', (['[-1.0, 7.0]', '[tiny, tiny]', '"""k-"""'], {'lw': '(3.0)'}), "([-1.0, 7.0], [tiny, tiny], 'k-', lw=3.0)\n", (730, 771), True, 'import pylab as plt\n'), ((843, 889), 'pylab.plot', 'plt.plot', (['[1.0, 4.0]', '[0.5, 0.5]', '"""k-"""'], {'lw': '(2.0)'}), "([1.0, 4.0], [0.5, 0.5], 'k-', lw=2.0)\n", (851, 889), True, 'import pylab as plt\n'), ((891, 929), 'pylab.text', 'plt.text', (['(2.5)', '(0.6)', '"""$T$"""'], {'ha': '"""center"""'}), "(2.5, 0.6, '$T$', ha='center')\n", (899, 929), True, 'import pylab as plt\n'), ((1064, 1113), 'pylab.text', 'plt.text', (['(6.1)', '(0.5)', '"""$F$"""'], {'ha': '"""left"""', 'va': '"""center"""'}), "(6.1, 0.5, '$F$', ha='left', va='center')\n", (1072, 1113), True, 'import pylab as plt\n'), ((1118, 1135), 'pylab.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (1126, 1135), True, 'import pylab as plt\n'), ((1140, 1155), 'pylab.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1148, 1155), True, 'import pylab as plt\n'), ((1160, 1175), 'pylab.savefig', 'plt.savefig', (['fn'], {}), '(fn)\n', (1171, 1175), True, 'import pylab as plt\n'), ((954, 1027), 'pylab.Arrow', 'plt.Arrow', (['(5.0)', '(0.5)', '(1.0)', '(0.0)'], {'facecolor': '"""k"""', 'edgecolor': '"""none"""', 'alpha': '(0.5)'}), "(5.0, 0.5, 1.0, 0.0, facecolor='k', edgecolor='none', alpha=0.5)\n", (963, 1027), True, 'import pylab as plt\n'), ((321, 356), 'numpy.array', 'np.array', (['[0.0, 1.0, 1.0, 0.0, 0.0]'], {}), '([0.0, 1.0, 1.0, 0.0, 0.0])\n', (329, 356), True, 'import numpy as np\n'), ((372, 407), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0, 1.0, 0.0]'], {}), '([0.0, 0.0, 1.0, 1.0, 0.0])\n', (380, 407), True, 'import numpy as np\n'), ((934, 943), 'pylab.gca', 'plt.gca', ([], {}), '()\n', (941, 943), True, 'import pylab as plt\n')] |
# Copyright (c) 2020 Spanish National Research Council
#
# 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 datetime
from multiprocessing.pool import ThreadPool
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
from utils import PATHS
from download import install
# Install xlrd >= 1.0.0 for Excel support
install('xlrd')
cant_popul = 581078
def fix_1207():
"""
Fix error in mobility dataset of Spain from INE (Instituto Nacional de Estadística).
"""
rawdir = PATHS.rawdir / 'maestra1' / 'municipios'
src = rawdir / '20200705_maestra_1_mitma_municipio.txt.gz'
dst = rawdir / '20200712_maestra_1_mitma_municipio.txt.gz'
df = pd.read_csv(src,
sep='|',
thousands='.',
dtype={'origen': 'string', 'destino': 'string'},
compression='gzip')
# Replace date
df['fecha'] = '20200712'
# Apply thousands separator
def add_sep(x):
x = str(x)
if len(x) > 3:
return f'{str(x)[:-3]}.{str(x)[-3:]}'
else:
return x
df['viajes'] = df['viajes'].apply(add_sep)
df['viajes_km'] = df['viajes_km'].apply(add_sep)
df.to_csv(dst,
sep='|',
compression='gzip',
index=False)
def process_day(tarfile):
"""
Process daily mobility files from INE.
Args:
tarfile [str, DataFrame]: Absolute path of mobility file.
Returns: Mobility dataframe.
"""
try:
df = pd.read_csv(tarfile,
sep='|',
thousands='.',
dtype={'origen': 'string', 'destino': 'string'},
compression='gzip')
except Exception as e:
print(f'Error processing {tarfile}')
raise Exception(e)
df['fecha'] = pd.to_datetime(df.fecha, format='%Y%m%d')
df['fecha'] = df['fecha'].dt.date
# Aggregate data inside same province
df['origen'] = df['origen'].transform(lambda x: x[:2])
df['destino'] = df['destino'].transform(lambda x: x[:2])
# Aggregate across hours and distances
df = df.groupby(['fecha', 'origen', 'destino']).sum().reset_index()
df = df.drop(['periodo', 'viajes_km'], 'columns')
return df
def process_mobility(day_files='all',
exp='maestra1',
res='municipios',
update=False,
force=False):
"""
Process daily mobility data. If 'all' is passed, it will process every file.
Args:
day_files [list, str]: List of absolute paths to day-tars to process.
exp: Folder.
res: Folder inside exp.
update: Update the data as of today's date
force: To overwrite already downloaded data
Returns: DataFrame of mobility flow data between autonomous communities in Spain.
"""
# Prepare files
rawdir = PATHS.rawdir / f'{exp}' / f'{res}'
if day_files == 'all':
day_files = sorted(os.listdir(rawdir))
day_files = [rawdir / d for d in day_files]
if not day_files:
day_files = sorted(day_files)
# Load INE code_map to add names to the tables
cod_path = PATHS.rawdir / f'{exp}' / '20_cod_prov.xls'
cod_map = pd.read_excel(cod_path, skiprows=4, names=['codigo', 'literal'], dtype={'codigo': str})
cod_map = dict(zip(cod_map.codigo, cod_map.literal))
# Load existing files
if update and (PATHS.processed / f'{exp}' / "province_flux.csv").exists():
previous_df = pd.read_csv(PATHS.processed / f'{exp}' / "province_flux.csv")
# Compare dates
last = datetime.datetime.strptime(previous_df['date'].iloc[-1], '%Y-%m-%d')
first = datetime.datetime.strptime(day_files[0].name[:8], '%Y%m%d')
if last + datetime.timedelta(days=1) != first and not force:
raise Exception(f'The last day ({last.date()}) saved and the first day ({first.date()}) '
'of the update are not consecutive. '
'You will probably be safer rerunning the download '
'and running the whole processing from scratch (update=False). '
'You can use force=True if you want to append the data '
'nevertheless.')
else:
previous_df = pd.DataFrame([])
# Parallelize the processing for speed
print('Processing mobility data...')
thread_num = 4
results = []
out = ThreadPool(thread_num).imap(process_day, day_files)
for r in tqdm(out, total=len(day_files)):
results.append(r)
full_df = pd.concat(results).reset_index()
# Clean and add id codes
full_df = full_df.rename(columns={'fecha': 'date',
'origen': 'province id origin',
'destino': 'province id destination',
'viajes': 'flux'})
full_df['province origin'] = full_df['province id origin'].map(cod_map)
full_df['province destination'] = full_df['province id destination'].map(cod_map)
full_df = full_df[['date', 'province origin', 'province id origin',
'province destination', 'province id destination', 'flux']]
dates_format = np.repeat("%Y/%m/%d", len(full_df.index), axis=0)
full_df['date'] = list(map(datetime.datetime.strftime, full_df['date'], dates_format))
# Append and save
full_df = pd.concat([previous_df, full_df])
save_path = PATHS.processed / f'{exp}'
save_path.exists() or os.makedirs(save_path)
full_df.to_csv(f'{save_path}/province_flux.csv', index=False)
return full_df
def process_sc(*argv):
"""
Process historical covid-19 file of Cantabria (Spain) from Cantabrian Health Service.
Args:
argv [DataFrame]: DataFrame to process. If nothing is passed, it will process from default folder.
Returns: DataFrame processed.
"""
fpath = PATHS.rawdir / 'covid' / 'region' / 'historical_cantb.csv'
save_path = PATHS.processed / 'covid' / 'region' / 'historical_cantb.csv'
try:
try:
df = argv[0]
except Exception as e:
df = pd.read_csv(fpath, sep=',')
df = df.fillna(0)
df.drop(['% CRECIMIENTO COVID*',
'CASOS RESIDENCIAS',
'C. RESID. ACTIVOS',
'PROF. SANITARIOS',
'P. SANIT. ACTIVOS',
'HOSP. VALDECILLA',
'HOSP. LIENCRES',
'HOSP. LAREDO',
'HOSP. SIERRALLANA',
'HOSP. TRES MARES',
'UCI HUMV',
'UCI SIERRALLANA',
'TEST*100.000 HAB.',
'TEST PCR',
'TEST*100.000 HAB..1',
'TEST ANTICUERPOS',
'TEST*100.000 HAB..2',
'TEST ANTICUERPOS +',
'TEST ANTIGENOS',
'TEST*100.000 HAB..3',
'TEST ANTIGENOS +',
'INCIDENCIA AC 14',
'CASOS 7 DIAS',
'CASOS 14 DIAS'],
axis='columns', inplace=True)
df = df.rename(columns={'FECHA': 'date',
'TOTAL CASOS': 'cumulative_cases',
'CASOS NUEVOS PCR*': 'daily_cases',
'% MEDIA MOVIL 7 DIÂAS*': 'moving_average_7',
'TOTAL HOSPITALIZADOS': 'hospital_occ',
'HOSPITALIZADOS UCI': 'icu_occ',
'FALLECIDOS': 'cumulative_deaths',
'TOTAL TEST': 'cumulative_total_tests'})
# New variables
# daily deaths
df['daily_deaths'] = df['cumulative_deaths'].fillna(0).diff()
# daily occupancy of hospital beds
newhosp = df['hospital_occ'].fillna(0).diff()
newhosp[newhosp < 0] = 0
df['new_hospital_cases'] = newhosp
# daily occupancy of ICU beds
newicu = df['icu_occ'].fillna(0).diff()
newicu[newicu < 0] = 0
df['new_icu_cases'] = newicu
# daily total tests
df['daily_total_tests'] = df['cumulative_total_tests'].fillna(0).diff()
# total cases in 7 and 14 days
cases7 = df['cumulative_cases'].to_numpy()[7:] - df['cumulative_cases'].to_numpy()[:-7]
df['cases7'] = np.append(np.repeat(0, 7), cases7)
cases14 = df['cumulative_cases'].to_numpy()[14:] - df['cumulative_cases'].to_numpy()[:-14]
df['cases14'] = np.append(np.repeat(0, 14), cases14)
# cumulative incidence in 7 and 14 days
df['incidence7'] = df['cases7'] * 100000 / cant_popul
df['incidence7'] = df['incidence7'].apply(np.ceil)
df['incidence14'] = df['cases14'] * 100000 / cant_popul
df['incidence14'] = df['incidence14'].apply(np.ceil)
# Fix some issues
df = df.fillna(0)
df.iloc[:, 1:] = df.iloc[:, 1:].apply(np.int64)
# daily positivity
df['daily_positivity'] = df['daily_cases'] / df['daily_total_tests']
df['daily_positivity'] = df['daily_positivity'].fillna(0)
df.loc[0, 'daily_positivity'] = 0
# Save
df.to_csv(f'{save_path}', index=False, header=True)
return df
except Exception as e:
print(f'Error processing {fpath}')
raise Exception(e)
def process_icane(*argv):
"""
Process covid-19 file of Cantabria (Spain) from ICANE.
Args:
argv [DataFrame]: DataFrame to process. If nothing is passed, it will process from default folder.
Returns: DataFrame processed.
"""
fpath = PATHS.rawdir / 'covid' / 'region' / 'all_data_cantb.csv'
save_path = PATHS.processed / 'covid' / 'region' / 'all_data_cantb.csv'
try:
try:
df = argv[0]
except Exception as e:
df = pd.read_csv(fpath, sep=',').copy()
# New variables and names
df = df.fillna(0)
df['hospital_occ'] = df[['Laredo', 'Liencres', 'Sierrallana', 'Tres Mares', 'Valdecilla']].sum(axis=1)
df['daily_total_tests'] = df[['Test Anticuerpos diarios', 'Test Antigenos diarios',
'Test PCR diarios']].sum(axis=1)
df.drop(['Recuperados',
'Laredo',
'Liencres',
'Sierrallana',
'<NAME>',
'Valdecilla',
'Cuantil 0,025 (R)',
'Cuantil 0,975 (R)',
'Media (R)',
'Dosis entregadas Pfizer (1)',
'Dosis entregadas Moderna (1)',
'Total Dosis entregadas (1)',
'Dosis administradas (2)',
'% sobre entregadas',
'Fecha de la última vacuna registrada (2)',
'Dosis entregadas AstraZeneca (1)',
'Nº Personas con al menos 1 dosis',
'Dosis entregadas Janssen (1)',
'UCI Sierrallana',
'UCI Valdecilla',
'Positividad',
'Incidencia 14 dias'],
axis='columns', inplace=True)
df = df.rename(columns={'Unnamed: 0': 'date',
'Casos': 'daily_cases',
'Casos.1': 'cumulative_cases',
'Fallecidos': 'daily_deaths',
'Fallecidos.1': 'cumulative_deaths',
'UCI': 'icu_occ',
# 'Positividad': 'positivity',
'Nº Personas vacunadas(pauta completada)': 'vaccinated_pp',
'Test Anticuerpos diarios': 'daily_antibody_tests',
'Test Antigenos diarios': 'daily_antigen_tests',
'Test PCR diarios': 'daily_pcr_tests'})
# New variables
# total cases in 7 and 14 days
cases7 = df['cumulative_cases'].to_numpy()[7:] - df['cumulative_cases'].to_numpy()[:-7]
df['cases7'] = np.append(np.repeat(0, 7), cases7)
cases14 = df['cumulative_cases'].to_numpy()[14:] - df['cumulative_cases'].to_numpy()[:-14]
df['cases14'] = np.append(np.repeat(0, 14), cases14)
# cumulative incidence in 7 and 14 days
df['incidence7'] = df['cases7'] * 100000 / cant_popul
df['incidence7'] = df['incidence7'].apply(np.ceil)
df['incidence14'] = df['cases14'] * 100000 / cant_popul
df['incidence14'] = df['incidence14'].apply(np.ceil)
# daily occupancy of hospital beds
newhosp = df['hospital_occ'].fillna(0).diff()
newhosp[newhosp < 0] = 0
df['new_hospital_cases'] = newhosp
# daily occupancy of ICU beds
newicu = df['icu_occ'].fillna(0).diff()
newicu[newicu < 0] = 0
df['new_icu_cases'] = newicu
# Fix some empty value errors
df.iloc[0, 1] = 1.0
df = df.fillna(0)
df.iloc[:, 1:] = df.iloc[:, 1:].apply(np.int64)
# daily positivity
df['daily_positivity'] = df['daily_cases'] / df['daily_total_tests']
df['daily_positivity'] = df['daily_positivity'].fillna(0)
df.loc[0, 'daily_positivity'] = 0
# Save
df.to_csv(f'{save_path}', index=False, header=True)
return df
except Exception as e:
print(f'Error processing {fpath}')
print(e)
raise Exception(e)
# TODO: Process covid-19 data of the municipalities.
if __name__ == '__main__':
# process_mobility(day_files='all',
# exp='maestra1',
# res='municipios',
# update=False,
# force=False)
process_sc()
process_icane()
| [
"download.install",
"os.listdir",
"numpy.repeat",
"pandas.read_csv",
"os.makedirs",
"datetime.datetime.strptime",
"multiprocessing.pool.ThreadPool",
"pandas.read_excel",
"pandas.DataFrame",
"datetime.timedelta",
"pandas.concat",
"pandas.to_datetime"
] | [((831, 846), 'download.install', 'install', (['"""xlrd"""'], {}), "('xlrd')\n", (838, 846), False, 'from download import install\n'), ((1183, 1296), 'pandas.read_csv', 'pd.read_csv', (['src'], {'sep': '"""|"""', 'thousands': '"""."""', 'dtype': "{'origen': 'string', 'destino': 'string'}", 'compression': '"""gzip"""'}), "(src, sep='|', thousands='.', dtype={'origen': 'string',\n 'destino': 'string'}, compression='gzip')\n", (1194, 1296), True, 'import pandas as pd\n'), ((2363, 2404), 'pandas.to_datetime', 'pd.to_datetime', (['df.fecha'], {'format': '"""%Y%m%d"""'}), "(df.fecha, format='%Y%m%d')\n", (2377, 2404), True, 'import pandas as pd\n'), ((3788, 3880), 'pandas.read_excel', 'pd.read_excel', (['cod_path'], {'skiprows': '(4)', 'names': "['codigo', 'literal']", 'dtype': "{'codigo': str}"}), "(cod_path, skiprows=4, names=['codigo', 'literal'], dtype={\n 'codigo': str})\n", (3801, 3880), True, 'import pandas as pd\n'), ((6005, 6038), 'pandas.concat', 'pd.concat', (['[previous_df, full_df]'], {}), '([previous_df, full_df])\n', (6014, 6038), True, 'import pandas as pd\n'), ((2031, 2148), 'pandas.read_csv', 'pd.read_csv', (['tarfile'], {'sep': '"""|"""', 'thousands': '"""."""', 'dtype': "{'origen': 'string', 'destino': 'string'}", 'compression': '"""gzip"""'}), "(tarfile, sep='|', thousands='.', dtype={'origen': 'string',\n 'destino': 'string'}, compression='gzip')\n", (2042, 2148), True, 'import pandas as pd\n'), ((4061, 4122), 'pandas.read_csv', 'pd.read_csv', (["(PATHS.processed / f'{exp}' / 'province_flux.csv')"], {}), "(PATHS.processed / f'{exp}' / 'province_flux.csv')\n", (4072, 4122), True, 'import pandas as pd\n'), ((4163, 4231), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["previous_df['date'].iloc[-1]", '"""%Y-%m-%d"""'], {}), "(previous_df['date'].iloc[-1], '%Y-%m-%d')\n", (4189, 4231), False, 'import datetime\n'), ((4248, 4307), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['day_files[0].name[:8]', '"""%Y%m%d"""'], {}), "(day_files[0].name[:8], '%Y%m%d')\n", (4274, 4307), False, 'import datetime\n'), ((4883, 4899), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (4895, 4899), True, 'import pandas as pd\n'), ((6108, 6130), 'os.makedirs', 'os.makedirs', (['save_path'], {}), '(save_path)\n', (6119, 6130), False, 'import os\n'), ((3530, 3548), 'os.listdir', 'os.listdir', (['rawdir'], {}), '(rawdir)\n', (3540, 3548), False, 'import os\n'), ((5031, 5053), 'multiprocessing.pool.ThreadPool', 'ThreadPool', (['thread_num'], {}), '(thread_num)\n', (5041, 5053), False, 'from multiprocessing.pool import ThreadPool\n'), ((5169, 5187), 'pandas.concat', 'pd.concat', (['results'], {}), '(results)\n', (5178, 5187), True, 'import pandas as pd\n'), ((8983, 8998), 'numpy.repeat', 'np.repeat', (['(0)', '(7)'], {}), '(0, 7)\n', (8992, 8998), True, 'import numpy as np\n'), ((9141, 9157), 'numpy.repeat', 'np.repeat', (['(0)', '(14)'], {}), '(0, 14)\n', (9150, 9157), True, 'import numpy as np\n'), ((12700, 12715), 'numpy.repeat', 'np.repeat', (['(0)', '(7)'], {}), '(0, 7)\n', (12709, 12715), True, 'import numpy as np\n'), ((12858, 12874), 'numpy.repeat', 'np.repeat', (['(0)', '(14)'], {}), '(0, 14)\n', (12867, 12874), True, 'import numpy as np\n'), ((6745, 6772), 'pandas.read_csv', 'pd.read_csv', (['fpath'], {'sep': '""","""'}), "(fpath, sep=',')\n", (6756, 6772), True, 'import pandas as pd\n'), ((4327, 4353), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (4345, 4353), False, 'import datetime\n'), ((10473, 10500), 'pandas.read_csv', 'pd.read_csv', (['fpath'], {'sep': '""","""'}), "(fpath, sep=',')\n", (10484, 10500), True, 'import pandas as pd\n')] |
'''
Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights on this computer program.
Using this computer program means that you agree to the terms in the LICENSE file (https://flame.is.tue.mpg.de/modellicense) included
with the FLAME model. Any use not explicitly granted by the LICENSE is prohibited.
Copyright 2020 Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. (MPG). acting on behalf of its
Max Planck Institute for Intelligent Systems. All rights reserved.
More information about FLAME is available at http://flame.is.tue.mpg.de.
For comments or questions, please email us at <EMAIL>
'''
import numpy as np
import chumpy as ch
from os.path import join
from smpl_webuser.serialization import load_model
from fitting.landmarks import load_embedding, landmark_error_3d
from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor
# -----------------------------------------------------------------------------
def fit_lmk3d( lmk_3d, # input landmark 3d
model, # model
lmk_face_idx, lmk_b_coords, # landmark embedding
weights, # weights for the objectives
shape_num=300, expr_num=100, opt_options=None ):
""" function: fit FLAME model to 3D landmarks
input:
lmk_3d: input landmark 3D, in shape (N,3)
model: FLAME face model
lmk_face_idx, lmk_b_coords: landmark embedding, in face indices and barycentric coordinates
weights: weights for each objective
shape_num, expr_num: numbers of shape and expression compoenents used
opt_options: optimizaton options
output:
model.r: fitted result vertices
model.f: fitted result triangulations (fixed in this code)
parms: fitted model parameters
"""
# variables
pose_idx = np.union1d(np.arange(3), np.arange(6,9)) # global rotation and jaw rotation
shape_idx = np.arange( 0, min(300,shape_num) ) # valid shape component range in "betas": 0-299
expr_idx = np.arange( 300, 300+min(100,expr_num) ) # valid expression component range in "betas": 300-399
used_idx = np.union1d( shape_idx, expr_idx )
model.betas[:] = np.random.rand( model.betas.size ) * 0.0 # initialized to zero
model.pose[:] = np.random.rand( model.pose.size ) * 0.0 # initialized to zero
free_variables = [ model.trans, model.pose[pose_idx], model.betas[used_idx] ]
# weights
print("fit_lmk3d(): use the following weights:")
for kk in weights.keys():
print("fit_lmk3d(): weights['%s'] = %f" % ( kk, weights[kk] ))
# objectives
# lmk
lmk_err = landmark_error_3d( mesh_verts=model,
mesh_faces=model.f,
lmk_3d=lmk_3d,
lmk_face_idx=lmk_face_idx,
lmk_b_coords=lmk_b_coords,
weight=weights['lmk'] )
# regularizer
shape_err = weights['shape'] * model.betas[shape_idx]
expr_err = weights['expr'] * model.betas[expr_idx]
pose_err = weights['pose'] * model.pose[3:] # exclude global rotation
objectives = {}
objectives.update( { 'lmk': lmk_err, 'shape': shape_err, 'expr': expr_err, 'pose': pose_err } )
# options
if opt_options is None:
print("fit_lmk3d(): no 'opt_options' provided, use default settings.")
import scipy.sparse as sp
opt_options = {}
opt_options['disp'] = 1
opt_options['delta_0'] = 0.1
opt_options['e_3'] = 1e-4
opt_options['maxiter'] = 2000
sparse_solver = lambda A, x: sp.linalg.cg(A, x, maxiter=opt_options['maxiter'])[0]
opt_options['sparse_solver'] = sparse_solver
# on_step callback
def on_step(_):
pass
# optimize
# step 1: rigid alignment
from time import time
timer_start = time()
print("\nstep 1: start rigid fitting...")
ch.minimize( fun = lmk_err,
x0 = [ model.trans, model.pose[0:3] ],
method = 'dogleg',
callback = on_step,
options = opt_options )
timer_end = time()
print("step 1: fitting done, in %f sec\n" % ( timer_end - timer_start ))
# step 2: non-rigid alignment
timer_start = time()
print("step 2: start non-rigid fitting...")
ch.minimize( fun = objectives,
x0 = free_variables,
method = 'dogleg',
callback = on_step,
options = opt_options )
timer_end = time()
print("step 2: fitting done, in %f sec\n" % ( timer_end - timer_start ))
# return results
parms = { 'trans': model.trans.r, 'pose': model.pose.r, 'betas': model.betas.r }
return model.r, model.f, parms
# -----------------------------------------------------------------------------
def run_fitting():
# input landmarks
lmk_path = './data/scan_lmks.npy'
# measurement unit of landmarks ['m', 'cm', 'mm']
unit = 'm'
scale_factor = get_unit_factor('m') / get_unit_factor(unit)
lmk_3d = scale_factor*np.load(lmk_path)
print("loaded 3d landmark from:", lmk_path)
# model
model_path = './models/generic_model.pkl' # change to 'female_model.pkl' or 'male_model.pkl', if gender is known
model = load_model(model_path) # the loaded model object is a 'chumpy' object, check https://github.com/mattloper/chumpy for details
print("loaded model from:", model_path)
# landmark embedding
lmk_emb_path = './models/flame_static_embedding.pkl'
lmk_face_idx, lmk_b_coords = load_embedding(lmk_emb_path)
print("loaded lmk embedding")
# output
output_dir = './output'
safe_mkdir(output_dir)
# weights
weights = {}
# landmark term
weights['lmk'] = 1.0
# shape regularizer (weight higher to regularize face shape more towards the mean)
weights['shape'] = 1e-3
# expression regularizer (weight higher to regularize facial expression more towards the mean)
weights['expr'] = 1e-3
# regularization of head rotation around the neck and jaw opening (weight higher for more regularization)
weights['pose'] = 1e-2
# number of shape and expression parameters (we do not recommend using too many parameters for fitting to sparse keypoints)
shape_num = 100
expr_num = 50
# optimization options
import scipy.sparse as sp
opt_options = {}
opt_options['disp'] = 1
opt_options['delta_0'] = 0.1
opt_options['e_3'] = 1e-4
opt_options['maxiter'] = 2000
sparse_solver = lambda A, x: sp.linalg.cg(A, x, maxiter=opt_options['maxiter'])[0]
opt_options['sparse_solver'] = sparse_solver
# run fitting
mesh_v, mesh_f, parms = fit_lmk3d( lmk_3d=lmk_3d, # input landmark 3d
model=model, # model
lmk_face_idx=lmk_face_idx, lmk_b_coords=lmk_b_coords, # landmark embedding
weights=weights, # weights for the objectives
shape_num=shape_num, expr_num=expr_num, opt_options=opt_options ) # options
# write result
output_path = join( output_dir, 'fit_lmk3d_result.obj' )
write_simple_obj( mesh_v=mesh_v, mesh_f=mesh_f, filepath=output_path, verbose=False )
# -----------------------------------------------------------------------------
if __name__ == '__main__':
run_fitting()
| [
"scipy.sparse.linalg.cg",
"numpy.union1d",
"numpy.random.rand",
"fitting.util.write_simple_obj",
"fitting.util.safe_mkdir",
"smpl_webuser.serialization.load_model",
"numpy.arange",
"os.path.join",
"fitting.landmarks.load_embedding",
"fitting.landmarks.landmark_error_3d",
"fitting.util.get_unit_f... | [((2280, 2311), 'numpy.union1d', 'np.union1d', (['shape_idx', 'expr_idx'], {}), '(shape_idx, expr_idx)\n', (2290, 2311), True, 'import numpy as np\n'), ((2782, 2938), 'fitting.landmarks.landmark_error_3d', 'landmark_error_3d', ([], {'mesh_verts': 'model', 'mesh_faces': 'model.f', 'lmk_3d': 'lmk_3d', 'lmk_face_idx': 'lmk_face_idx', 'lmk_b_coords': 'lmk_b_coords', 'weight': "weights['lmk']"}), "(mesh_verts=model, mesh_faces=model.f, lmk_3d=lmk_3d,\n lmk_face_idx=lmk_face_idx, lmk_b_coords=lmk_b_coords, weight=weights['lmk']\n )\n", (2799, 2938), False, 'from fitting.landmarks import load_embedding, landmark_error_3d\n'), ((4062, 4068), 'time.time', 'time', ([], {}), '()\n', (4066, 4068), False, 'from time import time\n'), ((4119, 4238), 'chumpy.minimize', 'ch.minimize', ([], {'fun': 'lmk_err', 'x0': '[model.trans, model.pose[0:3]]', 'method': '"""dogleg"""', 'callback': 'on_step', 'options': 'opt_options'}), "(fun=lmk_err, x0=[model.trans, model.pose[0:3]], method='dogleg',\n callback=on_step, options=opt_options)\n", (4130, 4238), True, 'import chumpy as ch\n'), ((4347, 4353), 'time.time', 'time', ([], {}), '()\n', (4351, 4353), False, 'from time import time\n'), ((4484, 4490), 'time.time', 'time', ([], {}), '()\n', (4488, 4490), False, 'from time import time\n'), ((4547, 4654), 'chumpy.minimize', 'ch.minimize', ([], {'fun': 'objectives', 'x0': 'free_variables', 'method': '"""dogleg"""', 'callback': 'on_step', 'options': 'opt_options'}), "(fun=objectives, x0=free_variables, method='dogleg', callback=\n on_step, options=opt_options)\n", (4558, 4654), True, 'import chumpy as ch\n'), ((4760, 4766), 'time.time', 'time', ([], {}), '()\n', (4764, 4766), False, 'from time import time\n'), ((5516, 5538), 'smpl_webuser.serialization.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (5526, 5538), False, 'from smpl_webuser.serialization import load_model\n'), ((5808, 5836), 'fitting.landmarks.load_embedding', 'load_embedding', (['lmk_emb_path'], {}), '(lmk_emb_path)\n', (5822, 5836), False, 'from fitting.landmarks import load_embedding, landmark_error_3d\n'), ((5917, 5939), 'fitting.util.safe_mkdir', 'safe_mkdir', (['output_dir'], {}), '(output_dir)\n', (5927, 5939), False, 'from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor\n'), ((7546, 7586), 'os.path.join', 'join', (['output_dir', '"""fit_lmk3d_result.obj"""'], {}), "(output_dir, 'fit_lmk3d_result.obj')\n", (7550, 7586), False, 'from os.path import join\n'), ((7593, 7680), 'fitting.util.write_simple_obj', 'write_simple_obj', ([], {'mesh_v': 'mesh_v', 'mesh_f': 'mesh_f', 'filepath': 'output_path', 'verbose': '(False)'}), '(mesh_v=mesh_v, mesh_f=mesh_f, filepath=output_path,\n verbose=False)\n', (7609, 7680), False, 'from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor\n'), ((1965, 1977), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (1974, 1977), True, 'import numpy as np\n'), ((1979, 1994), 'numpy.arange', 'np.arange', (['(6)', '(9)'], {}), '(6, 9)\n', (1988, 1994), True, 'import numpy as np\n'), ((2335, 2367), 'numpy.random.rand', 'np.random.rand', (['model.betas.size'], {}), '(model.betas.size)\n', (2349, 2367), True, 'import numpy as np\n'), ((2420, 2451), 'numpy.random.rand', 'np.random.rand', (['model.pose.size'], {}), '(model.pose.size)\n', (2434, 2451), True, 'import numpy as np\n'), ((5237, 5257), 'fitting.util.get_unit_factor', 'get_unit_factor', (['"""m"""'], {}), "('m')\n", (5252, 5257), False, 'from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor\n'), ((5260, 5281), 'fitting.util.get_unit_factor', 'get_unit_factor', (['unit'], {}), '(unit)\n', (5275, 5281), False, 'from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor\n'), ((5308, 5325), 'numpy.load', 'np.load', (['lmk_path'], {}), '(lmk_path)\n', (5315, 5325), True, 'import numpy as np\n'), ((6817, 6867), 'scipy.sparse.linalg.cg', 'sp.linalg.cg', (['A', 'x'], {'maxiter': "opt_options['maxiter']"}), "(A, x, maxiter=opt_options['maxiter'])\n", (6829, 6867), True, 'import scipy.sparse as sp\n'), ((3800, 3850), 'scipy.sparse.linalg.cg', 'sp.linalg.cg', (['A', 'x'], {'maxiter': "opt_options['maxiter']"}), "(A, x, maxiter=opt_options['maxiter'])\n", (3812, 3850), True, 'import scipy.sparse as sp\n')] |
import argparse
import os
import re
import time
import numpy as np
from time import sleep
from datasets import audio
import tensorflow as tf
from hparams import hparams, hparams_debug_string
from infolog import log
from tacotron.synthesizer import Synthesizer
from tqdm import tqdm
def generate_fast(model, text):
model.synthesize(text, None, None, None, None)
def run_live(args, checkpoint_path, hparams):
#Log to Terminal without keeping any records in files
log(hparams_debug_string())
synth = Synthesizer()
synth.load(checkpoint_path, hparams)
synth.session_open()
#Generate fast greeting message
greetings = 'Hello, Welcome to the Live testing tool. Please type a message and I will try to read it!'
log(greetings)
generate_fast(synth, greetings)
#Interaction loop
while True:
try:
text = input()
generate_fast(synth, text)
except KeyboardInterrupt:
leave = 'Thank you for testing our features. see you soon.'
log(leave)
generate_fast(synth, leave)
sleep(2)
break
synth.session_close()
def run_eval(args, checkpoint_path, output_dir, hparams, sentences):
eval_dir = os.path.join(output_dir, 'eval')
log_dir = os.path.join(output_dir, 'logs-eval')
if args.model == 'Tacotron-2':
assert os.path.normpath(eval_dir) == os.path.normpath(args.mels_dir) #mels_dir = wavenet_input_dir
#Create output path if it doesn't exist
os.makedirs(eval_dir, exist_ok=True)
os.makedirs(log_dir, exist_ok=True)
os.makedirs(os.path.join(log_dir, 'wavs'), exist_ok=True)
os.makedirs(os.path.join(log_dir, 'plots'), exist_ok=True)
log(hparams_debug_string())
synth = Synthesizer()
synth.load(checkpoint_path, hparams)
synth.session_open()
sentences = list(map(lambda s: s.strip(), sentences))
delta_size = hparams.tacotron_synthesis_batch_size if hparams.tacotron_synthesis_batch_size < len(sentences) else len(sentences)
batch_sentences = [sentences[i: i+hparams.tacotron_synthesis_batch_size] for i in range(0, len(sentences), delta_size)]
start = time.time()
for i, batch in enumerate(tqdm(batch_sentences)):
mel_filename = os.path.join(eval_dir, f'{i:03d}.npy')
mel = synth.eval(batch, args.speaker_id)
np.save(mel_filename, mel.T, allow_pickle=False)
wav = audio.inv_mel_spectrogram(mel.T, hparams)
audio.save_wav(wav, os.path.join(eval_dir, f'{i:03d}.wav'), hparams)
end = time.time() - start
log(f'Generated total batch of {delta_size} in {end:.3f} sec')
synth.session_close()
def run_synthesis(args, checkpoint_path, output_dir, hparams):
GTA = (args.GTA == 'True')
if GTA:
synth_dir = os.path.join(output_dir, 'gta')
#Create output path if it doesn't exist
os.makedirs(synth_dir, exist_ok=True)
else:
synth_dir = os.path.join(output_dir, 'natural')
#Create output path if it doesn't exist
os.makedirs(synth_dir, exist_ok=True)
log(hparams_debug_string())
synth = Synthesizer()
synth.load(checkpoint_path, hparams, gta=GTA)
synth.session_open()
frame_shift_ms = hparams.hop_size / hparams.sample_rate
for speaker_id, anchor_dir in enumerate(hparams.anchor_dirs):
metadata_filename = os.path.join(args.input_dir, anchor_dir, 'train.txt')
with open(metadata_filename, encoding='utf-8') as f:
metadata = [line.strip().split('|') for line in f]
hours = sum([int(x[2]) for x in metadata]) * frame_shift_ms / 3600
log(f'Loaded {anchor_dir} for {len(metadata)} examples ({hours:.2f} hours)')
metadata = [metadata[i: i+hparams.tacotron_synthesis_batch_size] for i in range(0, len(metadata), hparams.tacotron_synthesis_batch_size)]
mel_dir = os.path.join(args.input_dir, anchor_dir, 'mels')
for meta in tqdm(metadata):
texts = [m[3] for m in meta]
mel_filenames = [os.path.join(mel_dir, m[0]) for m in meta]
basenames = [os.path.basename(m).replace('.npy', '').replace('mel-', '') for m in mel_filenames]
synth.synthesize(texts, basenames, synth_dir, None, mel_filenames, speaker_id)
log(f'synthesized mel spectrograms at {synth_dir}')
synth.session_close()
def tacotron_synthesize(args, hparams, checkpoint, sentences=None):
output_dir = 'tacotron_' + args.output_dir
try:
checkpoint_path = tf.train.get_checkpoint_state(checkpoint).model_checkpoint_path
log(f'loaded model at {checkpoint_path}')
except:
raise RuntimeError(f'Failed to load checkpoint at {checkpoint}')
if args.mode == 'eval':
run_eval(args, checkpoint_path, output_dir, hparams, sentences)
elif args.mode == 'synthesis':
run_synthesis(args, checkpoint_path, output_dir, hparams)
else:
run_live(args, checkpoint_path, hparams)
| [
"tacotron.synthesizer.Synthesizer",
"os.makedirs",
"tqdm.tqdm",
"os.path.join",
"infolog.log",
"time.sleep",
"os.path.normpath",
"tensorflow.train.get_checkpoint_state",
"datasets.audio.inv_mel_spectrogram",
"os.path.basename",
"hparams.hparams_debug_string",
"time.time",
"numpy.save"
] | [((505, 518), 'tacotron.synthesizer.Synthesizer', 'Synthesizer', ([], {}), '()\n', (516, 518), False, 'from tacotron.synthesizer import Synthesizer\n'), ((719, 733), 'infolog.log', 'log', (['greetings'], {}), '(greetings)\n', (722, 733), False, 'from infolog import log\n'), ((1119, 1151), 'os.path.join', 'os.path.join', (['output_dir', '"""eval"""'], {}), "(output_dir, 'eval')\n", (1131, 1151), False, 'import os\n'), ((1163, 1200), 'os.path.join', 'os.path.join', (['output_dir', '"""logs-eval"""'], {}), "(output_dir, 'logs-eval')\n", (1175, 1200), False, 'import os\n'), ((1378, 1414), 'os.makedirs', 'os.makedirs', (['eval_dir'], {'exist_ok': '(True)'}), '(eval_dir, exist_ok=True)\n', (1389, 1414), False, 'import os\n'), ((1416, 1451), 'os.makedirs', 'os.makedirs', (['log_dir'], {'exist_ok': '(True)'}), '(log_dir, exist_ok=True)\n', (1427, 1451), False, 'import os\n'), ((1610, 1623), 'tacotron.synthesizer.Synthesizer', 'Synthesizer', ([], {}), '()\n', (1621, 1623), False, 'from tacotron.synthesizer import Synthesizer\n'), ((2000, 2011), 'time.time', 'time.time', ([], {}), '()\n', (2009, 2011), False, 'import time\n'), ((2362, 2424), 'infolog.log', 'log', (['f"""Generated total batch of {delta_size} in {end:.3f} sec"""'], {}), "(f'Generated total batch of {delta_size} in {end:.3f} sec')\n", (2365, 2424), False, 'from infolog import log\n'), ((2858, 2871), 'tacotron.synthesizer.Synthesizer', 'Synthesizer', ([], {}), '()\n', (2869, 2871), False, 'from tacotron.synthesizer import Synthesizer\n'), ((3905, 3956), 'infolog.log', 'log', (['f"""synthesized mel spectrograms at {synth_dir}"""'], {}), "(f'synthesized mel spectrograms at {synth_dir}')\n", (3908, 3956), False, 'from infolog import log\n'), ((472, 494), 'hparams.hparams_debug_string', 'hparams_debug_string', ([], {}), '()\n', (492, 494), False, 'from hparams import hparams, hparams_debug_string\n'), ((1465, 1494), 'os.path.join', 'os.path.join', (['log_dir', '"""wavs"""'], {}), "(log_dir, 'wavs')\n", (1477, 1494), False, 'import os\n'), ((1524, 1554), 'os.path.join', 'os.path.join', (['log_dir', '"""plots"""'], {}), "(log_dir, 'plots')\n", (1536, 1554), False, 'import os\n'), ((1577, 1599), 'hparams.hparams_debug_string', 'hparams_debug_string', ([], {}), '()\n', (1597, 1599), False, 'from hparams import hparams, hparams_debug_string\n'), ((2039, 2060), 'tqdm.tqdm', 'tqdm', (['batch_sentences'], {}), '(batch_sentences)\n', (2043, 2060), False, 'from tqdm import tqdm\n'), ((2080, 2118), 'os.path.join', 'os.path.join', (['eval_dir', 'f"""{i:03d}.npy"""'], {}), "(eval_dir, f'{i:03d}.npy')\n", (2092, 2118), False, 'import os\n'), ((2164, 2212), 'numpy.save', 'np.save', (['mel_filename', 'mel.T'], {'allow_pickle': '(False)'}), '(mel_filename, mel.T, allow_pickle=False)\n', (2171, 2212), True, 'import numpy as np\n'), ((2221, 2262), 'datasets.audio.inv_mel_spectrogram', 'audio.inv_mel_spectrogram', (['mel.T', 'hparams'], {}), '(mel.T, hparams)\n', (2246, 2262), False, 'from datasets import audio\n'), ((2341, 2352), 'time.time', 'time.time', ([], {}), '()\n', (2350, 2352), False, 'import time\n'), ((2564, 2595), 'os.path.join', 'os.path.join', (['output_dir', '"""gta"""'], {}), "(output_dir, 'gta')\n", (2576, 2595), False, 'import os\n'), ((2641, 2678), 'os.makedirs', 'os.makedirs', (['synth_dir'], {'exist_ok': '(True)'}), '(synth_dir, exist_ok=True)\n', (2652, 2678), False, 'import os\n'), ((2700, 2735), 'os.path.join', 'os.path.join', (['output_dir', '"""natural"""'], {}), "(output_dir, 'natural')\n", (2712, 2735), False, 'import os\n'), ((2781, 2818), 'os.makedirs', 'os.makedirs', (['synth_dir'], {'exist_ok': '(True)'}), '(synth_dir, exist_ok=True)\n', (2792, 2818), False, 'import os\n'), ((2825, 2847), 'hparams.hparams_debug_string', 'hparams_debug_string', ([], {}), '()\n', (2845, 2847), False, 'from hparams import hparams, hparams_debug_string\n'), ((3084, 3137), 'os.path.join', 'os.path.join', (['args.input_dir', 'anchor_dir', '"""train.txt"""'], {}), "(args.input_dir, anchor_dir, 'train.txt')\n", (3096, 3137), False, 'import os\n'), ((3548, 3596), 'os.path.join', 'os.path.join', (['args.input_dir', 'anchor_dir', '"""mels"""'], {}), "(args.input_dir, anchor_dir, 'mels')\n", (3560, 3596), False, 'import os\n'), ((3611, 3625), 'tqdm.tqdm', 'tqdm', (['metadata'], {}), '(metadata)\n', (3615, 3625), False, 'from tqdm import tqdm\n'), ((4187, 4228), 'infolog.log', 'log', (['f"""loaded model at {checkpoint_path}"""'], {}), "(f'loaded model at {checkpoint_path}')\n", (4190, 4228), False, 'from infolog import log\n'), ((1243, 1269), 'os.path.normpath', 'os.path.normpath', (['eval_dir'], {}), '(eval_dir)\n', (1259, 1269), False, 'import os\n'), ((1273, 1304), 'os.path.normpath', 'os.path.normpath', (['args.mels_dir'], {}), '(args.mels_dir)\n', (1289, 1304), False, 'import os\n'), ((2285, 2323), 'os.path.join', 'os.path.join', (['eval_dir', 'f"""{i:03d}.wav"""'], {}), "(eval_dir, f'{i:03d}.wav')\n", (2297, 2323), False, 'import os\n'), ((4121, 4162), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['checkpoint'], {}), '(checkpoint)\n', (4150, 4162), True, 'import tensorflow as tf\n'), ((950, 960), 'infolog.log', 'log', (['leave'], {}), '(leave)\n', (953, 960), False, 'from infolog import log\n'), ((995, 1003), 'time.sleep', 'sleep', (['(2)'], {}), '(2)\n', (1000, 1003), False, 'from time import sleep\n'), ((3679, 3706), 'os.path.join', 'os.path.join', (['mel_dir', 'm[0]'], {}), '(mel_dir, m[0])\n', (3691, 3706), False, 'import os\n'), ((3738, 3757), 'os.path.basename', 'os.path.basename', (['m'], {}), '(m)\n', (3754, 3757), False, 'import os\n')] |
# 引入类库
import tensorflow as tf
import numpy as np
from tensorflow import keras
# 使用下述语句来查看tensorflow版本,以下代码都是2.0版的
print(tf.__version__)
# 使用array来组织数据整理
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
# 定义模型model,该模型是具有一个输入(input_shape[1])和一个神经元输出的全连接(Dense)模型。
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
# 使用SGD优化器、和均方误差来编译模型。SGD和mean_squared_error后面脑补
model.compile(optimizer='sgd', loss='mean_squared_error')
# 开始训练, 500次
model.fit(xs, ys, epochs=500)
# 用训练好的model预测10.0,打印其预测值是多少
print(model.predict([10.0]))
| [
"numpy.array",
"tensorflow.keras.layers.Dense"
] | [((161, 215), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]'], {'dtype': 'float'}), '([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\n', (169, 215), True, 'import numpy as np\n'), ((222, 277), 'numpy.array', 'np.array', (['[-3.0, -1.0, 1.0, 3.0, 5.0, 7.0]'], {'dtype': 'float'}), '([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)\n', (230, 277), True, 'import numpy as np\n'), ((369, 413), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', ([], {'units': '(1)', 'input_shape': '[1]'}), '(units=1, input_shape=[1])\n', (387, 413), False, 'from tensorflow import keras\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 15:54:30 2018
@author: Brendan
"""
"""
######################
# run with:
# $ mpiexec -n N python preProcessFITS.py --processed_dir DIR --raw_dir DIR
# N = = number of processors
######################
"""
import glob
import numpy as np
import astropy.units as u
from astropy.time import Time
from astropy.coordinates import SkyCoord
import sunpy
from sunpy.map import Map
from sunpy.coordinates import frames
from sunpy.physics.solar_rotation import calculate_solar_rotate_shift
from sunpy.physics.differential_rotation import diffrot_map
from timeit import default_timer as timer
import time
import datetime
import sys
import os
havempi = True
try:
from mpi4py import MPI
except:
havempi = False
# TODO: Take as command line argument
#sub_reg_coords = [155,270,200,290]
import argparse
parser = argparse.ArgumentParser(description='preProcessFITS.py')
parser.add_argument('--processed_dir', type=str)
parser.add_argument('--raw_dir', type=str)
parser.add_argument('--Nfiles', type=str, default="all")
parser.add_argument('--sub_reg_coords', type=str)
args = parser.parse_args()
raw_dir = args.raw_dir
processed_dir = args.processed_dir
Nfiles = args.Nfiles
sub_reg_coords = args.sub_reg_coords
sub_reg_coords = [int(x.strip()) for x in sub_reg_coords.split(',') if x != '']
def datacube(flist_chunk):
# rebin region to desired fraction
def rebin(a, *args):
shape = a.shape
lenShape = len(shape)
factor = np.asarray(shape)/np.asarray(args)
evList = ['a.reshape('] + \
['args[%d],factor[%d],'%(i,i) for i in range(lenShape)] + \
[')'] + ['.mean(%d)'%(i+1) for i in range(lenShape)]
return eval(''.join(evList))
nf1 = len(flist_chunk)
exposure = np.empty((nf1))
timestamp = np.empty((nf1))
visAvg = np.empty((mapShape[0], mapShape[1]))
# image data is int16
dCube = np.empty((mapShape[0], mapShape[1], nf1), dtype=np.int16)
start_sub = timer()
T1 = 0
count = 0
dimCount = 0
# loop through datacube and extract timeseries, timestamps, exposures
for filename in flist_chunk:
smap = Map(filename).submap(c3, c4)
exposure[count] = (smap.exposure_time).value
timestamp[count] = Time(smap.date).jd
dmap = diffrot_map(smap, time=dt0).data
if dmap.shape != mapShape:
dimenDiff = np.array(dmap.shape) - np.array(mapShape)
dmap = dmap[:dmap.shape[0]-dimenDiff[0], :dmap.shape[1]-dimenDiff[1]]
dimCount += 1
visAvg += (dmap / (smap.exposure_time).value)
dCube[:,:,count] = dmap
count += 1
# estimate time remaining and print to screen
T = timer()
T2 = T - T1
if count == 0:
T_init = T - start_sub
T_est = T_init*nf1
else:
T_est = T2*(nf1-count)
T_min, T_sec = divmod(T_est, 60)
T_hr, T_min = divmod(T_min, 60)
print("Thread %i on row %i/%i, ETR: %i:%.2i:%.2i" %
(rank, count, nf1, T_hr, T_min, T_sec), flush=True)
T1 = T
# ---- trim dataCube and visual image
dCube = dCube[diffLatPix:-diffLatPix, xminI:-xminF]
visAvg = visAvg[diffLatPix:-diffLatPix, xminI:-xminF]
np.save('%s/chunk_%i_of_%i' % (processed_dir, rank+1, size), dCube)
print('Processor: %i, Dimension Errors: %i' % (rank+1, dimCount), flush=True)
#return dCube
return exposure, timestamp, visAvg
##############################################################################
if havempi:
# Get_size() pulls from "-n N" specified on command line
comm = MPI.COMM_WORLD # Set up comms
rank = comm.Get_rank() # Each processor gets its own "rank"
size = comm.Get_size()
else:
comm = None
rank = 0
size = 1
if int(sys.version[0]) != 3:
if rank == 0:
sys.exit("Python 3 is required if rank == 0")
else:
sys.exit()
if not os.path.exists(raw_dir):
if rank == 0:
sys.exit("Raw directory '%s' does not exist." % raw_dir)
else:
sys.exit()
if rank == 0:
tStart0 = datetime.datetime.fromtimestamp(time.time())
tStart = tStart0.strftime('%Y-%m-%d %H:%M:%S')
if not os.path.exists(processed_dir): os.makedirs(processed_dir)
# set variable from config file
x1,x2,y1,y2 = sub_reg_coords
# create a list of all the fits files
flist = sorted(glob.glob('%s/aia*.fits' % raw_dir))
if Nfiles != "all":
flist = flist[0:int(Nfiles)]
# TODO: if files not found, add in system.exit()
nf = len(flist)
# Select the middle image, to derotate around
mid_file = np.int(np.floor(nf / 2))
# make mapcube containing first and last maps & calculate derotation shifts
# if not centered at 0deg long, shift amount wont be enough --
# maybe only calculate latitude, use other method for longitude trim
mc_shifts = []
mapI = Map(flist[0])
mapF = Map(flist[-1])
mc_shifts.append(mapI)
mc_shifts.append(mapF)
#new_mapcube1 = Map(mc_shifts, cube=True)
new_mapcube1 = Map(mc_shifts, sequence=True)
shifts = calculate_solar_rotate_shift(new_mapcube1, layer_index=0)
# compute longitude / latitude shift over timespan
diffLon = np.abs(np.floor((np.floor(shifts['x'][1].value)/2.)))
# calculate rotation amount in pixels
diffLonPix = diffLon / (mapI.scale)[0].value
# calculate total latitude shift in pixels, x2 since underestimated?
diffLatPix = int((np.abs((shifts['y'][1].value)) / (mapI.scale)[1].value) * 2.)
#print(diffLon, diffLonPix)
#print(diffLatPix*mapI.scale[1].value, diffLatPix)
if diffLatPix == 0:
diffLatPix = 5 # value of zero messes with next steps
c3 = SkyCoord((x1-diffLon)*u.arcsec, y1*u.arcsec, frame=frames.Helioprojective)
c4 = SkyCoord((x2+diffLon)*u.arcsec, y2*u.arcsec, frame=frames.Helioprojective)
# get middle frame subregion & time to anchor derotation
midmap = Map(flist[mid_file]).submap(c3,c4)
dt0 = midmap.date
mapShape = midmap.data.shape
# calculate pixels to trim based off of what actual derotation trims
# *for some reason this result is different than method above
diffMapI = diffrot_map(mapI.submap(c3, c4), time=dt0)
diffMapF = diffrot_map(mapF.submap(c3, c4), time=dt0)
xminindI = np.argmin(np.fliplr(diffMapI.data), axis=1)[diffLatPix:-diffLatPix]
xminindF = np.argmin(diffMapF.data, axis=1)[diffLatPix:-diffLatPix]
xminI = mapShape[1] - np.min(xminindI)
xminF = mapShape[1] - np.min(xminindF)
del new_mapcube1, mc_shifts, diffMapI, diffMapF
# specify which chunks should be handled by each processor
subcube = np.array_split(flist, size)[rank]
start = timer()
ex, t, v_avg = datacube( subcube )
if havempi:
# Gather all results
all_ex = comm.gather(ex, root=0)
all_t = comm.gather(t, root=0)
all_v_avg = comm.gather(v_avg, root=0)
# Have one node stack the results
if rank == 0:
if havempi:
ex_arr = np.hstack(all_ex)
tArr = np.hstack(all_t)
else:
ex_arr = ex
tArr = t
all_v_avg = [v_avg]
tArr -= tArr[0] # calculate time since first image
tArr = np.around(tArr*86400) # get timestamps in seconds
# Calculate averaged visual image
for j in range(len(all_v_avg)):
if j == 0:
vAvgArr = all_v_avg[j]
else:
vAvgArr += all_v_avg[j]
vAvgArr /= nf
print("Saving files...", flush=True)
np.save('%s/exposures.npy' % processed_dir, ex_arr)
np.save('%s/timestamps.npy' % processed_dir, tArr)
np.save('%s/visual.npy' % processed_dir, vAvgArr)
# Load, stack, and save dataCube chunks
print("Merging dataCube chunks...", flush=True)
cube_temp = []
# load derotated cube chunks
for i in range(size):
temp = np.load('%s/chunk_%i_of_%i.npy' % (processed_dir, i+1, size))
cube_temp.append(temp)
cube_final = np.dstack(cube_temp)
del cube_temp
# delete temporary chunks
print("Deleting temporary files...", flush=True)
for j in range(size):
fn = '%s/chunk_%i_of_%i.npy' % (processed_dir, j+1, size)
# if file exists, delete it
if os.path.isfile(fn): os.remove(fn)
print("Saving final dataCube...", flush=True)
np.save('%s/dataCube.npy' % processed_dir, cube_final)
T_final = timer() - start
T_min_final, T_sec_final = divmod(T_final, 60)
T_hr_final, T_min_final = divmod(T_min_final, 60)
print("Total program time = %i:%.2i:%.2i" % (T_hr_final, T_min_final, T_sec_final), flush=True)
#print("Just finished region: %s %iA" % (date, wavelength), flush=True)
tEnd0 = datetime.datetime.fromtimestamp(time.time())
tEnd = tEnd0.strftime('%Y-%m-%d %H:%M:%S')
scriptName = os.path.splitext(os.path.basename(sys.argv[0]))[0]
#with open('%s_%i_region_details.txt' % (date, wavelength), 'w') as file:
with open('%s/log.txt' % processed_dir, 'a+') as file:
file.write("Region Details" + "\n")
file.write("==============" + "\n\n")
#file.write("Date: %s" % date + "\n")
#file.write("Wavelength: %i" % wavelength + "\n\n")
file.write("%s: Extract Data & Derotate" % scriptName + "\n")
file.write("----------------------------------------" + "\n")
file.write("FITS directory: %s" % raw_dir + "\n")
file.write("Processed directory: %s" % processed_dir + "\n")
file.write("Sub-region coordinates: (%i, %i)x, (%i, %i)y" % tuple(sub_reg_coords) + "\n")
file.write("First image timestamp: %s" % mapI.date.strftime('%Y-%m-%d %H:%M:%S') + "\n")
file.write("Last image timestamp: %s" % mapF.date.strftime('%Y-%m-%d %H:%M:%S') + "\n")
file.write("Number of Images: %i" % nf + "\n")
file.write("Program start time: %s" % tStart + "\n")
file.write("Program end time: %s" % tEnd + "\n\n") | [
"sunpy.physics.solar_rotation.calculate_solar_rotate_shift",
"numpy.hstack",
"numpy.array_split",
"numpy.array",
"sys.exit",
"numpy.save",
"os.remove",
"os.path.exists",
"argparse.ArgumentParser",
"numpy.asarray",
"numpy.empty",
"numpy.min",
"numpy.argmin",
"glob.glob",
"numpy.abs",
"n... | [((857, 913), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""preProcessFITS.py"""'}), "(description='preProcessFITS.py')\n", (880, 913), False, 'import argparse\n'), ((4966, 4979), 'sunpy.map.Map', 'Map', (['flist[0]'], {}), '(flist[0])\n', (4969, 4979), False, 'from sunpy.map import Map\n'), ((4987, 5001), 'sunpy.map.Map', 'Map', (['flist[-1]'], {}), '(flist[-1])\n', (4990, 5001), False, 'from sunpy.map import Map\n'), ((5106, 5135), 'sunpy.map.Map', 'Map', (['mc_shifts'], {'sequence': '(True)'}), '(mc_shifts, sequence=True)\n', (5109, 5135), False, 'from sunpy.map import Map\n'), ((5146, 5203), 'sunpy.physics.solar_rotation.calculate_solar_rotate_shift', 'calculate_solar_rotate_shift', (['new_mapcube1'], {'layer_index': '(0)'}), '(new_mapcube1, layer_index=0)\n', (5174, 5203), False, 'from sunpy.physics.solar_rotation import calculate_solar_rotate_shift\n'), ((5724, 5809), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['((x1 - diffLon) * u.arcsec)', '(y1 * u.arcsec)'], {'frame': 'frames.Helioprojective'}), '((x1 - diffLon) * u.arcsec, y1 * u.arcsec, frame=frames.Helioprojective\n )\n', (5732, 5809), False, 'from astropy.coordinates import SkyCoord\n'), ((5806, 5891), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['((x2 + diffLon) * u.arcsec)', '(y2 * u.arcsec)'], {'frame': 'frames.Helioprojective'}), '((x2 + diffLon) * u.arcsec, y2 * u.arcsec, frame=frames.Helioprojective\n )\n', (5814, 5891), False, 'from astropy.coordinates import SkyCoord\n'), ((6663, 6670), 'timeit.default_timer', 'timer', ([], {}), '()\n', (6668, 6670), True, 'from timeit import default_timer as timer\n'), ((1808, 1821), 'numpy.empty', 'np.empty', (['nf1'], {}), '(nf1)\n', (1816, 1821), True, 'import numpy as np\n'), ((1840, 1853), 'numpy.empty', 'np.empty', (['nf1'], {}), '(nf1)\n', (1848, 1853), True, 'import numpy as np\n'), ((1869, 1905), 'numpy.empty', 'np.empty', (['(mapShape[0], mapShape[1])'], {}), '((mapShape[0], mapShape[1]))\n', (1877, 1905), True, 'import numpy as np\n'), ((1949, 2006), 'numpy.empty', 'np.empty', (['(mapShape[0], mapShape[1], nf1)'], {'dtype': 'np.int16'}), '((mapShape[0], mapShape[1], nf1), dtype=np.int16)\n', (1957, 2006), True, 'import numpy as np\n'), ((2028, 2035), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2033, 2035), True, 'from timeit import default_timer as timer\n'), ((3344, 3413), 'numpy.save', 'np.save', (["('%s/chunk_%i_of_%i' % (processed_dir, rank + 1, size))", 'dCube'], {}), "('%s/chunk_%i_of_%i' % (processed_dir, rank + 1, size), dCube)\n", (3351, 3413), True, 'import numpy as np\n'), ((4026, 4049), 'os.path.exists', 'os.path.exists', (['raw_dir'], {}), '(raw_dir)\n', (4040, 4049), False, 'import os\n'), ((4490, 4525), 'glob.glob', 'glob.glob', (["('%s/aia*.fits' % raw_dir)"], {}), "('%s/aia*.fits' % raw_dir)\n", (4499, 4525), False, 'import glob\n'), ((4716, 4732), 'numpy.floor', 'np.floor', (['(nf / 2)'], {}), '(nf / 2)\n', (4724, 4732), True, 'import numpy as np\n'), ((6363, 6395), 'numpy.argmin', 'np.argmin', (['diffMapF.data'], {'axis': '(1)'}), '(diffMapF.data, axis=1)\n', (6372, 6395), True, 'import numpy as np\n'), ((6443, 6459), 'numpy.min', 'np.min', (['xminindI'], {}), '(xminindI)\n', (6449, 6459), True, 'import numpy as np\n'), ((6484, 6500), 'numpy.min', 'np.min', (['xminindF'], {}), '(xminindF)\n', (6490, 6500), True, 'import numpy as np\n'), ((6620, 6647), 'numpy.array_split', 'np.array_split', (['flist', 'size'], {}), '(flist, size)\n', (6634, 6647), True, 'import numpy as np\n'), ((7137, 7160), 'numpy.around', 'np.around', (['(tArr * 86400)'], {}), '(tArr * 86400)\n', (7146, 7160), True, 'import numpy as np\n'), ((7435, 7486), 'numpy.save', 'np.save', (["('%s/exposures.npy' % processed_dir)", 'ex_arr'], {}), "('%s/exposures.npy' % processed_dir, ex_arr)\n", (7442, 7486), True, 'import numpy as np\n'), ((7491, 7541), 'numpy.save', 'np.save', (["('%s/timestamps.npy' % processed_dir)", 'tArr'], {}), "('%s/timestamps.npy' % processed_dir, tArr)\n", (7498, 7541), True, 'import numpy as np\n'), ((7546, 7595), 'numpy.save', 'np.save', (["('%s/visual.npy' % processed_dir)", 'vAvgArr'], {}), "('%s/visual.npy' % processed_dir, vAvgArr)\n", (7553, 7595), True, 'import numpy as np\n'), ((7928, 7948), 'numpy.dstack', 'np.dstack', (['cube_temp'], {}), '(cube_temp)\n', (7937, 7948), True, 'import numpy as np\n'), ((8320, 8374), 'numpy.save', 'np.save', (["('%s/dataCube.npy' % processed_dir)", 'cube_final'], {}), "('%s/dataCube.npy' % processed_dir, cube_final)\n", (8327, 8374), True, 'import numpy as np\n'), ((2778, 2785), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2783, 2785), True, 'from timeit import default_timer as timer\n'), ((3939, 3984), 'sys.exit', 'sys.exit', (['"""Python 3 is required if rank == 0"""'], {}), "('Python 3 is required if rank == 0')\n", (3947, 3984), False, 'import sys\n'), ((4003, 4013), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4011, 4013), False, 'import sys\n'), ((4077, 4133), 'sys.exit', 'sys.exit', (['("Raw directory \'%s\' does not exist." % raw_dir)'], {}), '("Raw directory \'%s\' does not exist." % raw_dir)\n', (4085, 4133), False, 'import sys\n'), ((4152, 4162), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4160, 4162), False, 'import sys\n'), ((4232, 4243), 'time.time', 'time.time', ([], {}), '()\n', (4241, 4243), False, 'import time\n'), ((4307, 4336), 'os.path.exists', 'os.path.exists', (['processed_dir'], {}), '(processed_dir)\n', (4321, 4336), False, 'import os\n'), ((4338, 4364), 'os.makedirs', 'os.makedirs', (['processed_dir'], {}), '(processed_dir)\n', (4349, 4364), False, 'import os\n'), ((5949, 5969), 'sunpy.map.Map', 'Map', (['flist[mid_file]'], {}), '(flist[mid_file])\n', (5952, 5969), False, 'from sunpy.map import Map\n'), ((6294, 6318), 'numpy.fliplr', 'np.fliplr', (['diffMapI.data'], {}), '(diffMapI.data)\n', (6303, 6318), True, 'import numpy as np\n'), ((6942, 6959), 'numpy.hstack', 'np.hstack', (['all_ex'], {}), '(all_ex)\n', (6951, 6959), True, 'import numpy as np\n'), ((6975, 6991), 'numpy.hstack', 'np.hstack', (['all_t'], {}), '(all_t)\n', (6984, 6991), True, 'import numpy as np\n'), ((7809, 7872), 'numpy.load', 'np.load', (["('%s/chunk_%i_of_%i.npy' % (processed_dir, i + 1, size))"], {}), "('%s/chunk_%i_of_%i.npy' % (processed_dir, i + 1, size))\n", (7816, 7872), True, 'import numpy as np\n'), ((8222, 8240), 'os.path.isfile', 'os.path.isfile', (['fn'], {}), '(fn)\n', (8236, 8240), False, 'import os\n'), ((8392, 8399), 'timeit.default_timer', 'timer', ([], {}), '()\n', (8397, 8399), True, 'from timeit import default_timer as timer\n'), ((8739, 8750), 'time.time', 'time.time', ([], {}), '()\n', (8748, 8750), False, 'import time\n'), ((1501, 1518), 'numpy.asarray', 'np.asarray', (['shape'], {}), '(shape)\n', (1511, 1518), True, 'import numpy as np\n'), ((1519, 1535), 'numpy.asarray', 'np.asarray', (['args'], {}), '(args)\n', (1529, 1535), True, 'import numpy as np\n'), ((2315, 2330), 'astropy.time.Time', 'Time', (['smap.date'], {}), '(smap.date)\n', (2319, 2330), False, 'from astropy.time import Time\n'), ((2349, 2376), 'sunpy.physics.differential_rotation.diffrot_map', 'diffrot_map', (['smap'], {'time': 'dt0'}), '(smap, time=dt0)\n', (2360, 2376), False, 'from sunpy.physics.differential_rotation import diffrot_map\n'), ((5283, 5313), 'numpy.floor', 'np.floor', (["shifts['x'][1].value"], {}), "(shifts['x'][1].value)\n", (5291, 5313), True, 'import numpy as np\n'), ((5492, 5520), 'numpy.abs', 'np.abs', (["shifts['y'][1].value"], {}), "(shifts['y'][1].value)\n", (5498, 5520), True, 'import numpy as np\n'), ((8242, 8255), 'os.remove', 'os.remove', (['fn'], {}), '(fn)\n', (8251, 8255), False, 'import os\n'), ((8833, 8862), 'os.path.basename', 'os.path.basename', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (8849, 8862), False, 'import os\n'), ((2206, 2219), 'sunpy.map.Map', 'Map', (['filename'], {}), '(filename)\n', (2209, 2219), False, 'from sunpy.map import Map\n'), ((2441, 2461), 'numpy.array', 'np.array', (['dmap.shape'], {}), '(dmap.shape)\n', (2449, 2461), True, 'import numpy as np\n'), ((2464, 2482), 'numpy.array', 'np.array', (['mapShape'], {}), '(mapShape)\n', (2472, 2482), True, 'import numpy as np\n')] |
from distutils.core import setup, Extension
import os
import numpy
H2PACK_DIR = ".."
extra_cflags = ["-I"+H2PACK_DIR+"/include"]
extra_cflags += ["-g", "-std=gnu99", "-O3"]
extra_cflags += ["-DUSE_MKL", "-qopenmp", "-xHost", "-mkl"]
LIB = [H2PACK_DIR+"/lib/libH2Pack.a"]
extra_lflags = LIB + ["-g", "-O3", "-qopenmp", "-L${MKLROOT}/lib/intel64", "-mkl_rt", "-lpthread"]
def main():
setup(name="pyh2pack",
version="1.0.0",
description="Python interface for H2Pack",
author="<NAME>, <NAME>, and <NAME>",
author_email="<EMAIL>",
ext_modules=[Extension(
name = "pyh2pack",
sources = ["pyh2pack.c"],
include_dirs=[H2PACK_DIR+"/include", numpy.get_include()],
extra_compile_args = extra_cflags,
extra_link_args= extra_lflags,
)
]
)
if __name__ == "__main__":
main()
| [
"numpy.get_include"
] | [((717, 736), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (734, 736), False, 'import numpy\n')] |
import torch
from torch import nn
import numpy as np
import pytorch_lightning as pl
from .interpolations import TrilinearInterpolation
from .utils import *
class DirectVolumeRendering(nn.Module):
def __init__(self,
n_ray_samples,
feature_img_resolution,
depth_range,
fov,
feature_transfer_function,
alpha_transfer_function):
"""
:param n_ray_samples: step num along a ray
:param feature_img_resolution: resolution of rendered feature image
:param depth_range: tuple (depth start, depth end)
:param fov: (degree) field of view
:param feature_transfer_function: transfer function for converting features,
handling tensor of shape (batch, channel, num of eval points), output shape = (batch, new_channel, num of eval points)
:param alpha_transfer_function: transfer function for generating alpha values,
handling tensor of shape (batch, channel, num of eval points), output shape = (batch, 1, num of eval points)
"""
super(DirectVolumeRendering, self).__init__()
self.n_ray_samples = n_ray_samples
self.feature_img_resolution = feature_img_resolution
self.depth_range = depth_range
self.camera_matrix = nn.Parameter(self.get_camera_mat(fov))
self.feature_tf = feature_transfer_function
self.alpha_tf = alpha_transfer_function
self.trilinear_interpolator = TrilinearInterpolation()
def forward(self, volume, world_mat, add_noise, device):
"""
forward pass
:param volume: should be of shape [B,F,D,H,W], NOTICE!
:param world_mat: matrices specifying camera's positions and poses
:param add_noise: whether to add ray jitter AND scala noise
:param device: which device tensors on
:return: feature images rendered by DVR
"""
assert volume.shape[0] == world_mat.shape[0]
batch_size = world_mat.shape[0]
camera_mat = self.camera_matrix.repeat(batch_size, 1, 1)
self.device = device
feature_img = self.volume_render_image(volume, camera_mat, world_mat, batch_size, add_noise)
return feature_img
def image_points_to_world(self, image_points, camera_mat, world_mat, negative_depth=True):
''' Transforms points on image plane to world coordinates.
In contrast to transform_to_world, no depth value is needed as points on
the image plane have a fixed depth of 1.
Args:
image_points (tensor): image points tensor of size B x N x 2
camera_mat (tensor): camera matrix
world_mat (tensor): world matrix
'''
batch_size, n_pts, dim = image_points.shape
assert (dim == 2)
depth_image = torch.ones(batch_size, n_pts, 1).to(self.device)
if negative_depth:
depth_image *= -1.
return self.transform_to_world(image_points, depth_image, camera_mat, world_mat)
def cast_ray_and_get_eval_points(self, img_res, batch_size, depth_range, n_steps, camera_mat, world_mat,
ray_jittering):
# Arrange Pixels
pixels = self.arrange_pixels((img_res, img_res), batch_size)[1].to(self.device)
pixels[..., -1] *= -1.
n_points = img_res * img_res
# Project to 3D world
pixel_pos_wc = self.image_points_to_world(pixels, camera_mat, world_mat)
camera_pos_wc = self.origin_to_world(n_points, camera_mat, world_mat)
# batch_size x n_points x n_steps
step_depths = depth_range[0] + \
torch.linspace(0., 1., steps=n_steps).reshape(1, 1, -1) * (
depth_range[1] - depth_range[0])
step_depths = step_depths.to(self.device)
step_depths = step_depths.repeat(batch_size, n_points, 1)
if ray_jittering:
step_depths = self.add_noise_to_interval(step_depths)
point_pos_wc = self.get_evaluation_points(pixel_pos_wc, camera_pos_wc,
step_depths) # shape (batch, num of eval points, 3)
return point_pos_wc
def volume_render_image(self, volume, camera_mat, world_mat, batch_size, add_noise):
img_res = self.feature_img_resolution
n_steps = self.n_ray_samples
point_pos_wc = self.cast_ray_and_get_eval_points(img_res, batch_size, self.depth_range, n_steps,
camera_mat, world_mat,
add_noise) # shape (batch, num of eval points, 3)
volume_features = self.trilinear_interpolator(volume,
point_pos_wc.unsqueeze(
1)).squeeze(2) # shape (batch, channel, num of eval points)
# mask out out-of-bound positions
padding = 0.01
positions_valid = torch.all(point_pos_wc <= 1.0 + padding, dim=-1) & \
torch.all(point_pos_wc >= -1.0 - padding, dim=-1)
positions_valid = positions_valid.unsqueeze(1) \
.repeat(1, volume_features.shape[1], 1) # shape (batch, channel, num of eval points,)
volume_features[~positions_valid] = 0.0
if add_noise:
# As done in NeRF, add noise during training
volume_features += torch.randn_like(volume_features)
features = self.feature_tf(volume_features) # shape(batch, channel, num of eval points)
alphas = self.alpha_tf(volume_features) # shape(batch, 1, num of eval points)
# Reshape
n_points = img_res * img_res
features = features.reshape(
batch_size,
-1, # channels
n_points,
n_steps,
)
alphas = alphas.reshape(
batch_size,
n_points,
n_steps
)
# DVR composition
weights = self.calc_volume_weights(alphas)
feat_map = torch.sum(weights.unsqueeze(1) * features, dim=-1) # shape (Batch, channel, n_points)
# Reformat output
feat_map = feat_map.reshape(batch_size, -1, img_res, img_res) # B x feat x h x w
feat_map = feat_map.permute(0, 1, 3, 2) # new to flip x/y
return feat_map
@staticmethod
def arrange_pixels(resolution, batch_size, image_range=(-1., 1.)):
''' Arranges pixels for given resolution in range image_range.
The function returns the unscaled pixel locations as integers and the
scaled float values.
Args:
resolution (tuple): image resolution
batch_size (int): batch size
image_range (tuple): range of output points (default [-1, 1])
'''
h, w = resolution
# Arrange pixel location in scale resolution
pixel_locations = torch.meshgrid(torch.arange(0, w), torch.arange(0, h))
pixel_locations = torch.stack(
[pixel_locations[0], pixel_locations[1]],
dim=-1).long().view(1, -1, 2).repeat(batch_size, 1, 1)
pixel_scaled = pixel_locations.clone().float()
# Shift and scale points to match image_range
scale = (image_range[1] - image_range[0])
loc = scale / 2
pixel_scaled[:, :, 0] = scale * pixel_scaled[:, :, 0] / (w - 1) - loc
pixel_scaled[:, :, 1] = scale * pixel_scaled[:, :, 1] / (h - 1) - loc
return pixel_locations, pixel_scaled
def origin_to_world(self, n_points, camera_mat, world_mat):
""" Transforms origin (camera location) to world coordinates.
Args:
n_points (int): how often the transformed origin is repeated in the
form (batch_size, n_points, 3)
camera_mat (tensor): camera matrix
world_mat (tensor): world matrix
"""
batch_size = camera_mat.shape[0]
# Create origin in homogen coordinates
p = torch.zeros(batch_size, 4, n_points).to(self.device)
p[:, -1] = 1.
# Apply transformation
p_world = world_mat @ camera_mat @ p
# Transform points back to 3D coordinates
p_world = p_world[:, :3].permute(0, 2, 1)
return p_world
@staticmethod
def transform_to_world(pixels, depth, camera_mat, world_mat, use_absolute_depth=True):
''' Transforms pixel positions p with given depth value d to world coordinates.
Args:
pixels (tensor): pixel tensor of size B x N x 2
depth (tensor): depth tensor of size B x N x 1
camera_mat (tensor): camera matrix
world_mat (tensor): world matrix
'''
assert (pixels.shape[-1] == 2)
# Transform pixels to homogen coordinates
pixels = pixels.permute(0, 2, 1)
pixels = torch.cat([pixels, torch.ones_like(pixels)], dim=1)
# Project pixels into camera space
if use_absolute_depth:
pixels[:, :2] = pixels[:, :2] * depth.permute(0, 2, 1).abs()
pixels[:, 2:3] = pixels[:, 2:3] * depth.permute(0, 2, 1)
else:
pixels[:, :3] = pixels[:, :3] * depth.permute(0, 2, 1)
# Transform pixels to world space
p_world = world_mat @ camera_mat @ pixels
# Transform p_world back to 3D coordinates
p_world = p_world[:, :3].permute(0, 2, 1)
return p_world
@staticmethod
def calc_volume_weights(alpha):
# alpha: shape (batch, res*res, step_num)
weights = alpha * \
torch.cumprod(torch.cat([
torch.ones_like(alpha[:, :, :1]),
(1. - alpha + 1e-10), ], dim=-1), dim=-1)[..., :-1]
return weights
@staticmethod
def get_evaluation_points(pixels_world, camera_world, di):
batch_size = pixels_world.shape[0]
ray = pixels_world - camera_world
p = camera_world.unsqueeze(-2).contiguous() + \
di.unsqueeze(-1).contiguous() * ray.unsqueeze(-2).contiguous()
p = p.reshape(batch_size, -1, 3)
return p
@staticmethod
def add_noise_to_interval(di):
di_mid = .5 * (di[..., 1:] + di[..., :-1])
di_high = torch.cat([di_mid, di[..., -1:]], dim=-1)
di_low = torch.cat([di[..., :1], di_mid], dim=-1)
noise = torch.rand_like(di_low)
ti = di_low + (di_high - di_low) * noise
return ti
@staticmethod
def get_camera_mat(fov, invert=True):
focal = 1. / np.tan(0.5 * np.radians(fov))
focal = focal.astype(np.float32)
mat = torch.tensor([
[focal, 0., 0., 0.],
[0., focal, 0., 0.],
[0., 0., 1, 0.],
[0., 0., 0., 1.]
]).reshape(1, 4, 4)
if invert:
mat = torch.inverse(mat)
return mat
class DirectVolumeRenderer(pl.LightningModule):
""" Direct Volume Renderer.
Args:
n_ray_samples (int): number of samples per ray
depth_range (tuple): near and far depth plane
feature_img_resolution (int): resolution of volume-rendered image
neural_renderer (nn.Module): neural renderer
fov (float): field of view
"""
def __init__(self,
volume,
feature_transfer_function,
alpha_transfer_function,
n_ray_samples,
feature_img_resolution,
fov,
depth_range,
neural_renderer=None,
):
super().__init__()
self.neural_renderer = None if neural_renderer is None else neural_renderer
self.volume = nn.Parameter(volume.unsqueeze(0), requires_grad=False)
self.dvr_op = DirectVolumeRendering(n_ray_samples, feature_img_resolution, depth_range, fov,
feature_transfer_function, alpha_transfer_function)
def forward(self, world_mat, mode="training"):
batch_size = world_mat.shape[0]
volume_batch = self.volume.repeat(batch_size, 1, 1, 1, 1)
add_noise = mode == "training"
feature_img = self.dvr_op(volume_batch, world_mat, add_noise, self.device)
if self.neural_renderer is not None:
rgb = self.neural_renderer(feature_img)
else:
rgb = feature_img
return rgb
def predict_step(self, batch, _batch_idx, _data_loader_idx=None):
return self(batch, mode="predict")
| [
"numpy.radians",
"torch.ones_like",
"torch.rand_like",
"torch.stack",
"torch.cat",
"torch.randn_like",
"torch.arange",
"torch.tensor",
"torch.inverse",
"torch.linspace",
"torch.zeros",
"torch.all",
"torch.ones"
] | [((10269, 10310), 'torch.cat', 'torch.cat', (['[di_mid, di[..., -1:]]'], {'dim': '(-1)'}), '([di_mid, di[..., -1:]], dim=-1)\n', (10278, 10310), False, 'import torch\n'), ((10328, 10368), 'torch.cat', 'torch.cat', (['[di[..., :1], di_mid]'], {'dim': '(-1)'}), '([di[..., :1], di_mid], dim=-1)\n', (10337, 10368), False, 'import torch\n'), ((10385, 10408), 'torch.rand_like', 'torch.rand_like', (['di_low'], {}), '(di_low)\n', (10400, 10408), False, 'import torch\n'), ((5033, 5081), 'torch.all', 'torch.all', (['(point_pos_wc <= 1.0 + padding)'], {'dim': '(-1)'}), '(point_pos_wc <= 1.0 + padding, dim=-1)\n', (5042, 5081), False, 'import torch\n'), ((5112, 5161), 'torch.all', 'torch.all', (['(point_pos_wc >= -1.0 - padding)'], {'dim': '(-1)'}), '(point_pos_wc >= -1.0 - padding, dim=-1)\n', (5121, 5161), False, 'import torch\n'), ((5476, 5509), 'torch.randn_like', 'torch.randn_like', (['volume_features'], {}), '(volume_features)\n', (5492, 5509), False, 'import torch\n'), ((6971, 6989), 'torch.arange', 'torch.arange', (['(0)', 'w'], {}), '(0, w)\n', (6983, 6989), False, 'import torch\n'), ((6991, 7009), 'torch.arange', 'torch.arange', (['(0)', 'h'], {}), '(0, h)\n', (7003, 7009), False, 'import torch\n'), ((10847, 10865), 'torch.inverse', 'torch.inverse', (['mat'], {}), '(mat)\n', (10860, 10865), False, 'import torch\n'), ((2842, 2874), 'torch.ones', 'torch.ones', (['batch_size', 'n_pts', '(1)'], {}), '(batch_size, n_pts, 1)\n', (2852, 2874), False, 'import torch\n'), ((8038, 8074), 'torch.zeros', 'torch.zeros', (['batch_size', '(4)', 'n_points'], {}), '(batch_size, 4, n_points)\n', (8049, 8074), False, 'import torch\n'), ((8914, 8937), 'torch.ones_like', 'torch.ones_like', (['pixels'], {}), '(pixels)\n', (8929, 8937), False, 'import torch\n'), ((10643, 10751), 'torch.tensor', 'torch.tensor', (['[[focal, 0.0, 0.0, 0.0], [0.0, focal, 0.0, 0.0], [0.0, 0.0, 1, 0.0], [0.0, \n 0.0, 0.0, 1.0]]'], {}), '([[focal, 0.0, 0.0, 0.0], [0.0, focal, 0.0, 0.0], [0.0, 0.0, 1,\n 0.0], [0.0, 0.0, 0.0, 1.0]])\n', (10655, 10751), False, 'import torch\n'), ((10571, 10586), 'numpy.radians', 'np.radians', (['fov'], {}), '(fov)\n', (10581, 10586), True, 'import numpy as np\n'), ((3676, 3715), 'torch.linspace', 'torch.linspace', (['(0.0)', '(1.0)'], {'steps': 'n_steps'}), '(0.0, 1.0, steps=n_steps)\n', (3690, 3715), False, 'import torch\n'), ((9659, 9691), 'torch.ones_like', 'torch.ones_like', (['alpha[:, :, :1]'], {}), '(alpha[:, :, :1])\n', (9674, 9691), False, 'import torch\n'), ((7037, 7098), 'torch.stack', 'torch.stack', (['[pixel_locations[0], pixel_locations[1]]'], {'dim': '(-1)'}), '([pixel_locations[0], pixel_locations[1]], dim=-1)\n', (7048, 7098), False, 'import torch\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
GOAL
Compute time-mean OHF in each grid cell
PROGRAMMER
<NAME>
LAST UPDATE
29/04/2020
'''
# Options
exp = 'D012'
save_var = True
start_year = 2130
end_year = 2179
# Standard libraries
import numpy as np
from netCDF4 import Dataset
import time
start_time = time.time()
# Working directories
dir_input = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/post-proc/' + str(exp) + '/OHT_transects/'
dir_grid = '/nobackup/rossby24/proj/rossby/joint_exp/oseaice/grid/'
dir_output = dir_input
# Load modeled OHT (computed with compute_oht.py)
filename = dir_input + 'oht_' + str(exp) + '.npy'
oht_u,oht_v = np.load(filename)
# Load grid sizes in X (gridx), Y (gridy)
filename = dir_grid + 'coordinates.nc'
fh = Dataset(filename, mode='r')
gridx = fh.variables['e1u'][:]
gridy = fh.variables['e2u'][:]
fh.close()
# Load grid size in Z (gridz) and depth
filename = dir_grid + 'mesh_zgr.nc'
fh = Dataset(filename, mode='r')
gridz = fh.variables['e3u'][:]
gridz = gridz[0,:,:,:]
mbathy = fh.variables['mbathy'][:]
mbathy = mbathy[0,:,:]
gdepu = fh.variables['gdepu'][:]
gdepu = gdepu[0,:,:,:]
depth=np.zeros((np.size(mbathy,0),np.size(mbathy,1)))
for i in np.arange(np.size(mbathy,0)):
for j in np.arange(np.size(mbathy,1)):
depth[i,j] = gdepu[mbathy[i,j],i,j]
nz,ny,nx = gridz.shape
fh.close()
# Dimensions
nyears = np.size(oht_u,0)
nmy = np.size(oht_u,1)
ny = np.size(oht_u,2)
nx = np.size(oht_u,3)
# Compute time-mean OHF (W/m^2) in each grid cell
oht_u_mean = np.nanmean(oht_u,axis=(0,1))
oht_u_mean = oht_u_mean / (gridy * depth)
oht_v_mean = np.nanmean(oht_v,axis=(0,1))
oht_v_mean = oht_v_mean / (gridx * depth)
# Check dimensions of OHF
print(np.size(oht_u_mean))
print(np.size(oht_u_mean,0))
print(np.size(oht_u_mean,1))
# Save variables
if save_var == True:
filename = dir_output + 'oht_mean_' + str(exp) + '.npy'
np.save(filename,[oht_u_mean,oht_v_mean])
# Computing time
print("--- %s seconds ---" % (time.time() - start_time))
| [
"numpy.size",
"netCDF4.Dataset",
"numpy.nanmean",
"numpy.load",
"time.time",
"numpy.save"
] | [((322, 333), 'time.time', 'time.time', ([], {}), '()\n', (331, 333), False, 'import time\n'), ((668, 685), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (675, 685), True, 'import numpy as np\n'), ((773, 800), 'netCDF4.Dataset', 'Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (780, 800), False, 'from netCDF4 import Dataset\n'), ((956, 983), 'netCDF4.Dataset', 'Dataset', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (963, 983), False, 'from netCDF4 import Dataset\n'), ((1389, 1406), 'numpy.size', 'np.size', (['oht_u', '(0)'], {}), '(oht_u, 0)\n', (1396, 1406), True, 'import numpy as np\n'), ((1412, 1429), 'numpy.size', 'np.size', (['oht_u', '(1)'], {}), '(oht_u, 1)\n', (1419, 1429), True, 'import numpy as np\n'), ((1434, 1451), 'numpy.size', 'np.size', (['oht_u', '(2)'], {}), '(oht_u, 2)\n', (1441, 1451), True, 'import numpy as np\n'), ((1456, 1473), 'numpy.size', 'np.size', (['oht_u', '(3)'], {}), '(oht_u, 3)\n', (1463, 1473), True, 'import numpy as np\n'), ((1537, 1567), 'numpy.nanmean', 'np.nanmean', (['oht_u'], {'axis': '(0, 1)'}), '(oht_u, axis=(0, 1))\n', (1547, 1567), True, 'import numpy as np\n'), ((1621, 1651), 'numpy.nanmean', 'np.nanmean', (['oht_v'], {'axis': '(0, 1)'}), '(oht_v, axis=(0, 1))\n', (1631, 1651), True, 'import numpy as np\n'), ((1225, 1243), 'numpy.size', 'np.size', (['mbathy', '(0)'], {}), '(mbathy, 0)\n', (1232, 1243), True, 'import numpy as np\n'), ((1725, 1744), 'numpy.size', 'np.size', (['oht_u_mean'], {}), '(oht_u_mean)\n', (1732, 1744), True, 'import numpy as np\n'), ((1752, 1774), 'numpy.size', 'np.size', (['oht_u_mean', '(0)'], {}), '(oht_u_mean, 0)\n', (1759, 1774), True, 'import numpy as np\n'), ((1781, 1803), 'numpy.size', 'np.size', (['oht_u_mean', '(1)'], {}), '(oht_u_mean, 1)\n', (1788, 1803), True, 'import numpy as np\n'), ((1907, 1950), 'numpy.save', 'np.save', (['filename', '[oht_u_mean, oht_v_mean]'], {}), '(filename, [oht_u_mean, oht_v_mean])\n', (1914, 1950), True, 'import numpy as np\n'), ((1168, 1186), 'numpy.size', 'np.size', (['mbathy', '(0)'], {}), '(mbathy, 0)\n', (1175, 1186), True, 'import numpy as np\n'), ((1186, 1204), 'numpy.size', 'np.size', (['mbathy', '(1)'], {}), '(mbathy, 1)\n', (1193, 1204), True, 'import numpy as np\n'), ((1268, 1286), 'numpy.size', 'np.size', (['mbathy', '(1)'], {}), '(mbathy, 1)\n', (1275, 1286), True, 'import numpy as np\n'), ((1997, 2008), 'time.time', 'time.time', ([], {}), '()\n', (2006, 2008), False, 'import time\n')] |
#!/usr/bin/env python3
import os, sys, platform, math
import ctypes as ct
import numpy as np
class DubinsWrapper:
libgdip = None
def init_library(self):
try:
file_extension = '.so'
if platform.system() =='cli':
file_extension = '.dll'
elif platform.system() =='Windows':
file_extension = '.dll'
elif platform.system() == 'Darwin':
file_extension = '.dylib'
else:
file_extension = '.so'
libfullpath = os.path.abspath(os.path.join(os.path.dirname(__file__), '../gdip/lib/libGDIP' + file_extension))
print("Loading " + libfullpath)
DubinsWrapper.libgdip = ct.CDLL(libfullpath)
except:
print ('----------------------------------------------------')
print ('The GDIP library could not be loaded.')
print ('----------------------------------------------------')
exit(1)
DubinsWrapper.libgdip.new_GdipAPI.restype = ct.c_void_p
def __del__(self):
#print("Destruct Dubins maneuver")
self.gdip_destruct(self.object_hanle)
def __init__(self):
#initialize the GDIP library (only for the first time)
if DubinsWrapper.libgdip is None:
self.init_library()
# create instance of the maneuver
self.object_hanle = self.libgdip.new_GdipAPI()
self.gdip_set_configurations = ct.CFUNCTYPE \
(None, ct.c_void_p, ct.c_double*3, ct.c_double*3, ct.c_double) \
(("python_set_configurations", DubinsWrapper.libgdip))
self.gdip_set_configurations_dip = ct.CFUNCTYPE \
(None, ct.c_void_p, ct.c_double*2, ct.c_double*2, ct.c_double*2, ct.c_double*2, ct.c_double) \
(("python_set_configurations_dip", DubinsWrapper.libgdip))
self.gdip_set_configurations_gdip = ct.CFUNCTYPE \
(None, ct.c_void_p, ct.c_double*2, ct.c_double*2, ct.c_double, ct.c_double*2, ct.c_double*2, ct.c_double, ct.c_double) \
(("python_set_configurations_gdip", DubinsWrapper.libgdip))
self.gdip_get_length = ct.CFUNCTYPE (ct.c_double, ct.c_void_p) (("python_get_length", DubinsWrapper.libgdip))
self.gdip_sample_state_to_tmp = ct.CFUNCTYPE (None, ct.c_void_p, ct.c_double) (("python_sample_state_to_tmp", DubinsWrapper.libgdip))
self.gdip_get_tmp_x = ct.CFUNCTYPE(ct.c_double, ct.c_void_p) (("python_get_tmp_x", DubinsWrapper.libgdip))
self.gdip_get_tmp_y = ct.CFUNCTYPE(ct.c_double, ct.c_void_p) (("python_get_tmp_y", DubinsWrapper.libgdip))
self.gdip_get_tmp_theta = ct.CFUNCTYPE(ct.c_double, ct.c_void_p) (("python_get_tmp_theta", DubinsWrapper.libgdip))
self.gdip_destruct = ct.CFUNCTYPE(None, ct.c_void_p) (("python_destruct", DubinsWrapper.libgdip))
@staticmethod
def shortest_path(start, end, turning_radius):
"""
Construct Dubins maneuver between two configurations
Parameters
----------
start: numpy array(double*3)
start configuration
end: numpy array(double*3)
end configuration
turning_radius: double
minimum turning radius
"""
man = DubinsWrapper()
arrtype = ct.c_double * 3
arr_p1 = arrtype()
arr_p2 = arrtype()
c_radius = ct.c_double()
for i in range(0,3):
arr_p1[i] = start[i]
arr_p2[i] = end[i]
c_radius = turning_radius
man.gdip_set_configurations(man.object_hanle, arr_p1, arr_p2, c_radius)
return man
@staticmethod
def shortest_path_DIP(point1, interval1, point2, interval2, turning_radius):
"""
Construct Dubins maneuver between two configurations
Parameters
----------
point1: numpy array(double*2)
start position
interval1: numpy array(double*2)
angle interval for point1 (right_angle, diff)
the interval is then [right_angle, right_angle + diff]
point2: numpy array(double*2)
end position
interval2: numpy array(double*2)
angle interval for point2 (right_angle, diff)
the interval is then [right_angle, right_angle + diff]
turning_radius: double
minimum turning radius
"""
man = DubinsWrapper()
arrtype = ct.c_double * 2
arr_p1 = arrtype()
arr_i1 = arrtype()
arr_p2 = arrtype()
arr_i2 = arrtype()
c_radius = ct.c_double()
arr_p1[0] = point1[0]
arr_p1[1] = point1[1]
arr_i1[0] = interval1[0]
arr_i1[1] = interval1[1]
arr_p2[0] = point2[0]
arr_p2[1] = point2[1]
arr_i2[0] = interval2[0]
arr_i2[1] = interval2[1]
c_radius = turning_radius
man.gdip_set_configurations_dip(man.object_hanle, arr_p1, arr_i1, arr_p2, arr_i2, c_radius)
return man
@staticmethod
def shortest_path_GDIP(point1, interval1, radius1, point2, interval2, radius2, turning_radius):
"""
Construct Dubins maneuver between two configurations
Parameters
----------
point1: numpy array(double*2)
start position
interval1: numpy array(double*2)
angle interval for point1 (right_angle, diff)
the interval is then [right_angle, right_angle + diff]
point2: numpy array(double*2)
end position
interval2: numpy array(double*2)
angle interval for point2 (right_angle, diff)
the interval is then [right_angle, right_angle + diff]
turning_radius: double
minimum turning radius
"""
man = DubinsWrapper()
arrtype = ct.c_double * 2
arr_p1 = arrtype()
arr_i1 = arrtype()
arr_p2 = arrtype()
arr_i2 = arrtype()
arr_p1[0] = point1[0]
arr_p1[1] = point1[1]
arr_i1[0] = interval1[0]
arr_i1[1] = interval1[1]
arr_p2[0] = point2[0]
arr_p2[1] = point2[1]
arr_i2[0] = interval2[0]
arr_i2[1] = interval2[1]
c_radius = ct.c_double()
c_radius = turning_radius
c_radius1 = ct.c_double()
c_radius1 = radius1
c_radius2 = ct.c_double()
c_radius2 = radius2
man.gdip_set_configurations_gdip(man.object_hanle, arr_p1, arr_i1, c_radius1, arr_p2, arr_i2, c_radius2, c_radius)
return man
def get_length(self):
"""
Get length of the maneuver
Returns
-------
bool
True if there is collision, False otherwise
"""
return self.gdip_get_length(self.object_hanle)
def sample_many(self, step):
"""
Sample the manuver based on the step
Parameters
----------
step: double
step for the sampling
Returns
-------
states
"""
length = self.get_length()
lens = np.arange(0, length, step)
path = []
for l in lens:
self.gdip_sample_state_to_tmp(self.object_hanle, l)
state = [self.gdip_get_tmp_x(self.object_hanle), self.gdip_get_tmp_y(self.object_hanle), self.gdip_get_tmp_theta(self.object_hanle)]
path.append(state)
return [path, lens]
if __name__ == "__main__":
a = DubinsWrapper()
a.shortest_path((0,0,0), (1,1,2), 1)
print(a.get_length()) | [
"ctypes.CFUNCTYPE",
"os.path.dirname",
"platform.system",
"ctypes.c_double",
"ctypes.CDLL",
"numpy.arange"
] | [((3432, 3445), 'ctypes.c_double', 'ct.c_double', ([], {}), '()\n', (3443, 3445), True, 'import ctypes as ct\n'), ((4623, 4636), 'ctypes.c_double', 'ct.c_double', ([], {}), '()\n', (4634, 4636), True, 'import ctypes as ct\n'), ((6274, 6287), 'ctypes.c_double', 'ct.c_double', ([], {}), '()\n', (6285, 6287), True, 'import ctypes as ct\n'), ((6343, 6356), 'ctypes.c_double', 'ct.c_double', ([], {}), '()\n', (6354, 6356), True, 'import ctypes as ct\n'), ((6406, 6419), 'ctypes.c_double', 'ct.c_double', ([], {}), '()\n', (6417, 6419), True, 'import ctypes as ct\n'), ((7138, 7164), 'numpy.arange', 'np.arange', (['(0)', 'length', 'step'], {}), '(0, length, step)\n', (7147, 7164), True, 'import numpy as np\n'), ((734, 754), 'ctypes.CDLL', 'ct.CDLL', (['libfullpath'], {}), '(libfullpath)\n', (741, 754), True, 'import ctypes as ct\n'), ((1508, 1586), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['None', 'ct.c_void_p', '(ct.c_double * 3)', '(ct.c_double * 3)', 'ct.c_double'], {}), '(None, ct.c_void_p, ct.c_double * 3, ct.c_double * 3, ct.c_double)\n', (1520, 1586), True, 'import ctypes as ct\n'), ((1711, 1828), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['None', 'ct.c_void_p', '(ct.c_double * 2)', '(ct.c_double * 2)', '(ct.c_double * 2)', '(ct.c_double * 2)', 'ct.c_double'], {}), '(None, ct.c_void_p, ct.c_double * 2, ct.c_double * 2, ct.\n c_double * 2, ct.c_double * 2, ct.c_double)\n', (1723, 1828), True, 'import ctypes as ct\n'), ((1957, 2100), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['None', 'ct.c_void_p', '(ct.c_double * 2)', '(ct.c_double * 2)', 'ct.c_double', '(ct.c_double * 2)', '(ct.c_double * 2)', 'ct.c_double', 'ct.c_double'], {}), '(None, ct.c_void_p, ct.c_double * 2, ct.c_double * 2, ct.\n c_double, ct.c_double * 2, ct.c_double * 2, ct.c_double, ct.c_double)\n', (1969, 2100), True, 'import ctypes as ct\n'), ((2209, 2247), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['ct.c_double', 'ct.c_void_p'], {}), '(ct.c_double, ct.c_void_p)\n', (2221, 2247), True, 'import ctypes as ct\n'), ((2337, 2381), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['None', 'ct.c_void_p', 'ct.c_double'], {}), '(None, ct.c_void_p, ct.c_double)\n', (2349, 2381), True, 'import ctypes as ct\n'), ((2470, 2508), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['ct.c_double', 'ct.c_void_p'], {}), '(ct.c_double, ct.c_void_p)\n', (2482, 2508), True, 'import ctypes as ct\n'), ((2585, 2623), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['ct.c_double', 'ct.c_void_p'], {}), '(ct.c_double, ct.c_void_p)\n', (2597, 2623), True, 'import ctypes as ct\n'), ((2704, 2742), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['ct.c_double', 'ct.c_void_p'], {}), '(ct.c_double, ct.c_void_p)\n', (2716, 2742), True, 'import ctypes as ct\n'), ((2823, 2854), 'ctypes.CFUNCTYPE', 'ct.CFUNCTYPE', (['None', 'ct.c_void_p'], {}), '(None, ct.c_void_p)\n', (2835, 2854), True, 'import ctypes as ct\n'), ((228, 245), 'platform.system', 'platform.system', ([], {}), '()\n', (243, 245), False, 'import os, sys, platform, math\n'), ((312, 329), 'platform.system', 'platform.system', ([], {}), '()\n', (327, 329), False, 'import os, sys, platform, math\n'), ((586, 611), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (601, 611), False, 'import os, sys, platform, math\n'), ((400, 417), 'platform.system', 'platform.system', ([], {}), '()\n', (415, 417), False, 'import os, sys, platform, math\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 13:40:20 2020
@author: tjards
This module implements potential fields for obstacle avoidance
based on the technique @ ref: https://arxiv.org/pdf/1704.04672.pdf
"""
import numpy as np
class potentialField:
def __init__(self, traj, Po, gamma=1, eta=1 ,obsRad=1, obsRange = 10):
self.Po = Po
self.gamma = gamma
self.eta = eta
self.obsRad = obsRad
self.default_ctrlType = traj.ctrlType
self.obsRange = obsRange
# def overlap(self, type, flag):
# print("collision detected: error (%s)" % (type))
# self.alert_overLap = np.seterrcall(self.overlap)
# self.alert = np.seterr(divide='call')
def computeAttract(self):
# pd is the vehicle position (vector)
# pt is the target position (vector)
# gamma is the scaling factor
self.va = -np.multiply(self.gamma,(self.pd-self.pt))
#return va
# execute this only if with obstacle avoidance region
def computeRepulse(self):
# pd is the vehicle position (vector)
# Po is the obstacle position(s) (array of vectors):
# xo_1 xo_2 ... xo_n
# yo_1 yo_2 ... yo_n
# zo_1 zo_2 ... zo_n
# example: Po = np.array([[x1,x2,x3],[y1,y2,y3],[z1,z2,z3]])
# eta is the scaling factor
self.nObs = len(self.Po[1]) # number of obstacles
self.Pdo = np.zeros((3,self.nObs)) # initialize array of differences
self.Pdo_mags = np.zeros((1,self.nObs)) # intialize magnitudes
self.vr = np.zeros((3,1))
self.flag = 0 # count the obstacles in range
for i in range(0,self.nObs):
self.Pdo[:,[i]] = self.pd - self.Po[:,[i]]
self.Pdo_mags[0,i] = np.linalg.norm(self.Pdo[:,i])
# only count the obstacle if inside the radius
#if 0 < self.Pdo_mags[0,i] < self.obsRad:
if 0 < self.Pdo_mags[0,i] < self.obsRange:
self.vr += self.eta*np.multiply(self.Pdo[:,[i]],np.divide(1,np.power(self.Pdo_mags[0,i],4)))
self.flag += 1
#return Pdo, Pdo_mags, vr, flag
def updateTraj(self, pd, pt, traj):
self.pd = np.array(pd,ndmin=2).transpose()
self.pt = np.array(pt,ndmin=2).transpose()
self.computeAttract()
#va = computeAttract(pd,pt,gamma)
self.computeRepulse()
#Pdo, Pdo_mags, vr, flag = computeRepulse(pd,Po,eta,obsRad)
self.vd = self.va - self.vr
if self.flag > 0:
#print('obstacle detected')
traj.ctrlType = "xyz_vel" # use velocity control
traj.sDes[3:6] = np.squeeze(self.vd)
else:
traj.ctrlType = self.default_ctrlType # return to user-defined control type
#%% Test
# pd = np.array([0,0,0],ndmin=2).transpose()
# #Po = np.array([[x1,x2,x3],[y1,y2,y3],[z1,z2,z3]])
# Po = np.array([[2,1,1],[1.2,1.1,1.1],[1.3,1,1.7]])
# pt = np.array([5,5,5],ndmin=2).transpose()
# gamma = 1
# eta = 0.2
# obsRad = 5 #only count obstacles in this radius
# vd, flag = computeDesVel(pd,pt,Po,gamma,eta,obsRad)
| [
"numpy.multiply",
"numpy.power",
"numpy.squeeze",
"numpy.array",
"numpy.zeros",
"numpy.linalg.norm"
] | [((1551, 1575), 'numpy.zeros', 'np.zeros', (['(3, self.nObs)'], {}), '((3, self.nObs))\n', (1559, 1575), True, 'import numpy as np\n'), ((1640, 1664), 'numpy.zeros', 'np.zeros', (['(1, self.nObs)'], {}), '((1, self.nObs))\n', (1648, 1664), True, 'import numpy as np\n'), ((1707, 1723), 'numpy.zeros', 'np.zeros', (['(3, 1)'], {}), '((3, 1))\n', (1715, 1723), True, 'import numpy as np\n'), ((962, 1004), 'numpy.multiply', 'np.multiply', (['self.gamma', '(self.pd - self.pt)'], {}), '(self.gamma, self.pd - self.pt)\n', (973, 1004), True, 'import numpy as np\n'), ((1942, 1972), 'numpy.linalg.norm', 'np.linalg.norm', (['self.Pdo[:, i]'], {}), '(self.Pdo[:, i])\n', (1956, 1972), True, 'import numpy as np\n'), ((2932, 2951), 'numpy.squeeze', 'np.squeeze', (['self.vd'], {}), '(self.vd)\n', (2942, 2951), True, 'import numpy as np\n'), ((2436, 2457), 'numpy.array', 'np.array', (['pd'], {'ndmin': '(2)'}), '(pd, ndmin=2)\n', (2444, 2457), True, 'import numpy as np\n'), ((2487, 2508), 'numpy.array', 'np.array', (['pt'], {'ndmin': '(2)'}), '(pt, ndmin=2)\n', (2495, 2508), True, 'import numpy as np\n'), ((2248, 2280), 'numpy.power', 'np.power', (['self.Pdo_mags[0, i]', '(4)'], {}), '(self.Pdo_mags[0, i], 4)\n', (2256, 2280), True, 'import numpy as np\n')] |
import argparse
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import scipy as sp
import scipy.stats
import pyemma
from pyemma.util.contexts import settings
import MDAnalysis as mda
# My own functions
from pensa import *
def workflow_torsions_jsd(args, feat_a, feat_b, data_a, data_b, tors='bb'):
# Use only features that are common to both ensembles
if args.only_common_sctors and tors=='sc':
select_a, select_b = select_common_features(feat_a[tors+'-torsions'],
feat_b[tors+'-torsions'])
else:
select_a = np.arange(len(feat_a[tors+'-torsions']))
select_b = np.arange(len(feat_b[tors+'-torsions']))
# Relative Entropy analysis with BB torsions
relen = relative_entropy_analysis(list(np.array(feat_a[tors+'-torsions'])[select_a]),
list(np.array(feat_b[tors+'-torsions'])[select_b]),
data_a[tors+'-torsions'][:,select_a],
data_b[tors+'-torsions'][:,select_b],
bin_width=None, bin_num=10, verbose=False,
override_name_check=args.override_name_check)
names, jsd, kld_ab, kld_ba = relen
# Save all results (per feature) in CSV files
np.savetxt(args.out_results+'_'+tors+'-torsions_relative-entropy.csv', np.array(relen).T,
fmt='%s', delimiter=',', header='Name, JSD(A,B), KLD(A,B), KLD(B,A)')
# Save the Jensen-Shannon distance as "B factor" in a PDB file
vis = residue_visualization(names, jsd, args.ref_file_a,
args.out_plots+"_"+tors+"-torsions_jsd.pdf",
args.out_vispdb+"_"+tors+"-torsions_jsd.pdb",
y_label='max. JS dist. of '+tors.upper()+' torsions')
# Print the features with the highest values
print(tors.upper()+" torsions with the strongest deviations (JSD):")
sf = sort_features(names, jsd)
for f in sf[:args.print_num]: print(f[0], f[1])
return names, jsd
def workflow_torsions_kss(args, feat_a, feat_b, data_a, data_b, tors='bb'):
# Use only features that are common to both ensembles
if args.only_common_sctors and tors=='sc':
select_a, select_b = select_common_features(feat_a[tors+'-torsions'],
feat_b[tors+'-torsions'])
else:
select_a = np.arange(len(feat_a[tors+'-torsions']))
select_b = np.arange(len(feat_b[tors+'-torsions']))
# Kolmogorov-Smirnov analysis with BB torsions
ksana = kolmogorov_smirnov_analysis(list(np.array(feat_a[tors+'-torsions'])[select_a]),
list(np.array(feat_b[tors+'-torsions'])[select_b]),
data_a[tors+'-torsions'][:,select_a],
data_b[tors+'-torsions'][:,select_b],
verbose=False,
override_name_check=args.override_name_check)
names, kss, ksp = ksana
# Save all results (per feature) in CSV files
np.savetxt(args.out_results+'_'+tors+'-torsions_kolmogorov-smirnov.csv', np.array(ksana).T,
fmt='%s', delimiter=',', header='Name, KSS(A,B), p-value')
# Save the Kolmogorov-Smirnov statistic as "B factor" in a PDB file
vis = residue_visualization(names, kss, args.ref_file_a,
args.out_plots+"_"+tors+"-torsions_kss.pdf",
args.out_vispdb+"_"+tors+"-torsions_kss.pdb",
y_label='max. KS stat. of '+tors.upper()+' torsions')
# Print the features with the highest values
print(tors.upper()+" torsions with the strongest deviations (KSS):")
sf = sort_features(names, kss)
for f in sf[:args.print_num]: print(f[0], f[1])
return names, kss
def workflow_torsions_ssi(args, feat_a, feat_b, data_a, data_b, tors='bb'):
# Use only features that are common to both ensembles
if args.only_common_sctors and tors=='sc':
select_a, select_b = select_common_features(feat_a[tors+'-torsions'],
feat_b[tors+'-torsions'])
else:
select_a = np.arange(len(feat_a[tors+'-torsions']))
select_b = np.arange(len(feat_b[tors+'-torsions']))
# SSI analysis with BB torsions
ana = ssi_ensemble_analysis(feat_a, feat_b, data_a, data_b, torsions = tors,
verbose=False, override_name_check=args.override_name_check)
resnames, ssi = ana
# Save all results (per feature) in CSV files
np.savetxt(args.out_results+'_'+tors+'-torsions_state-specific-information.csv', np.array(ana).T,
fmt='%s', delimiter=',', header='Name, SSI(A,B)')
# Save the state-specific information as "B factor" in a PDB file
vis = residue_visualization(resnames, ssi, args.ref_file_a,
args.out_plots+"_"+tors+"-torsions_ssi.pdf",
args.out_vispdb+"_"+tors+"-torsions_ssi.pdb",
y_label='SSI of '+tors.upper()+' torsions')
# Print the features with the highest values
print(tors.upper()+" torsions with the strongest deviations (SSI):")
sf = sort_features(resnames, ssi)
for f in sf[:args.print_num]: print(f[0], f[1])
return resnames, ssi
# -------------#
# --- MAIN --- #
# -------------#
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument( "--ref_file_a", type=str, default='traj/rhodopsin_arrbound_receptor.gro')
parser.add_argument( "--trj_file_a", type=str, default='traj/rhodopsin_arrbound_receptor.xtc')
parser.add_argument( "--ref_file_b", type=str, default='traj/rhodopsin_gibound_receptor.gro')
parser.add_argument( "--trj_file_b", type=str, default='traj/rhodopsin_gibound_receptor.xtc')
parser.add_argument( "--out_plots", type=str, default='plots/rhodopsin_receptor' )
parser.add_argument( "--out_vispdb", type=str, default='vispdb/rhodopsin_receptor' )
parser.add_argument( "--out_results", type=str, default='results/rhodopsin_receptor' )
parser.add_argument( "--start_frame", type=int, default=0 )
parser.add_argument( "--print_num", type=int, default=12 )
parser.add_argument( "--override_name_check", dest="override_name_check", default=False, action="store_true")
parser.add_argument( "--only_common_sctors", dest="only_common_sctors", default=False, action="store_true")
args = parser.parse_args()
# -- FEATURES --
# Load Features
feat_a, data_a = get_structure_features(args.ref_file_a, args.trj_file_a, args.start_frame)
feat_b, data_b = get_structure_features(args.ref_file_b, args.trj_file_b, args.start_frame)
# Report dimensions
print('Feature dimensions from', args.trj_file_a)
for k in data_a.keys():
print(k, data_a[k].shape)
print('Feature dimensions from', args.trj_file_b)
for k in data_b.keys():
print(k, data_b[k].shape)
# -- TORSIONS -- #
print('BACKBONE TORSIONS')
names, jsd = workflow_torsions_jsd(args, feat_a, feat_b, data_a, data_b, tors='bb')
names, kss = workflow_torsions_kss(args, feat_a, feat_b, data_a, data_b, tors='bb')
names, ssi = workflow_torsions_ssi(args, feat_a, feat_b, data_a, data_b, tors='bb')
print('SIDECHAIN TORSIONS')
names, jsd = workflow_torsions_jsd(args, feat_a, feat_b, data_a, data_b, tors='sc')
names, kss = workflow_torsions_kss(args, feat_a, feat_b, data_a, data_b, tors='sc')
names, ssi = workflow_torsions_ssi(args, feat_a, feat_b, data_a, data_b, tors='sc')
# -- BACKBONE C-ALPHA DISTANCES --
print('BACKBONE C-ALPHA DISTANCES')
# Relative entropy analysis for C-alpha distances
relen = relative_entropy_analysis(feat_a['bb-distances'], feat_b['bb-distances'],
data_a['bb-distances'], data_b['bb-distances'],
bin_width=0.01, verbose=False)
names, jsd, kld_ab, kld_ba = relen
# Save all results (per feature) in a CSV file
np.savetxt(args.out_results+'_bb-distances_relative-entropy.csv', np.array(relen).T,
fmt='%s', delimiter=',', header='Name, JSD(A,B), KLD(A,B), KLD(B,A)')
# Print the features with the highest values
print("Backbone C-alpha distances with the strongest deviations:")
sf = sort_features(names, jsd)
for f in sf[:args.print_num]: print(f[0], f[1])
# Visualize the deviations in a matrix plot
matrix = distances_visualization(names, jsd,
args.out_plots+"_bb-distances-distributions_jsd.pdf",
vmin = 0.0, vmax = 1.0)
# Difference-of-the-mean analysis for C-alpha distances
meanda = mean_difference_analysis(feat_a['bb-distances'], feat_b['bb-distances'],
data_a['bb-distances'], data_b['bb-distances'],
verbose=False)
names, avg, diff = meanda
# Save all results (per feature) in a CSV file
np.savetxt(args.out_results+'_bb-distances_difference-of-mean.csv', np.array(meanda).T,
fmt='%s', delimiter=',', header='Name, average, difference')
# Sort the distances by their differences
print("Backbone C-alpha distances with the strongest differences of their mean value:")
sf = sort_features(names, diff)
for f in sf[:args.print_num]: print(f[0], f[1])
# Visualize the deviations in a matrix plot
matrix = distances_visualization(names, diff, args.out_plots+"_bb-diststances_difference-of-mean.pdf")
| [
"numpy.array",
"argparse.ArgumentParser"
] | [((5651, 5676), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5674, 5676), False, 'import argparse\n'), ((1442, 1457), 'numpy.array', 'np.array', (['relen'], {}), '(relen)\n', (1450, 1457), True, 'import numpy as np\n'), ((3317, 3332), 'numpy.array', 'np.array', (['ksana'], {}), '(ksana)\n', (3325, 3332), True, 'import numpy as np\n'), ((4866, 4879), 'numpy.array', 'np.array', (['ana'], {}), '(ana)\n', (4874, 4879), True, 'import numpy as np\n'), ((8421, 8436), 'numpy.array', 'np.array', (['relen'], {}), '(relen)\n', (8429, 8436), True, 'import numpy as np\n'), ((9429, 9445), 'numpy.array', 'np.array', (['meanda'], {}), '(meanda)\n', (9437, 9445), True, 'import numpy as np\n'), ((819, 855), 'numpy.array', 'np.array', (["feat_a[tors + '-torsions']"], {}), "(feat_a[tors + '-torsions'])\n", (827, 855), True, 'import numpy as np\n'), ((910, 946), 'numpy.array', 'np.array', (["feat_b[tors + '-torsions']"], {}), "(feat_b[tors + '-torsions'])\n", (918, 946), True, 'import numpy as np\n'), ((2721, 2757), 'numpy.array', 'np.array', (["feat_a[tors + '-torsions']"], {}), "(feat_a[tors + '-torsions'])\n", (2729, 2757), True, 'import numpy as np\n'), ((2814, 2850), 'numpy.array', 'np.array', (["feat_b[tors + '-torsions']"], {}), "(feat_b[tors + '-torsions'])\n", (2822, 2850), True, 'import numpy as np\n')] |
import numpy as np
import pytest
from nanomesh import MeshContainer, Mesher3D, TetraMesh, TriangleMesh
from nanomesh.image2mesh._mesher3d import BoundingBox, pad
@pytest.fixture
def image_cube():
from nanomesh import Volume
data = np.ones([10, 10, 10], dtype=int)
data[2:7, 2:7, 2:7] = 0
return Volume(data)
@pytest.fixture
def mesh_box():
"""Box triangle mesh."""
points = np.array([[0., 0., 0.], [10., 0., 0.], [0., 20., 0.],
[10., 20., 0.], [0., 0., 30.], [10., 0., 30.],
[0., 20., 30.], [10., 20., 30.]])
cells = np.array([[0, 4, 6], [0, 6, 2], [5, 1, 3], [5, 3, 7], [0, 1, 5],
[0, 5, 4], [6, 7, 3], [6, 3, 2], [1, 0, 2], [1, 2, 3],
[4, 5, 7], [4, 7, 6]])
return TriangleMesh(points=points, cells=cells)
@pytest.mark.parametrize('side,width, expected_bbox', (
('top', 5,
BoundingBox(xmin=0.0, xmax=10.0, ymin=0.0, ymax=20.0, zmin=0.0,
zmax=35.0)),
('bottom', 5,
BoundingBox(
xmin=0.0, xmax=10.0, ymin=0.0, ymax=20.0, zmin=-5.0, zmax=30.0)),
('left', 10,
BoundingBox(
xmin=0.0, xmax=10.0, ymin=-10.0, ymax=20.0, zmin=0.0, zmax=30.0)),
('right', np.pi,
BoundingBox(
xmin=0.0, xmax=10.0, ymin=0.0, ymax=20 + np.pi, zmin=0.0, zmax=30.0)),
('front', 0.1,
BoundingBox(
xmin=-0.1, xmax=10.0, ymin=0.0, ymax=20.0, zmin=0.0, zmax=30.0)),
('back', 123,
BoundingBox(
xmin=0.0, xmax=133.0, ymin=0.0, ymax=20.0, zmin=0.0, zmax=30.0)),
))
def test_mesh3d_pad(mesh_box, side, width, expected_bbox):
"""Test mesh3d.pad function."""
out = pad(mesh_box, side=side, width=width)
assert len(out.points) == len(mesh_box.points) + 4
assert len(out.cells) == len(mesh_box.cells) + 10
bbox = BoundingBox.from_points(out.points)
assert bbox == expected_bbox
def test_mesh3d_pad_no_width(mesh_box):
"""Test early return when width==0."""
out = pad(mesh_box, side='top', width=0)
assert out is mesh_box
def test_mesh3d_pad_invalid_side(mesh_box):
"""Test invalide keyword argument."""
with pytest.raises(ValueError):
_ = pad(mesh_box, side='FAIL', width=123)
@pytest.mark.parametrize('side,label,name,expected_labels', (
('left', None, None, {
1: 633,
2: 1729,
3: 290
}),
('front', 1, None, {
1: 857,
2: 1851
}),
('back', 2, None, {
1: 620,
2: 1966
}),
('left', 3, None, {
1: 633,
2: 1729,
3: 290
}),
('bottom', np.pi, None, {
1: 608,
2: 1794,
3: 277
}),
('right', 3, None, {
1: 611,
2: 1760,
3: 300
}),
('bottom', None, 'moo', {
1: 608,
2: 1794,
3: 277
}),
('bottom', None, 'background', {
1: 885,
2: 1794,
}),
('bottom', None, 'X', {
1: 608,
2: 2071,
}),
))
def test_pad_label(image_cube, side, label, name, expected_labels):
"""Test `label` parameter for `pad`."""
mesher = Mesher3D(image_cube)
mesher.generate_contour()
mesher.pad_contour(side=side, width=1, label=label, name=name)
mesh = mesher.tetrahedralize(opts='-pAq1.2')
assert isinstance(mesh, MeshContainer)
tetra_mesh = mesh.get('tetra')
assert isinstance(tetra_mesh, TetraMesh)
unique, counts = np.unique(tetra_mesh.labels, return_counts=True)
labels = dict(zip(unique, counts))
if pytest.OS_MATCHES_DATA_GEN:
# https://github.com/hpgem/nanomesh/issues/144
assert expected_labels == labels
keys = tuple(tetra_mesh.field_to_number.keys())
default_keys = ('background', 'X')
if not name:
assert keys == default_keys
elif name in default_keys:
assert keys == default_keys
else:
assert keys == default_keys + (name, )
| [
"nanomesh.image2mesh._mesher3d.BoundingBox",
"numpy.ones",
"numpy.unique",
"nanomesh.TriangleMesh",
"nanomesh.image2mesh._mesher3d.BoundingBox.from_points",
"nanomesh.Volume",
"pytest.mark.parametrize",
"numpy.array",
"nanomesh.image2mesh._mesher3d.pad",
"pytest.raises",
"nanomesh.Mesher3D"
] | [((2247, 2800), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""side,label,name,expected_labels"""', "(('left', None, None, {(1): 633, (2): 1729, (3): 290}), ('front', 1, None,\n {(1): 857, (2): 1851}), ('back', 2, None, {(1): 620, (2): 1966}), (\n 'left', 3, None, {(1): 633, (2): 1729, (3): 290}), ('bottom', np.pi,\n None, {(1): 608, (2): 1794, (3): 277}), ('right', 3, None, {(1): 611, (\n 2): 1760, (3): 300}), ('bottom', None, 'moo', {(1): 608, (2): 1794, (3):\n 277}), ('bottom', None, 'background', {(1): 885, (2): 1794}), ('bottom',\n None, 'X', {(1): 608, (2): 2071}))"], {}), "('side,label,name,expected_labels', (('left', None,\n None, {(1): 633, (2): 1729, (3): 290}), ('front', 1, None, {(1): 857, (\n 2): 1851}), ('back', 2, None, {(1): 620, (2): 1966}), ('left', 3, None,\n {(1): 633, (2): 1729, (3): 290}), ('bottom', np.pi, None, {(1): 608, (2\n ): 1794, (3): 277}), ('right', 3, None, {(1): 611, (2): 1760, (3): 300}\n ), ('bottom', None, 'moo', {(1): 608, (2): 1794, (3): 277}), ('bottom',\n None, 'background', {(1): 885, (2): 1794}), ('bottom', None, 'X', {(1):\n 608, (2): 2071})))\n", (2270, 2800), False, 'import pytest\n'), ((243, 275), 'numpy.ones', 'np.ones', (['[10, 10, 10]'], {'dtype': 'int'}), '([10, 10, 10], dtype=int)\n', (250, 275), True, 'import numpy as np\n'), ((316, 328), 'nanomesh.Volume', 'Volume', (['data'], {}), '(data)\n', (322, 328), False, 'from nanomesh import Volume\n'), ((405, 572), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [10.0, 20.0, 0.0], [\n 0.0, 0.0, 30.0], [10.0, 0.0, 30.0], [0.0, 20.0, 30.0], [10.0, 20.0, 30.0]]'], {}), '([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [10.0, 20.0,\n 0.0], [0.0, 0.0, 30.0], [10.0, 0.0, 30.0], [0.0, 20.0, 30.0], [10.0, \n 20.0, 30.0]])\n', (413, 572), True, 'import numpy as np\n'), ((598, 744), 'numpy.array', 'np.array', (['[[0, 4, 6], [0, 6, 2], [5, 1, 3], [5, 3, 7], [0, 1, 5], [0, 5, 4], [6, 7, 3\n ], [6, 3, 2], [1, 0, 2], [1, 2, 3], [4, 5, 7], [4, 7, 6]]'], {}), '([[0, 4, 6], [0, 6, 2], [5, 1, 3], [5, 3, 7], [0, 1, 5], [0, 5, 4],\n [6, 7, 3], [6, 3, 2], [1, 0, 2], [1, 2, 3], [4, 5, 7], [4, 7, 6]])\n', (606, 744), True, 'import numpy as np\n'), ((797, 837), 'nanomesh.TriangleMesh', 'TriangleMesh', ([], {'points': 'points', 'cells': 'cells'}), '(points=points, cells=cells)\n', (809, 837), False, 'from nanomesh import MeshContainer, Mesher3D, TetraMesh, TriangleMesh\n'), ((1682, 1719), 'nanomesh.image2mesh._mesher3d.pad', 'pad', (['mesh_box'], {'side': 'side', 'width': 'width'}), '(mesh_box, side=side, width=width)\n', (1685, 1719), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1842, 1877), 'nanomesh.image2mesh._mesher3d.BoundingBox.from_points', 'BoundingBox.from_points', (['out.points'], {}), '(out.points)\n', (1865, 1877), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((2007, 2041), 'nanomesh.image2mesh._mesher3d.pad', 'pad', (['mesh_box'], {'side': '"""top"""', 'width': '(0)'}), "(mesh_box, side='top', width=0)\n", (2010, 2041), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((3128, 3148), 'nanomesh.Mesher3D', 'Mesher3D', (['image_cube'], {}), '(image_cube)\n', (3136, 3148), False, 'from nanomesh import MeshContainer, Mesher3D, TetraMesh, TriangleMesh\n'), ((3444, 3492), 'numpy.unique', 'np.unique', (['tetra_mesh.labels'], {'return_counts': '(True)'}), '(tetra_mesh.labels, return_counts=True)\n', (3453, 3492), True, 'import numpy as np\n'), ((2167, 2192), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2180, 2192), False, 'import pytest\n'), ((2206, 2243), 'nanomesh.image2mesh._mesher3d.pad', 'pad', (['mesh_box'], {'side': '"""FAIL"""', 'width': '(123)'}), "(mesh_box, side='FAIL', width=123)\n", (2209, 2243), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((916, 990), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(10.0)', 'ymin': '(0.0)', 'ymax': '(20.0)', 'zmin': '(0.0)', 'zmax': '(35.0)'}), '(xmin=0.0, xmax=10.0, ymin=0.0, ymax=20.0, zmin=0.0, zmax=35.0)\n', (927, 990), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1033, 1108), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(10.0)', 'ymin': '(0.0)', 'ymax': '(20.0)', 'zmin': '(-5.0)', 'zmax': '(30.0)'}), '(xmin=0.0, xmax=10.0, ymin=0.0, ymax=20.0, zmin=-5.0, zmax=30.0)\n', (1044, 1108), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1143, 1219), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(10.0)', 'ymin': '(-10.0)', 'ymax': '(20.0)', 'zmin': '(0.0)', 'zmax': '(30.0)'}), '(xmin=0.0, xmax=10.0, ymin=-10.0, ymax=20.0, zmin=0.0, zmax=30.0)\n', (1154, 1219), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1258, 1343), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(10.0)', 'ymin': '(0.0)', 'ymax': '(20 + np.pi)', 'zmin': '(0.0)', 'zmax': '(30.0)'}), '(xmin=0.0, xmax=10.0, ymin=0.0, ymax=20 + np.pi, zmin=0.0, zmax=30.0\n )\n', (1269, 1343), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1375, 1450), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(-0.1)', 'xmax': '(10.0)', 'ymin': '(0.0)', 'ymax': '(20.0)', 'zmin': '(0.0)', 'zmax': '(30.0)'}), '(xmin=-0.1, xmax=10.0, ymin=0.0, ymax=20.0, zmin=0.0, zmax=30.0)\n', (1386, 1450), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n'), ((1486, 1561), 'nanomesh.image2mesh._mesher3d.BoundingBox', 'BoundingBox', ([], {'xmin': '(0.0)', 'xmax': '(133.0)', 'ymin': '(0.0)', 'ymax': '(20.0)', 'zmin': '(0.0)', 'zmax': '(30.0)'}), '(xmin=0.0, xmax=133.0, ymin=0.0, ymax=20.0, zmin=0.0, zmax=30.0)\n', (1497, 1561), False, 'from nanomesh.image2mesh._mesher3d import BoundingBox, pad\n')] |
from __future__ import division
from glob import glob
import os.path as osp
import os
import random
import subprocess
import argparse
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.data import load_img , darken, gen_istd
os.environ["CUDA_VISIBLE_DEVICES"]=str(np.argmax([int(x.split()[2]) for x in subprocess.Popen("nvidia-smi -q -d Memory | grep -A4 GPU | grep Free", shell=True, stdout=subprocess.PIPE).stdout.readlines()]))
seed = 2020#2019
np.random.seed(seed)
tf.set_random_seed(seed)
random.seed(seed)
parser = argparse.ArgumentParser()
parser.add_argument("--data_root", default="data")
parser.add_argument("--out", default="dbg")
ARGS = parser.parse_args()
data_root=ARGS.data_root
output_dir=osp.join(data_root,ARGS.out)
mask_dir=osp.join(data_root,"SynShadow")
mask_subdir="matte"
img_dir=osp.join(data_root,"flashAmbient")
img_subdirs=["People_Photos","Objects_Photos",
"Plants_Photos","Rooms_Photos",
"Shelves_Photos","Toys_Photos"]
train_out=osp.join(output_dir,"train")
test_out=osp.join(output_dir,"test")
for p in(train_out,test_out):
if not osp.exists(p):
os.makedirs(p)
gen_istd(img_dir,mask_dir,"train.csv",train_out,"train")
gen_istd(img_dir,mask_dir,"val.csv",test_out,"test") | [
"os.path.exists",
"argparse.ArgumentParser",
"os.makedirs",
"subprocess.Popen",
"os.path.join",
"random.seed",
"utils.data.gen_istd",
"numpy.random.seed",
"tensorflow.set_random_seed"
] | [((505, 525), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (519, 525), True, 'import numpy as np\n'), ((526, 550), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (544, 550), True, 'import tensorflow as tf\n'), ((551, 568), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (562, 568), False, 'import random\n'), ((579, 604), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (602, 604), False, 'import argparse\n'), ((766, 795), 'os.path.join', 'osp.join', (['data_root', 'ARGS.out'], {}), '(data_root, ARGS.out)\n', (774, 795), True, 'import os.path as osp\n'), ((805, 837), 'os.path.join', 'osp.join', (['data_root', '"""SynShadow"""'], {}), "(data_root, 'SynShadow')\n", (813, 837), True, 'import os.path as osp\n'), ((865, 900), 'os.path.join', 'osp.join', (['data_root', '"""flashAmbient"""'], {}), "(data_root, 'flashAmbient')\n", (873, 900), True, 'import os.path as osp\n'), ((1041, 1070), 'os.path.join', 'osp.join', (['output_dir', '"""train"""'], {}), "(output_dir, 'train')\n", (1049, 1070), True, 'import os.path as osp\n'), ((1079, 1107), 'os.path.join', 'osp.join', (['output_dir', '"""test"""'], {}), "(output_dir, 'test')\n", (1087, 1107), True, 'import os.path as osp\n'), ((1187, 1247), 'utils.data.gen_istd', 'gen_istd', (['img_dir', 'mask_dir', '"""train.csv"""', 'train_out', '"""train"""'], {}), "(img_dir, mask_dir, 'train.csv', train_out, 'train')\n", (1195, 1247), False, 'from utils.data import load_img, darken, gen_istd\n'), ((1244, 1300), 'utils.data.gen_istd', 'gen_istd', (['img_dir', 'mask_dir', '"""val.csv"""', 'test_out', '"""test"""'], {}), "(img_dir, mask_dir, 'val.csv', test_out, 'test')\n", (1252, 1300), False, 'from utils.data import load_img, darken, gen_istd\n'), ((1148, 1161), 'os.path.exists', 'osp.exists', (['p'], {}), '(p)\n', (1158, 1161), True, 'import os.path as osp\n'), ((1171, 1185), 'os.makedirs', 'os.makedirs', (['p'], {}), '(p)\n', (1182, 1185), False, 'import os\n'), ((359, 469), 'subprocess.Popen', 'subprocess.Popen', (['"""nvidia-smi -q -d Memory | grep -A4 GPU | grep Free"""'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), "('nvidia-smi -q -d Memory | grep -A4 GPU | grep Free',\n shell=True, stdout=subprocess.PIPE)\n", (375, 469), False, 'import subprocess\n')] |
import csv
import cv2
import numpy as np
import math
import tensorflow as tf
import time
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.preprocessing.image import ImageDataGenerator
from keras import regularizers
from keras.models import Sequential
from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D
from keras.optimizers import Adam
def read_lines(csv_path):
lines = []
with open(csv_path) as csvfile:
reading = csv.reader(csvfile)
for line in reading:
lines.append(line)
return lines
def load_images(all_data, correction, split):
images, measurements = [], []
lr_images, lr_steer = [], []
steer_correction = correction # parameter to tune ---------------
for d in range(len(all_data)):
lines = read_lines(all_data[d] + '/driving_log.csv')
image_path = all_data[d] + '/IMG/'
for line in lines:
cur_measure = float(line[3]) # steering angle
img_name = line[0].split('/')[-1]
bgr = cv2.imread(image_path + img_name) # the input images are jpg images(BGR)
image = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
images.append(image)
measurements.append(cur_measure)
# augmentation - flip the image
image_flipped = cv2.flip(image, 1)# image_flipped = np.fliplr(image)
images.append(image_flipped)
measurements.append(-cur_measure)
# get left and right images
left_name = line[1].split('/')[-1]
right_name = line[2].split('/')[-1]
rgb_l = cv2.cvtColor(cv2.imread(image_path + left_name), cv2.COLOR_BGR2RGB)
rgb_r = cv2.cvtColor(cv2.imread(image_path + right_name), cv2.COLOR_BGR2RGB)
lr_images.append(rgb_l)
lr_steer.append(cur_measure+steer_correction*0.05*np.random.random())
lr_images.append(rgb_r)
lr_steer.append(cur_measure-steer_correction*0.05*np.random.random())
print('Total images: ', len(images))
train_x, valid_x, train_y, valid_y = train_test_split(images, measurements, test_size=split, random_state=40)
train_x += lr_images
train_y += lr_steer
assert len(train_x) == len(train_y)
return train_x, valid_x, train_y, valid_y
def augmentation(x, y ,activate=False):
# image augmentation generator
if activate==True:
temp_x, temp_y = [], []
# tf.keras.preprocessing.image.ImageDataGenerator
data_aug = ImageDataGenerator(rotation_range=12, shear_range=7, zoom_range=0.2,channel_shift_range=15)
for i in range(len(y)):
target = x[i] # the image that need to be augmented
t1 = np.expand_dims(target, 0)
iterator = data_aug.flow(t1, batch_size=1)
batch = iterator.next()
image = batch[0].astype('uint8')
temp_x.append(image)
temp_y.append(y[i])
X_aug = np.concatenate((x, temp_x))
y_aug = np.concatenate((y, temp_y))
return X_aug, y_aug
else:
return x, y
def generator(input_images, labels, batch_size=64):
# generate the next training batch
num_samples = len(input_images)
while True: # Loop forever so the generator never terminates
shuffle(input_images, labels)
for offset in range(0, num_samples, batch_size):
batch_x = input_images[offset:offset+batch_size]
batch_y = labels[offset:offset+batch_size]
X_train = np.array(batch_x)
y_train = np.array(batch_y)
yield shuffle(X_train, y_train)
def preprocess():
# establish and normalize the model
model = Sequential()
model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))
model.add(Cropping2D(cropping=((60, 22), (0,0))))
return model
def LeNet():
model = preprocess()
model.add(Conv2D(6,(5,5), activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(16,(5,5), activation='relu'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(120))
model.add(Dense(84))
model.add(Dense(1))
return model
def Nvidia():
# Nvidia end-to-end architechture
# source: https://developer.nvidia.com/blog/deep-learning-self-driving-cars/
beta = 0.0001
l2_regu = False
model = preprocess()
if l2_regu == True:
model.add(Conv2D(24, (5, 5), strides=(2,2), activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Conv2D(36, (5, 5), strides=(2,2), activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Conv2D(48, (5, 5), strides=(2,2), activation='relu', kernel_regularizer=regularizers.l2(beta)))
# model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Conv2D(64, (3, 3), activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Dropout(0.4))
model.add(Flatten())
model.add(Dense(1164, activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Dropout(0.6))
model.add(Dense(100, activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Dense(50, activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Dense(10, activation='relu', kernel_regularizer=regularizers.l2(beta)))
model.add(Dense(1))
else:
model.add(Conv2D(24, (5, 5), strides=(2,2), activation='relu'))
model.add(Conv2D(36, (5, 5), strides=(2,2), activation='relu'))
model.add(Conv2D(48, (5, 5), strides=(2,2), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(1164, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1))
return model
# start of model -----------------------------------------------------------------
print('Behavioral Cloning Project:')
steer_correct = 0.2
split_percent = 0.2 # the percentage of validation set
all_data_paths = ['./recover1', './data1','./data2', './data3', './data4', './data5', './data8', './data9']
start_time = time.time()
X_train, X_valid, y_train, y_valid = load_images(all_data_paths, steer_correct, split_percent)# note that the type of these above outputs are lists!
print('Data loading time(s): ', time.time()-start_time)
print('Number of images(before augmentation): '+ str(len(X_train)))
print('Number of validation samples: ', len(X_valid))
# X_aug, y_aug = augmentation(X_train, y_train) - data augmentation is not used.
learning_rate = 0.0001
batch_size = 64
number_of_epochs = 5
n_train = len(X_train)
n_valid = len(X_valid)
next_train = generator(X_train, y_train, batch_size=batch_size)
next_valid = generator(X_valid, y_valid, batch_size=batch_size)
model = Nvidia()
model.compile(optimizer=Adam(lr=learning_rate), loss='mse')
print(model.summary())
history_object = model.fit_generator(next_train, steps_per_epoch=math.ceil(n_train/batch_size),
validation_data=next_valid, validation_steps=math.ceil(n_valid/batch_size),
epochs=number_of_epochs, verbose=1)
model.save('model.h5')
print('Model saved.')
print()
| [
"keras.layers.Conv2D",
"keras.preprocessing.image.ImageDataGenerator",
"numpy.array",
"keras.layers.Dense",
"keras.layers.Cropping2D",
"numpy.random.random",
"numpy.concatenate",
"csv.reader",
"keras.optimizers.Adam",
"keras.layers.Flatten",
"keras.layers.MaxPooling2D",
"sklearn.model_selectio... | [((5890, 5901), 'time.time', 'time.time', ([], {}), '()\n', (5899, 5901), False, 'import time\n'), ((1921, 1993), 'sklearn.model_selection.train_test_split', 'train_test_split', (['images', 'measurements'], {'test_size': 'split', 'random_state': '(40)'}), '(images, measurements, test_size=split, random_state=40)\n', (1937, 1993), False, 'from sklearn.model_selection import train_test_split\n'), ((3382, 3394), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3392, 3394), False, 'from keras.models import Sequential\n'), ((523, 542), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (533, 542), False, 'import csv\n'), ((2305, 2401), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rotation_range': '(12)', 'shear_range': '(7)', 'zoom_range': '(0.2)', 'channel_shift_range': '(15)'}), '(rotation_range=12, shear_range=7, zoom_range=0.2,\n channel_shift_range=15)\n', (2323, 2401), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((2679, 2706), 'numpy.concatenate', 'np.concatenate', (['(x, temp_x)'], {}), '((x, temp_x))\n', (2693, 2706), True, 'import numpy as np\n'), ((2717, 2744), 'numpy.concatenate', 'np.concatenate', (['(y, temp_y)'], {}), '((y, temp_y))\n', (2731, 2744), True, 'import numpy as np\n'), ((2989, 3018), 'sklearn.utils.shuffle', 'shuffle', (['input_images', 'labels'], {}), '(input_images, labels)\n', (2996, 3018), False, 'from sklearn.utils import shuffle\n'), ((3406, 3466), 'keras.layers.Lambda', 'Lambda', (['(lambda x: x / 255.0 - 0.5)'], {'input_shape': '(160, 320, 3)'}), '(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3))\n', (3412, 3466), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3479, 3518), 'keras.layers.Cropping2D', 'Cropping2D', ([], {'cropping': '((60, 22), (0, 0))'}), '(cropping=((60, 22), (0, 0)))\n', (3489, 3518), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3581, 3617), 'keras.layers.Conv2D', 'Conv2D', (['(6)', '(5, 5)'], {'activation': '"""relu"""'}), "(6, (5, 5), activation='relu')\n", (3587, 3617), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3628, 3642), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {}), '()\n', (3640, 3642), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3655, 3692), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(5, 5)'], {'activation': '"""relu"""'}), "(16, (5, 5), activation='relu')\n", (3661, 3692), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3703, 3717), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {}), '()\n', (3715, 3717), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3730, 3739), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3737, 3739), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3752, 3762), 'keras.layers.Dense', 'Dense', (['(120)'], {}), '(120)\n', (3757, 3762), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3775, 3784), 'keras.layers.Dense', 'Dense', (['(84)'], {}), '(84)\n', (3780, 3784), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((3797, 3805), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (3802, 3805), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((6083, 6094), 'time.time', 'time.time', ([], {}), '()\n', (6092, 6094), False, 'import time\n'), ((6587, 6609), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'learning_rate'}), '(lr=learning_rate)\n', (6591, 6609), False, 'from keras.optimizers import Adam\n'), ((6711, 6742), 'math.ceil', 'math.ceil', (['(n_train / batch_size)'], {}), '(n_train / batch_size)\n', (6720, 6742), False, 'import math\n'), ((6789, 6820), 'math.ceil', 'math.ceil', (['(n_valid / batch_size)'], {}), '(n_valid / batch_size)\n', (6798, 6820), False, 'import math\n'), ((1017, 1050), 'cv2.imread', 'cv2.imread', (['(image_path + img_name)'], {}), '(image_path + img_name)\n', (1027, 1050), False, 'import cv2\n'), ((1101, 1137), 'cv2.cvtColor', 'cv2.cvtColor', (['bgr', 'cv2.COLOR_BGR2RGB'], {}), '(bgr, cv2.COLOR_BGR2RGB)\n', (1113, 1137), False, 'import cv2\n'), ((1252, 1270), 'cv2.flip', 'cv2.flip', (['image', '(1)'], {}), '(image, 1)\n', (1260, 1270), False, 'import cv2\n'), ((2486, 2511), 'numpy.expand_dims', 'np.expand_dims', (['target', '(0)'], {}), '(target, 0)\n', (2500, 2511), True, 'import numpy as np\n'), ((3214, 3231), 'numpy.array', 'np.array', (['batch_x'], {}), '(batch_x)\n', (3222, 3231), True, 'import numpy as np\n'), ((3254, 3271), 'numpy.array', 'np.array', (['batch_y'], {}), '(batch_y)\n', (3262, 3271), True, 'import numpy as np\n'), ((4584, 4596), 'keras.layers.Dropout', 'Dropout', (['(0.4)'], {}), '(0.4)\n', (4591, 4596), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((4610, 4619), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4617, 4619), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((4719, 4731), 'keras.layers.Dropout', 'Dropout', (['(0.6)'], {}), '(0.6)\n', (4726, 4731), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((4998, 5006), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (5003, 5006), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5027, 5080), 'keras.layers.Conv2D', 'Conv2D', (['(24)', '(5, 5)'], {'strides': '(2, 2)', 'activation': '"""relu"""'}), "(24, (5, 5), strides=(2, 2), activation='relu')\n", (5033, 5080), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5093, 5146), 'keras.layers.Conv2D', 'Conv2D', (['(36)', '(5, 5)'], {'strides': '(2, 2)', 'activation': '"""relu"""'}), "(36, (5, 5), strides=(2, 2), activation='relu')\n", (5099, 5146), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5159, 5212), 'keras.layers.Conv2D', 'Conv2D', (['(48)', '(5, 5)'], {'strides': '(2, 2)', 'activation': '"""relu"""'}), "(48, (5, 5), strides=(2, 2), activation='relu')\n", (5165, 5212), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5225, 5262), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (5231, 5262), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5276, 5313), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (5282, 5313), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5327, 5339), 'keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (5334, 5339), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5353, 5362), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (5360, 5362), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5376, 5406), 'keras.layers.Dense', 'Dense', (['(1164)'], {'activation': '"""relu"""'}), "(1164, activation='relu')\n", (5381, 5406), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5420, 5449), 'keras.layers.Dense', 'Dense', (['(100)'], {'activation': '"""relu"""'}), "(100, activation='relu')\n", (5425, 5449), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5463, 5491), 'keras.layers.Dense', 'Dense', (['(50)'], {'activation': '"""relu"""'}), "(50, activation='relu')\n", (5468, 5491), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5505, 5533), 'keras.layers.Dense', 'Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (5510, 5533), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((5547, 5555), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (5552, 5555), False, 'from keras.layers import Dense, Flatten, Activation, Lambda, Conv2D, MaxPooling2D, Dropout, Cropping2D\n'), ((1507, 1541), 'cv2.imread', 'cv2.imread', (['(image_path + left_name)'], {}), '(image_path + left_name)\n', (1517, 1541), False, 'import cv2\n'), ((1586, 1621), 'cv2.imread', 'cv2.imread', (['(image_path + right_name)'], {}), '(image_path + right_name)\n', (1596, 1621), False, 'import cv2\n'), ((3290, 3315), 'sklearn.utils.shuffle', 'shuffle', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (3297, 3315), False, 'from sklearn.utils import shuffle\n'), ((4110, 4131), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4125, 4131), False, 'from keras import regularizers\n'), ((4218, 4239), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4233, 4239), False, 'from keras import regularizers\n'), ((4326, 4347), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4341, 4347), False, 'from keras import regularizers\n'), ((4455, 4476), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4470, 4476), False, 'from keras import regularizers\n'), ((4548, 4569), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4563, 4569), False, 'from keras import regularizers\n'), ((4683, 4704), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4698, 4704), False, 'from keras import regularizers\n'), ((4794, 4815), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4809, 4815), False, 'from keras import regularizers\n'), ((4878, 4899), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4893, 4899), False, 'from keras import regularizers\n'), ((4962, 4983), 'keras.regularizers.l2', 'regularizers.l2', (['beta'], {}), '(beta)\n', (4977, 4983), False, 'from keras import regularizers\n'), ((1722, 1740), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1738, 1740), True, 'import numpy as np\n'), ((1822, 1840), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1838, 1840), True, 'import numpy as np\n')] |
"""
Simple main file to test the cython wrappers for the c functions
"""
from dummy_data import py_get_numbers
import numpy as np
if __name__ == "__main__":
numbers = np.array(py_get_numbers(5))
print(numbers)
print("Sum of numbers: ", np.sum(numbers))
| [
"numpy.sum",
"dummy_data.py_get_numbers"
] | [((182, 199), 'dummy_data.py_get_numbers', 'py_get_numbers', (['(5)'], {}), '(5)\n', (196, 199), False, 'from dummy_data import py_get_numbers\n'), ((250, 265), 'numpy.sum', 'np.sum', (['numbers'], {}), '(numbers)\n', (256, 265), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
from dbquery import DBQuery
class Evaluator(object):
def __init__(self, data_dir, cfg):
self.db = DBQuery(data_dir)
self.cfg = cfg
def _init_dict(self):
dic = {}
for domain in self.cfg.belief_domains:
dic[domain] = {}
return dic
def match_rate_goal(self, goal, booked_entity):
"""
judge if the selected entity meets the constraint
"""
score = []
for domain in self.cfg.belief_domains:
if goal['book'][domain]:
tot = len(goal['inform'][domain].keys())
if tot == 0:
continue
entity_id = booked_entity[domain]
if not entity_id:
score.append(0)
continue
if domain == 'taxi':
score.append(1)
continue
match = 0
entity = self.db.dbs[domain][int(entity_id)]
for k, v in goal['inform'][domain].items():
k = self.cfg.mapping[domain][k]
if k == 'leaveAt':
try:
v_constraint = int(v.split(':')[0]) * 100 + int(v.split(':')[1])
v_select = int(entity['leaveAt'].split(':')[0]) * 100 + int(entity['leaveAt'].split(':')[1])
if v_constraint <= v_select:
match += 1
except (ValueError, IndexError):
match += 1
elif k == 'arriveBy':
try:
v_constraint = int(v.split(':')[0]) * 100 + int(v.split(':')[1])
v_select = int(entity['arriveBy'].split(':')[0]) * 100 + int(
entity['arriveBy'].split(':')[1])
if v_constraint >= v_select:
match += 1
except (ValueError, IndexError):
match += 1
else:
if v.strip() == entity[k].strip():
match += 1
score.append(match / tot)
return score
def inform_F1_goal(self, goal, sys_history):
"""
judge if all the requested information is answered
"""
inform_slot = {}
for domain in self.cfg.belief_domains:
inform_slot[domain] = set()
for da in sys_history:
domain, intent, slot, p = da.split('-')
if intent in ['inform', 'recommend', 'offerbook',
'offerbooked'] and slot != 'none' and domain in self.cfg.belief_domains:
inform_slot[domain].add(slot)
TP, FP, FN = 0, 0, 0
for domain in self.cfg.belief_domains:
for k in goal['request'][domain]:
if k in inform_slot[domain]:
TP += 1
else:
FN += 1
for k in inform_slot[domain]:
# exclude slots that are informed by users
if k not in goal['request'][domain] and k not in goal['inform'][domain] and k in self.cfg.requestable[
domain]:
FP += 1
return TP, FP, FN
def match_rate(self, metadata, aggregate=False):
booked_entity = metadata['belief_state']['booked']
"""
goal = {'book':{}, 'inform':self._init_dict()}
goal['book'] = metadata['user_goal']['book']
for da, v in metadata['history']['user'].items():
d, i, s, p = da.split('-')
if i in ['inform', 'recommend', 'offerbook', 'offerbooked'] and s in self.cfg.mapping[d]:
goal['inform'][d][s] = v
"""
goal = metadata['user_goal']
score = self.match_rate_goal(goal, booked_entity)
if not aggregate:
return score
else:
return np.mean(score) if score else None
def inform_F1(self, metadata, aggregate=False):
sys_history = dict(metadata['history']['sys'], **metadata['last_sys_action'])
"""
goal = {'request':self._init_dict(), 'inform':self._init_dict()}
for da, v in metadata['history']['user'].items():
d, i, s, p = da.split('-')
if i in ['inform', 'recommend', 'offerbook', 'offerbooked'] and s in self.cfg.mapping[d]:
goal['inform'][d][s] = v
elif i == 'request':
goal['request'][d][s] = v
"""
goal = metadata['user_goal']
TP, FP, FN = self.inform_F1_goal(goal, sys_history)
if not aggregate:
return [TP, FP, FN]
else:
try:
rec = TP / (TP + FN)
except ZeroDivisionError:
return None, None, None
try:
prec = TP / (TP + FP)
F1 = 2 * prec * rec / (prec + rec)
except ZeroDivisionError:
return 0, rec, 0
return prec, rec, F1
| [
"numpy.mean",
"dbquery.DBQuery"
] | [((156, 173), 'dbquery.DBQuery', 'DBQuery', (['data_dir'], {}), '(data_dir)\n', (163, 173), False, 'from dbquery import DBQuery\n'), ((4067, 4081), 'numpy.mean', 'np.mean', (['score'], {}), '(score)\n', (4074, 4081), True, 'import numpy as np\n')] |
# Variables
DATASET_PATH = '../data/'
MODEL = 'ResNet13'
RESULT_PATH = './result_' + MODEL + '/'
DEBUG = False
GPU = True
# Shared parameters
epochs = 20
momentum = 0.9
# Import the necessary libraries
import numpy as np
import torch
import matplotlib.pyplot as plt
import json
import time
from tqdm import tqdm
# Device settings
device = torch.device('cuda:0' if torch.cuda.is_available() and GPU else 'cpu')
# Loading the Fashion-MNIST dataset
from torchvision import datasets, transforms
# Define the network architecture
from torch import nn, optim
if MODEL == 'MLP4':
batch_size = 1024
learning_rate = 0.1
plt_title = "Implementation of 4-layer dense network"
from mlp4 import MLP4
transform = transforms.Compose([transforms.ToTensor(),
])
model = MLP4().to(device)
criterion = nn.CrossEntropyLoss().to(device)
elif MODEL == 'LeNet5':
batch_size = 16
learning_rate = 0.05
plt_title = "Implementation of LeNet5 on Fashon-MNIST"
from lenet import LeNet5
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5), (0.5)),
])
model = LeNet5().to(device)
criterion = nn.CrossEntropyLoss().to(device)
elif MODEL == 'LeNet11':
batch_size = 128
learning_rate = 0.01
plt_title = "Implementation of LeNet11 on Fashon-MNIST"
from lenet import LeNet11
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5), (0.5)),
])
model = LeNet11().to(device)
criterion = nn.CrossEntropyLoss().to(device)
elif MODEL == 'VGG11':
batch_size = 16
learning_rate = 0.001
plt_title = "Implementation of VGG11 on Fashon-MNIST"
transform = transforms.Compose([transforms.ToTensor(),
transforms.Resize((224, 224)),
transforms.Normalize((0.5), (0.5)),
])
from vgg11 import VGG11
model = VGG11(in_channels=1, num_classes=10).to(device)
criterion = nn.CrossEntropyLoss().to(device)
elif MODEL == 'ResNet18':
batch_size = 64
learning_rate = 0.005
plt_title = "Implementation of ResNet18 on Fashon-MNIST"
transform = transforms.Compose([transforms.ToTensor(),
transforms.Resize((224, 224)),
transforms.Normalize((0.5), (0.5)),
])
from resnet import resnet18
model = resnet18(n_classes=10, input_channels=1).to(device)
criterion = nn.CrossEntropyLoss().to(device)
elif MODEL == 'ResNet13':
batch_size = 64
learning_rate = 0.005
plt_title = "Implementation of ResNet13 on Fashon-MNIST"
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5), (0.5)),
])
from resnet import resnet28_13
model = resnet28_13(n_classes=10, input_channels=1).to(device)
criterion = nn.CrossEntropyLoss().to(device)
else:
print("Model not valid")
quit()
# Same optimizer for justice
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)
# Download and load the training data
trainset = datasets.FashionMNIST(DATASET_PATH, download = True, train = True, transform = transform)
testset = datasets.FashionMNIST(DATASET_PATH, download = True, train = False, transform = transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size = batch_size, shuffle = True)
testloader = torch.utils.data.DataLoader(testset, batch_size = batch_size, shuffle = True)
# Examine a sample if DEBUG is set
if (DEBUG):
print("CUDA:", torch.cuda.is_available())
dataiter = iter(trainloader)
images, labels = dataiter.next()
print("Checking images.")
print("Type", type(images))
print("Shape", images.shape)
print("Label Shape", labels.shape)
plt.cla()
plt.clf()
plt.imshow(images[1].numpy().squeeze(), cmap = 'Greys_r')
plt.savefig(RESULT_PATH + 'sample.png')
print("One sample image saved as `sample.png`.")
def to_one_hot(labels, device):
onehot = torch.zeros(labels.shape[0], 10).to(device)
return onehot.scatter(dim=1, index=labels.view(-1, 1).to(device), value=1.)
# Initiate the timer to instrument the performance
timer_start = time.process_time_ns()
epoch_times = [timer_start]
train_losses, test_losses, accuracies = [], [], []
for e in range(epochs):
running_loss = 0
print("Epoch: {:03d}/{:03d}..".format(e+1, epochs))
# Training pass
print("Training pass:")
for data in tqdm(trainloader, total=len(trainloader)):
images, labels = data
images = images.to(device)
labels = to_one_hot(labels, device)
optimizer.zero_grad()
output = model.forward(images).to(device)
loss = criterion(output, labels).to(device)
loss.backward()
optimizer.step()
running_loss += loss.item()
# Testing pass
print("Validation pass:")
test_loss = 0
accuracy = 0
# Turn off gradients for validation, saves memory and computation
with torch.no_grad():
# Set the model to evaluation mode
model.eval()
# Validation pass
for data in tqdm(testloader, total=len(testloader)):
images, labels = data
images = images.to(device)
labels = labels.to(device)
labels_one_hot = to_one_hot(labels, device)
log_ps = model(images).to(device)
test_loss += criterion(log_ps, labels_one_hot)
ps = torch.exp(log_ps).to(device)
top_p, top_class = ps.topk(1, dim = 1)
equals = (top_class == labels.view(*top_class.shape))
accuracy += torch.mean(equals.type(torch.FloatTensor))
model.train()
train_losses.append(running_loss/len(trainloader))
test_losses.append(float(test_loss.cpu())/len(testloader))
accuracies.append(float(accuracy)/len(testloader))
epoch_times.append(time.process_time_ns())
print("Training loss: {:.3f}..".format(running_loss/len(trainloader)),
"Test loss: {:.3f}..".format(test_loss/len(testloader)),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)),
"Cur time(ns): {}".format(epoch_times[-1]))
fig, ax = plt.subplots(figsize=(10, 8))
ax.plot(train_losses, label="Training loss")
ax.plot(test_losses, label="Validation loss")
ax.set_xlabel("Epoch")
ax.set_ylabel("Cross Entropy Loss")
ax.legend()
ax2 = ax.twinx()
ax2.plot(np.array(accuracies)*100, label="Accuracy", color='g')
ax2.set_ylabel("Accuracy (%)")
plt.title(plt_title)
plt.savefig(RESULT_PATH + 'training_proc.png', dpi = 100)
with open(RESULT_PATH + 'torch_results.json', 'w+') as f:
json.dump({
'train_losses': train_losses,
'test_losses': test_losses,
'epoch_times': epoch_times,
'accuracies': accuracies,
}, f)
# eval
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torchvision import datasets
from sklearn.metrics import precision_recall_fscore_support
y_test, pred = [], []
for images, labels in testloader:
images = images.to(device)
labels = labels.to(device)
labels_one_hot = to_one_hot(labels, device)
log_ps = model(images).to(device)
ps = torch.exp(log_ps).to(device)
top_p, top_class = ps.topk(1, dim = 1)
pred += list(top_class.cpu().numpy().flatten())
y_test += list(labels.view(*top_class.shape).cpu().numpy().flatten())
precision, recall, fscore, _ = precision_recall_fscore_support(y_test, pred)
classes = [
'T-shirt/top',
'Trouser',
'Pullover',
'Dress',
'Coat',
'Sandal',
'Shirt',
'Sneaker',
'Bag',
'Ankle boot',
]
print("Precision \n", precision)
print("Recall \n", recall)
print("F-score \n", fscore)
print('\nMeasures', end=' ')
for c in classes:
print('&', c, end=' ')
print('\\\\\nPrecision', end=' ')
for p in precision:
print('& {:.3f}'.format(p), end=' ')
print('\\\\\nRecall', end=' ')
for r in recall:
print('& {:.3f}'.format(r), end=' ')
print('\\\\\nF-score', end=' ')
for f in fscore:
print('& {:.3f}'.format(f), end=' ')
print('\\\\') | [
"mlp4.MLP4",
"torch.nn.CrossEntropyLoss",
"torch.exp",
"numpy.array",
"torch.cuda.is_available",
"time.process_time_ns",
"lenet.LeNet5",
"resnet.resnet28_13",
"matplotlib.pyplot.subplots",
"torchvision.transforms.ToTensor",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.savefig",
"vgg11.VGG11",... | [((3256, 3344), 'torchvision.datasets.FashionMNIST', 'datasets.FashionMNIST', (['DATASET_PATH'], {'download': '(True)', 'train': '(True)', 'transform': 'transform'}), '(DATASET_PATH, download=True, train=True, transform=\n transform)\n', (3277, 3344), False, 'from torchvision import datasets\n'), ((3356, 3445), 'torchvision.datasets.FashionMNIST', 'datasets.FashionMNIST', (['DATASET_PATH'], {'download': '(True)', 'train': '(False)', 'transform': 'transform'}), '(DATASET_PATH, download=True, train=False, transform=\n transform)\n', (3377, 3445), False, 'from torchvision import datasets\n'), ((3461, 3535), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'batch_size', 'shuffle': '(True)'}), '(trainset, batch_size=batch_size, shuffle=True)\n', (3488, 3535), False, 'import torch\n'), ((3553, 3626), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testset'], {'batch_size': 'batch_size', 'shuffle': '(True)'}), '(testset, batch_size=batch_size, shuffle=True)\n', (3580, 3626), False, 'import torch\n'), ((4324, 4346), 'time.process_time_ns', 'time.process_time_ns', ([], {}), '()\n', (4344, 4346), False, 'import time\n'), ((6190, 6219), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (6202, 6219), True, 'import matplotlib.pyplot as plt\n'), ((6494, 6514), 'matplotlib.pyplot.title', 'plt.title', (['plt_title'], {}), '(plt_title)\n', (6503, 6514), True, 'import matplotlib.pyplot as plt\n'), ((6515, 6570), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(RESULT_PATH + 'training_proc.png')"], {'dpi': '(100)'}), "(RESULT_PATH + 'training_proc.png', dpi=100)\n", (6526, 6570), True, 'import matplotlib.pyplot as plt\n'), ((7438, 7483), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_test', 'pred'], {}), '(y_test, pred)\n', (7469, 7483), False, 'from sklearn.metrics import precision_recall_fscore_support\n'), ((3917, 3926), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (3924, 3926), True, 'import matplotlib.pyplot as plt\n'), ((3929, 3938), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (3936, 3938), True, 'import matplotlib.pyplot as plt\n'), ((4001, 4040), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(RESULT_PATH + 'sample.png')"], {}), "(RESULT_PATH + 'sample.png')\n", (4012, 4040), True, 'import matplotlib.pyplot as plt\n'), ((6634, 6764), 'json.dump', 'json.dump', (["{'train_losses': train_losses, 'test_losses': test_losses, 'epoch_times':\n epoch_times, 'accuracies': accuracies}", 'f'], {}), "({'train_losses': train_losses, 'test_losses': test_losses,\n 'epoch_times': epoch_times, 'accuracies': accuracies}, f)\n", (6643, 6764), False, 'import json\n'), ((3696, 3721), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3719, 3721), False, 'import torch\n'), ((5082, 5097), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5095, 5097), False, 'import torch\n'), ((5899, 5921), 'time.process_time_ns', 'time.process_time_ns', ([], {}), '()\n', (5919, 5921), False, 'import time\n'), ((6408, 6428), 'numpy.array', 'np.array', (['accuracies'], {}), '(accuracies)\n', (6416, 6428), True, 'import numpy as np\n'), ((367, 392), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (390, 392), False, 'import torch\n'), ((735, 756), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (754, 756), False, 'from torchvision import datasets, transforms\n'), ((803, 809), 'mlp4.MLP4', 'MLP4', ([], {}), '()\n', (807, 809), False, 'from mlp4 import MLP4\n'), ((835, 856), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (854, 856), False, 'from torch import nn, optim\n'), ((4136, 4168), 'torch.zeros', 'torch.zeros', (['labels.shape[0]', '(10)'], {}), '(labels.shape[0], 10)\n', (4147, 4168), False, 'import torch\n'), ((7214, 7231), 'torch.exp', 'torch.exp', (['log_ps'], {}), '(log_ps)\n', (7223, 7231), False, 'import torch\n'), ((1051, 1072), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1070, 1072), False, 'from torchvision import datasets, transforms\n'), ((1108, 1138), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (1128, 1138), False, 'from torchvision import datasets, transforms\n'), ((1189, 1197), 'lenet.LeNet5', 'LeNet5', ([], {}), '()\n', (1195, 1197), False, 'from lenet import LeNet5\n'), ((1223, 1244), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1242, 1244), False, 'from torch import nn, optim\n'), ((1443, 1464), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1462, 1464), False, 'from torchvision import datasets, transforms\n'), ((1500, 1530), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (1520, 1530), False, 'from torchvision import datasets, transforms\n'), ((1581, 1590), 'lenet.LeNet11', 'LeNet11', ([], {}), '()\n', (1588, 1590), False, 'from lenet import LeNet11\n'), ((1616, 1637), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1635, 1637), False, 'from torch import nn, optim\n'), ((5494, 5511), 'torch.exp', 'torch.exp', (['log_ps'], {}), '(log_ps)\n', (5503, 5511), False, 'import torch\n'), ((1804, 1825), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1823, 1825), False, 'from torchvision import datasets, transforms\n'), ((1861, 1890), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224, 224)'], {}), '((224, 224))\n', (1878, 1890), False, 'from torchvision import datasets, transforms\n'), ((1926, 1956), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (1946, 1956), False, 'from torchvision import datasets, transforms\n'), ((2033, 2069), 'vgg11.VGG11', 'VGG11', ([], {'in_channels': '(1)', 'num_classes': '(10)'}), '(in_channels=1, num_classes=10)\n', (2038, 2069), False, 'from vgg11 import VGG11\n'), ((2095, 2116), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2114, 2116), False, 'from torch import nn, optim\n'), ((2289, 2310), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2308, 2310), False, 'from torchvision import datasets, transforms\n'), ((2346, 2375), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224, 224)'], {}), '((224, 224))\n', (2363, 2375), False, 'from torchvision import datasets, transforms\n'), ((2411, 2441), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (2431, 2441), False, 'from torchvision import datasets, transforms\n'), ((2522, 2562), 'resnet.resnet18', 'resnet18', ([], {'n_classes': '(10)', 'input_channels': '(1)'}), '(n_classes=10, input_channels=1)\n', (2530, 2562), False, 'from resnet import resnet18\n'), ((2588, 2609), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2607, 2609), False, 'from torch import nn, optim\n'), ((2782, 2803), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2801, 2803), False, 'from torchvision import datasets, transforms\n'), ((2839, 2869), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5)', '(0.5)'], {}), '(0.5, 0.5)\n', (2859, 2869), False, 'from torchvision import datasets, transforms\n'), ((2953, 2996), 'resnet.resnet28_13', 'resnet28_13', ([], {'n_classes': '(10)', 'input_channels': '(1)'}), '(n_classes=10, input_channels=1)\n', (2964, 2996), False, 'from resnet import resnet28_13\n'), ((3022, 3043), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (3041, 3043), False, 'from torch import nn, optim\n')] |
from principal_DNN_MNIST import *
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
# Reloading modules just in case
if __name__ == "__main__" :
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(path="mnist.npz")
data_mnist = scale_and_read_img(x_train)
test_data = scale_and_read_img(x_test) # scaling test data
labels = transform_labels(y_train) #transforming labels
layers = [data_mnist[0, :].shape[0], 700, 600, 500, 400, 300, 200, 100, 50, 10]
test_dnn = MNIST_DNN(layers)
print('begin unsupervised training')
test_dnn = test_dnn.pretrain_DNN(data_mnist, batch_size=150, n_epoch=15000)
print('Unsupervised training is done')
print('begin supervised training')
test_dnn = test_dnn.retropropagation(data_mnist, labels, lr_rate=0.1, batch_size=150, n_epoch=30000)
print('Supervised training is done')
test_dnn.test_dnn(test_data, y_test)
generated = test_dnn.generer_image_DBN(data_mnist[0, :].shape[0], 10, rows=28, cols=28, max_iter=15000)
### L'effet du nombre de couches sur la classification
hidden_mult = 6
layers_list = []
layers=[200]
for i in range(2,hidden_mult+1):
layers_list.append(i*layers)
for layers in layers_list:
layers.insert(0, data_mnist[0, :].shape[0])
layers.append(10)
test_pretrain, test_retro = [], []
for layer in layers_list:
dnn_pretrain = MNIST_DNN(layer)
dnn_retro = MNIST_DNN(layer)
print('Training pretrained version')
print('begin unsupervised training')
dnn_pretrain = dnn_pretrain.pretrain_DNN(data_mnist, batch_size=150, n_epoch=15000)
print('Unsupervised training is done')
print('Begin supervised training')
dnn_pretrain = dnn_pretrain.retropropagation(data_mnist, labels, lr_rate=0.1, batch_size=150, n_epoch=40000)
print('Supervised training is done')
print('Training non pretrained version')
print('Begin supervised training')
dnn_retro = dnn_retro.retropropagation(data_mnist, labels, lr_rate=0.1, batch_size=150, n_epoch=40000)
print('Supervised training is done')
test_pretrain.append(dnn_pretrain.test_dnn(test_data, y_test))
test_retro.append(dnn_retro.test_dnn(test_data, y_test))
plt.figure(figsize=(15,6))
plt.plot([i for i in range(2,hidden_mult+1)], test_pretrain, '--g', label='Modèle pré-entraîné') # dashed cyan
plt.plot([i for i in range(2,hidden_mult+1)], test_retro, '-.k', label='Modèle non pré-entraîné') # dashdot black
plt.grid()
plt.legend(loc="upper right")
plt.title('Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée');
plt.xlabel('Numéro de couche cachée')
plt.ylabel('Pourcentage d\'erreurs de classification');
plt.figure(figsize=(15,6))
plt.plot([i for i in range(2,hidden_mult+1)], test_pretrain, '--g', label='Modèle pré-entraîné') # dashed cyan
plt.plot([i for i in range(2,hidden_mult+1)], test_retro, '-.k', label='Modèle non pré-entraîné') # dashdot black
plt.ylim(0,4)
plt.grid()
plt.legend(loc="upper right")
plt.title('Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée');
plt.xlabel('Numéro de couche cachée')
plt.ylabel('Pourcentage d\'erreurs de classification');
### L'effet du nombre de neurones de la couche cachée sur la classification
hidden_mult = 7
layers_list = []
for i in range(2,hidden_mult+1):
layers=[100, 100]
for j in range(len(layers)):
layers[j] *= i
layers_list.append(layers)
for layers in layers_list:
layers.insert(0, data_mnist[0, :].shape[0])
layers.append(10)
test_pretrain_size, test_retro_size = [], []
for layer in layers_list:
dnn_pretrain = MNIST_DNN(layer)
dnn_retro = MNIST_DNN(layer)
print('Training pretrained version')
print('begin unsupervised training')
dnn_pretrain = dnn_pretrain.pretrain_DNN(data_mnist, batch_size=150, n_epoch=15000)
print('Unsupervised training is done')
print('Begin supervised training')
dnn_pretrain = dnn_pretrain.retropropagation(data_mnist, labels, lr_rate=0.1, batch_size=150, n_epoch=30000)
print('Supervised training is done')
print('Training non pretrained version')
print('Begin supervised training')
dnn_retro = dnn_retro.retropropagation(data_mnist, labels, lr_rate=0.1, batch_size=150, n_epoch=30000)
print('Supervised training is done')
test_pretrain_size.append(dnn_pretrain.test_dnn(test_data, y_test))
test_retro_size.append(dnn_retro.test_dnn(test_data, y_test))
plt.figure(figsize=(15,6))
plt.plot([100*i for i in range(2,hidden_mult+1)], test_pretrain_size, '--g', label='Modèle pré-entraîné') # dashed cyan
plt.plot([100*i for i in range(2,hidden_mult+1)], test_retro_size, '-.k', label='Modèle non pré-entraîné') # dashdot black
plt.ylim(0,4)
plt.grid()
plt.legend(loc="upper right")
plt.title('Pourcentage d\'erreurs de classification par rapport au nombre de neurones dans les couches cachées');
plt.xlabel('Nombre de neurones dans les couches cachées')
plt.ylabel('Pourcentage d\'erreurs de classification');
### L'effet du L'effet du nombre d'échantillons d'apprentissage sur l'erreur de classification
sizes = [1000, 3000, 7000, 10000, 30000]
data_list = []
labels_list = []
layers = [data_mnist[0, :].shape[0], 200, 200, 10]
for size in sizes:
idx = np.random.choice(np.arange(data_mnist.shape[0]), size)
data_sample = data[idx]
labels_sample = labels[idx]
data_list.append(data_sample)
labels_list.append(labels_sample)
labels_list.append(labels)
data_list.append(data_mnist)
test_pretrain_data, test_retro_data = [], []
for i in range(len(sizes)):
dnn_pretrain = MNIST_DNN(layers)
dnn_retro = MNIST_DNN(layers)
print('Training pretrained version')
print('begin unsupervised training')
dnn_pretrain = dnn_pretrain.pretrain_DNN(data_list[i], batch_size=150, n_epoch=15000)
print('Unsupervised training is done')
print('Begin supervised training')
dnn_pretrain = dnn_pretrain.retropropagation(data_list[i], labels_list[i], lr_rate=0.1, batch_size=150, n_epoch=30000)
print('Supervised training is done')
print('Training non pretrained version')
print('Begin supervised training')
dnn_retro = dnn_retro.retropropagation(data_list[i], labels_list[i], lr_rate=0.1, batch_size=150, n_epoch=30000)
print('Supervised training is done')
test_pretrain_data.append(dnn_pretrain.test_dnn(test_data, y_test))
test_retro_data.append(dnn_retro.test_dnn(test_data, y_test))
plt.figure(figsize=(15,6))
plt.plot(sizes, test_pretrain_data, '--g', label='Modèle pré-entraîné') # dashed cyan
plt.plot(sizes, test_retro_data, '-.k', label='Modèle non pré-entraîné') # dashdot black
plt.ylim(0,4)
plt.grid()
plt.legend(loc="upper right")
plt.title('Pourcentage d\'erreurs de classification par rapport à la taille de l\'ensemble de données d\'entraînement.');
plt.xlabel('Taille de l\'ensemble de données d\'entraînement')
plt.ylabel('Pourcentage d\'erreurs de classification'); | [
"matplotlib.pyplot.grid",
"tensorflow.keras.datasets.mnist.load_data",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend"
] | [((221, 272), 'tensorflow.keras.datasets.mnist.load_data', 'tf.keras.datasets.mnist.load_data', ([], {'path': '"""mnist.npz"""'}), "(path='mnist.npz')\n", (254, 272), True, 'import tensorflow as tf\n'), ((2462, 2489), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)'}), '(figsize=(15, 6))\n', (2472, 2489), True, 'import matplotlib.pyplot as plt\n'), ((2729, 2739), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2737, 2739), True, 'import matplotlib.pyplot as plt\n'), ((2745, 2774), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (2755, 2774), True, 'import matplotlib.pyplot as plt\n'), ((2780, 2881), 'matplotlib.pyplot.title', 'plt.title', (['"""Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée"""'], {}), '(\n "Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée"\n )\n', (2789, 2881), True, 'import matplotlib.pyplot as plt\n'), ((2879, 2916), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Numéro de couche cachée"""'], {}), "('Numéro de couche cachée')\n", (2889, 2916), True, 'import matplotlib.pyplot as plt\n'), ((2922, 2975), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Pourcentage d\'erreurs de classification"""'], {}), '("Pourcentage d\'erreurs de classification")\n', (2932, 2975), True, 'import matplotlib.pyplot as plt\n'), ((2989, 3016), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)'}), '(figsize=(15, 6))\n', (2999, 3016), True, 'import matplotlib.pyplot as plt\n'), ((3256, 3270), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(4)'], {}), '(0, 4)\n', (3264, 3270), True, 'import matplotlib.pyplot as plt\n'), ((3275, 3285), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (3283, 3285), True, 'import matplotlib.pyplot as plt\n'), ((3291, 3320), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (3301, 3320), True, 'import matplotlib.pyplot as plt\n'), ((3326, 3427), 'matplotlib.pyplot.title', 'plt.title', (['"""Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée"""'], {}), '(\n "Pourcentage d\'erreurs de classification par rapport au numéro de couche cachée"\n )\n', (3335, 3427), True, 'import matplotlib.pyplot as plt\n'), ((3425, 3462), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Numéro de couche cachée"""'], {}), "('Numéro de couche cachée')\n", (3435, 3462), True, 'import matplotlib.pyplot as plt\n'), ((3468, 3521), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Pourcentage d\'erreurs de classification"""'], {}), '("Pourcentage d\'erreurs de classification")\n', (3478, 3521), True, 'import matplotlib.pyplot as plt\n'), ((5001, 5028), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)'}), '(figsize=(15, 6))\n', (5011, 5028), True, 'import matplotlib.pyplot as plt\n'), ((5286, 5300), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(4)'], {}), '(0, 4)\n', (5294, 5300), True, 'import matplotlib.pyplot as plt\n'), ((5305, 5315), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (5313, 5315), True, 'import matplotlib.pyplot as plt\n'), ((5321, 5350), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (5331, 5350), True, 'import matplotlib.pyplot as plt\n'), ((5356, 5477), 'matplotlib.pyplot.title', 'plt.title', (['"""Pourcentage d\'erreurs de classification par rapport au nombre de neurones dans les couches cachées"""'], {}), '(\n "Pourcentage d\'erreurs de classification par rapport au nombre de neurones dans les couches cachées"\n )\n', (5365, 5477), True, 'import matplotlib.pyplot as plt\n'), ((5475, 5532), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Nombre de neurones dans les couches cachées"""'], {}), "('Nombre de neurones dans les couches cachées')\n", (5485, 5532), True, 'import matplotlib.pyplot as plt\n'), ((5538, 5591), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Pourcentage d\'erreurs de classification"""'], {}), '("Pourcentage d\'erreurs de classification")\n', (5548, 5591), True, 'import matplotlib.pyplot as plt\n'), ((7250, 7277), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 6)'}), '(figsize=(15, 6))\n', (7260, 7277), True, 'import matplotlib.pyplot as plt\n'), ((7282, 7353), 'matplotlib.pyplot.plot', 'plt.plot', (['sizes', 'test_pretrain_data', '"""--g"""'], {'label': '"""Modèle pré-entraîné"""'}), "(sizes, test_pretrain_data, '--g', label='Modèle pré-entraîné')\n", (7290, 7353), True, 'import matplotlib.pyplot as plt\n'), ((7373, 7445), 'matplotlib.pyplot.plot', 'plt.plot', (['sizes', 'test_retro_data', '"""-.k"""'], {'label': '"""Modèle non pré-entraîné"""'}), "(sizes, test_retro_data, '-.k', label='Modèle non pré-entraîné')\n", (7381, 7445), True, 'import matplotlib.pyplot as plt\n'), ((7467, 7481), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(4)'], {}), '(0, 4)\n', (7475, 7481), True, 'import matplotlib.pyplot as plt\n'), ((7486, 7496), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (7494, 7496), True, 'import matplotlib.pyplot as plt\n'), ((7502, 7531), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (7512, 7531), True, 'import matplotlib.pyplot as plt\n'), ((7537, 7664), 'matplotlib.pyplot.title', 'plt.title', (['"""Pourcentage d\'erreurs de classification par rapport à la taille de l\'ensemble de données d\'entraînement."""'], {}), '(\n "Pourcentage d\'erreurs de classification par rapport à la taille de l\'ensemble de données d\'entraînement."\n )\n', (7546, 7664), True, 'import matplotlib.pyplot as plt\n'), ((7664, 7724), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Taille de l\'ensemble de données d\'entraînement"""'], {}), '("Taille de l\'ensemble de données d\'entraînement")\n', (7674, 7724), True, 'import matplotlib.pyplot as plt\n'), ((7732, 7785), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Pourcentage d\'erreurs de classification"""'], {}), '("Pourcentage d\'erreurs de classification")\n', (7742, 7785), True, 'import matplotlib.pyplot as plt\n'), ((5910, 5940), 'numpy.arange', 'np.arange', (['data_mnist.shape[0]'], {}), '(data_mnist.shape[0])\n', (5919, 5940), True, 'import numpy as np\n')] |
import os
import time
import sqlalchemy
import numpy as np
import pandas as pd
import datetime as dt
# Used to record elapsed time
start_time = time.time()
# Define unit constants
CUBE_IN_PER_GALLON = 231
CUBE_IN_PER_CUBIC_FT = 1728
# The default length of time between 'prior_date' and 'current_date' if incomplete data is given
DEFAULT_DAYS_BETWEEN = 90
# The path to the sqlite file
db_path = os.path.join('SQLiteWaterUsage', 'student.sqlite')
engine = sqlalchemy.create_engine('sqlite:///' + db_path) # Read the sqlite file into sqlalchemy
# Read the Water table into a dataframe
df_water = pd.read_sql_table('Water', engine, parse_dates=True)
# Delete unnecessary columns
df_water = df_water.drop(
columns=['service_id', 'account_number', 'service', 'meter_number', 'transaction_date', 'transaction_type', 'units',
'description', 'id'])
# Convert the 'current_reading' column into floats
df_water['current_reading'] = df_water['current_reading'].astype(float)
# Delete rows with 0 as a value for 'current_reading'
df_water = df_water[df_water['current_reading'] > 0]
# Convert the 'prior_date' and 'current_date' into datetime or None
def convert_to_datetime(s):
if s is None:
return None
try:
return dt.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
except ValueError:
return None
df_water['prior_date'] = df_water['prior_date'].apply(convert_to_datetime)
df_water['current_date'] = df_water['current_date'].apply(convert_to_datetime)
# Create an empty column, filled with 0s by default, to store gpd for the time period
# Data will be added to the column as it is calculated
gpd_list = [0 for counter in range(len(df_water.index))]
df_water['GPD'] = gpd_list
# Converts a numpy.datetime64 to a datetime.datetime object by converting dt64 to UTC time (for later use)
def datetime64_to_datetime(dt64):
return dt.datetime.utcfromtimestamp((dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's'))
# Convert values from cubic ft to gallons
df_water['current_reading'] = df_water['current_reading'].apply(lambda x: x * CUBE_IN_PER_CUBIC_FT / CUBE_IN_PER_GALLON)
# Create a dataframe to store the average GPD for each house, but leave it blank
df_base_dictionary = {'address_street_number': [], 'address_street_name': [], 'GPD': []}
df_gpd = pd.DataFrame(df_base_dictionary)
# Mark the 'GPD' column as floats
df_gpd['GPD'] = df_gpd['GPD'].astype(float)
print('Building table of average gallons used per day (average GPD)...')
# Iterate through every unique street
street_names = df_water['address_street_name'].unique()
for street in street_names:
# Get the list of all house numbers on that street
house_numbers = df_water[df_water['address_street_name'] == street]['address_street_number'].unique()
# Create a row for each house
for house in house_numbers:
df_gpd.loc[len(df_gpd)] = [house, street, 0]
print("Done!\n")
print("Calculating all average GPDs...")
# Go through every house and calculate the GPD
for index, row in df_gpd.iterrows():
# Grab the portion of the df_water that has to do with this house
df = df_water[df_water['address_street_name'] == row['address_street_name']]
df = df[df['address_street_number'] == row['address_street_number']]
df = df.sort_values(by='prior_date')
df = df.reset_index(drop=True)
for indx in range(1, len(df.index) - 1):
df = df.drop(index=indx) # Drop all but the first and last rows
df = df.reset_index(drop=True)
difference_in_gallons = df.iloc[1, :]['current_reading'] - df.iloc[0, :]['current_reading']
start_date = df.iloc[0, :]['current_date']
end_date = df.iloc[1, :]['current_date']
# If the start_date is valid, convert it into a datetime
if not pd.isnull(start_date):
start_date = datetime64_to_datetime(start_date)
else:
# No start_date, use 90 days after the prior_date
start_date = datetime64_to_datetime(df.iloc[0, :]['prior_date']) + dt.timedelta(days=90)
# If the end_date is valid, convert it into a datetime
if not pd.isnull(end_date):
end_date = datetime64_to_datetime(end_date)
else:
# No end date, use 90 days after the prior_date
end_date = datetime64_to_datetime(df.iloc[1, :]['prior_date']) + dt.timedelta(days=90)
days_between = (end_date - start_date).days
gallons_per_day = difference_in_gallons / days_between
df_gpd.loc[index, 'GPD'] = gallons_per_day
print("Done!\n")
print("Sorting table by street name, then by house number")
df_gpd = df_gpd.sort_values(by=['address_street_name', 'address_street_number'])
print("Done!\n")
print("Creating table of street GPDs...")
# Create a dataframe for each street
street_gpd_base_dict = {'street': [], 'GPD': []}
street_gpd = pd.DataFrame(street_gpd_base_dict)
for street in street_names:
house_data = df_gpd[df_gpd['address_street_name'] == street]
gpd = house_data['GPD'].sum()
street_gpd.loc[len(street_gpd)] = [street, gpd]
street_gpd = street_gpd.sort_values(by=['street'])
print("Done!\n")
elapsed_time = time.time() - start_time
# Round elapsed time to 2 decimal places
print("Elapsed time: {0} seconds".format(round(elapsed_time * 100) / 100))
# Returns the number of houses with more than min_gpd gpd
def count_by_min_gpd(min_gpd):
temp_df = df_gpd[df_gpd['GPD'] > min_gpd]
return len(temp_df.index)
print('\n{0} households have an average GPD greater than 300'.format(count_by_min_gpd(300)))
print('{0} households have an average GPD greater than 500'.format(count_by_min_gpd(500)))
print('{0} households have an average GPD greater than 1000\n'.format(count_by_min_gpd(1000)))
print("Saving GPD data to 'household_gpd.csv'...")
df_gpd.to_csv('household_gpd.csv', index=False)
print('Done!\n')
print("Saving street GPD data to 'streets.csv'...")
street_gpd.to_csv('streets.csv', index=False)
print('Done!\n')
print("Saving all GPD data to 'gpd.xlsx'...")
# Write to Excel sheet
with pd.ExcelWriter('gpd.xlsx') as writer:
df_gpd.to_excel(writer, index=False, sheet_name='Household GPD')
street_gpd.to_excel(writer, index=False, sheet_name='Street GPD')
print("Done!")
| [
"pandas.isnull",
"pandas.DataFrame",
"datetime.datetime.strptime",
"sqlalchemy.create_engine",
"os.path.join",
"datetime.timedelta",
"numpy.timedelta64",
"numpy.datetime64",
"pandas.read_sql_table",
"pandas.ExcelWriter",
"time.time"
] | [((145, 156), 'time.time', 'time.time', ([], {}), '()\n', (154, 156), False, 'import time\n'), ((400, 450), 'os.path.join', 'os.path.join', (['"""SQLiteWaterUsage"""', '"""student.sqlite"""'], {}), "('SQLiteWaterUsage', 'student.sqlite')\n", (412, 450), False, 'import os\n'), ((460, 508), 'sqlalchemy.create_engine', 'sqlalchemy.create_engine', (["('sqlite:///' + db_path)"], {}), "('sqlite:///' + db_path)\n", (484, 508), False, 'import sqlalchemy\n'), ((601, 653), 'pandas.read_sql_table', 'pd.read_sql_table', (['"""Water"""', 'engine'], {'parse_dates': '(True)'}), "('Water', engine, parse_dates=True)\n", (618, 653), True, 'import pandas as pd\n'), ((2330, 2362), 'pandas.DataFrame', 'pd.DataFrame', (['df_base_dictionary'], {}), '(df_base_dictionary)\n', (2342, 2362), True, 'import pandas as pd\n'), ((4807, 4841), 'pandas.DataFrame', 'pd.DataFrame', (['street_gpd_base_dict'], {}), '(street_gpd_base_dict)\n', (4819, 4841), True, 'import pandas as pd\n'), ((5109, 5120), 'time.time', 'time.time', ([], {}), '()\n', (5118, 5120), False, 'import time\n'), ((6007, 6033), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['"""gpd.xlsx"""'], {}), "('gpd.xlsx')\n", (6021, 6033), True, 'import pandas as pd\n'), ((1259, 1303), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['s', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(s, '%Y-%m-%d %H:%M:%S')\n", (1279, 1303), True, 'import datetime as dt\n'), ((3782, 3803), 'pandas.isnull', 'pd.isnull', (['start_date'], {}), '(start_date)\n', (3791, 3803), True, 'import pandas as pd\n'), ((4097, 4116), 'pandas.isnull', 'pd.isnull', (['end_date'], {}), '(end_date)\n', (4106, 4116), True, 'import pandas as pd\n'), ((1961, 1983), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""s"""'], {}), "(1, 's')\n", (1975, 1983), True, 'import numpy as np\n'), ((4004, 4025), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(90)'}), '(days=90)\n', (4016, 4025), True, 'import datetime as dt\n'), ((4309, 4330), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(90)'}), '(days=90)\n', (4321, 4330), True, 'import datetime as dt\n'), ((1920, 1957), 'numpy.datetime64', 'np.datetime64', (['"""1970-01-01T00:00:00Z"""'], {}), "('1970-01-01T00:00:00Z')\n", (1933, 1957), True, 'import numpy as np\n')] |
from ast import literal_eval
import json
import requests
import csv
from io import StringIO
from flask import Flask, request, jsonify, Response
import psycopg2
from numpy import transpose, array
from bm25 import BM25L
from preprocessing import preprocess
SELECT_CORPUS_FIELDS = "SELECT code, name, txt_ementa FROM corpus;"
SELECT_ST_FIELDS = "SELECT name, text FROM solicitacoes;"
SELECT_CORPUS = "SELECT text_preprocessed FROM corpus;"
SELECT_ST = "SELECT text_preprocessed FROM solicitacoes;"
INSERT_DATA_CORPUS = "INSERT INTO corpus (code, name, txt_ementa, text, text_preprocessed) VALUES ('{}','{}','{}','{}','{}');"
SELECT_ROOT_BY_PROPOSICAO = "SELECT cod_proposicao_raiz FROM arvore_proposicoes WHERE cod_proposicao = {}"
SELECT_AVORE_BY_RAIZ = "SELECT * FROM arvore_proposicoes WHERE cod_proposicao_raiz IN {}"
session = requests.Session()
session.trust_env = False
connection = psycopg2.connect(host="ulyssesdb", database="admin",user="admin", password="<PASSWORD>", port=5432)
app = Flask(__name__)
def load_corpus(con):
with con.cursor() as cursor:
cursor.execute(SELECT_CORPUS_FIELDS)
try:
(codes, names, ementas) = (array(x) for x in transpose( cursor.fetchall() ))
cursor.execute(SELECT_CORPUS)
tokenized_corpus = cursor.fetchall()
tokenized_corpus = ["[" + entry[0][1:-1] + "]" for entry in tokenized_corpus]
except:
(codes, names, ementas, tokenized_corpus) = [],[],[],[]
tokenized_corpus = [literal_eval(i) for i in tokenized_corpus]
print("Loaded", len(names), "documents")
return (codes, names, ementas, tokenized_corpus)
def load_solicitacoes(con):
with con.cursor() as cursor:
cursor.execute(SELECT_ST_FIELDS)
try:
(names, texts) = (array(x) for x in transpose( cursor.fetchall() ))
cursor.execute(SELECT_ST)
tokenized_sts = cursor.fetchall()
tokenized_sts = ["[" + entry[0][1:-1] + "]" for entry in tokenized_sts]
except:
(names, texts, tokenized_sts) = [],[],[],[]
tokenized_sts = [literal_eval(i) for i in tokenized_sts]
print("Loaded", len(names), "Solicitações de Trabalho")
return (names, texts, tokenized_sts)
# Loading data
print("Loading corpus...")
(codes, names, ementas, tokenized_corpus) = load_corpus(connection)
(names_sts, texto_sts, tokenized_sts) = load_solicitacoes(connection)
# Loading model with dataset
try:
model = BM25L(tokenized_corpus)
except:
model = None
try:
model_st = BM25L(tokenized_sts)
except:
model_st = None
print("===IT'S ALIVE!===")
def getPastFeedback(con):
try:
with con.cursor() as cur:
cur.execute("SELECT query, user_feedback FROM feedback;")
(queries, feedbacks) = transpose(cur.fetchall())
feedbacks = [literal_eval(i) for i in feedbacks]
except:
queries, feedbacks = [], []
scores = []
all_queries = []
for entry, q in zip(feedbacks, queries):
scores.append([[i["id"], float(i["score"]), float(i["score_normalized"])] for i in entry if i["class"]!='i'])
all_queries.append(q)
return all_queries, scores
def retrieveDocuments(query, n, raw_query, improve_similarity, con):
indexes = list(range(len(codes)))
past_queries, scores = getPastFeedback(con)
slice_indexes, scores, scores_normalized = model.get_top_n(query, indexes, n=n,
improve_similarity=improve_similarity, raw_query= raw_query, past_queries=past_queries,
retrieved_docs=scores, names=names)
selected_codes = codes[slice_indexes]
selected_ementas = ementas[slice_indexes]
selected_names = names[slice_indexes]
return selected_codes, selected_ementas, selected_names, scores, scores_normalized
def retrieveSTs(query, n, raw_query, improve_similarity, con):
indexes = list(range(len(names_sts)))
past_queries, scores = getPastFeedback(con)
slice_indexes, scores, scores_normalized = model_st.get_top_n(query, indexes, n=n,
improve_similarity=improve_similarity, raw_query= raw_query, past_queries=past_queries,
retrieved_docs=scores, names=names_sts)
selected_sts = texto_sts[slice_indexes]
selected_names = names_sts[slice_indexes]
return selected_names, selected_sts, scores, scores_normalized
def getRelationsFromTree(retrieved_doc):
with connection.cursor() as cursor:
cursor.execute(SELECT_ROOT_BY_PROPOSICAO.format(retrieved_doc))
roots = cursor.fetchall()
# Considerando que documento seja uma raiz
if (len(roots) == 0):
roots.append((retrieved_doc,))
roots = [str(i[0]) for i in roots]
cursor.execute(SELECT_AVORE_BY_RAIZ.format("(%s)" % ",".join(roots)))
results = cursor.fetchall()
results = list(map(lambda x: {"numero_sequencia": x[0],"nivel": x[1],"cod_proposicao": x[2],
"cod_proposicao_referenciada": x[3],"cod_proposicao_raiz": x[4],
"tipo_referencia": x[5]}, results))
return results
@app.route('/', methods=["POST"])
def lookForSimilar():
if (model == None):
return Response(status=500)
args = request.json
try:
query = args["text"]
except:
return ""
try:
k = args["num_proposicoes"]
except:
k = 20
try:
query_expansion = int(args["expansao"])
if (query_expansion == 0):
query_expansion = False
else:
query_expansion = True
except:
query_expansion = True
try:
improve_similarity = int(args["improve-similarity"])
if (improve_similarity == 0):
improve_similarity = False
else:
improve_similarity = True
except:
improve_similarity = True
k = min(k, len(codes), len(names_sts))
if (query_expansion):
resp = session.post("http://expand-query:5003", json={"query": query})
if (resp.status_code == 200):
query = json.loads(resp.content)["query"]
preprocessed_query = preprocess(query)
# Recuperando das solicitações de trabalho
selected_names_sts, selected_sts, scores_sts, scores_sts_normalized = retrieveSTs(preprocessed_query, k,
improve_similarity=improve_similarity, raw_query=query, con=connection)
resp_results_sts = list()
for i in range(k):
resp_results_sts.append({"name": selected_names_sts[i], "texto": selected_sts[i].strip(),
"score": scores_sts[i], "score_normalized": scores_sts_normalized[i], "tipo": "ST"})
# Recuperando do corpus das proposições
selected_codes, selected_ementas, selected_names, scores, scores_normalized = retrieveDocuments(preprocessed_query, k,
improve_similarity=improve_similarity, raw_query=query, con=connection)
resp_results = list()
for i in range(k):
# Propostas relacionadas pela árvore de proposições
relations_tree = getRelationsFromTree(selected_codes[i])
resp_results.append({"id": selected_codes[i], "name": selected_names[i],
"texto": selected_ementas[i].strip(), "score": scores[i], "score_normalized": scores_normalized[i],
"tipo": "PR", "arvore": relations_tree})
response = {"proposicoes": resp_results, "solicitacoes": resp_results_sts}
return jsonify(response)
@app.route('/insert', methods=["POST"])
def insertDocs():
content = request.data.decode("utf-8")
io = StringIO(content)
reader = csv.reader(io, delimiter=',')
data = [row for row in reader]
columns = data[0]
data = data[1:]
try:
idx_text = columns.index("text")
idx_ementa = columns.index("txt_ementa")
idx_code = columns.index("code")
idx_name = columns.index("name")
data = transpose( data )
text = data[idx_text]
txt_ementa = data[idx_ementa]
code = data[idx_code]
name = data[idx_name]
text_preprocessed = ['{' + ','.join(['"'+str(entry)+'"' for entry in preprocess(txt)]) + '}' for txt in text]
data_insert = transpose( [code, name, txt_ementa, text, text_preprocessed] )
with connection.cursor() as cursor:
for d in data_insert:
cursor.execute(INSERT_DATA_CORPUS.format(*d))
connection.commit()
# Reloading model
print("RELOADING...")
(codes, names, ementas, tokenized_corpus) = load_corpus(connection)
model = BM25L(tokenized_corpus)
print("RELOAD DONE")
except:
return Response(status=500)
return Response(status=201)
if __name__=="__main__":
app.run(host="0.0.0.0", debug=True, use_reloader=False, port=5000)
| [
"psycopg2.connect",
"preprocessing.preprocess",
"json.loads",
"requests.Session",
"flask.Flask",
"bm25.BM25L",
"flask.request.data.decode",
"ast.literal_eval",
"numpy.array",
"flask.Response",
"io.StringIO",
"numpy.transpose",
"csv.reader",
"flask.jsonify"
] | [((832, 850), 'requests.Session', 'requests.Session', ([], {}), '()\n', (848, 850), False, 'import requests\n'), ((891, 996), 'psycopg2.connect', 'psycopg2.connect', ([], {'host': '"""ulyssesdb"""', 'database': '"""admin"""', 'user': '"""admin"""', 'password': '"""<PASSWORD>"""', 'port': '(5432)'}), "(host='ulyssesdb', database='admin', user='admin', password\n ='<PASSWORD>', port=5432)\n", (907, 996), False, 'import psycopg2\n'), ((997, 1012), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1002, 1012), False, 'from flask import Flask, request, jsonify, Response\n'), ((2511, 2534), 'bm25.BM25L', 'BM25L', (['tokenized_corpus'], {}), '(tokenized_corpus)\n', (2516, 2534), False, 'from bm25 import BM25L\n'), ((2581, 2601), 'bm25.BM25L', 'BM25L', (['tokenized_sts'], {}), '(tokenized_sts)\n', (2586, 2601), False, 'from bm25 import BM25L\n'), ((6216, 6233), 'preprocessing.preprocess', 'preprocess', (['query'], {}), '(query)\n', (6226, 6233), False, 'from preprocessing import preprocess\n'), ((7670, 7687), 'flask.jsonify', 'jsonify', (['response'], {}), '(response)\n', (7677, 7687), False, 'from flask import Flask, request, jsonify, Response\n'), ((7762, 7790), 'flask.request.data.decode', 'request.data.decode', (['"""utf-8"""'], {}), "('utf-8')\n", (7781, 7790), False, 'from flask import Flask, request, jsonify, Response\n'), ((7800, 7817), 'io.StringIO', 'StringIO', (['content'], {}), '(content)\n', (7808, 7817), False, 'from io import StringIO\n'), ((7831, 7860), 'csv.reader', 'csv.reader', (['io'], {'delimiter': '""","""'}), "(io, delimiter=',')\n", (7841, 7860), False, 'import csv\n'), ((8930, 8950), 'flask.Response', 'Response', ([], {'status': '(201)'}), '(status=201)\n', (8938, 8950), False, 'from flask import Flask, request, jsonify, Response\n'), ((5287, 5307), 'flask.Response', 'Response', ([], {'status': '(500)'}), '(status=500)\n', (5295, 5307), False, 'from flask import Flask, request, jsonify, Response\n'), ((8145, 8160), 'numpy.transpose', 'transpose', (['data'], {}), '(data)\n', (8154, 8160), False, 'from numpy import transpose, array\n'), ((8433, 8493), 'numpy.transpose', 'transpose', (['[code, name, txt_ementa, text, text_preprocessed]'], {}), '([code, name, txt_ementa, text, text_preprocessed])\n', (8442, 8493), False, 'from numpy import transpose, array\n'), ((8817, 8840), 'bm25.BM25L', 'BM25L', (['tokenized_corpus'], {}), '(tokenized_corpus)\n', (8822, 8840), False, 'from bm25 import BM25L\n'), ((1523, 1538), 'ast.literal_eval', 'literal_eval', (['i'], {}), '(i)\n', (1535, 1538), False, 'from ast import literal_eval\n'), ((2140, 2155), 'ast.literal_eval', 'literal_eval', (['i'], {}), '(i)\n', (2152, 2155), False, 'from ast import literal_eval\n'), ((2884, 2899), 'ast.literal_eval', 'literal_eval', (['i'], {}), '(i)\n', (2896, 2899), False, 'from ast import literal_eval\n'), ((8897, 8917), 'flask.Response', 'Response', ([], {'status': '(500)'}), '(status=500)\n', (8905, 8917), False, 'from flask import Flask, request, jsonify, Response\n'), ((1166, 1174), 'numpy.array', 'array', (['x'], {}), '(x)\n', (1171, 1174), False, 'from numpy import transpose, array\n'), ((1811, 1819), 'numpy.array', 'array', (['x'], {}), '(x)\n', (1816, 1819), False, 'from numpy import transpose, array\n'), ((6157, 6181), 'json.loads', 'json.loads', (['resp.content'], {}), '(resp.content)\n', (6167, 6181), False, 'import json\n'), ((8369, 8384), 'preprocessing.preprocess', 'preprocess', (['txt'], {}), '(txt)\n', (8379, 8384), False, 'from preprocessing import preprocess\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 07:32:21 2019
@author: thomas
"""
import numpy as np
import sounddevice as sd
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
# quantize samples
def quantize(x,Rmin,Rmax):
xhat=np.zeros(np.size(x))
indx=0
for xc in x:
i = np.where((Rmin<=xc) & (Rmax>xc))
xhat[indx]=(Rmin[i]+Rmax[i])/2.0
indx=indx+1
return(xhat)
minv=-32767
maxv=+32768
Dv=4096
R=np.arange(minv,maxv,Dv)
Rmin=R[0:len(R)-1]
Rmax=R[1:len(R)]
# read audio samples
input_data = read("/usr/share/sounds/alsa/Rear_Center.wav","rb")
audio = input_data[1]
audio = np.array(audio)
rate = input_data[0]
# quantize audio
audio_q=quantize(audio,Rmin,Rmax)
audio_q=np.array(audio_q,dtype=np.int16)
font = {'family' : 'serif',
'weight' : 'normal',
'size' : 16}
plt.rc('font', **font)
plt.plot(audio_q)
plt.ylim(-32767,+32768)
plt.ylabel('$\hat{x_i}$')
plt.xlabel('$i$')
plt.tight_layout()
plt.savefig('sampledsound4096.png')
sd.play(audio_q, rate) | [
"matplotlib.pyplot.savefig",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.size",
"sounddevice.play",
"numpy.array",
"scipy.io.wavfile.read",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.ylim",
"matplotlib.pypl... | [((497, 522), 'numpy.arange', 'np.arange', (['minv', 'maxv', 'Dv'], {}), '(minv, maxv, Dv)\n', (506, 522), True, 'import numpy as np\n'), ((592, 644), 'scipy.io.wavfile.read', 'read', (['"""/usr/share/sounds/alsa/Rear_Center.wav"""', '"""rb"""'], {}), "('/usr/share/sounds/alsa/Rear_Center.wav', 'rb')\n", (596, 644), False, 'from scipy.io.wavfile import read\n'), ((674, 689), 'numpy.array', 'np.array', (['audio'], {}), '(audio)\n', (682, 689), True, 'import numpy as np\n'), ((771, 804), 'numpy.array', 'np.array', (['audio_q'], {'dtype': 'np.int16'}), '(audio_q, dtype=np.int16)\n', (779, 804), True, 'import numpy as np\n'), ((886, 908), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **font)\n", (892, 908), True, 'import matplotlib.pyplot as plt\n'), ((910, 927), 'matplotlib.pyplot.plot', 'plt.plot', (['audio_q'], {}), '(audio_q)\n', (918, 927), True, 'import matplotlib.pyplot as plt\n'), ((928, 952), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-32767)', '(+32768)'], {}), '(-32767, +32768)\n', (936, 952), True, 'import matplotlib.pyplot as plt\n'), ((952, 978), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$\\\\hat{x_i}$"""'], {}), "('$\\\\hat{x_i}$')\n", (962, 978), True, 'import matplotlib.pyplot as plt\n'), ((978, 995), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$i$"""'], {}), "('$i$')\n", (988, 995), True, 'import matplotlib.pyplot as plt\n'), ((996, 1014), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1012, 1014), True, 'import matplotlib.pyplot as plt\n'), ((1015, 1050), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""sampledsound4096.png"""'], {}), "('sampledsound4096.png')\n", (1026, 1050), True, 'import matplotlib.pyplot as plt\n'), ((1052, 1074), 'sounddevice.play', 'sd.play', (['audio_q', 'rate'], {}), '(audio_q, rate)\n', (1059, 1074), True, 'import sounddevice as sd\n'), ((290, 300), 'numpy.size', 'np.size', (['x'], {}), '(x)\n', (297, 300), True, 'import numpy as np\n'), ((342, 378), 'numpy.where', 'np.where', (['((Rmin <= xc) & (Rmax > xc))'], {}), '((Rmin <= xc) & (Rmax > xc))\n', (350, 378), True, 'import numpy as np\n')] |
import os
import re
#from tqdm import tqdm
import numpy as np
import pandas as pd
import preprocessor as tp
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
tp.set_options(tp.OPT.URL,tp.OPT.MENTION)
#import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import make_scorer, f1_score, accuracy_score, recall_score, precision_score, classification_report, precision_recall_fscore_support
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.svm import SVC, LinearSVC
import nltk
# Uncomment to download "stopwords"
#nltk.download("stopwords")
from nltk.corpus import stopwords
import copy
#import torch
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.svm import SVC
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score, roc_curve, auc, f1_score
import pickle
import json
import jsonlines
import operator
from collections import OrderedDict
seed = 2020
# recommended learning rate for Adam 5e-5, 3e-5, 2e-5
learning_rate = 2e-5
# we will do just 1 epoch for illustration, though multiple epochs might be better as long as we will not overfit the model
number_of_epochs = 1
'''
dataset_name_list = ['HateEval_spanish']
train_set_list = ['HateEval_spanish']
test_set_list = ['test_tweet_spanish']
'''
dataset_name_list = ['WH', 'HateEval', 'davidson', 'goldback', 'Founta_2018', 'grimmer']
train_set_list = ['WH','davidson','HateEval', 'goldback','Founta_2018', 'grimmer']
test_set_list = ['test_tweet']
classifier_list = ['NB', 'LR']
#classifier_list = ['LR']
dataset_location = {}
dataset_location['WH'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/Waseem_and_Hovy_2016/data.csv"
dataset_location['HateEval'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/SemEval-2019/hateval2019_en_train.csv"
dataset_location['davidson'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/davidson_2017/labeled_data.csv"
dataset_location['goldback'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/Golbeck_2017/onlineHarassmentDataset.tdf"
dataset_location['rezvan'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/Rezvan_2018/final.csv"
dataset_location['grimmer'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/Grimminger_2020/combined_train_test.tsv"
dataset_location['HateEval_spanish'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/SemEval-2019/hateval2019_es_train.csv"
dataset_location['Founta_2018'] = "/work2/04549/mustaf/lonestar/data/Hate_Speech_data/Founta_2018/hatespeech_text_label_vote.csv"
#dataset_location['test_tweet'] = "/scratch/07807/dinesh/Tweet-Filtering/English-Tweets/2017-10-01-08-00-01.json"
#dataset_location['test_tweet'] = "2017-10-01-08-00-01.json"
# the following two address contains the same 49 tweets json file for 1st unterface where we have collected 4668 tweets annottaion
#dataset_location['test_tweet'] = "/work2/04549/mustaf/maverick2/twitter_corpus/English-Tweets/"
#dataset_location['test_tweet'] = "/work2/07807/dinesh/stampede2/English-Tweets/PreviousAnalyzedFile/"
# this is the new 100 tweets json file we are doring for 2nd interface, we will collect 5,000 tweet for annotation
# contains 13674964 tweets
dataset_location['test_tweet'] = "/work2/07807/dinesh/stampede2/English-Tweets/CurrentAnalyzedFile/"
dataset_location['test_tweet_spanish'] = "/work2/04549/mustaf/maverick2/spanish-tweets/2017-10-01-08-00-01.json"
dataset_separator = {}
dataset_separator['WH'] = "\t"
dataset_separator['HateEval'] = ','
dataset_separator['HateEval_spanish'] = ','
dataset_separator['davidson'] = ','
dataset_separator['goldback'] = '\t'
dataset_separator['rezvan'] = ','
dataset_separator['Founta_2018'] = '\t'
dataset_separator['grimmer'] = '\t'
def text_preprocessing(s):
s = s.lower()
# Change 't to 'not'
s = re.sub(r"\'t", " not", s)
# Remove @name
s = re.sub(r'(@.*?)[\s]', ' ', s)
# Isolate and remove punctuations except '?'
s = re.sub(r'([\'\"\.\(\)\!\?\\\/\,])', r' \1 ', s)
s = re.sub(r'[^\w\s\?]', ' ', s)
# Remove some special characters
s = re.sub(r'([\;\:\|\n])', ' ', s)
# Remove stopwords except 'not' and 'can'
#s = " ".join([word for word in s.split()
# if word not in stopwords.words('english')
# or word in ['not', 'can']])
# Remove trailing whitespace
s = re.sub(r'\s+', ' ', s).strip()
return s
def read_data(dataset_name, file_address):
test_tweets_list = []
test_tweets_raw = []
if dataset_name == "WH":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name], header= None, encoding='utf-8')
df.columns = ["id", "text", "label"]
df = df.drop(columns=['id'])
df.loc[(df.label == 'none'), 'label'] = 0
df.loc[(df.label == 'none '), 'label'] = 0
df.loc[(df.label == 'sexism'), 'label'] = 1
df.loc[(df.label == 'racism'), 'label'] = 1
elif dataset_name == "HateEval":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
#print(df.columns)
df = df.drop(columns=['id','TR','AG'])
#print(df.columns)
df = df.rename(columns={"HS": "label"})
#print(df.columns)
elif dataset_name == "HateEval_spanish":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
# print(df.columns)
df = df.drop(columns=['id', 'TR', 'AG'])
# print(df.columns)
df = df.rename(columns={"HS": "label"})
# print(df.columns)
elif dataset_name == "davidson":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
df = df.drop(columns=['index','count','hate_speech','offensive_language','neither'])
df = df.rename(columns = {"class": "label", "tweet": "text"})
#print(df.columns)
df.loc[(df.label == 0), 'label'] = 1
df.loc[(df.label == 2), 'label'] = 0
#print(df.sample(20))
elif dataset_name == "goldback":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name], encoding = "ISO-8859-1")
df = df.drop(columns=['ID'])
df = df.rename(columns={"Code": "label", "Tweet": "text"})
df.loc[(df.label == 'H'), 'label'] = 1
df.loc[(df.label == 'N'), 'label'] = 0
#print(df.sample(10))
elif dataset_name == "rezvan":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
df.columns = ["text", "label"]
df.loc[(df.label == 'yes'), 'label'] = 1
df.loc[(df.label == 'Yes'), 'label'] = 1
df.loc[(df.label == 'YES'), 'label'] = 1
df.loc[(df.label == 'yes '), 'label'] = 1
df.loc[(df.label == 'no'), 'label'] = 0
df.loc[(df.label == 'No'), 'label'] = 0
df.loc[(df.label == 'NO'), 'label'] = 0
df.loc[(df.label == 'N'), 'label'] = 0
df.loc[(df.label == 'Other'), 'label'] = 0
df.loc[(df.label == 'others'), 'label'] = 0
df.loc[(df.label == 'Others'), 'label'] = 0
df.loc[(df.label == 'racism'), 'label'] = 1
df.loc[(df.label == 'not sure'), 'label'] = 0
df.loc[(df.label == 'Not Sure'), 'label'] = 0
df.loc[(df.label == 'Not sure'), 'label'] = 0
df.dropna(inplace = True)
elif dataset_name == "Founta_2018":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
df.columns = ["text", "label", "count"]
df = df.drop(columns=['count'])
df.loc[(df.label == 'normal'), 'label'] = 0
df.loc[(df.label == 'abusive'), 'label'] = 0
df.loc[(df.label == 'spam'), 'label'] = 0
df.loc[(df.label == 'offensive'), 'label'] = 0
df.loc[(df.label == 'cyberbullying'), 'label'] = 0
df.loc[(df.label == 'Aggressive'), 'label'] = 0
df.loc[(df.label == 'hateful'), 'label'] = 1
elif dataset_name == "grimmer":
df = pd.read_csv(dataset_location[dataset_name], sep=dataset_separator[dataset_name])
#df.columns = ["text", "label", "count"]
# text Trump Biden West HOF
df = df.drop(columns=['Trump', 'Biden', 'West'])
df.columns = ["text", "label"]
print(df.label.value_counts())
df.loc[(df.label == 'Non-Hateful'), 'label'] = 0
df.loc[(df.label == 'Hateful'), 'label'] = 1
elif dataset_name == "test_tweet" or dataset_name == "test_tweet_spanish":
input_test_file_name = os.path.basename(file_address)
input_test_file_name = input_test_file_name[:input_test_file_name.index(".json")]
print(input_test_file_name)
input_test_file_base_address = dataset_location[dataset_name]
print(input_test_file_base_address)
file_name_preprocessed = os.path.join(input_test_file_base_address, input_test_file_name + "_preprocessed.pickle")
file_name_raw = os.path.join(input_test_file_base_address, input_test_file_name + "_raw.pickle")
#file_name_preprocessed = dataset_name+"_preprocessed.pickle"
#file_name_raw = dataset_name + "_raw.pickle"
if os.path.exists(file_name_preprocessed) and os.path.exists(file_name_raw):
test_tweets_list = pickle.load(open(file_name_preprocessed, "rb"))
test_tweets_raw = pickle.load(open(file_name_raw, "rb"))
return test_tweets_list, test_tweets_raw
else:
all_tweet_content = []
with open(file_address) as f:
for line in f:
data = json.loads(line)
text = data['text']
twitter_id = data['id']
#test_tweets_raw.append(text)
#test_tweets_list.append(text_preprocessing(text))
all_tweet_content.append([twitter_id, text_preprocessing(text), text])
#pickle.dump(test_tweets_list, open(file_name_preprocessed, "wb"))
#pickle.dump(test_tweets_raw, open(file_name_raw, "wb"))
df = pd.DataFrame(all_tweet_content, columns=['twitter_id', 'processed_text', 'text'])
return df
X = df.text.values
y = df.label.values
y = y.astype(int)
return df, X, y
def train_test_seprataion(data):
X = data.text.values
y = data.label.values
y = y.astype(int)
X_train, X_val, y_train, y_val = train_test_split(X, y, stratify=y, test_size=0.2, random_state=seed)
return X_train, X_val, y_train, y_val
def tfidf_vector_generation(dataset_name):
X_train, X_val, y_train, y_val = train_test_seprataion(read_data(dataset_name)[0], None)
# Preprocess text
X_train_preprocessed = np.array([text_preprocessing(text) for text in X_train])
X_val_preprocessed = np.array([text_preprocessing(text) for text in X_val])
# Calculate TF-IDF
tf_idf = TfidfVectorizer(ngram_range=(1, 3),
binary=True,
smooth_idf=False)
X_train_tfidf = tf_idf.fit_transform(X_train_preprocessed)
X_val_tfidf = tf_idf.transform(X_val_preprocessed)
return X_train_tfidf, X_val_tfidf, y_train, y_val
def f1_m(y_true, y_pred):
return f1_score(y_true, y_pred, average='binary')
def compute_and_save_tfidf_vectorizer(train_dataset):
tfidf_feature_file_name = train_dataset + "_" + "tf_idf_features.pickle"
tfidf_model_file_name = train_dataset + "_" + "tf_idf_model.pickle"
data_x_y_file_name = train_dataset + "_" + "data_x_y.pickle"
if os.path.exists(tfidf_feature_file_name) and os.path.exists(tfidf_model_file_name) and os.path.exists(data_x_y_file_name):
tf_idf_model = pickle.load(open(tfidf_model_file_name, "rb"))
tf_idf_features = pickle.load(open(tfidf_feature_file_name, "rb"))
data_x_y = pickle.load(open(data_x_y_file_name, "rb"))
train_X = data_x_y[0]
train_y = data_x_y[1]
return tf_idf_model, tf_idf_features, train_X, train_y
else:
_, train_X, train_y = read_data(train_dataset, None)
train_X_preprocessed = np.array([text_preprocessing(text) for text in train_X])
tf_idf_model = TfidfVectorizer(ngram_range=(1, 3),
binary=True,
smooth_idf=False)
tf_idf_features = tf_idf_model.fit_transform(train_X_preprocessed)
pickle.dump(tf_idf_features, open(tfidf_feature_file_name, "wb"))
pickle.dump(tf_idf_model, open(tfidf_model_file_name, "wb"))
data_x_y = (train_X, train_y)
pickle.dump(data_x_y, open(data_x_y_file_name, "wb"))
return tf_idf_model, tf_idf_features, train_X, train_y
def train_and_save_model(classifier, train_dataset):
trained_model_file_name = classifier + "_" + train_dataset + "_.pickle"
if os.path.exists(trained_model_file_name):
model = pickle.load(open(trained_model_file_name, "rb"))
return model
else:
model = None
if classifier == "NB":
model = MultinomialNB()
elif classifier == "LR":
model = LogisticRegression()
elif classifier == "GB":
model = GradientBoostingClassifier(random_state=seed)
if classifier == "rbf_svm":
model = SVC(probability= True, C=0.01, kernel="rbf") # default rbf
elif classifier == "svm_linear":
model = LinearSVC(C=0.01)
tf_idf_model, tf_idf_features, train_X, train_y = compute_and_save_tfidf_vectorizer(train_dataset)
model.fit(tf_idf_features, train_y)
pickle.dump(model, open(trained_model_file_name, "wb"))
return model
def get_ranked_list_of_tweet_ids(y_preds): # y_pred (pred[0], pred[1])
id = 0
id_prediction = {}
for pred in y_preds:
id_prediction[id] = pred[1]
id = id + 1
sorted_ids = sorted(id_prediction, key=id_prediction.get, reverse=True) # sort tweetid by the predicted score on hate class (1) in descending order
return sorted_ids
def remove_emoji(string):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002500-\U00002BEF" # chinese char
u"\U00002702-\U000027B0"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
u"\U0001f926-\U0001f937"
u"\U00010000-\U0010ffff"
u"\u2640-\u2642"
u"\u2600-\u2B55"
u"\u200d"
u"\u23cf"
u"\u23e9"
u"\u231a"
u"\ufe0f" # dingbats
u"\u3030"
"]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', string)
# pool classifier, if we have M dataset and N classifiers
# then in total we M*N classifier to train
# we pool using M*N classifiers
if __name__ == "__main__":
#read_data('test_tweet')
#exit(0)
prediction_is_done = 1 # 0 no prediction is done
pool_start = 9000
pool_end = 20000
output_file_base_name = "/work2/07807/dinesh/stampede2/English-Tweets/CurrentAnalyzedFile/pooled_tweets/pool_depth_"
data_tf_idf_models = {} # key is the dataset_name value is tf_idf_model
data_tf_idf_features = {} # key is the dataset_name value is tf_idf_model
data_x_y = {} # key is the dataset_name and value is the tuple (train_X, train_y)
data_trained_model = {} # key is the dataset_name_classifier and value is the traind model
# generate M*N trained_model
for dataset_name in dataset_name_list:
if dataset_name == "test_tweet":
continue
tf_idf_model, tf_idf_features, train_X, train_y = compute_and_save_tfidf_vectorizer(dataset_name)
data_tf_idf_models[dataset_name] = tf_idf_model
data_tf_idf_features[dataset_name] = tf_idf_features
data_x_y[dataset_name] = (train_X, train_y)
for classifier in classifier_list:
print(dataset_name, classifier)
trained_model = train_and_save_model(classifier, dataset_name)
data_trained_model[dataset_name+"_"+classifier] = trained_model
ranked_tweets_ids = {} # key dataset_name_classifier # value is the tweets id sorted by sorted by class=1 socre
test_dataset = test_set_list[0]
# run this part for new predcition on tests file
if prediction_is_done == 0:
data_frame_list = []
for test_file in os.listdir(dataset_location[test_dataset]):
if ".json" not in test_file:
continue
test_file_name = test_file[:test_file.index(".json")]
test_file_location = os.path.join(dataset_location[test_dataset], test_file)
if os.path.getsize(test_file_location) == 0:
# skipping because some json file contains nothing
continue
print(test_file_location)
test_X = []
test_X_raw = []
test_y = []
test_df = read_data(test_dataset, test_file_location) # returing preprocess tweets
test_X = test_df['processed_text']
for dataset_name in train_set_list:
for classifier in classifier_list:
print(test_file_name, dataset_name, classifier)
tf_idf_model = data_tf_idf_models[dataset_name]
trained_model = data_trained_model[dataset_name+"_"+classifier]
test_tf_idf_features = tf_idf_model.transform(test_X)
y_pred_probs = trained_model.predict_proba(test_tf_idf_features)
hate_class_probabilty = []
for probability in y_pred_probs:
hate_class_probabilty.append(probability[1])
test_df['prediction'] = hate_class_probabilty
final_df = test_df.drop(columns=['processed_text'])
pickle.dump(final_df, open(os.path.join(dataset_location[test_dataset], dataset_name + "_" + classifier + "_" + test_file_name + ".df"), "wb"))
#print(final_df.head())
data_frame_list.append(copy.deepcopy(final_df))
final_df = None
else:
# for prediction on new test data
print("POOLING and DUMPING")
for pool_depth in range(pool_start, pool_end + 100, 500):
data_frame_list = []
for test_file in os.listdir(dataset_location[test_dataset]):
if ".json" not in test_file:
continue
test_file_location = os.path.join(dataset_location[test_dataset], test_file)
if os.path.getsize(test_file_location) == 0:
# skipping because some json file contains nothing
continue
test_file_name = test_file[:test_file.index(".json")]
for dataset_name in train_set_list:
for classifier in classifier_list:
temp_df = pickle.load(open(os.path.join(dataset_location[test_dataset], dataset_name + "_" + classifier + "_" + test_file_name + ".df"),"rb"))
temp_df = temp_df.sort_values('prediction',ascending = False)
#print(temp_df)
temp_df = temp_df.head(pool_depth)
#print(temp_df)
data_frame_list.append(copy.deepcopy(temp_df))
temp_df = None
combined_df = pd.concat(data_frame_list)
combined_df = combined_df.sort_values('prediction',ascending = False)
filtered_df = combined_df[combined_df['prediction'] >= 0.9]
# randomly sample 5000 tweets from dataframe
filtered_df = filtered_df.sample(n=5000)
#print(filtered_df)
unique_tweets = filtered_df.text.unique()
print(pool_depth, len(unique_tweets))
final_tweets = []
for pooled_tweet in unique_tweets:
raw_tweets_without_RT = re.compile('RT @').sub('@', pooled_tweet, count=1)
raw_tweets_without_RT = raw_tweets_without_RT.replace(":", "").strip()
cleaned_tweet = tp.clean(raw_tweets_without_RT)
without_emoji_tweet = remove_emoji(cleaned_tweet)
if len(without_emoji_tweet.split(" ")) >= 3:
final_tweets.append(cleaned_tweet)
final_tweets = list(set(final_tweets))
output_file_name = output_file_base_name + str(pool_depth) + "_tweets_" + str(
len(final_tweets)) + "_pooled_tweets_filtered.text"
print(output_file_name)
with jsonlines.open(output_file_name, mode='w') as writer:
for pooled_tweet in final_tweets:
manifest_str = {}
manifest_str['source'] = pooled_tweet
writer.write(manifest_str)
exit(0)
#for pool_depth in range(10, len(test_X)+1000, 10):
for pool_depth in range(10, 1000, 10):
pooled_tmp_tweets_id = []
for k, list_of_tweetids in ranked_tweets_ids.items():
#print(k, list_of_tweetids)
pooled_tmp_tweets_id = pooled_tmp_tweets_id + list_of_tweetids[:pool_depth]
pooled_tweet_ids = list(set(pooled_tmp_tweets_id))
pooled_cost = len(pooled_tweet_ids)
if test_dataset == "test_tweet" or test_dataset == "test_tweet_spanish":
print(pool_depth, pooled_cost)
pooled_tweets = []
for pooled_tweet_id in pooled_tweet_ids:
raw_tweets_without_RT = re.compile('RT @').sub('@', test_X_raw[pooled_tweet_id], count=1)
raw_tweets_without_RT = raw_tweets_without_RT.replace(":","").strip()
pooled_tweets.append(tp.clean(raw_tweets_without_RT))
pickle.dump(pooled_tweets, open(test_dataset+"_"+str(pool_depth)+"_pooled_tweets.pickle", "wb"))
with jsonlines.open(test_dataset+"_"+str(pool_depth)+"_pooled_tweets.text", mode='w') as writer:
for pooled_tweet in pooled_tweets:
manifest_str = {}
manifest_str['source'] = pooled_tweet
writer.write(manifest_str)
continue
total_hate = np.count_nonzero(np.array(test_y))
total_cost = len(test_y)
#print(pooled_tweets_id)
#print(len(pooled_tweets_id), len(test_y))
#print(test_X[0], test_y[0])
pooled_tweets_label = []
for tweet_id in pooled_tweet_ids:
pooled_tweets_label.append(test_y[tweet_id])
current_hate = np.count_nonzero(np.array(pooled_tweets_label))
recall_value = current_hate*1.0/total_hate
budget_incur_ratio = pooled_cost*1.0/total_cost
print(pool_depth, pooled_cost, total_cost, budget_incur_ratio, current_hate, total_hate, recall_value)
| [
"pandas.read_csv",
"re.compile",
"jsonlines.open",
"numpy.array",
"copy.deepcopy",
"os.path.exists",
"preprocessor.clean",
"os.listdir",
"pandas.set_option",
"sklearn.naive_bayes.MultinomialNB",
"pandas.DataFrame",
"os.path.getsize",
"json.loads",
"sklearn.model_selection.train_test_split"... | [((109, 148), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (122, 148), True, 'import pandas as pd\n'), ((149, 191), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', 'None'], {}), "('display.max_columns', None)\n", (162, 191), True, 'import pandas as pd\n'), ((193, 235), 'preprocessor.set_options', 'tp.set_options', (['tp.OPT.URL', 'tp.OPT.MENTION'], {}), '(tp.OPT.URL, tp.OPT.MENTION)\n', (207, 235), True, 'import preprocessor as tp\n'), ((4103, 4128), 're.sub', 're.sub', (['"""\\\\\'t"""', '""" not"""', 's'], {}), '("\\\\\'t", \' not\', s)\n', (4109, 4128), False, 'import re\n'), ((4156, 4185), 're.sub', 're.sub', (['"""(@.*?)[\\\\s]"""', '""" """', 's'], {}), "('(@.*?)[\\\\s]', ' ', s)\n", (4162, 4185), False, 'import re\n'), ((4243, 4301), 're.sub', 're.sub', (['"""([\\\\\'\\\\"\\\\.\\\\(\\\\)\\\\!\\\\?\\\\\\\\\\\\/\\\\,])"""', '""" \\\\1 """', 's'], {}), '(\'([\\\\\\\'\\\\"\\\\.\\\\(\\\\)\\\\!\\\\?\\\\\\\\\\\\/\\\\,])\', \' \\\\1 \', s)\n', (4249, 4301), False, 'import re\n'), ((4299, 4329), 're.sub', 're.sub', (['"""[^\\\\w\\\\s\\\\?]"""', '""" """', 's'], {}), "('[^\\\\w\\\\s\\\\?]', ' ', s)\n", (4305, 4329), False, 'import re\n'), ((4373, 4407), 're.sub', 're.sub', (['"""([\\\\;\\\\:\\\\|\\\\n])"""', '""" """', 's'], {}), "('([\\\\;\\\\:\\\\|\\\\n])', ' ', s)\n", (4379, 4407), False, 'import re\n'), ((10724, 10792), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'stratify': 'y', 'test_size': '(0.2)', 'random_state': 'seed'}), '(X, y, stratify=y, test_size=0.2, random_state=seed)\n', (10740, 10792), False, 'from sklearn.model_selection import train_test_split\n'), ((11196, 11262), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'ngram_range': '(1, 3)', 'binary': '(True)', 'smooth_idf': '(False)'}), '(ngram_range=(1, 3), binary=True, smooth_idf=False)\n', (11211, 11262), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((11534, 11576), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (11542, 11576), False, 'from sklearn.metrics import accuracy_score, roc_curve, auc, f1_score\n'), ((13151, 13190), 'os.path.exists', 'os.path.exists', (['trained_model_file_name'], {}), '(trained_model_file_name)\n', (13165, 13190), False, 'import os\n'), ((14396, 14515), 're.compile', 're.compile', (['"""[😀-🙏🌀-🗿🚀-\U0001f6ff\U0001f1e0-🇿─-⯯✂-➰✂-➰Ⓜ-🉑🤦-🤷𐀀-\U0010ffff♀-♂☀-⭕\u200d⏏⏩⌚️〰]+"""'], {'flags': 're.UNICODE'}), "(\n '[😀-🙏🌀-🗿🚀-\\U0001f6ff\\U0001f1e0-🇿─-⯯✂-➰✂-➰Ⓜ-🉑🤦-🤷𐀀-\\U0010ffff♀-♂☀-⭕\\u200d⏏⏩⌚️〰]+'\n , flags=re.UNICODE)\n", (14406, 14515), False, 'import re\n'), ((4831, 4947), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]', 'header': 'None', 'encoding': '"""utf-8"""'}), "(dataset_location[dataset_name], sep=dataset_separator[\n dataset_name], header=None, encoding='utf-8')\n", (4842, 4947), True, 'import pandas as pd\n'), ((11856, 11895), 'os.path.exists', 'os.path.exists', (['tfidf_feature_file_name'], {}), '(tfidf_feature_file_name)\n', (11870, 11895), False, 'import os\n'), ((11900, 11937), 'os.path.exists', 'os.path.exists', (['tfidf_model_file_name'], {}), '(tfidf_model_file_name)\n', (11914, 11937), False, 'import os\n'), ((11942, 11976), 'os.path.exists', 'os.path.exists', (['data_x_y_file_name'], {}), '(data_x_y_file_name)\n', (11956, 11976), False, 'import os\n'), ((12495, 12561), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'ngram_range': '(1, 3)', 'binary': '(True)', 'smooth_idf': '(False)'}), '(ngram_range=(1, 3), binary=True, smooth_idf=False)\n', (12510, 12561), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((17223, 17265), 'os.listdir', 'os.listdir', (['dataset_location[test_dataset]'], {}), '(dataset_location[test_dataset])\n', (17233, 17265), False, 'import os\n'), ((4646, 4668), 're.sub', 're.sub', (['"""\\\\s+"""', '""" """', 's'], {}), "('\\\\s+', ' ', s)\n", (4652, 4668), False, 'import re\n'), ((5285, 5370), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (5296, 5370), True, 'import pandas as pd\n'), ((13360, 13375), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (13373, 13375), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((13605, 13648), 'sklearn.svm.SVC', 'SVC', ([], {'probability': '(True)', 'C': '(0.01)', 'kernel': '"""rbf"""'}), "(probability=True, C=0.01, kernel='rbf')\n", (13608, 13648), False, 'from sklearn.svm import SVC\n'), ((17432, 17487), 'os.path.join', 'os.path.join', (['dataset_location[test_dataset]', 'test_file'], {}), '(dataset_location[test_dataset], test_file)\n', (17444, 17487), False, 'import os\n'), ((19214, 19256), 'os.listdir', 'os.listdir', (['dataset_location[test_dataset]'], {}), '(dataset_location[test_dataset])\n', (19224, 19256), False, 'import os\n'), ((20297, 20323), 'pandas.concat', 'pd.concat', (['data_frame_list'], {}), '(data_frame_list)\n', (20306, 20323), True, 'import pandas as pd\n'), ((23139, 23155), 'numpy.array', 'np.array', (['test_y'], {}), '(test_y)\n', (23147, 23155), True, 'import numpy as np\n'), ((23486, 23515), 'numpy.array', 'np.array', (['pooled_tweets_label'], {}), '(pooled_tweets_label)\n', (23494, 23515), True, 'import numpy as np\n'), ((5602, 5687), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (5613, 5687), True, 'import pandas as pd\n'), ((13429, 13449), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (13447, 13449), False, 'from sklearn.linear_model import LogisticRegression\n'), ((13726, 13743), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {'C': '(0.01)'}), '(C=0.01)\n', (13735, 13743), False, 'from sklearn.svm import LinearSVC\n'), ((17503, 17538), 'os.path.getsize', 'os.path.getsize', (['test_file_location'], {}), '(test_file_location)\n', (17518, 17538), False, 'import os\n'), ((19370, 19425), 'os.path.join', 'os.path.join', (['dataset_location[test_dataset]', 'test_file'], {}), '(dataset_location[test_dataset], test_file)\n', (19382, 19425), False, 'import os\n'), ((21018, 21049), 'preprocessor.clean', 'tp.clean', (['raw_tweets_without_RT'], {}), '(raw_tweets_without_RT)\n', (21026, 21049), True, 'import preprocessor as tp\n'), ((21498, 21540), 'jsonlines.open', 'jsonlines.open', (['output_file_name'], {'mode': '"""w"""'}), "(output_file_name, mode='w')\n", (21512, 21540), False, 'import jsonlines\n'), ((5917, 6002), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (5928, 6002), True, 'import pandas as pd\n'), ((13503, 13548), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'random_state': 'seed'}), '(random_state=seed)\n', (13529, 13548), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((19446, 19481), 'os.path.getsize', 'os.path.getsize', (['test_file_location'], {}), '(test_file_location)\n', (19461, 19481), False, 'import os\n'), ((22629, 22660), 'preprocessor.clean', 'tp.clean', (['raw_tweets_without_RT'], {}), '(raw_tweets_without_RT)\n', (22637, 22660), True, 'import preprocessor as tp\n'), ((6361, 6469), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]', 'encoding': '"""ISO-8859-1"""'}), "(dataset_location[dataset_name], sep=dataset_separator[\n dataset_name], encoding='ISO-8859-1')\n", (6372, 6469), True, 'import pandas as pd\n'), ((18934, 18957), 'copy.deepcopy', 'copy.deepcopy', (['final_df'], {}), '(final_df)\n', (18947, 18957), False, 'import copy\n'), ((20848, 20866), 're.compile', 're.compile', (['"""RT @"""'], {}), "('RT @')\n", (20858, 20866), False, 'import re\n'), ((22440, 22458), 're.compile', 're.compile', (['"""RT @"""'], {}), "('RT @')\n", (22450, 22458), False, 'import re\n'), ((6745, 6830), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (6756, 6830), True, 'import pandas as pd\n'), ((18730, 18842), 'os.path.join', 'os.path.join', (['dataset_location[test_dataset]', "(dataset_name + '_' + classifier + '_' + test_file_name + '.df')"], {}), "(dataset_location[test_dataset], dataset_name + '_' +\n classifier + '_' + test_file_name + '.df')\n", (18742, 18842), False, 'import os\n'), ((20207, 20229), 'copy.deepcopy', 'copy.deepcopy', (['temp_df'], {}), '(temp_df)\n', (20220, 20229), False, 'import copy\n'), ((7716, 7801), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (7727, 7801), True, 'import pandas as pd\n'), ((19818, 19930), 'os.path.join', 'os.path.join', (['dataset_location[test_dataset]', "(dataset_name + '_' + classifier + '_' + test_file_name + '.df')"], {}), "(dataset_location[test_dataset], dataset_name + '_' +\n classifier + '_' + test_file_name + '.df')\n", (19830, 19930), False, 'import os\n'), ((8314, 8399), 'pandas.read_csv', 'pd.read_csv', (['dataset_location[dataset_name]'], {'sep': 'dataset_separator[dataset_name]'}), '(dataset_location[dataset_name], sep=dataset_separator[dataset_name]\n )\n', (8325, 8399), True, 'import pandas as pd\n'), ((8840, 8870), 'os.path.basename', 'os.path.basename', (['file_address'], {}), '(file_address)\n', (8856, 8870), False, 'import os\n'), ((9144, 9237), 'os.path.join', 'os.path.join', (['input_test_file_base_address', "(input_test_file_name + '_preprocessed.pickle')"], {}), "(input_test_file_base_address, input_test_file_name +\n '_preprocessed.pickle')\n", (9156, 9237), False, 'import os\n'), ((9258, 9343), 'os.path.join', 'os.path.join', (['input_test_file_base_address', "(input_test_file_name + '_raw.pickle')"], {}), "(input_test_file_base_address, input_test_file_name + '_raw.pickle'\n )\n", (9270, 9343), False, 'import os\n'), ((9476, 9514), 'os.path.exists', 'os.path.exists', (['file_name_preprocessed'], {}), '(file_name_preprocessed)\n', (9490, 9514), False, 'import os\n'), ((9519, 9548), 'os.path.exists', 'os.path.exists', (['file_name_raw'], {}), '(file_name_raw)\n', (9533, 9548), False, 'import os\n'), ((10380, 10465), 'pandas.DataFrame', 'pd.DataFrame', (['all_tweet_content'], {'columns': "['twitter_id', 'processed_text', 'text']"}), "(all_tweet_content, columns=['twitter_id', 'processed_text',\n 'text'])\n", (10392, 10465), True, 'import pandas as pd\n'), ((9900, 9916), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (9910, 9916), False, 'import json\n')] |
import os
import cv2
import copy
import shutil
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from sklearn.metrics import roc_auc_score
from models.scse import SCSEUnet
gpu_ids = '0, 1'
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_ids
class MyDataset(Dataset):
def __init__(self, test_path='', size=896):
self.test_path = test_path
self.size = size
self.filelist = sorted(os.listdir(self.test_path))
self.transform = transforms.Compose([
np.float32,
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
def __getitem__(self, idx):
return self.load_item(idx)
def __len__(self):
return len(self.filelist)
def load_item(self, idx):
fname1, fname2 = self.test_path + self.filelist[idx], ''
img = cv2.imread(fname1)[..., ::-1]
H, W, _ = img.shape
mask = np.zeros([H, W, 3])
H, W, _ = img.shape
img = img.astype('float') / 255.
mask = mask.astype('float') / 255.
return self.transform(img), self.tensor(mask[:, :, :1]), fname1.split('/')[-1]
def tensor(self, img):
return torch.from_numpy(img).float().permute(2, 0, 1)
class Detector(nn.Module):
def __init__(self):
super(Detector, self).__init__()
self.name = 'detector'
self.det_net = SCSEUnet(backbone_arch='senet154', num_channels=3)
def forward(self, Ii):
Mo = self.det_net(Ii)
return Mo
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.save_dir = 'weights/'
self.networks = Detector()
self.gen = nn.DataParallel(self.networks).cuda()
def forward(self, Ii):
return self.gen(Ii)
def load(self, path=''):
self.gen.load_state_dict(torch.load(self.save_dir + path + '%s_weights.pth' % self.networks.name))
def forensics_test(model):
test_size = '896'
test_path = 'data/input/'
decompose(test_path, test_size)
print('Decomposition complete.')
test_dataset = MyDataset(test_path='temp/input_decompose_' + test_size + '/', size=int(test_size))
path_out = 'temp/input_decompose_' + test_size + '_pred/'
test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=1)
rm_and_make_dir(path_out)
for items in test_loader:
Ii, Mg = (item.cuda() for item in items[:-1])
filename = items[-1]
Mo = model(Ii)
Mo = Mo * 255.
Mo = Mo.permute(0, 2, 3, 1).cpu().detach().numpy()
for i in range(len(Mo)):
Mo_tmp = Mo[i][..., ::-1]
cv2.imwrite(path_out + filename[i][:-4] + '.png', Mo_tmp)
print('Prediction complete.')
if os.path.exists('temp/input_decompose_' + test_size + '/'):
shutil.rmtree('temp/input_decompose_' + test_size + '/')
path_pre = merge(test_path, test_size)
print('Merging complete.')
path_gt = 'data/mask/'
if os.path.exists(path_gt):
flist = sorted(os.listdir(path_pre))
auc, f1, iou = [], [], []
for file in flist:
pre = cv2.imread(path_pre + file)
gt = cv2.imread(path_gt + file[:-4] + '.png')
H, W, C = pre.shape
Hg, Wg, C = gt.shape
if H != Hg or W != Wg:
gt = cv2.resize(gt, (W, H))
gt[gt > 127] = 255
gt[gt <= 127] = 0
if np.max(gt) != np.min(gt):
auc.append(roc_auc_score((gt.reshape(H * W * C) / 255).astype('int'), pre.reshape(H * W * C) / 255.))
pre[pre > 127] = 255
pre[pre <= 127] = 0
a, b = metric(pre / 255, gt / 255)
f1.append(a)
iou.append(b)
print('Evaluation: AUC: %5.4f, F1: %5.4f, IOU: %5.4f' % (np.mean(auc), np.mean(f1), np.mean(iou)))
return 0
def decompose(test_path, test_size):
flist = sorted(os.listdir(test_path))
size_list = [int(test_size)]
for size in size_list:
path_out = 'temp/input_decompose_' + str(size) + '/'
rm_and_make_dir(path_out)
rtn_list = [[]]
for file in flist:
img = cv2.imread(test_path + file)
# img = cv2.rotate(img, cv2.cv2.ROTATE_180)
H, W, _ = img.shape
size_idx = 0
while size_idx < len(size_list) - 1:
if H < size_list[size_idx+1] or W < size_list[size_idx+1]:
break
size_idx += 1
rtn_list[size_idx].append(file)
size = size_list[size_idx]
path_out = 'temp/input_decompose_' + str(size) + '/'
X, Y = H // (size // 2) + 1, W // (size // 2) + 1
idx = 0
for x in range(X-1):
if x * size // 2 + size > H:
break
for y in range(Y-1):
if y * size // 2 + size > W:
break
img_tmp = img[x * size // 2: x * size // 2 + size, y * size // 2: y * size // 2 + size, :]
cv2.imwrite(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)
idx += 1
img_tmp = img[x * size // 2: x * size // 2 + size, -size:, :]
cv2.imwrite(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)
idx += 1
for y in range(Y - 1):
if y * size // 2 + size > W:
break
img_tmp = img[-size:, y * size // 2: y * size // 2 + size, :]
cv2.imwrite(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)
idx += 1
img_tmp = img[-size:, -size:, :]
cv2.imwrite(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)
idx += 1
return rtn_list
def merge(path, test_size):
path_d = 'temp/input_decompose_' + test_size + '_pred/'
path_r = 'data/output/'
rm_and_make_dir(path_r)
size = int(test_size)
gk = gkern(size)
gk = 1 - gk
for file in sorted(os.listdir(path)):
img = cv2.imread(path + file)
H, W, _ = img.shape
X, Y = H // (size // 2) + 1, W // (size // 2) + 1
idx = 0
rtn = np.ones((H, W, 3), dtype=np.float32) * -1
for x in range(X-1):
if x * size // 2 + size > H:
break
for y in range(Y-1):
if y * size // 2 + size > W:
break
img_tmp = cv2.imread(path_d + file[:-4] + '_%03d.png' % idx)
weight_cur = copy.deepcopy(rtn[x * size // 2: x * size // 2 + size, y * size // 2: y * size // 2 + size, :])
h1, w1, _ = weight_cur.shape
gk_tmp = cv2.resize(gk, (w1, h1))
weight_cur[weight_cur != -1] = gk_tmp[weight_cur != -1]
weight_cur[weight_cur == -1] = 0
weight_tmp = copy.deepcopy(weight_cur)
weight_tmp = 1 - weight_tmp
rtn[x * size // 2: x * size // 2 + size, y * size // 2: y * size // 2 + size, :] = weight_cur * rtn[x * size // 2: x * size // 2 + size, y * size // 2: y * size // 2 + size, :] + weight_tmp * img_tmp
idx += 1
img_tmp = cv2.imread(path_d + file[:-4] + '_%03d.png' % idx)
weight_cur = copy.deepcopy(rtn[x * size // 2: x * size // 2 + size, -size:, :])
h1, w1, _ = weight_cur.shape
gk_tmp = cv2.resize(gk, (w1, h1))
weight_cur[weight_cur != -1] = gk_tmp[weight_cur != -1]
weight_cur[weight_cur == -1] = 0
weight_tmp = copy.deepcopy(weight_cur)
weight_tmp = 1 - weight_tmp
rtn[x * size // 2: x * size // 2 + size, -size:, :] = weight_cur * rtn[x * size // 2: x * size // 2 + size, -size:, :] + weight_tmp * img_tmp
idx += 1
for y in range(Y - 1):
if y * size // 2 + size > W:
break
img_tmp = cv2.imread(path_d + file[:-4] + '_%03d.png' % idx)
weight_cur = copy.deepcopy(rtn[-size:, y * size // 2: y * size // 2 + size, :])
h1, w1, _ = weight_cur.shape
gk_tmp = cv2.resize(gk, (w1, h1))
weight_cur[weight_cur != -1] = gk_tmp[weight_cur != -1]
weight_cur[weight_cur == -1] = 0
weight_tmp = copy.deepcopy(weight_cur)
weight_tmp = 1 - weight_tmp
rtn[-size:, y * size // 2: y * size // 2 + size, :] = weight_cur * rtn[-size:, y * size // 2: y * size // 2 + size, :] + weight_tmp * img_tmp
idx += 1
img_tmp = cv2.imread(path_d + file[:-4] + '_%03d.png' % idx)
weight_cur = copy.deepcopy(rtn[-size:, -size:, :])
h1, w1, _ = weight_cur.shape
gk_tmp = cv2.resize(gk, (w1, h1))
weight_cur[weight_cur != -1] = gk_tmp[weight_cur != -1]
weight_cur[weight_cur == -1] = 0
weight_tmp = copy.deepcopy(weight_cur)
weight_tmp = 1 - weight_tmp
rtn[-size:, -size:, :] = weight_cur * rtn[-size:, -size:, :] + weight_tmp * img_tmp
idx += 1
rtn[rtn < 127] = 0
rtn[rtn >= 127] = 255
cv2.imwrite(path_r + file[:-4] + '.png', np.uint8(rtn))
return path_r
def gkern(kernlen=7, nsig=3):
"""Returns a 2D Gaussian kernel."""
# x = np.linspace(-nsig, nsig, kernlen+1)
# kern1d = np.diff(st.norm.cdf(x))
# kern2d = np.outer(kern1d, kern1d)
# rtn = kern2d/kern2d.sum()
# rtn = np.concatenate([rtn[..., None], rtn[..., None], rtn[..., None]], axis=2)
rtn = [[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]
rtn = np.array(rtn, dtype=np.float32)
rtn = np.concatenate([rtn[..., None], rtn[..., None], rtn[..., None]], axis=2)
rtn = cv2.resize(rtn, (kernlen, kernlen))
return rtn
def rm_and_make_dir(path):
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
def metric(premask, groundtruth):
seg_inv, gt_inv = np.logical_not(premask), np.logical_not(groundtruth)
true_pos = float(np.logical_and(premask, groundtruth).sum()) # float for division
true_neg = np.logical_and(seg_inv, gt_inv).sum()
false_pos = np.logical_and(premask, gt_inv).sum()
false_neg = np.logical_and(seg_inv, groundtruth).sum()
f1 = 2 * true_pos / (2 * true_pos + false_pos + false_neg + 1e-6)
cross = np.logical_and(premask, groundtruth)
union = np.logical_or(premask, groundtruth)
iou = np.sum(cross) / (np.sum(union) + 1e-6)
if np.sum(cross) + np.sum(union) == 0:
iou = 1
return f1, iou
if __name__ == '__main__':
model = Model().cuda()
model.load()
model.eval()
forensics_test(model=model)
| [
"numpy.uint8",
"torch.utils.data.DataLoader",
"numpy.logical_not",
"torch.from_numpy",
"numpy.array",
"copy.deepcopy",
"os.path.exists",
"numpy.mean",
"os.listdir",
"models.scse.SCSEUnet",
"numpy.max",
"numpy.concatenate",
"numpy.min",
"torchvision.transforms.ToTensor",
"numpy.ones",
"... | [((2342, 2418), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'test_dataset', 'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(1)'}), '(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=1)\n', (2352, 2418), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((2849, 2906), 'os.path.exists', 'os.path.exists', (["('temp/input_decompose_' + test_size + '/')"], {}), "('temp/input_decompose_' + test_size + '/')\n", (2863, 2906), False, 'import os\n'), ((3082, 3105), 'os.path.exists', 'os.path.exists', (['path_gt'], {}), '(path_gt)\n', (3096, 3105), False, 'import os\n'), ((9551, 9582), 'numpy.array', 'np.array', (['rtn'], {'dtype': 'np.float32'}), '(rtn, dtype=np.float32)\n', (9559, 9582), True, 'import numpy as np\n'), ((9593, 9665), 'numpy.concatenate', 'np.concatenate', (['[rtn[..., None], rtn[..., None], rtn[..., None]]'], {'axis': '(2)'}), '([rtn[..., None], rtn[..., None], rtn[..., None]], axis=2)\n', (9607, 9665), True, 'import numpy as np\n'), ((9676, 9711), 'cv2.resize', 'cv2.resize', (['rtn', '(kernlen, kernlen)'], {}), '(rtn, (kernlen, kernlen))\n', (9686, 9711), False, 'import cv2\n'), ((9763, 9783), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (9777, 9783), False, 'import os\n'), ((9817, 9834), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (9828, 9834), False, 'import os\n'), ((10281, 10317), 'numpy.logical_and', 'np.logical_and', (['premask', 'groundtruth'], {}), '(premask, groundtruth)\n', (10295, 10317), True, 'import numpy as np\n'), ((10330, 10365), 'numpy.logical_or', 'np.logical_or', (['premask', 'groundtruth'], {}), '(premask, groundtruth)\n', (10343, 10365), True, 'import numpy as np\n'), ((1012, 1031), 'numpy.zeros', 'np.zeros', (['[H, W, 3]'], {}), '([H, W, 3])\n', (1020, 1031), True, 'import numpy as np\n'), ((1470, 1520), 'models.scse.SCSEUnet', 'SCSEUnet', ([], {'backbone_arch': '"""senet154"""', 'num_channels': '(3)'}), "(backbone_arch='senet154', num_channels=3)\n", (1478, 1520), False, 'from models.scse import SCSEUnet\n'), ((2916, 2972), 'shutil.rmtree', 'shutil.rmtree', (["('temp/input_decompose_' + test_size + '/')"], {}), "('temp/input_decompose_' + test_size + '/')\n", (2929, 2972), False, 'import shutil\n'), ((4030, 4051), 'os.listdir', 'os.listdir', (['test_path'], {}), '(test_path)\n', (4040, 4051), False, 'import os\n'), ((4265, 4293), 'cv2.imread', 'cv2.imread', (['(test_path + file)'], {}), '(test_path + file)\n', (4275, 4293), False, 'import cv2\n'), ((5659, 5721), 'cv2.imwrite', 'cv2.imwrite', (["(path_out + file[:-4] + '_%03d.png' % idx)", 'img_tmp'], {}), "(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)\n", (5670, 5721), False, 'import cv2\n'), ((5993, 6009), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (6003, 6009), False, 'import os\n'), ((6026, 6049), 'cv2.imread', 'cv2.imread', (['(path + file)'], {}), '(path + file)\n', (6036, 6049), False, 'import cv2\n'), ((8536, 8586), 'cv2.imread', 'cv2.imread', (["(path_d + file[:-4] + '_%03d.png' % idx)"], {}), "(path_d + file[:-4] + '_%03d.png' % idx)\n", (8546, 8586), False, 'import cv2\n'), ((8608, 8645), 'copy.deepcopy', 'copy.deepcopy', (['rtn[-size:, -size:, :]'], {}), '(rtn[-size:, -size:, :])\n', (8621, 8645), False, 'import copy\n'), ((8700, 8724), 'cv2.resize', 'cv2.resize', (['gk', '(w1, h1)'], {}), '(gk, (w1, h1))\n', (8710, 8724), False, 'import cv2\n'), ((8851, 8876), 'copy.deepcopy', 'copy.deepcopy', (['weight_cur'], {}), '(weight_cur)\n', (8864, 8876), False, 'import copy\n'), ((9793, 9812), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (9806, 9812), False, 'import shutil\n'), ((9893, 9916), 'numpy.logical_not', 'np.logical_not', (['premask'], {}), '(premask)\n', (9907, 9916), True, 'import numpy as np\n'), ((9918, 9945), 'numpy.logical_not', 'np.logical_not', (['groundtruth'], {}), '(groundtruth)\n', (9932, 9945), True, 'import numpy as np\n'), ((10376, 10389), 'numpy.sum', 'np.sum', (['cross'], {}), '(cross)\n', (10382, 10389), True, 'import numpy as np\n'), ((490, 516), 'os.listdir', 'os.listdir', (['self.test_path'], {}), '(self.test_path)\n', (500, 516), False, 'import os\n'), ((939, 957), 'cv2.imread', 'cv2.imread', (['fname1'], {}), '(fname1)\n', (949, 957), False, 'import cv2\n'), ((1931, 2003), 'torch.load', 'torch.load', (["(self.save_dir + path + '%s_weights.pth' % self.networks.name)"], {}), "(self.save_dir + path + '%s_weights.pth' % self.networks.name)\n", (1941, 2003), False, 'import torch\n'), ((2750, 2807), 'cv2.imwrite', 'cv2.imwrite', (["(path_out + filename[i][:-4] + '.png')", 'Mo_tmp'], {}), "(path_out + filename[i][:-4] + '.png', Mo_tmp)\n", (2761, 2807), False, 'import cv2\n'), ((3130, 3150), 'os.listdir', 'os.listdir', (['path_pre'], {}), '(path_pre)\n', (3140, 3150), False, 'import os\n'), ((3231, 3258), 'cv2.imread', 'cv2.imread', (['(path_pre + file)'], {}), '(path_pre + file)\n', (3241, 3258), False, 'import cv2\n'), ((3276, 3316), 'cv2.imread', 'cv2.imread', (["(path_gt + file[:-4] + '.png')"], {}), "(path_gt + file[:-4] + '.png')\n", (3286, 3316), False, 'import cv2\n'), ((5262, 5324), 'cv2.imwrite', 'cv2.imwrite', (["(path_out + file[:-4] + '_%03d.png' % idx)", 'img_tmp'], {}), "(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)\n", (5273, 5324), False, 'import cv2\n'), ((5526, 5588), 'cv2.imwrite', 'cv2.imwrite', (["(path_out + file[:-4] + '_%03d.png' % idx)", 'img_tmp'], {}), "(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)\n", (5537, 5588), False, 'import cv2\n'), ((6166, 6202), 'numpy.ones', 'np.ones', (['(H, W, 3)'], {'dtype': 'np.float32'}), '((H, W, 3), dtype=np.float32)\n', (6173, 6202), True, 'import numpy as np\n'), ((7184, 7234), 'cv2.imread', 'cv2.imread', (["(path_d + file[:-4] + '_%03d.png' % idx)"], {}), "(path_d + file[:-4] + '_%03d.png' % idx)\n", (7194, 7234), False, 'import cv2\n'), ((7260, 7325), 'copy.deepcopy', 'copy.deepcopy', (['rtn[x * size // 2:x * size // 2 + size, -size:, :]'], {}), '(rtn[x * size // 2:x * size // 2 + size, -size:, :])\n', (7273, 7325), False, 'import copy\n'), ((7389, 7413), 'cv2.resize', 'cv2.resize', (['gk', '(w1, h1)'], {}), '(gk, (w1, h1))\n', (7399, 7413), False, 'import cv2\n'), ((7552, 7577), 'copy.deepcopy', 'copy.deepcopy', (['weight_cur'], {}), '(weight_cur)\n', (7565, 7577), False, 'import copy\n'), ((7909, 7959), 'cv2.imread', 'cv2.imread', (["(path_d + file[:-4] + '_%03d.png' % idx)"], {}), "(path_d + file[:-4] + '_%03d.png' % idx)\n", (7919, 7959), False, 'import cv2\n'), ((7985, 8050), 'copy.deepcopy', 'copy.deepcopy', (['rtn[-size:, y * size // 2:y * size // 2 + size, :]'], {}), '(rtn[-size:, y * size // 2:y * size // 2 + size, :])\n', (7998, 8050), False, 'import copy\n'), ((8114, 8138), 'cv2.resize', 'cv2.resize', (['gk', '(w1, h1)'], {}), '(gk, (w1, h1))\n', (8124, 8138), False, 'import cv2\n'), ((8277, 8302), 'copy.deepcopy', 'copy.deepcopy', (['weight_cur'], {}), '(weight_cur)\n', (8290, 8302), False, 'import copy\n'), ((9128, 9141), 'numpy.uint8', 'np.uint8', (['rtn'], {}), '(rtn)\n', (9136, 9141), True, 'import numpy as np\n'), ((10048, 10079), 'numpy.logical_and', 'np.logical_and', (['seg_inv', 'gt_inv'], {}), '(seg_inv, gt_inv)\n', (10062, 10079), True, 'import numpy as np\n'), ((10102, 10133), 'numpy.logical_and', 'np.logical_and', (['premask', 'gt_inv'], {}), '(premask, gt_inv)\n', (10116, 10133), True, 'import numpy as np\n'), ((10156, 10192), 'numpy.logical_and', 'np.logical_and', (['seg_inv', 'groundtruth'], {}), '(seg_inv, groundtruth)\n', (10170, 10192), True, 'import numpy as np\n'), ((10393, 10406), 'numpy.sum', 'np.sum', (['union'], {}), '(union)\n', (10399, 10406), True, 'import numpy as np\n'), ((10422, 10435), 'numpy.sum', 'np.sum', (['cross'], {}), '(cross)\n', (10428, 10435), True, 'import numpy as np\n'), ((10438, 10451), 'numpy.sum', 'np.sum', (['union'], {}), '(union)\n', (10444, 10451), True, 'import numpy as np\n'), ((600, 621), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (619, 621), False, 'from torchvision import transforms\n'), ((635, 689), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (655, 689), False, 'from torchvision import transforms\n'), ((1774, 1804), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.networks'], {}), '(self.networks)\n', (1789, 1804), True, 'import torch.nn as nn\n'), ((3438, 3460), 'cv2.resize', 'cv2.resize', (['gt', '(W, H)'], {}), '(gt, (W, H))\n', (3448, 3460), False, 'import cv2\n'), ((3545, 3555), 'numpy.max', 'np.max', (['gt'], {}), '(gt)\n', (3551, 3555), True, 'import numpy as np\n'), ((3559, 3569), 'numpy.min', 'np.min', (['gt'], {}), '(gt)\n', (3565, 3569), True, 'import numpy as np\n'), ((5088, 5150), 'cv2.imwrite', 'cv2.imwrite', (["(path_out + file[:-4] + '_%03d.png' % idx)", 'img_tmp'], {}), "(path_out + file[:-4] + '_%03d.png' % idx, img_tmp)\n", (5099, 5150), False, 'import cv2\n'), ((6430, 6480), 'cv2.imread', 'cv2.imread', (["(path_d + file[:-4] + '_%03d.png' % idx)"], {}), "(path_d + file[:-4] + '_%03d.png' % idx)\n", (6440, 6480), False, 'import cv2\n'), ((6510, 6607), 'copy.deepcopy', 'copy.deepcopy', (['rtn[x * size // 2:x * size // 2 + size, y * size // 2:y * size // 2 + size, :]'], {}), '(rtn[x * size // 2:x * size // 2 + size, y * size // 2:y *\n size // 2 + size, :])\n', (6523, 6607), False, 'import copy\n'), ((6676, 6700), 'cv2.resize', 'cv2.resize', (['gk', '(w1, h1)'], {}), '(gk, (w1, h1))\n', (6686, 6700), False, 'import cv2\n'), ((6851, 6876), 'copy.deepcopy', 'copy.deepcopy', (['weight_cur'], {}), '(weight_cur)\n', (6864, 6876), False, 'import copy\n'), ((9967, 10003), 'numpy.logical_and', 'np.logical_and', (['premask', 'groundtruth'], {}), '(premask, groundtruth)\n', (9981, 10003), True, 'import numpy as np\n'), ((3917, 3929), 'numpy.mean', 'np.mean', (['auc'], {}), '(auc)\n', (3924, 3929), True, 'import numpy as np\n'), ((3931, 3942), 'numpy.mean', 'np.mean', (['f1'], {}), '(f1)\n', (3938, 3942), True, 'import numpy as np\n'), ((3944, 3956), 'numpy.mean', 'np.mean', (['iou'], {}), '(iou)\n', (3951, 3956), True, 'import numpy as np\n'), ((1275, 1296), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (1291, 1296), False, 'import torch\n')] |
import pandas as pd
import numpy as np
import os
import glob
from datetime import datetime, timedelta
import gzip
import time
import pkg_resources
import logging
from joblib import Parallel, delayed
from tempset.logger import Logger
class AggregateOutput(Logger):
def __init__(self,
gz_dir,
summary_file='./output_dir/summary.csv',
output_dir = './output_dir',
write_logfile=False
):
# start time for model run
self.start_time = time.time()
self.logfile = os.path.join(output_dir, f'tempset_logfile_{self.start_time}.log')
self.write_logfile = write_logfile
# initialize console handler for logger
self.console_handler()
if self.write_logfile:
self.file_handler()
logging.info('Starting batch processing of IDF files')
# inherit logger class attributes
super(AggregateOutput, self).__init__(self.write_logfile, self.logfile)
self.gz_dir = gz_dir
self.summary_file = summary_file
self.convert_J_to_kWh = 2.777e-7
#execute aggregation
self.aggregate_data(gz_dir=self.gz_dir)
def parse_filelname(self, filename):
"""
method to parse string name to get simulation id and intiial str name
:param filename: str -> filename ending with .gz
:return id: int -> simulation id corresponding to the .gz file
:return file_init: str -> str corresponding to the initial file
"""
file_init = filename.split('.')[0]
id = file_init.split('_')[-1] # the last digit is the number
return id, file_init
def read_gz_files(self, filename):
"""
method to read gz file to extract DF
:param filename: file ending with a gz
:return df: DataFrame -> corresponding to the simulation outputs
"""
with gzip.open(filename) as f:
'Read each file'
df = pd.read_csv(f)
return df
def remove_design_day(self, df):
"""
method to remove design day from simulation output
:param df: pd.DataFrame -> df containing output simulations including design day
:return df_o: pd.DataFrame -> df containing output simulations wiihout design day
"""
start_date = ' 01/01'
date_stamps = df['Date/Time']
idx_all = np.where(date_stamps.str.startswith(start_date))[
0] # check where df starts with first of Jan, everything before is DD
# print('idx all: ', idx_all)
first_idx = idx_all[0]
df_o = (df.iloc[first_idx:]).reset_index(drop=True)
return df_o
def create_df_daily(self, df_mtr, df_out, timeRes=24):
"""
method to aggregate results at a daily timescale
:param df_mtr: pd.DataFrame -> df containing outputs from mtr file in e+ simulations
:param df_out: pd.DatFrame -> df containing outputs from output file in e+ simulations
:param timeRes: int -> time resolution over which data is to be aggregated
:return df_elec_sum: pd.Series -> outputs aggregating the total electricity consumption
:return df_elec_peak: pd.Series -> outputs to find the maximum hourly consumption
:return df_tc_mean: pd.Series -> outputs containing aggregated mean PPD in core zone
"""
df_elec = df_mtr['Electricity:Facility [J](Hourly)'] * self.convert_J_to_kWh
df_elec_mean = df_elec.rolling(window=timeRes).sum()
df_elec_peak = df_elec.rolling(window=timeRes).max()
df_elec_mean = df_elec_mean.dropna().reset_index(drop=True) # drop Nan values
df_elec_sum = df_elec_mean[::timeRes].reset_index(drop=True)
df_elec_peak = df_elec_peak.dropna().reset_index(drop=True)
df_elec_peak = df_elec_peak[::timeRes].reset_index(drop=True)
'Thermal Comfort Mean'
'Add more zones if necessary'
hr = df_out.index.values % timeRes + 1
df_out['hr'] = hr
# print('hr: ', hr)
df_tc = df_out['CORE_ZN:Zone Thermal Comfort Fanger Model PPD [%](Hourly)'] # mean across different zonesi
df_tc[((hr <= 7) | (hr > 18))] = 0
df_tc_mean = df_tc.rolling(window=timeRes).sum() / 11
df_tc_mean = df_tc_mean.dropna().reset_index(drop=True)
df_tc_mean = df_tc_mean[::timeRes].reset_index(drop=True)
return df_elec_sum, df_elec_peak, df_tc_mean
'Global functions for plotting'
def generate_date_axis(self, day_array=np.arange(0, 365), day_start=0, year=2017):
"""
method to generate a date exis given integer array
:param day_start: np.array -> containing the number of days for which the date needs to be generated
:param year: int -> year (2017 in e+ simulations)
:return df_time: pd.Series: datetime corresponding to day_start + day_array
"""
dt = datetime(year, 1, 1)
dtDelta = timedelta(days=day_start)
init_time = dt + dtDelta
out_time = [init_time + timedelta(days=int(i)) for i in day_array]
df_time = pd.to_datetime(out_time).to_series()
df_time.reset_index(drop=True, inplace=True)
return df_time
def aggregate_data(self, gz_dir):
"""
method to compile all functions to generate summary file
:param gz_dir:
:return:
"""
# Get the data axis'
days = self.generate_date_axis()
self.list_of_files = sorted(glob.glob('*.csv.gz'))
main_dir = os.getcwd()
os.chdir(gz_dir)
# initialize empty summary file
summary = []
for filename in sorted(glob.glob('*.csv.gz')):
num_period = filename.count('.')
file_init = filename.split('.')[0]
sim_number = file_init.split('_')[-1]
if num_period == 2: # only two periods 2 in strings, 2 in decimals or if the string is the reference file
id, file_str = self.parse_filelname(filename=filename)
df_out = self.read_gz_files(filename=filename)
meter_file = file_str + '.meter.csv.gz'
df_meter = self.read_gz_files(filename=meter_file)
'Remove design days and append to llist'
df, df_meter = self.remove_design_day(df_out), self.remove_design_day(df_meter)
'Get the daily dataframes'
df_e, df_p, df_tc = self.create_df_daily(df_mtr=df_meter, df_out=df)
data = {'date': days, 'daily_elec_total': df_e, 'daily_elec_peak': df_p, 'daily_tc_mean': df_tc}
df = pd.DataFrame(data)
df['sim_id'] = sim_number
summary.append(df)
logging.info(f"Completed read for filename: {filename}")
df_summary = pd.concat(summary)
df_summary.to_csv(self.summary_file)
'Get back to the main working directory'
os.chdir(main_dir)
return None
def aggregate_data(gz_dir,
summary_file):
"""
wrapper to call AggregateOutput class to generate summary file
:param gz_dir: str -> full path hosting the .gz directory
:param summary_file: strt -> full path to .csv file where the output summaries are to be written
:return:
"""
AggregateOutput(gz_dir=gz_dir, summary_file=summary_file)
return None
if __name__ == "__main__":
gz_dir = '/projects/im3/bend/aowabin_test/tbd/output'
summary_file = '/projects/im3/bend/aowabin_test/tbd/dump/dump.csv'
aggregate_data(gz_dir=gz_dir, summary_file=summary_file)
| [
"datetime.datetime",
"pandas.read_csv",
"gzip.open",
"pandas.to_datetime",
"os.path.join",
"logging.info",
"os.getcwd",
"os.chdir",
"pandas.concat",
"glob.glob",
"pandas.DataFrame",
"datetime.timedelta",
"time.time",
"numpy.arange"
] | [((563, 574), 'time.time', 'time.time', ([], {}), '()\n', (572, 574), False, 'import time\n'), ((601, 667), 'os.path.join', 'os.path.join', (['output_dir', 'f"""tempset_logfile_{self.start_time}.log"""'], {}), "(output_dir, f'tempset_logfile_{self.start_time}.log')\n", (613, 667), False, 'import os\n'), ((873, 927), 'logging.info', 'logging.info', (['"""Starting batch processing of IDF files"""'], {}), "('Starting batch processing of IDF files')\n", (885, 927), False, 'import logging\n'), ((4695, 4712), 'numpy.arange', 'np.arange', (['(0)', '(365)'], {}), '(0, 365)\n', (4704, 4712), True, 'import numpy as np\n'), ((5093, 5113), 'datetime.datetime', 'datetime', (['year', '(1)', '(1)'], {}), '(year, 1, 1)\n', (5101, 5113), False, 'from datetime import datetime, timedelta\n'), ((5133, 5158), 'datetime.timedelta', 'timedelta', ([], {'days': 'day_start'}), '(days=day_start)\n', (5142, 5158), False, 'from datetime import datetime, timedelta\n'), ((5738, 5749), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5747, 5749), False, 'import os\n'), ((5759, 5775), 'os.chdir', 'os.chdir', (['gz_dir'], {}), '(gz_dir)\n', (5767, 5775), False, 'import os\n'), ((7067, 7085), 'pandas.concat', 'pd.concat', (['summary'], {}), '(summary)\n', (7076, 7085), True, 'import pandas as pd\n'), ((7193, 7211), 'os.chdir', 'os.chdir', (['main_dir'], {}), '(main_dir)\n', (7201, 7211), False, 'import os\n'), ((2006, 2025), 'gzip.open', 'gzip.open', (['filename'], {}), '(filename)\n', (2015, 2025), False, 'import gzip\n'), ((2080, 2094), 'pandas.read_csv', 'pd.read_csv', (['f'], {}), '(f)\n', (2091, 2094), True, 'import pandas as pd\n'), ((5695, 5716), 'glob.glob', 'glob.glob', (['"""*.csv.gz"""'], {}), "('*.csv.gz')\n", (5704, 5716), False, 'import glob\n'), ((5877, 5898), 'glob.glob', 'glob.glob', (['"""*.csv.gz"""'], {}), "('*.csv.gz')\n", (5886, 5898), False, 'import glob\n'), ((5290, 5314), 'pandas.to_datetime', 'pd.to_datetime', (['out_time'], {}), '(out_time)\n', (5304, 5314), True, 'import pandas as pd\n'), ((6866, 6884), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (6878, 6884), True, 'import pandas as pd\n'), ((6985, 7042), 'logging.info', 'logging.info', (['f"""Completed read for filename: {filename}"""'], {}), "(f'Completed read for filename: {filename}')\n", (6997, 7042), False, 'import logging\n')] |
#! /usr/bin/env python
"""
This is a small self-contained application that demonstrates usage of networks deployed from Barista
in other applications. If net definition and weight's files obtained by training the caffe mnist example
are supplied via command line parameters, the user can draw digits [0-9] in the window, use the net
to classify the result and print the result to stdout.
- Drawing works by pressing the left mouse button and moving the mouse
- The "Return"-Button grabs the image and starts the classification
- The "Backspace"-Button clears the image.
"""
#
#
# Python package dependencies:
# pygame
# caffe
# numpy
import pygame
import caffe
import numpy as np
import argparse
# Argument parsing
parser = argparse.ArgumentParser(description='Interactively classify handwritten digits using neural nets.', epilog=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-m', '--model', help='Model (.prototxt) file', type=str, required=True)
parser.add_argument('-w', '--weights', help='Weights (.caffemodel) file', type=str, required=True)
args = parser.parse_args()
#######################################################
# Setup caffe for classification
#######################################################
#load the model
net = caffe.Net(args.model, args.weights, caffe.TEST)
# load input and configure preprocessing
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
transformer.set_raw_scale('data', 1.0)
# Change the batch size to a single image
net.blobs['data'].reshape(1,1,28,28)
#######################################################
# Proprecessing helper functions
#######################################################
# Find the required offset (i.e. difference between center of weight and center of the image)
def find_offset(grid):
x_acc = 0;
y_acc = 0;
h = grid.shape[0]
w = grid.shape[1]
num_points = 0;
for y in np.arange(h):
for x in np.arange(w):
val = (grid[y,x] > 0)
x_acc += (x-w/2.0) * val
y_acc += (y-h/2.0) * val
if val:
num_points += 1
if num_points == 0:
return (0,0)
x_acc /= num_points
y_acc /= num_points
return (y_acc, x_acc)
# Shift and resample values in grid and thus centering the center of weight in the center of the image
def shift(grid):
offset = find_offset(grid)
h = grid.shape[0]
w = grid.shape[1]
image = np.zeros((h, w, 1))
for y in np.arange(h):
for x in np.arange(w):
x_n = int(np.round(x+offset[1]))
y_n = int(np.round(y+offset[0]))
if x_n < 0 or x_n >= w:
val = 0
elif y_n < 0 or y_n >= h:
val = 0
else:
val = grid[y_n,x_n]
image[y,x] = val
return image
# Classify a given image and output the index of the class with the highest probability according to the net and caffe
def classify(pixels):
image = np.zeros((pixels.shape[0], pixels.shape[1], 1))
image[:,:,0] = pixels[:,:]
image = np.transpose(image, (1,0,2))
image = shift(image)
data = np.asarray([transformer.preprocess('data', image)])
out = net.forward_all(data = data)
prob = out['probabilities']
cls = prob.argmax()
return cls
#######################################################
# Pygame application stuff
#######################################################
# Create screen of specified size
screen_size = (112,112)
screen = pygame.display.set_mode(screen_size)
# Global variables/constants used for drawing
currently_drawing = False
last_pos = (0, 0)
draw_color = (255, 255, 255)
clear_color = (0, 0, 0)
brush_radius = 3
# draw a line of circles from start to finish
def roundline(srf, color, start, end, radius):
dx = end[0]-start[0]
dy = end[1]-start[1]
distance = max(abs(dx), abs(dy))
for i in range(distance):
x = int( start[0]+float(i)/distance*dx)
y = int( start[1]+float(i)/distance*dy)
pygame.draw.circle(srf, color, (x, y), radius)
try:
while True:
e = pygame.event.wait()
if e.type == pygame.QUIT:
raise StopIteration
if e.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.circle(screen, draw_color, e.pos, brush_radius)
currently_drawing = True
if e.type == pygame.MOUSEBUTTONUP:
currently_drawing = False
if e.type == pygame.MOUSEMOTION:
if currently_drawing:
pygame.draw.circle(screen, draw_color, e.pos, brush_radius)
roundline(screen, draw_color, e.pos, last_pos, brush_radius)
last_pos = e.pos
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_RETURN:
array = pygame.PixelArray(screen)
cls = classify(array)
print("The net says says: {}".format(cls))
if e.key == pygame.K_BACKSPACE:
screen.fill(clear_color)
pygame.display.flip()
except StopIteration:
pass
pygame.quit()
| [
"pygame.draw.circle",
"pygame.quit",
"argparse.ArgumentParser",
"caffe.io.Transformer",
"pygame.display.set_mode",
"pygame.display.flip",
"numpy.round",
"pygame.event.wait",
"numpy.zeros",
"pygame.PixelArray",
"caffe.Net",
"numpy.transpose",
"numpy.arange"
] | [((733, 905), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Interactively classify handwritten digits using neural nets."""', 'epilog': '__doc__', 'formatter_class': 'argparse.RawTextHelpFormatter'}), "(description=\n 'Interactively classify handwritten digits using neural nets.', epilog=\n __doc__, formatter_class=argparse.RawTextHelpFormatter)\n", (756, 905), False, 'import argparse\n'), ((1285, 1332), 'caffe.Net', 'caffe.Net', (['args.model', 'args.weights', 'caffe.TEST'], {}), '(args.model, args.weights, caffe.TEST)\n', (1294, 1332), False, 'import caffe\n'), ((1389, 1449), 'caffe.io.Transformer', 'caffe.io.Transformer', (["{'data': net.blobs['data'].data.shape}"], {}), "({'data': net.blobs['data'].data.shape})\n", (1409, 1449), False, 'import caffe\n'), ((3589, 3625), 'pygame.display.set_mode', 'pygame.display.set_mode', (['screen_size'], {}), '(screen_size)\n', (3612, 3625), False, 'import pygame\n'), ((5135, 5148), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (5146, 5148), False, 'import pygame\n'), ((1983, 1995), 'numpy.arange', 'np.arange', (['h'], {}), '(h)\n', (1992, 1995), True, 'import numpy as np\n'), ((2516, 2535), 'numpy.zeros', 'np.zeros', (['(h, w, 1)'], {}), '((h, w, 1))\n', (2524, 2535), True, 'import numpy as np\n'), ((2549, 2561), 'numpy.arange', 'np.arange', (['h'], {}), '(h)\n', (2558, 2561), True, 'import numpy as np\n'), ((3060, 3107), 'numpy.zeros', 'np.zeros', (['(pixels.shape[0], pixels.shape[1], 1)'], {}), '((pixels.shape[0], pixels.shape[1], 1))\n', (3068, 3107), True, 'import numpy as np\n'), ((3151, 3181), 'numpy.transpose', 'np.transpose', (['image', '(1, 0, 2)'], {}), '(image, (1, 0, 2))\n', (3163, 3181), True, 'import numpy as np\n'), ((2014, 2026), 'numpy.arange', 'np.arange', (['w'], {}), '(w)\n', (2023, 2026), True, 'import numpy as np\n'), ((2580, 2592), 'numpy.arange', 'np.arange', (['w'], {}), '(w)\n', (2589, 2592), True, 'import numpy as np\n'), ((4102, 4148), 'pygame.draw.circle', 'pygame.draw.circle', (['srf', 'color', '(x, y)', 'radius'], {}), '(srf, color, (x, y), radius)\n', (4120, 4148), False, 'import pygame\n'), ((4183, 4202), 'pygame.event.wait', 'pygame.event.wait', ([], {}), '()\n', (4200, 4202), False, 'import pygame\n'), ((5080, 5101), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (5099, 5101), False, 'import pygame\n'), ((4326, 4385), 'pygame.draw.circle', 'pygame.draw.circle', (['screen', 'draw_color', 'e.pos', 'brush_radius'], {}), '(screen, draw_color, e.pos, brush_radius)\n', (4344, 4385), False, 'import pygame\n'), ((2616, 2639), 'numpy.round', 'np.round', (['(x + offset[1])'], {}), '(x + offset[1])\n', (2624, 2639), True, 'import numpy as np\n'), ((2661, 2684), 'numpy.round', 'np.round', (['(y + offset[0])'], {}), '(y + offset[0])\n', (2669, 2684), True, 'import numpy as np\n'), ((4595, 4654), 'pygame.draw.circle', 'pygame.draw.circle', (['screen', 'draw_color', 'e.pos', 'brush_radius'], {}), '(screen, draw_color, e.pos, brush_radius)\n', (4613, 4654), False, 'import pygame\n'), ((4864, 4889), 'pygame.PixelArray', 'pygame.PixelArray', (['screen'], {}), '(screen)\n', (4881, 4889), False, 'import pygame\n')] |
import logging
import numpy as np
from .spaic2 import spaic2_betaspect as bs
from .spaic2 import spaic2_pot2density as p2d
logging.basicConfig(level=logging.INFO)
EPS = 1.0**-6
class Spaic2Solver:
logger = logging.getLogger(name='Spaic2Solver')
default_woodsaxon_params = np.array([
0.84, 0.39, 0.78, 0.80, 0.91, 0.20, 0.34, 0.77, 0.28, 0.55
])
default_quantum_numbers = np.array([
[2, 1]
], dtype=np.int32)
default_cluster_radius = np.float64(11.)# rclus
default_cluster_steepness = np.float64(0.9) # drclus
def __init__(self):
self.logger.debug('__init__')
# Define flags prior to calling self.init()
self.cluster_steepness_flag = False
self.cluster_radius_flag = False
self.woodsaxon_params_flag = False
self.init()
self.spectra_computed = False
def init(self):
"""Initialize the default potential and qms
@property'es initial point to undefined states, thus
necessitating an alternative initialization.
"""
self.cluster_radius = self.default_cluster_radius # setter
self.cluster_steepness = self.default_cluster_steepness # setter
self.woodsaxon_params = self.default_woodsaxon_params # setter
qns = self.default_quantum_numbers
# Here p2d is accessed, not bs.
prs = np.array(p2d.pararho, dtype=np.float64)
is_valid = len(qns.shape) == 2 and qns.shape[1] == 2
assert is_valid, "QNs example: {} (received {})".format(self.default_quantum_numbers, qns)
bs.set_density_and_qns(prs, qns)
def plot(self, **kwargs):
if not self.spectra_computed:
self.compute_spectra()
show = kwargs.get('show', True)
fs = kwargs.get('fontsize', 14)
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
ax = plt.subplot(311)
plt.plot(p2d.rr, self.woodsaxon_potential, label='Wood-Saxon Pot.')
plt.plot(bs.rr, self.density_potential, label='e- Density Pot.')
plt.legend(loc=0)
plt.grid()
ax = plt.subplot(312)
for q, qn in enumerate(self.quantum_numbers):
plt.plot(self.frequencies, self.spectra[:, q], label=str(qn))
plt.grid()
plt.subplot(313, sharex=ax)
for q, qn in enumerate(self.quantum_numbers):
plt.plot(self.frequencies, self.beta_spectra[:, q], label=str(qn))
plt.grid()
plt.xlim(self.frequencies.min(), self.frequencies.max())
if show: plt.show()
# Common interface
def __del__(self):
self.logger.debug('__del__')
p2d.free_all_memory()
bs.free_all_memory()
@property
def cluster_radius(self):
"""Return cluster radius used for generating the charge distribution.
"""
return p2d.rclus
@cluster_radius.setter
def cluster_radius(self, params):
"""Set the cluster radius used for generating the charge distribution.
"""
params = np.float64(params)
assert isinstance(params,np.float64), "received {}".format(params)
# set variable in p2d
#p2d.rclus = params
p2d.rclus = np.array(params, dtype=np.float64)
self.cluster_radius_flag = True
# Determine the density parameters and transmit them to betaSpect
if self.cluster_steepness_flag and self.woodsaxon_params_flag:
# "If condition" only important for __init__ where cluster_steepness is not set.
p2d.compute_density()
self.update_density_params(p2d.pararho)
@property
def cluster_steepness(self):
"""Return cluster steepness used for generating the charge distribution.
"""
return p2d.drclus
@cluster_steepness.setter
def cluster_steepness(self, params):
"""Set the cluster steepness used for generating the charge distribution.
"""
params = np.float64(params)
assert isinstance(params,np.float64), "received {}".format(params)
# set variable in p2d
p2d.drclus = params
self.cluster_steepness_flag = True
# Determine the density parameters and transmit them to betaSpect
if self.cluster_radius_flag and self.woodsaxon_params_flag:
p2d.compute_density()
self.update_density_params(p2d.pararho)
@property
def density_params(self):
"""Return c coefficients describing the charge distribtion.
"""
return bs.para
@density_params.setter
def density_params(self, params):
params = np.asarray(params, dtype=np.float64)
assert len(params.shape) == 1, "received {}".format(params)
self.update_density_params(params)
@property
def woodsaxon_params(self):
"""Return B coefficients defining the bumped Wood-Saxon potential.
"""
return 0.5 * (p2d.parapot + 1.0)
@woodsaxon_params.setter
def woodsaxon_params(self, params):
"""Set B coefficients defining the bumped Wood-Saxon potential.
"""
self.logger.debug('woodsaxon_params.setter')
params = np.asarray(params, dtype=np.float64)
assert len(params.shape) == 1, "received {}".format(params)
assert all(params >= 0.0) and all(params <= 1.0), "received {}".format(params)
p2d.set_woodsaxon_params(params)
self.woodsaxon_params_flag = True
# Compute new p2d.pararho (!= density_params which is bs.para)
if self.cluster_radius_flag and self.cluster_steepness_flag:
# "If condition" only important for __init__ where cluster
# parameters might not yet be set.
self.logger.debug('compute_density')
# p2d.diagnostics()
p2d.compute_density()
# Transmit pararho from pot2density to betaSpect
self.update_density_params(p2d.pararho)
@property
def woodsaxon_potential(self):
"""Return the bumped Wood-Saxon potential.
"""
return p2d.woodsaxon_potential
# Interface to spaic2_betaspect
@property
def beta_spectra(self):
assert self.spectra_computed, "Explicitely call compute_spectra first."
return bs.beta
@property
def spectra(self):
assert self.spectra_computed, "Explicitely call compute_spectra first."
return bs.spec
@property
def frequencies(self):
return bs.freq
@property
def density_potential(self):
assert self.spectra_computed, "Explicitely call compute_spectra first."
return bs.pot
@property
def radius(self):
assert self.spectra_computed, "Explicitely call compute_spectra first."
return bs.rr
@property
def bpsi(self):
assert self.spectra_computed, "Explicitely call compute_spectra first."
return bs.bpsi+bs.eb
@property
def quantum_numbers(self):
return bs.quantum_numbers
@quantum_numbers.setter
def quantum_numbers(self, qns):
qns = np.array(qns, dtype=np.int32)
prs = np.array(self.density_params, dtype=np.float64)
is_valid = len(qns.shape) == 2 and qns.shape[1] == 2
assert is_valid, "QNs example: {} (received {})".format(self.default_quantum_numbers, qns)
bs.set_density_and_qns(prs, qns)
def update_density_params(self, dparams):
self.logger.debug('update_density_params')
prs = np.array(dparams)
self.spectra_computed = False
# Only important for __init__ where quantum_numbers are None.
if self.quantum_numbers is not None:
qns = np.array(self.quantum_numbers)
bs.set_density_and_qns(prs, qns)
def compute_spectra(self):
bs.compute_beta()
self.spectra_computed = True
| [
"logging.basicConfig",
"logging.getLogger",
"matplotlib.pyplot.grid",
"numpy.float64",
"matplotlib.pyplot.plot",
"numpy.asarray",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((125, 164), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (144, 164), False, 'import logging\n'), ((215, 253), 'logging.getLogger', 'logging.getLogger', ([], {'name': '"""Spaic2Solver"""'}), "(name='Spaic2Solver')\n", (232, 253), False, 'import logging\n'), ((286, 354), 'numpy.array', 'np.array', (['[0.84, 0.39, 0.78, 0.8, 0.91, 0.2, 0.34, 0.77, 0.28, 0.55]'], {}), '([0.84, 0.39, 0.78, 0.8, 0.91, 0.2, 0.34, 0.77, 0.28, 0.55])\n', (294, 354), True, 'import numpy as np\n'), ((406, 440), 'numpy.array', 'np.array', (['[[2, 1]]'], {'dtype': 'np.int32'}), '([[2, 1]], dtype=np.int32)\n', (414, 440), True, 'import numpy as np\n'), ((493, 509), 'numpy.float64', 'np.float64', (['(11.0)'], {}), '(11.0)\n', (503, 509), True, 'import numpy as np\n'), ((548, 563), 'numpy.float64', 'np.float64', (['(0.9)'], {}), '(0.9)\n', (558, 563), True, 'import numpy as np\n'), ((1393, 1432), 'numpy.array', 'np.array', (['p2d.pararho'], {'dtype': 'np.float64'}), '(p2d.pararho, dtype=np.float64)\n', (1401, 1432), True, 'import numpy as np\n'), ((1869, 1897), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (1879, 1897), True, 'import matplotlib.pyplot as plt\n'), ((1911, 1927), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (1922, 1927), True, 'import matplotlib.pyplot as plt\n'), ((1936, 2003), 'matplotlib.pyplot.plot', 'plt.plot', (['p2d.rr', 'self.woodsaxon_potential'], {'label': '"""Wood-Saxon Pot."""'}), "(p2d.rr, self.woodsaxon_potential, label='Wood-Saxon Pot.')\n", (1944, 2003), True, 'import matplotlib.pyplot as plt\n'), ((2012, 2076), 'matplotlib.pyplot.plot', 'plt.plot', (['bs.rr', 'self.density_potential'], {'label': '"""e- Density Pot."""'}), "(bs.rr, self.density_potential, label='e- Density Pot.')\n", (2020, 2076), True, 'import matplotlib.pyplot as plt\n'), ((2085, 2102), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(0)'}), '(loc=0)\n', (2095, 2102), True, 'import matplotlib.pyplot as plt\n'), ((2111, 2121), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2119, 2121), True, 'import matplotlib.pyplot as plt\n'), ((2135, 2151), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (2146, 2151), True, 'import matplotlib.pyplot as plt\n'), ((2288, 2298), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2296, 2298), True, 'import matplotlib.pyplot as plt\n'), ((2307, 2334), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {'sharex': 'ax'}), '(313, sharex=ax)\n', (2318, 2334), True, 'import matplotlib.pyplot as plt\n'), ((2476, 2486), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2484, 2486), True, 'import matplotlib.pyplot as plt\n'), ((3058, 3076), 'numpy.float64', 'np.float64', (['params'], {}), '(params)\n', (3068, 3076), True, 'import numpy as np\n'), ((3230, 3264), 'numpy.array', 'np.array', (['params'], {'dtype': 'np.float64'}), '(params, dtype=np.float64)\n', (3238, 3264), True, 'import numpy as np\n'), ((3987, 4005), 'numpy.float64', 'np.float64', (['params'], {}), '(params)\n', (3997, 4005), True, 'import numpy as np\n'), ((4645, 4681), 'numpy.asarray', 'np.asarray', (['params'], {'dtype': 'np.float64'}), '(params, dtype=np.float64)\n', (4655, 4681), True, 'import numpy as np\n'), ((5197, 5233), 'numpy.asarray', 'np.asarray', (['params'], {'dtype': 'np.float64'}), '(params, dtype=np.float64)\n', (5207, 5233), True, 'import numpy as np\n'), ((7098, 7127), 'numpy.array', 'np.array', (['qns'], {'dtype': 'np.int32'}), '(qns, dtype=np.int32)\n', (7106, 7127), True, 'import numpy as np\n'), ((7142, 7189), 'numpy.array', 'np.array', (['self.density_params'], {'dtype': 'np.float64'}), '(self.density_params, dtype=np.float64)\n', (7150, 7189), True, 'import numpy as np\n'), ((7503, 7520), 'numpy.array', 'np.array', (['dparams'], {}), '(dparams)\n', (7511, 7520), True, 'import numpy as np\n'), ((2570, 2580), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2578, 2580), True, 'import matplotlib.pyplot as plt\n'), ((7692, 7722), 'numpy.array', 'np.array', (['self.quantum_numbers'], {}), '(self.quantum_numbers)\n', (7700, 7722), True, 'import numpy as np\n')] |
import numpy as np
from scipy import stats
def create_data(N = 10):
a = np.random.randn(N) + 2 #mean = 2, var = 1
b = np.random.randn(N) #mean = 0, var = 1
return a, b
def variance(a,b):
var_a = a.var(ddof = 1) #Numpy uses the population (N) and not sample (N-1), thus pass ddof = 1
var_b = b.var(ddof = 1)
return var_a, var_b
def pooledstd(var_a, var_b):
"""
Calculates the pooled standard deviation (Sp)
"""
sp = np.sqrt((var_a + var_b) / 2)
return sp
def t_stat(a, b, sp, N = 10):
"""
Calculates the t-statistic and the degrees of freedom (df)
"""
t = (a.mean() - b.mean())/(sp * np.sqrt(2/N))
df = 2*N - 2
return t, df
def p_value():
N = 10
a, b = create_data(N = N)
var_a, var_b = variance(a, b)
sp = pooledstd(var_a, var_b)
t, df = t_stat(a, b, sp, N = N)
p = 1 - stats.t.cdf(t, df)
p = p*2 #Since it is a 2-tailed test
print('t-stat: ', t,'P: ', p)
t2, p2 = stats.ttest_ind(a, b)
print('t-stat scipy: ', t2,'P scipy: ', p2)
if __name__ == "__main__":
p_value()
| [
"scipy.stats.t.cdf",
"numpy.sqrt",
"numpy.random.randn",
"scipy.stats.ttest_ind"
] | [((127, 145), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (142, 145), True, 'import numpy as np\n'), ((461, 489), 'numpy.sqrt', 'np.sqrt', (['((var_a + var_b) / 2)'], {}), '((var_a + var_b) / 2)\n', (468, 489), True, 'import numpy as np\n'), ((984, 1005), 'scipy.stats.ttest_ind', 'stats.ttest_ind', (['a', 'b'], {}), '(a, b)\n', (999, 1005), False, 'from scipy import stats\n'), ((77, 95), 'numpy.random.randn', 'np.random.randn', (['N'], {}), '(N)\n', (92, 95), True, 'import numpy as np\n'), ((877, 895), 'scipy.stats.t.cdf', 'stats.t.cdf', (['t', 'df'], {}), '(t, df)\n', (888, 895), False, 'from scipy import stats\n'), ((655, 669), 'numpy.sqrt', 'np.sqrt', (['(2 / N)'], {}), '(2 / N)\n', (662, 669), True, 'import numpy as np\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import collections
import csv
import json
import sys
import numpy as np
EXISTING = 'existing'
OCCURRENCE = 'occurrence'
EXISTING_PERCENTAGE = 'existing_percentage'
NOTEXISTING_PERCENTAGE = 'notexisting_percentage'
NOTEXISTING = 'notexisting'
UNIQUE = 'unique'
AVG = 'avg'
VAR = 'var'
STD = 'std'
MAX = 'max'
MIN = 'min'
MAX_VALUE = 'max_value'
MIN_VALUE = 'min_value'
MAX_LEN = 'max_len'
MIN_LEN = 'min_len'
FIELD_NAME = 'field_name'
def get_header():
return [EXISTING,
OCCURRENCE,
EXISTING_PERCENTAGE,
NOTEXISTING_PERCENTAGE,
NOTEXISTING,
UNIQUE,
AVG,
VAR,
STD,
MAX,
MIN,
MAX_VALUE,
MIN_VALUE,
MAX_LEN,
MIN_LEN,
FIELD_NAME]
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def traverse(obj, path):
if isinstance(obj, dict):
for k, v in obj.items():
for c, w in traverse(v, path + "#!?#!?#!?" + str(k)):
yield c, w
elif isinstance(obj, list):
for elem in obj:
for c, w in traverse(elem, path + "#!?#!?#!?"):
yield c, w
if len(path) > 0 and not isinstance(obj, list):
yield path, obj
def getname(string):
array = string.rsplit("#!?#!?#!?")
rstr = array[0]
for elem in array[1:-1]:
rstr = rstr + elem + " > "
return rstr + array[-1]
def shortname(string):
if string[-2:] == "> ":
string = string[:-2]
return string.replace("> >", ">").strip()
def str_max_map_len(array):
return str(max(map(len, array), default=0))
def str_min_map_len(array):
return str(min(map(len, array), default=0))
def getpercent(value, hitcount):
return (value) / float(hitcount) * 100
def getnotexisting(value, hitcount):
notexisting = hitcount - value
if notexisting < 0:
return 0
else:
return notexisting
def generate_field_statistics(statsmap, valstats, percentage_stats, hitcount, len_val):
field_statistics = []
for key, value in statsmap:
unique = None
if key in valstats:
unique = len(valstats[key])
data = []
for obj in valstats[key]:
data.append(valstats[key][obj])
if len(data) > 0:
npdata = np.asarray(data)
else:
npdata = np.asarray([0])
field_statistic = {
EXISTING: "{0:.0f}".format(percentage_stats[key]),
OCCURRENCE: value,
EXISTING_PERCENTAGE: "{0:.2f}".format(getpercent(percentage_stats[key], hitcount)),
NOTEXISTING_PERCENTAGE: "{0:.2f}".format(
getpercent(getnotexisting(percentage_stats[key], hitcount), hitcount)),
NOTEXISTING: getnotexisting(value, hitcount),
UNIQUE: unique,
AVG: "{0:.2f}".format(np.mean(npdata)),
VAR: "{0:.2f}".format(np.var(npdata)),
STD: "{0:.2f}".format(np.std(npdata)),
MAX: max(data, default=0),
MIN: min(data, default=0),
MAX_VALUE: str(max(valstats[key], key=lambda x: valstats[key][x], default=0)).strip()[0:int(len_val) - 2],
MIN_VALUE: str(min(valstats[key], key=lambda x: valstats[key][x], default=0)).strip()[0:int(len_val) - 2],
MAX_LEN: str_max_map_len(valstats[key]),
MIN_LEN: str_max_map_len(valstats[key]),
FIELD_NAME: key}
field_statistics.append(field_statistic)
return field_statistics
def simple_text_print(field_statistics, hitcount, headless, delimiter, len_val):
if not headless:
print("Total Records: " + str(hitcount))
format_string = str(
"{:8s}{:1s}{:9s}{:1s}{:6s}{:1s}{:6s}{:1s}{:14s}{:1s}{:7s}{:1s}{:10s}{:1s}{:16s}{:1s}{:10s}{:1s}{:10s}{:1s}{:9s}{:1s}" + "{:" + len_val + "s}" + "{:1s}" + "{:" + len_val + "s}" + "{:1s}{:7s}{:1s}{:7s}{:1s}{:40s}")
print(format_string.format(
"existing", delimiter,
"occurrence", delimiter,
"%", delimiter,
"!%", delimiter,
"notexisting", delimiter,
"unique", delimiter,
"avg", delimiter,
"var", delimiter,
"std", delimiter,
"max", delimiter,
"min", delimiter,
"max-value", delimiter,
"min-value", delimiter,
"max-len", delimiter,
"min-len", delimiter,
"field name"))
for field_statistic in field_statistics:
format_string = str(
"{:>8.0f}{:1s}{:>9d}{:1s}{:>6.2f}{:1s}{:>6.2f}{:1s}{:>14d}{:1s}{:>7d}{:1s}{:>10.2f}{:1s}{:>16.2f}{:1s}{:>10.2f}{:1s}{:>10d}{:1s}{:>9d}{:1s}" + "{:>" + len_val + "s}" + "{:1s}{:>" + len_val + "s}{:1s}{:>7s}{:1s}{:>7s}{:1s}{:<40s}")
print(format_string.format(
float(field_statistic[EXISTING]), delimiter,
int(field_statistic[OCCURRENCE]), delimiter,
float(field_statistic[EXISTING_PERCENTAGE]), delimiter,
float(field_statistic[NOTEXISTING_PERCENTAGE]), delimiter,
int(field_statistic[NOTEXISTING]), delimiter,
int(field_statistic[UNIQUE]), delimiter,
float(field_statistic[AVG]), delimiter,
float(field_statistic[VAR]), delimiter,
float(field_statistic[STD]), delimiter,
int(field_statistic[MAX]), delimiter,
int(field_statistic[MIN]), delimiter,
'"' + field_statistic[MAX_VALUE] + '"', delimiter,
'"' + field_statistic[MIN_VALUE] + '"', delimiter,
field_statistic[MAX_LEN], delimiter,
field_statistic[MIN_LEN], delimiter,
'"' + field_statistic[FIELD_NAME] + '"'))
def csv_print(field_statistics):
header = get_header()
with sys.stdout as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=header, dialect='unix')
writer.writeheader()
for field_statistic in field_statistics:
writer.writerow(field_statistic)
def run():
parser = argparse.ArgumentParser(
description='return field statistics of an line-delimited JSON Document or Input-Stream')
parser.add_argument('-marc', action="store_true", help='Ignore Marc Indicator')
parser.add_argument('-help', action="store_true", help='print more help')
parser.add_argument('-headless', action="store_true", help='don\'t print header')
parser.add_argument('-len_val', type=str, default="17",
help='specify the length for the values of "max-value" and "min-value"')
parser.add_argument('-no_whitespace', default="|", type=str, help='don\'t count values only including whitespaces')
parser.add_argument('-delimiter', default="|", type=str, help='delimiter to use')
parser.add_argument('-csv-output', action="store_true",
help='prints the output as pure CSV data (all values are quoted)', dest='csv_output')
args = parser.parse_args()
if args.help:
parser.print_usage(sys.stderr)
exit(-1)
hitcount = 0
stats = {}
percentage_stats = {}
valstats = {}
for line in sys.stdin:
recordstats = [] # array to save the field paths per record, so we don't count paths twice (e.g. array-elements)
try:
jline = json.loads(line)
hitcount += 1
except ValueError:
eprint("unclean jsonline: ")
eprint(line)
continue
for key, val in traverse(jline, ""):
if isinstance(val, str) and args.no_whitespace and (not val or val.isspace()):
continue # ignore vals which are lists or empty strings
path = getname(key)
if args.marc:
array = key.rsplit("#!?#!?#!?")
if len(array) >= 4:
array[3] = " > "
path = "".join(array)
path = shortname(path)
if path not in valstats:
valstats[path] = {}
if str(val) in valstats[path]:
valstats[path][str(val)] += 1
else:
valstats[path][str(val)] = {}
valstats[path][str(val)] = 1
if path not in recordstats: # append path to recordstats array by first iteration. after that, we ignore that path.
recordstats.append(path)
if path in percentage_stats:
percentage_stats[path] += 1
else:
percentage_stats[path] = 1
if path in stats:
stats[path] += 1
else:
stats[path] = 1
# eprint(path)
sortedstats = collections.OrderedDict(sorted(stats.items()))
field_statistics = generate_field_statistics(sortedstats.items(), valstats, percentage_stats, hitcount,
args.len_val)
if not args.csv_output:
simple_text_print(field_statistics, hitcount, args.headless, args.delimiter, args.len_val)
else:
csv_print(field_statistics)
if __name__ == "__main__":
run()
| [
"csv.DictWriter",
"numpy.mean",
"json.loads",
"argparse.ArgumentParser",
"numpy.asarray",
"numpy.std",
"numpy.var"
] | [((6162, 6285), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""return field statistics of an line-delimited JSON Document or Input-Stream"""'}), "(description=\n 'return field statistics of an line-delimited JSON Document or Input-Stream'\n )\n", (6185, 6285), False, 'import argparse\n'), ((5953, 6011), 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'header', 'dialect': '"""unix"""'}), "(csvfile, fieldnames=header, dialect='unix')\n", (5967, 6011), False, 'import csv\n'), ((2433, 2449), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (2443, 2449), True, 'import numpy as np\n'), ((2485, 2500), 'numpy.asarray', 'np.asarray', (['[0]'], {}), '([0])\n', (2495, 2500), True, 'import numpy as np\n'), ((7429, 7445), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (7439, 7445), False, 'import json\n'), ((2982, 2997), 'numpy.mean', 'np.mean', (['npdata'], {}), '(npdata)\n', (2989, 2997), True, 'import numpy as np\n'), ((3034, 3048), 'numpy.var', 'np.var', (['npdata'], {}), '(npdata)\n', (3040, 3048), True, 'import numpy as np\n'), ((3085, 3099), 'numpy.std', 'np.std', (['npdata'], {}), '(npdata)\n', (3091, 3099), True, 'import numpy as np\n')] |
import numpy as np
import BPNN_model, KNN_sequence_Model
import RNN_models, CNN_models, AttentionModel, Incremental_Learning_models
import configparser
import json
import time
def rnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, cell_type, random_seed=None):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('%s_model test start' % cell_type)
model = RNN_models.FixedLengthRNN(sequence_fix_length, data['features'].shape[1],
class_num=class_num, cell_type=cell_type)
# lstm.train(data['features'], data['labels'], 1, 1024, training_sample_ids,
# foresight_steps=foresight_steps, reset_flag=True)
# lstm.test(data['features'], data['labels'], test_sample_ids)
# lstm.save_model('./model/rnn_model')
start_time = time.time()
model.train_v2(data['features'], data['labels'], data['samples_length'], 1, 1024, training_sample_ids,
test_sample_ids, foresight_steps=0, reset_flag=True, record_flag=False, random_seed=random_seed)
end_time = time.time()
print('cost training time %f' % (end_time - start_time))
model.test_v2(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# model.save_model('./model/%s_model_v2' % cell_type)
whole_time_on_test = model.test_time(data['features'], data['labels'], data['samples_length'], test_sample_ids)
whole_time_on_test_str = '%s time cost on predicting %d test samples: %fs\n' % (cell_type,
len(test_sample_ids),
whole_time_on_test)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
# print('cost time %f' % (end_time - start_time))
print('%s_model test over\n' % cell_type)
return whole_time_on_test_str
def cnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, random_seed=None):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('cnn_model test start')
cnn = CNN_models.ConvSequence2One(sequence_fix_length, data['features'].shape[1],
class_num=class_num)
# cnn.train(data['features'], data['labels'], 1, 1024, training_sample_ids)
# cnn.test(data['features'], data['labels'], test_sample_ids)
# cnn.save_model('./model/cnn_model')
start_time = time.time()
cnn.train_v2(data['features'], data['labels'], data['samples_length'], 1, 1024, training_sample_ids, test_sample_ids,
foresight_steps=0, reset_flag=True, record_flag=False, random_seed=random_seed)
end_time = time.time()
print('cost training time %f' % (end_time - start_time))
cnn.test_v2(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# cnn.save_model('./model/cnn_model_v2')
whole_time_on_test = cnn.test_time(data['features'], data['labels'], data['samples_length'], test_sample_ids)
whole_time_on_test_str = 'cnn time cost on predicting %d test samples: %fs\n' % (len(test_sample_ids),
whole_time_on_test)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
# print('cost time %f' % (end_time - start_time))
print('cnn_model test over\n')
return whole_time_on_test_str
def atn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, random_seed=None):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('atn_model test start')
atn = AttentionModel.CNN_Attention(sequence_fix_length, data['features'].shape[1], class_num=class_num,
network_hyperparameters='./data/attention_network_hyperparameters_v2.json')
# atn.train(data['features'], data['labels'], 1, 1024, training_sample_ids)
# atn.test(data['features'], data['labels'], test_sample_ids)
# atn.save_model('./model/atn_model_new')
start_time = time.time()
atn.train_v2(data['features'], data['labels'], data['samples_length'], 1, 1024, training_sample_ids, test_sample_ids,
foresight_steps=0, reset_flag=True, record_flag=False, random_seed=random_seed)
end_time = time.time()
print('cost training time %f' % (end_time - start_time))
atn.test_v2(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# atn.save_model('./model/atn_model_v2')
whole_time_on_test = atn.test_time(data['features'], data['labels'], data['samples_length'], test_sample_ids)
whole_time_on_test_str = 'sum_a_cnn time cost on predicting %d test samples: %fs\n' % (len(test_sample_ids),
whole_time_on_test)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
# print('cost time %f' % (end_time - start_time))
print('atn_model test over\n')
return whole_time_on_test_str
def incremental_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, incremental_sample_ids, random_seed=None):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('incremental_model test start')
incre_cnn_a = Incremental_Learning_models.Incremental_CNN_Attention(sequence_fix_length, data['features'].shape[1],
class_num=class_num,
network_hyperparameters='./data/attention_network_hyperparameters_v2.json',
incremental_net_hyperparameters='./data/Incremental_CNN_A.json')
incre_cnn_a.incremental_simulation(data['features'], data['labels'], data['samples_length'], 2, 1024,
training_sample_ids, test_sample_ids, incremental_sample_ids,
foresight_steps=0, reset_flag=True, record_flag=False, random_seed=random_seed)
# atn.train(data['features'], data['labels'], 1, 1024, training_sample_ids)
# atn.test(data['features'], data['labels'], test_sample_ids)
# atn.save_model('./model/atn_model_new')
# start_time = time.time()
# incre_cnn_a.train_v2(data['features'], data['labels'], data['samples_length'], 1, 1024, training_sample_ids, test_sample_ids,
# foresight_steps=0, reset_flag=True, record_flag=True, random_seed=random_seed)
# end_time = time.time()
# print('cost training time %f' % (end_time - start_time))
# incre_cnn_a.test_v2(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# incre_cnn_a.save_model('./model/atn_model_v2')
#
# whole_time_on_test = incre_cnn_a.test_time(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# whole_time_on_test_str = 'sum_a_cnn time cost on predicting %d test samples: %fs\n' % (len(test_sample_ids),
# whole_time_on_test)
#
# print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
# # print('cost time %f' % (end_time - start_time))
# print('atn_model test over\n')
# return whole_time_on_test_str
def bpnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, random_seed=None):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('bpnn_model test start')
bpnn = BPNN_model.BPNN(sequence_fix_length, data['features'].shape[1], class_num=class_num)
# bpnn.train(data['features'], data['labels'], 1, 4096, training_sample_ids,
# foresight_steps=foresight_steps, reset_flag=True)
# bpnn.test(data['features'], data['labels'], test_sample_ids)
# bpnn.save_model('./model/bpnn_model')
start_time = time.time()
bpnn.train_v2(data['features'], data['labels'], data['samples_length'], 1, 1024, training_sample_ids, test_sample_ids,
foresight_steps=0, reset_flag=True, record_flag=False, random_seed=random_seed)
end_time = time.time()
print('cost training time %f' % (end_time - start_time))
bpnn.test_v2(data['features'], data['labels'], data['samples_length'], test_sample_ids)
# bpnn.save_model('./model/bpnn_model_v2')
whole_time_on_test = bpnn.test_time(data['features'], data['labels'], data['samples_length'], test_sample_ids)
whole_time_on_test_str = 'bpnn time cost on predicting %d test samples: %fs\n' % (len(test_sample_ids),
whole_time_on_test)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
# print('cost time %f' % (end_time - start_time))
print('bpnn_model test over\n')
return whole_time_on_test_str
def knn_exams(data, training_sample_ids, test_sample_ids):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print('knn_model test start')
start_time = time.time()
knn = KNN_sequence_Model.KNN_Sequence()
# knn.train(data['features'], data['labels'], training_sample_ids, data['samples_length'])
knn.test_cpu(data['features'], data['labels'], test_sample_ids[-10000:], data['samples_length'], 100)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
end_time = time.time()
print('cost time %f' % (end_time - start_time))
print('knn_model test over\n')
return
def exam1and2():
common_para = configparser.ConfigParser()
common_para.read('common_para.ini')
sequence_fix_length = common_para['common_parameters'].getint('sequence_fix_length')
foresight_steps = common_para['common_parameters'].getint('foresight_steps')
class_num = common_para['common_parameters'].getint('class_num')
random_seed = common_para['common_parameters'].getint('random_seed')
data = np.load(common_para['path']['data_file'])
# print(data['features'])
# print(data['labels'])
# print(data['samples_length'])
# print(data['features'].shape)
# print(data['labels'].shape)
# print(data['samples_length'].shape)
### generate training samples' id
# sample_num = data['labels'].shape[0]
# sample_ids = [i for i in range(sample_num)]
# training_sample_ids = random.sample(sample_ids, int(0.7*sample_num))
# test_sample_ids = list(set(sample_ids) - set(training_sample_ids))
# training_sample_ids = [i for i in range(10000)]
# test_sample_ids = [i for i in range(1000, 2000)]
with open(common_para['path']['data_set_ids_file'], 'r') as f:
data_set_ids = json.load(f)
training_sample_ids = data_set_ids['training_set']
test_sample_ids = data_set_ids['test_set']
# training_sample_ids = list(map(int, data_set_ids['training_set']))
# test_sample_ids = list(map(int, data_set_ids['test_set']))
# print(type(training_sample_ids), type(test_sample_ids))
time_str = ''
# rnn exams
# lstm
tstr = rnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids,
'lstm', random_seed)
time_str += tstr
# gru
tstr = rnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, 'gru',
random_seed)
time_str += tstr
# sru
tstr = rnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids, 'sru',
random_seed)
time_str += tstr
# cnn exams
tstr = cnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids,
random_seed)
time_str += tstr
#
# # attention net exams
tstr = atn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids,
random_seed)
time_str += tstr
#
# traditional ways
# BPNN exams
tstr = bpnn_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids,
random_seed)
time_str += tstr
# with open('./data/time_cost.txt', 'w+') as file:
# file.write(time_str)
# todo add dtw exams
# # KNN exams
# knn_exams(data, training_sample_ids, test_sample_ids)
def exam3():
common_para = configparser.ConfigParser()
common_para.read('common_para.ini')
sequence_fix_length = common_para['common_parameters'].getint('sequence_fix_length')
foresight_steps = common_para['common_parameters'].getint('foresight_steps')
class_num = common_para['common_parameters'].getint('class_num')
random_seed = common_para['common_parameters'].getint('random_seed')
data = np.load(common_para['path']['data_file'])
# print(data['features'])
# print(data['labels'])
# print(data['samples_length'])
# print(data['features'].shape)
# print(data['labels'].shape)
# print(data['samples_length'].shape)
# Incremental exams
with open(common_para['path']['data_set_incremental_ids_file'], 'r') as f:
data_set_ids = json.load(f)
training_sample_ids = data_set_ids['training_set']
test_sample_ids = data_set_ids['test_set']
incremental_sample_ids = data_set_ids['incremental_set']
incremental_exams(sequence_fix_length, foresight_steps, class_num, data, training_sample_ids, test_sample_ids,
incremental_sample_ids, random_seed)
if __name__ == '__main__':
exam1and2()
exam3()
| [
"BPNN_model.BPNN",
"configparser.ConfigParser",
"RNN_models.FixedLengthRNN",
"KNN_sequence_Model.KNN_Sequence",
"numpy.load",
"AttentionModel.CNN_Attention",
"json.load",
"Incremental_Learning_models.Incremental_CNN_Attention",
"time.time",
"CNN_models.ConvSequence2One"
] | [((448, 567), 'RNN_models.FixedLengthRNN', 'RNN_models.FixedLengthRNN', (['sequence_fix_length', "data['features'].shape[1]"], {'class_num': 'class_num', 'cell_type': 'cell_type'}), "(sequence_fix_length, data['features'].shape[1],\n class_num=class_num, cell_type=cell_type)\n", (473, 567), False, 'import RNN_models, CNN_models, AttentionModel, Incremental_Learning_models\n'), ((876, 887), 'time.time', 'time.time', ([], {}), '()\n', (885, 887), False, 'import time\n'), ((1126, 1137), 'time.time', 'time.time', ([], {}), '()\n', (1135, 1137), False, 'import time\n'), ((2231, 2331), 'CNN_models.ConvSequence2One', 'CNN_models.ConvSequence2One', (['sequence_fix_length', "data['features'].shape[1]"], {'class_num': 'class_num'}), "(sequence_fix_length, data['features'].shape[1],\n class_num=class_num)\n", (2258, 2331), False, 'import RNN_models, CNN_models, AttentionModel, Incremental_Learning_models\n'), ((2571, 2582), 'time.time', 'time.time', ([], {}), '()\n', (2580, 2582), False, 'import time\n'), ((2817, 2828), 'time.time', 'time.time', ([], {}), '()\n', (2826, 2828), False, 'import time\n'), ((3801, 3983), 'AttentionModel.CNN_Attention', 'AttentionModel.CNN_Attention', (['sequence_fix_length', "data['features'].shape[1]"], {'class_num': 'class_num', 'network_hyperparameters': '"""./data/attention_network_hyperparameters_v2.json"""'}), "(sequence_fix_length, data['features'].shape[1],\n class_num=class_num, network_hyperparameters=\n './data/attention_network_hyperparameters_v2.json')\n", (3829, 3983), False, 'import RNN_models, CNN_models, AttentionModel, Incremental_Learning_models\n'), ((4224, 4235), 'time.time', 'time.time', ([], {}), '()\n', (4233, 4235), False, 'import time\n'), ((4470, 4481), 'time.time', 'time.time', ([], {}), '()\n', (4479, 4481), False, 'import time\n'), ((5506, 5782), 'Incremental_Learning_models.Incremental_CNN_Attention', 'Incremental_Learning_models.Incremental_CNN_Attention', (['sequence_fix_length', "data['features'].shape[1]"], {'class_num': 'class_num', 'network_hyperparameters': '"""./data/attention_network_hyperparameters_v2.json"""', 'incremental_net_hyperparameters': '"""./data/Incremental_CNN_A.json"""'}), "(sequence_fix_length,\n data['features'].shape[1], class_num=class_num, network_hyperparameters\n ='./data/attention_network_hyperparameters_v2.json',\n incremental_net_hyperparameters='./data/Incremental_CNN_A.json')\n", (5559, 5782), False, 'import RNN_models, CNN_models, AttentionModel, Incremental_Learning_models\n'), ((7761, 7850), 'BPNN_model.BPNN', 'BPNN_model.BPNN', (['sequence_fix_length', "data['features'].shape[1]"], {'class_num': 'class_num'}), "(sequence_fix_length, data['features'].shape[1], class_num=\n class_num)\n", (7776, 7850), False, 'import BPNN_model, KNN_sequence_Model\n'), ((8123, 8134), 'time.time', 'time.time', ([], {}), '()\n', (8132, 8134), False, 'import time\n'), ((8371, 8382), 'time.time', 'time.time', ([], {}), '()\n', (8380, 8382), False, 'import time\n'), ((9298, 9309), 'time.time', 'time.time', ([], {}), '()\n', (9307, 9309), False, 'import time\n'), ((9320, 9353), 'KNN_sequence_Model.KNN_Sequence', 'KNN_sequence_Model.KNN_Sequence', ([], {}), '()\n', (9351, 9353), False, 'import BPNN_model, KNN_sequence_Model\n'), ((9646, 9657), 'time.time', 'time.time', ([], {}), '()\n', (9655, 9657), False, 'import time\n'), ((9792, 9819), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (9817, 9819), False, 'import configparser\n'), ((10184, 10225), 'numpy.load', 'np.load', (["common_para['path']['data_file']"], {}), "(common_para['path']['data_file'])\n", (10191, 10225), True, 'import numpy as np\n'), ((12652, 12679), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (12677, 12679), False, 'import configparser\n'), ((13044, 13085), 'numpy.load', 'np.load', (["common_para['path']['data_file']"], {}), "(common_para['path']['data_file'])\n", (13051, 13085), True, 'import numpy as np\n'), ((10911, 10923), 'json.load', 'json.load', (['f'], {}), '(f)\n', (10920, 10923), False, 'import json\n'), ((13419, 13431), 'json.load', 'json.load', (['f'], {}), '(f)\n', (13428, 13431), False, 'import json\n'), ((375, 386), 'time.time', 'time.time', ([], {}), '()\n', (384, 386), False, 'import time\n'), ((1833, 1844), 'time.time', 'time.time', ([], {}), '()\n', (1842, 1844), False, 'import time\n'), ((2171, 2182), 'time.time', 'time.time', ([], {}), '()\n', (2180, 2182), False, 'import time\n'), ((3414, 3425), 'time.time', 'time.time', ([], {}), '()\n', (3423, 3425), False, 'import time\n'), ((3741, 3752), 'time.time', 'time.time', ([], {}), '()\n', (3750, 3752), False, 'import time\n'), ((5073, 5084), 'time.time', 'time.time', ([], {}), '()\n', (5082, 5084), False, 'import time\n'), ((5430, 5441), 'time.time', 'time.time', ([], {}), '()\n', (5439, 5441), False, 'import time\n'), ((7699, 7710), 'time.time', 'time.time', ([], {}), '()\n', (7708, 7710), False, 'import time\n'), ((8973, 8984), 'time.time', 'time.time', ([], {}), '()\n', (8982, 8984), False, 'import time\n'), ((9232, 9243), 'time.time', 'time.time', ([], {}), '()\n', (9241, 9243), False, 'import time\n'), ((9616, 9627), 'time.time', 'time.time', ([], {}), '()\n', (9625, 9627), False, 'import time\n')] |
'''
###############################################################################
"MajoranaNanowire" Python3 Module
v 1.0 (2020)
Created by <NAME> (2018)
###############################################################################
"Function" submodule
This sub-package contains some functions required for the "Hamiltonian"
sub-package.
###############################################################################
'''
#%%############################################################################
######################## Required Packages ############################
###############################################################################
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
import scipy.linalg
from scipy import constants
from MajoranaNanowires.third_functions import pfaffian as pf
#%% ############################# Functions
#%%
def FermiDirac(E,kT,mu=0):
"""
Computes the Fermi-Dirac distribution.
Parameters
----------
E: scalar or arr
Energies.
kT: scalar
Temperature (in units of energy).
mu: scalar or arr
Fermi energy.
Returns
-------
result: scalar or arr
Fermi-Dirac distribution for the given energies.
"""
np.seterr(over='ignore')
np.seterr(divide='ignore')
return (1/(1+np.exp((E-mu)/kT)))
#%%
def density_TF(phi,kT=0,E_F=0,material='InAs',band='conduction',Vz=0):
"""
Computes the charge density of a 3D (free) electron gas in the Thomas-Fermi
approximation.
Parameters
----------
phi: scalar or arr
Electrostatic energy.
kT: scalar
Temperature (in units of energy).
E_F: scalar or arr
Fermi energy.
material: str or dic
Material for which is evaluated. For a general material,
'material' is a dictionary with arguments m_eff (conduction
effective mass), m_eff_hh (heavy hole effective mass), m_eff_lh
(light hole effective mass), and E_gap (semiconductor gap). These
parameters are already saved in this function for InAs and InSb,
which can be chosen by choosing material='InAs' or 'InSb',
resprectively.
band: str
Whether to include 'conduction', 'valence' or 'both' bands in the
calculations.
Vz: scalar
Zeeman splitting.
Returns
-------
den: scalar or arr
Charge density in the Thomas-Fermi approximation for the given
electrostatic energies.
"""
np.seterr(invalid='ignore')
if material=='InAs':
m_eff=0.023
m_eff_hh=0.41
m_eff_lh=0.026
E_gap=418
elif material=='InSb':
m_eff=0.015
m_eff_hh=0.43
m_eff_lh=0.015
E_gap=170
else:
if 'E_gap' in material:
material['m_eff'], material['m_eff_hh'], material['m_eff_lh'], material['E_gap'] = m_eff, m_eff_hh, m_eff_lh, E_gap
else:
material['m_eff'] = m_eff
if band=='conduction':
if Vz==0:
den_e=-1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F)*1e-3*constants.e*FermiDirac(-phi-E_F,kT))/constants.hbar)**3*1e-27
den=np.nan_to_num(den_e,0)
else:
den_e=-1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F+Vz)*1e-3*constants.e*FermiDirac(-phi-E_F-Vz,kT))/constants.hbar)**3*1e-27
den_e=den_e-1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F-Vz)*1e-3*constants.e*FermiDirac(-phi-E_F+Vz,kT))/constants.hbar)**3*1e-27
den=np.nan_to_num(den_e,0)
elif band=='valence':
if Vz==0:
den_hh=1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap,kT))/constants.hbar)**3*1e-27
den_lh=1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap,kT))/constants.hbar)**3*1e-27
den=np.nan_to_num(den_hh+den_lh,0)
else:
den_hh=1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F-Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap+Vz,kT))/constants.hbar)**3*1e-27
den_hh=den_hh+1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F+Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap-Vz,kT))/constants.hbar)**3*1e-27
den_lh=1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F-Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap+Vz,kT))/constants.hbar)**3*1e-27
den_lh=den_lh+1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F+Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap-Vz,kT))/constants.hbar)**3*1e-27
den=np.nan_to_num(den_hh+den_lh,0)
elif band=='both':
if Vz==0:
den_e=-1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F)*1e-3*constants.e*FermiDirac(-phi-E_F,kT))/constants.hbar)**3*1e-27
den_e=np.nan_to_num(den_e,0)
den_hh=1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap,kT))/constants.hbar)**3*1e-27
den_lh=1.0/(3*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap,kT))/constants.hbar)**3*1e-27
den_h=np.nan_to_num(den_hh+den_lh,0)
den=den_e+den_h
else:
den_e=-1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F+Vz)*1e-3*constants.e*FermiDirac(-phi-E_F-Vz,kT))/constants.hbar)**3*1e-27
den_e=den_e-1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff*constants.m_e*np.abs(phi+E_F-Vz)*1e-3*constants.e*FermiDirac(-phi-E_F+Vz,kT))/constants.hbar)**3*1e-27
den_e=np.nan_to_num(den_e,0)
den_hh=1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F-Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap+Vz,kT))/constants.hbar)**3*1e-27
den_hh=den_hh+1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_hh*constants.m_e*np.abs(-phi-E_gap-E_F+Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap-Vz,kT))/constants.hbar)**3*1e-27
den_lh=1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F-Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap+Vz,kT))/constants.hbar)**3*1e-27
den_lh=den_lh+1.0/(6*constants.pi**2)*(np.sqrt(2*m_eff_lh*constants.m_e*np.abs(-phi-E_gap-E_F+Vz)*1e-3*constants.e*FermiDirac(phi+E_F+E_gap-Vz,kT))/constants.hbar)**3*1e-27
den_h=np.nan_to_num(den_hh+den_lh,0)
den=den_e+den_h
return (den)
#%% ############################# Array manipulation
#%%
def order_eig(E,U=0,sparse='yes',BdG='yes'):
"""
Order the eigenfunctions from smaller to larger. If BdG==yes and
sparse==yes, it also ensures that there are the same number of positive
eigenvalues than negative.
Parameters
----------
E: arr
Eigenvalues.
U: arr
Eigenvectors.
sparse: {'yes','no'}
Whether the eigenspectrum has been computed from a sparse matrix.
BdG: {'yes','no'}
Whether the eigenspectrum must have BdG symmetry or not.
Returns
-------
E, U: arrs
Eigenspectrum ordered from smaller to larger eigenvalues.
"""
n_eig=len(E)
if np.isscalar(U):
if BdG=='yes':
if sparse=='yes':
idx = np.argsort(E)
E = E[idx]
if (np.abs(E[0]+E[n_eig-1])>0.00001)and(np.sign(E[0]+E[n_eig-1])==1):
E[n_eig-1]=-E[n_eig-2]
elif (np.abs(E[0]+E[n_eig-1])>0.00001)and(np.sign(E[0]+E[n_eig-1])==-1):
E[0]=-E[1]
idx = np.argsort(E)
return (idx)
else:
if BdG=='yes':
if sparse=='yes':
idx = np.argsort(E)
E = E[idx]
U = U[:,idx]
if (np.abs(E[0]+E[n_eig-1])>0.00001)and(np.sign(E[0]+E[n_eig-1])==1):
E[n_eig-1]=-E[n_eig-2]
elif (np.abs(E[0]+E[n_eig-1])>0.00001)and(np.sign(E[0]+E[n_eig-1])==-1):
E[0]=-E[1]
idx = np.argsort(E)
E = E[idx]
U = U[:,idx]
return (E),(U)
#%%
def length(vec):
"""
Length of a given vector. If vec is an scalar, its length is 1.
Parameters
----------
vec: scalar or arr
Input vector
Returns
-------
length: int
Length of vec. If vec is an scalar, its length is 1.
"""
if np.ndim(vec)==0:
length=1
else:
length=len(vec)
return length
#%%
def diagonal(N,k=0,init=0,step=1):
"""
Indices of some diagonal of a given marix. It is more efficient than its
numpy counterpart.
Parameters
----------
N: int
Length of the diagonal (number of elements).
k: int
Offset of the off-diagonal. k=0 is the main diagonal, k>0 is a
diagonal in the upper-part of the Hamiltonian, and k<0 in the
lower one.
init: int
The starting element of the diagonal.
step: int
The step between elements in the diagonal.
Returns
-------
indices: tuple of arr
Indices of the diagonal. The first element of the tuple are the
row elements, and the second one are the column ones.
"""
assert np.isscalar(k), 'The offset k must be a scalar'
if k==0:
indices=(np.arange(init,N,step=step),np.arange(init,N,step=step))
elif k>0:
indices=(np.arange(init,N-k,step=step),np.arange(init,N-k,step=step)+k)
elif k<0:
indices=(np.arange(init,N+k,step=step)-k,np.arange(init,N+k,step=step))
return(indices)
#%%
def concatenate(arg):
"""
Concatenate a list of arrays.
Parameters
----------
arg: tuple or list of arr
List of arrays to be concatenated.
Returns
-------
con: arr or list
Array or list of the concatenated list.
"""
if isinstance(arg[0],tuple) and len(arg[0])==2:
index_1, index_2 = np.array([]), np.array([])
for i in range(len(arg)):
index_1 = np.append(index_1,arg[i][0])
index_2 = np.append(index_2,arg[i][1])
indices=(index_1,index_2)
else:
indices=np.concatenate(arg)
return(indices)
#%%
def between(arg, interval):
"""
Computes whether a given number is between a given interval or not.
Parameters
----------
arg: scalar
Number to be evaluated.
interval: tuple
Interval in which perform the evaluation.
Returns
-------
result: bool
If arg is between interval, result=True, and result=False in other
case.
"""
if arg>=interval[0] and arg<=interval[1]:
result=True
else:
result=False
return(result)
#%%
def arg_isclose(vec,val):
"""
Find the index of a given vector that corresponds to the element of the
array "vec" which is closest to to an specific value "val".
Parameters
----------
vec: arr
Array in which it is desired to find the closest element.
val: scalar
Closest value.
Returns
-------
result: int
Index of the element of vec closest to val.
"""
arg=np.argmin(np.abs(vec-val))
return(arg)
#%% ############################# Constructors or extractors
#%%
def build_mesh(N,L,mesh_type='regular',fact=0.5,asym=1):
"""
Build a 2D inhomogeneous rectangular mesh.
Parameters
----------
N: arr
Number of sites in each direction.
L: arr
Length en each direction.
mesh_type: str
Whether to build a 'regular' mesh, or an inhomogeneous one with a
discretization given by a 'geometric' distribution, an 'exponential'
separation, or a 'random' one.
fact: scalar
Factor which regulates the separations between sites.
asym: scalar
The asymmetry between the factors applied for the x and y direction.
Returns
-------
x, y: mesh
Mesh in the x and y directions.
dis: mesh
Mesh with the discretization in each point.
"""
if mesh_type=='regular':
x, y = np.linspace(-L[1]/2,L[1]/2,N[0]), np.linspace(-L[0]/2,L[0]/2,N[1])
dis=np.array([np.abs(x[1]-x[0]),np.abs(y[1]-y[0])])
x,y=np.meshgrid(x,y,indexing='ij')
return (x,y,dis)
elif mesh_type=='geometric':
xm,ym=np.zeros(N), np.zeros(N)
dis_m=np.array([np.zeros(N),np.zeros(N)])
for i in range(N[0]):
for j in range(N[1]):
xm[i,j]=(L[0]/2*fact**np.abs(i-int((N[0]-1)/2))-L[0]/2)*np.sign(i-int((N[0]-1)/2))*(L[0]/(L[0]/2*fact**np.abs(0-int((N[0]-1)/2))-L[0]/2)/2)
ym[i,j]=(L[1]/2*fact**np.abs(j-int((N[1]-1)/2))-L[1]/2)*np.sign(j-int((N[1]-1)/2))*(L[1]/(L[1]/2*fact**np.abs(0-int((N[1]-1)/2))-L[1]/2)/2)
for i in range(N[0]):
for j in range(N[1]):
if not(j==0 or j==N[1]-1):
dis_m[1,i,j]=np.abs(ym[i,j+1]-ym[i,j])/2+np.abs(ym[i,j-1]-ym[i,j])/2
if not(i==0 or i==N[0]-1):
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])/2+np.abs(xm[i,j]-xm[i+1,j])/2
if i==0:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i+1,j])
elif i==N[0]-1:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])
if j==0:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j+1])
elif j==N[1]-1:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j-1])
return (xm,ym,dis_m)
elif mesh_type=='exponential':
np.seterr(all='ignore')
xm,ym=np.zeros(N), np.zeros(N)
dis_m=np.array([np.zeros(N),np.zeros(N)])
for i in range(N[0]):
for j in range(N[1]):
xm[i,j]=(1-np.exp(-np.abs(i-int((N[0]-1)/2))*fact))*np.sign(i-int((N[0]-1)/2))*(1-np.exp(-np.abs(N[0]-int((N[0]-1)/2))*fact))**(-1)*L[0]/2
ym[i,j]=(1-np.exp(-np.abs(j-int((N[1]-1)/2))*fact/asym))*np.sign(j-int((N[1]-1)/2))*(1-np.exp(-np.abs(N[1]-int((N[1]-1)/2))*fact/asym))**(-1)*L[1]/2
for i in range(N[0]):
for j in range(N[1]):
if not(j==0 or j==N[1]-1):
dis_m[1,i,j]=np.abs(ym[i,j+1]-ym[i,j])/2+np.abs(ym[i,j-1]-ym[i,j])/2
if not(i==0 or i==N[0]-1):
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])/2+np.abs(xm[i,j]-xm[i+1,j])/2
if i==0:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i+1,j])
elif i==N[0]-1:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])
if j==0:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j+1])
elif j==N[1]-1:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j-1])
return (xm,ym,dis_m)
elif mesh_type=='random':
x,y,dis=build_mesh(N,L,mesh_type='regular')
xm,ym=np.zeros(N), np.zeros(N)
dis_m=np.array([np.zeros(N),np.zeros(N)])
for i in range(N[0]):
for j in range(N[1]):
xp, yp = x[:,0]+(np.random.rand(N[0])-0.5)*dis[0]*fact, y[0,:]+(np.random.rand(N[0])-0.5)*dis[1]*fact
xm[i,j],ym[i,j]=xp[i],yp[j]
for i in range(N[0]):
for j in range(N[1]):
if not(j==0 or j==N[1]-1):
dis_m[1,i,j]=np.abs(ym[i,j+1]-ym[i,j])/2+np.abs(ym[i,j-1]-ym[i,j])/2
if not(i==0 or i==N[0]-1):
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])/2+np.abs(xm[i,j]-xm[i+1,j])/2
if i==0:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i+1,j])
elif i==N[0]-1:
dis_m[0,i,j]=np.abs(xm[i,j]-xm[i-1,j])
if j==0:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j+1])
elif j==N[1]-1:
dis_m[1,i,j]=np.abs(ym[i,j]-ym[i,j-1])
return (xm,ym,dis_m)
#%%
def get_potential(phi_in,x,y,z,symmetry='none',mesh_type='none'):
"""
Obtain the potential from a function for a given sites.
Parameters
----------
phi_in: fun
Fenics function of the electrostatic potential.
x,y,z: arr
Points in which evaluate the potential.
symmetry: {'none','x','y','z','full-shell'}
Imposed symmetry of the potential.
mesh_type:___
______________________________
Returns
-------
phi_out: arr
Electrostatic potential in the sites given by x,y,z.
"""
phi_out=np.zeros((len(x),len(y),len(z)))
if symmetry=='none':
for i in range(len(x)):
for j in range(len(y)):
for k in range(len(z)):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
elif symmetry=='y':
if mesh_type=='none':
for i in range(len(x)):
for j in range(int((len(y)-1)/2)+1):
for k in range(len(z)):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
phi_out[i,len(y)-j-1,k]=phi_out[i,j,k]
elif mesh_type=='yz-mesh':
for i in range(len(x)):
for j in range(int((len(y[:,0])-1)/2)+1):
for k in range(len(z[0,:])):
phi_out[i,j,k]=phi_in(x[i],y[j,k],z[j,k])
phi_out[i,len(y[:,0])-j-1,k]=phi_out[i,j,k]
elif symmetry=='yz':
for i in range(len(x)):
for j in range(int((len(y)-1)/2)+1):
for k in range(int((len(z)-1)/2)+1):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
phi_out[i,len(y)-j-1,k]=phi_out[i,j,k]
phi_out[i,j,len(z)-k-1]=phi_out[i,j,k]
phi_out[i,len(y)-j-1,len(z)-k-1]=phi_out[i,j,k]
elif symmetry=='xy':
for i in range(int((len(x)-1)/2)+1):
for j in range(int((len(y)-1)/2)+1):
for k in range(len(z)):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
phi_out[i,len(y)-j-1,k]=phi_out[i,j,k]
phi_out[len(x)-i-1,j,k]=phi_out[i,j,k]
phi_out[len(x)-i-1,len(y)-j-1,k]=phi_out[i,j,k]
elif symmetry=='x':
for i in range(int((len(x)-1)/2)+1):
for j in range(len(y)):
for k in range(len(z)):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
phi_out[len(x)-i-1,j,k]=phi_out[i,j,k]
elif symmetry=='full-shell':
for i in range(len(x)):
for j in range(int((len(y)-1)/2)+1):
for k in range(len(z)):
if (z[k]>=0) and (y[j]<=z[k]/np.tan(np.pi/3)) and (y[j]>=-z[k]/np.tan(np.pi/3)):
phi_out[i,j,k]=phi_in(x[i],y[j],z[k])
phi_out[i,len(y)-j-1,k]=phi_out[i,j,k]
for l in range(1,4):
phi_out[i,int(round((j-25)*np.cos(np.pi/3*l)-(k-25)*np.sin(np.pi/3*l)))+25,int(round((j-25)*np.sin(np.pi/3*l)+(k-25)*np.cos(np.pi/3*l)))+25]=phi_out[i,j,k]
phi_out[i,int(round((len(y)-j-1-25)*np.cos(np.pi/3*l)-(k-25)*np.sin(np.pi/3*l)))+25,int(round((len(y)-j-1-25)*np.sin(np.pi/3*l)+(k-25)*np.cos(np.pi/3*l)))+25]=phi_out[i,j,k]
for j in range(int((len(y)-1)/2)+1):
for k in range(len(z)):
if phi_out[i,j,k]==0:
phi_out[i,j,k]=phi_out[i,int(j+1),k]
for j in range(int((len(y)-1)/2)+1):
for k in range(len(z)):
if phi_out[i,j,k]==0:
phi_out[i,j,k]=phi_out[i,int(j+2),k]
phi_out[i,len(y)-j-1,k]=phi_out[i,j,k]
return (phi_out)
#%%
def get_ElectricField(phi,x,y,z):
"""
Obtain the electric field of a given electrostatic potential.
Parameters
----------
phi: arr
Electrostatic potential.
x,y,z: arr
Points in which it is evaluated the potential.
Returns
-------
E: arr
Electric field of phi. Each element E[i] is the electric field in
each direction.
"""
dis=np.array([np.abs(x[1]-x[0]),np.abs(y[1]-y[0]),np.abs(z[1]-z[0])])
if np.ndim(phi)==3:
Ex, Ey, Ez = np.gradient(phi,dis[0],dis[1],dis[2])
return (np.array([Ex,Ey,Ez]))
elif np.ndim(phi)==2:
Ey, Ez = np.gradient(phi,dis[1],dis[2])
return (np.array([Ey,Ez]))
elif np.ndim(phi)==1:
Ex = np.gradient(phi,dis)
return (Ex)
#%% ############################# Modifiers
#%%
def mask_hexagonal(fun_in,y,z,x=0,change=np.nan,mesh_type='regular'):
"""
Hexagonal mask. This function change the values for those points of fun_in
which are outside the hexagonal section.
Parameters
----------
fun_in: arr
Function to be masked.
y,z: arr
Points of the section in which it is evaluated the function.
x: arr
Points of the length in which it is evaluated the function. If x=0,
then it is only evaluated in 2D.
change: value
Value to which change those points outside of the hexagonal section.
Returns
-------
fun_out: arr
Masked function.
"""
if np.isscalar(x):
if mesh_type=='regular':
Ny, Nz = len(y), len(z)
Ly, Lz = y[Ny-1]*2, z[Nz-1]*2
a0=Ly/2
b0=a0*np.sin(np.pi/3)
fun_out=np.zeros((len(y),len(z)))
for j in range(Ny):
for k in range(Nz):
if not(between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0))):
fun_out[j,k]=change
else:
fun_out[j,k]=fun_in[j,k]
else:
Ny, Nz = len(y[:,0]), len(z[0,:])
Ly, Lz = y[Ny-1,0]*2, z[0,Nz-1]*2
a0=Ly/2
b0=a0*np.sin(np.pi/3)
fun_out=np.zeros((Ny,Nz))
for j in range(Ny):
for k in range(Nz):
if not(between(z[j,k], (-b0,b0)) and between(z[j,k],(2*b0/a0*y[j,k]-2*b0,-2*b0/a0*y[j,k]+2*b0)) and between(z[j,k],(-2*b0/a0*y[j,k]-2*b0,2*b0/a0*y[j,k]+2*b0))):
fun_out[j,k]=change
else:
fun_out[j,k]=fun_in[j,k]
if change=='masked':
fun_out=np.ma.array(fun_out, mask=np.isnan(fun_out))
else:
Ny, Nz = len(y), len(z)
Ly, Lz = y[Ny-1]*2, z[Nz-1]*2
a0=Ly/2
b0=a0*np.sin(np.pi/3)
fun_out=np.zeros((len(x),len(y),len(z)))
for j in range(Ny):
for k in range(Nz):
if not(between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0))):
fun_out[:,j,k]=np.ones(len(x))*change
else:
fun_out[:,j,k]=fun_in[:,j,k]
if change=='masked':
fun_out=np.ma.array(fun_out, mask=np.isnan(fun_out))
return (fun_out)
#%%
def mask_wire(fun_in,N,dis,change=np.nan,include=np.array(['wire']),W_w=0,W_l1=0,W_l2=0,faces_l1=np.array([]),faces_l2=np.array([])):
"""
Mask for wires. This function change the values for those points of fun_in
which are outside the hexagonal section and/or layers surrounding the wire.
Parameters
----------
fun_in: arr
Function to be masked.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
change: value
Value to which change those points outside of the hexagonal section.
include: arr
Whether to include the wire ('wire') and/or some layers ('layer_1
and/or 'layer_2').
W_w: float
Width of the nanowire. If W_w=0, then the width is taken as N*dis.
W_l1: float
Width of the first layer surrounding the wire. W_l1=0 means that
there is no layer.
W_l2: float
Width of the first layer surrounding the wire. W_l1=0 means that
there is no (second) layer.
faces_l1: arr
Facets that the first layer covers to the wire. Each facet is
labeled with a number from 1 to 6 (the upper one is 1, and the rest
are numbered clockwise). Each element of the array denotes with a
string (e.g. np.array(['1','2'])) if such facet is covered.
faces_l2: arr
Same for the second layer.
Returns
-------
fun_out: arr
Masked function.
"""
if len(N)==3:
Nx, Ny, Nz = N
dis_x, dis_y, dis_z = dis
fun_in=fun_in[0]
elif len(N)==2:
Ny, Nz = N
dis_y, dis_z = dis
y, z= np.linspace(-(Ny-1)*dis_y/2,(Ny-1)*dis_y/2,Ny), np.linspace(-(Nz-1)*dis_z/2,(Nz-1)*dis_z/2,Nz)
if np.isscalar(W_w):
if W_w==0:
W_w=Ny*dis_y
a0=W_w/2
b0=a0*np.sin(np.pi/3)
elif not(np.isscalar(W_w)):
a0=Ny*dis_y/2
b0=Nz*dis_z/2*np.sin(np.pi/3)
if faces_l1.size==0:
faces_l1=np.array(['0'])
if faces_l2.size==0:
faces_l2=np.array(['0'])
fun_out=np.zeros((Ny,Nz))
for j in range(Ny):
for k in range(Nz):
if (include=='wire').any():
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0))):
fun_out[j,k]=fun_in[j,k]
else:
fun_out[j,k]=change
if (include=='layer_1').any():
if (faces_l1=='1').any() and ((between(y[j], (-a0/2,a0/2)) and between(z[k], (b0,b0+W_l1)))):
fun_out[j,k]=fun_in[j,k]
elif (faces_l1=='2').any() and ((between(z[k], (-2*b0/a0*y[j]+2*b0,2*b0/a0*y[j]+W_l1)) and between(z[k], (2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0+W_l1)))):
fun_out[j,k]=fun_in[j,k]
elif (faces_l1=='6').any() and ((between(z[k], (2*b0/a0*y[j]+2*b0,-2*b0/a0*y[j]+W_l1)) and between(z[k], (-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0+W_l1)))):
fun_out[j,k]=fun_in[j,k]
elif (faces_l1=='3').any() and ((between(z[k], (-b0,2*b0/a0*y[j]-2*b0)) and between(z[k], (2*b0/a0*y[j]-2*b0-W_l1,-2*b0/a0*y[j]+2*b0+W_l1)))):
fun_out[j,k]=fun_in[j,k]
elif (faces_l1=='5').any() and ((between(z[k], (-b0,-2*b0/a0*y[j]-2*b0)) and between(z[k], (-2*b0/a0*y[j]-2*b0-W_l1,2*b0/a0*y[j]+2*b0+W_l1)))):
fun_out[j,k]=fun_in[j,k]
elif (faces_l1=='4').any() and ((between(y[j], (-a0/2-W_l1/2,a0/2+W_l1/2)) and between(z[k], (-b0-W_l1,-b0)))):
fun_out[j,k]=fun_in[j,k]
if (include=='layer_2').any():
if (faces_l2=='1').any():
if (faces_l1=='1').any() and ((between(y[j], (-a0/2,a0/2)) and between(z[k], (b0+W_l1,b0+W_l1+W_l2)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='1').any() and ((between(y[j], (-a0/2,a0/2)) and between(z[k], (b0,b0+W_l2)))):
fun_out[j,k]=fun_in[j,k]
if (faces_l2=='2').any():
if (faces_l1=='2').any() and ((between(z[k], (-2*b0/a0*y[j]+2*b0+W_l1,2*b0/a0*y[j]+W_l1+W_l2)) and between(z[k], (2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0+W_l1+W_l2)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='2').any() and ((between(z[k], (-2*b0/a0*y[j]+2*b0,2*b0/a0*y[j]+W_l2)) and between(z[k], (2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0+W_l2)))):
fun_out[j,k]=fun_in[j,k]
if (faces_l2=='6').any():
if (faces_l1=='6').any() and ((between(z[k], (2*b0/a0*y[j]+2*b0+W_l1,-2*b0/a0*y[j]+W_l1+W_l2)) and between(z[k], (-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0+W_l1+W_l2)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='6').any() and ((between(z[k], (2*b0/a0*y[j]+2*b0,-2*b0/a0*y[j]+W_l2)) and between(z[k], (-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0+W_l2)))):
fun_out[j,k]=fun_in[j,k]
if (faces_l2=='3').any():
if (faces_l1=='3').any() and ((between(z[k], (-b0,2*b0/a0*y[j]-2*b0-W_l1)) and between(z[k], (2*b0/a0*y[j]-2*b0-W_l1-W_l2,-2*b0/a0*y[j]+2*b0+W_l1+W_l2)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='3').any() and ((between(z[k], (-b0,2*b0/a0*y[j]-2*b0)) and between(z[k], (2*b0/a0*y[j]-2*b0-W_l2,-2*b0/a0*y[j]+2*b0+W_l2)))):
fun_out[j,k]=fun_in[j,k]
if (faces_l2=='5').any():
if (faces_l1=='5').any() and ((between(z[k], (-b0,-2*b0/a0*y[j]-2*b0-W_l1)) and between(z[k], (-2*b0/a0*y[j]-2*b0-W_l1-W_l2,2*b0/a0*y[j]+2*b0+W_l1+W_l2)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='5').any() and ((between(z[k], (-b0,-2*b0/a0*y[j]-2*b0)) and between(z[k], (-2*b0/a0*y[j]-2*b0-W_l2,2*b0/a0*y[j]+2*b0+W_l2)))):
fun_out[j,k]=fun_in[j,k]
if (faces_l2=='4').any():
if (faces_l1=='4').any() and ((between(y[j], (-a0/2-W_l1/2-W_l2/2,a0/2+W_l1/2+W_l2/2)) and between(z[k], (-b0-W_l1-W_l2,-b0)))):
fun_out[j,k]=fun_in[j,k]
elif not(faces_l1=='4').any() and ((between(y[j], (-a0/2-W_l2/2,a0/2+W_l2/2)) and between(z[k], (-b0-W_l2,-b0)))):
fun_out[j,k]=fun_in[j,k]
if change=='masked':
fun_out=np.ma.array(fun_out, mask=np.isnan(fun_out))
if len(N)==3:
fun_out=np.tile(fun_out,(Nx,1,1))
return (fun_out)
#%%
def interface(N,dis,width,faces,a0,b0):
"""
Find points close to the some nanowire facet (assuming an hexagonal cross-
section nanowire).
Parameters
----------
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
witdh: float
Width of the "close region" to the facet.
faces: arr
Which facets include in the search. Each facet is labeled with a
number from 1 to 6 (the upper one is 1, and the rest are numbered
clockwise). Each element of the array denotes with a string (e.g.
np.array(['1','2'])) if such facet is covered.
Returns
-------
sites: arr
Array with the
"""
L=np.array([(N[0]-1)*dis[0], (N[1]-1)*dis[1], (N[2]-1)*dis[2]])
x, y =np.linspace(-L[1]/2,L[1]/2,N[1]), np.linspace(-L[2]/2,L[2]/2,N[2])
fun_out=np.zeros(N[1::],dtype=int)
for i in range(N[1]):
for j in range(N[2]):
if (faces=='1').any() and ((between(x[i], (-a0/2,a0/2)) and between(y[j], (b0-width,b0)) and between(y[j], (-2*b0/a0*x[i],b0))and between(y[j], (2*b0/a0*x[i],b0)))):
fun_out[i,j]=1
elif (faces=='6').any() and ((between(y[j], (-2*b0/a0*x[i]+2*b0-width*b0/a0*2,2*b0/a0*x[i])) and between(y[j], (2*b0/a0*x[i]-2*b0-width,-2*b0/a0*x[i]+2*b0)) and between(y[j], (0,b0)) )):
fun_out[i,j]=1
elif (faces=='2').any() and ((between(y[j], (2*b0/a0*x[i]+2*b0-width*b0/a0*2,-2*b0/a0*x[i])) and between(y[j], (-2*b0/a0*x[i]-2*b0-width,2*b0/a0*x[i]+2*b0)) and between(y[j], (0,b0)) )):
fun_out[i,j]=1
elif (faces=='5').any() and ((between(y[j], (-b0,2*b0/a0*x[i]-2*b0+width*b0/a0*2)) and between(y[j], (2*b0/a0*x[i]-2*b0,-2*b0/a0*x[i]+2*b0+width)) and between(y[j], (-b0,0)) )):
fun_out[i,j]=1
elif (faces=='3').any() and ((between(y[j], (-b0,-2*b0/a0*x[i]-2*b0+width*b0/a0*2)) and between(y[j], (-2*b0/a0*x[i]-2*b0,2*b0/a0*x[i]+2*b0+width)) and between(y[j], (-b0,0)) )):
fun_out[i,j]=1
elif (faces=='4').any() and ((between(x[i], (-a0/2,a0/2)) and between(y[j], (-b0,-b0+width)))):
fun_out[i,j]=1
fun_out_end=np.zeros(N)
for i in range(N[0]):
fun_out_end[i,:,:]=fun_out
return fun_out_end
#%%
def H_rectangular2hexagonal(H,N,dis,BdG='no',output='H',m=0,sparse='yes'):
"""
Transform a Hamiltonian of a nanwoire with rectangular cross-section to a
nanowire with an hexagonal one.
Parameters
----------
H: arr
Hamiltonian with rectangular section.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: str
Whether the Hamiltonian has BdG symmetry.
m: int
Number of sites of the discretized Hamiltonian with the hexagonal
section.
output: str
Whether to return the Hamiltonian (output='H'), the number of sites
of the discretized Hamiltonian with the hexagonal section
(output='m_hex'), or the sites that are inside of the nanowire
section (output='sites').
Returns
-------
Depends on the parameter output.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
Nx, Ny, Nz = N[0], N[1], N[2]
Ly, Lz = dis[1]*Ny, dis[2]*Nz
y, z = np.linspace(-float(Ly)/2,float(Ly)/2,Ny), np.linspace(-float(Lz)/2,float(Lz)/2,Nz)
a0=float(Ly)/2
b0=a0*np.sin(np.pi/3)*(Lz/Ly)
l=0
if (output=='H'):
if m==0:
m=H_rectangular2hexagonal(H,N,dis,BdG=BdG,output='m_hex',m=0)
if BdG=='no':
if sparse=='yes':
H_del=scipy.sparse.dok_matrix((m,2*Nx*Ny*Nz),dtype=complex)
else:
H_del=np.zeros((m,2*Nx*Ny*Nz),dtype=complex)
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
H_del[l,2*(k+(j+i*Ny)*Nz)]=1
H_del[l+1,2*(k+(j+i*Ny)*Nz)+1]=1
l=l+2
elif BdG=='yes':
if sparse=='yes':
H_del=scipy.sparse.dok_matrix((m,4*Nx*Ny*Nz),dtype=complex)
else:
H_del=np.zeros((m,4*Nx*Ny*Nz),dtype=complex)
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
H_del[l,2*(k+(j+i*Ny)*Nz)]=1
H_del[l+1,2*(k+(j+i*Ny)*Nz)+1]=1
H_del[l+int(m/2),2*(k+(j+i*Ny)*Nz)+int(2*Nx*Ny*Nz)]=1
H_del[l+1+int(m/2),2*(k+(j+i*Ny)*Nz)+1+int(2*Nx*Ny*Nz)]=1
l=l+2
H=H_del.dot(H.dot(H_del.transpose()))
return (H)
elif (output=='m_hex'):
m=0
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
m=m+1
if BdG=='no':
m=m*2
elif BdG=='yes':
m=m*4
return (m)
elif (output=='sites'):
m=0
sites=np.array([])
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
if (between(z[k], (b0-dis[2],b0))):
sites=np.append(sites,m)
m=m+2
return (sites)
#%%
def U_rectangular2hexagonal(U_in,N,dis,BdG='no',m=0):
"""
Transform a wavefunction of a nanwoire with rectangular cross-section to a
nanowire with an hexagonal one, erasing to this end the elements of the
Hamiltonian outside the hexagonal section of the wire.
Parameters
----------
U_in: arr
Wavefunction of a nanowire with rectangular section.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: str
Whether the Hamiltonian has BdG symmetry.
m: int
Number of sites of the hexagonal cross-section nanowire. It can be
computed using the function Function.H_rectangular2hexagonal.
Returns
-------
U: arr
Wavefunction of a nanowire with hexagonal section.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
if scipy.sparse.issparse(U_in):
U_in=U_in.todense()
Nx, Ny, Nz = N[0], N[1], N[2]
Ly, Lz = dis[1]*Ny, dis[2]*Nz
y, z = np.linspace(-float(Ly)/2,float(Ly)/2,Ny), np.linspace(-float(Lz)/2,float(Lz)/2,Nz)
a0=float(Ly)/2
b0=a0*np.sin(np.pi/3)*(Lz/Ly)
n_eig=np.shape(U_in)[1]
l=0
if BdG=='no':
U=np.zeros((m,n_eig),dtype=complex)
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
U[l,:], U[l+1,:] = U_in[2*(k+(j+i*Ny)*Nz),:], U_in[2*(k+(j+i*Ny)*Nz)+1,:]
l=l+2
elif BdG=='yes':
U=np.zeros((m,n_eig),dtype=complex)
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
U[l,:], U[l+1,:] = U_in[2*(k+(j+i*Ny)*Nz),:], U_in[2*(k+(j+i*Ny)*Nz)+1,:]
U[l+int(m/2),:], U[l+1+int(m/2),:] = U_in[2*(k+(j+i*Ny)*Nz)+int(2*Nx*Ny*Nz),:], U_in[2*(k+(j+i*Ny)*Nz)+1+int(2*Nx*Ny*Nz),:]
l=l+2
U=scipy.sparse.dok_matrix(U)
return (U)
#%%
def U_hexagonal2rectangular(U_in,N,dis,BdG='no',space='position'):
"""
Transform a wavefunction of a nanwoire with hexagonal cross-section to a
nanowire with an rectangular one, filling with zeros the new elements
outside the hexagonal section of the wire.
Parameters
----------
U_in: arr
Wavefunction of a nanowire with hexagonal section.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: str
Whether the Hamiltonian has BdG symmetry.
space: str
Whether the wavefunction is in position space or momentum.
Returns
-------
U: arr
Wavefunction of a nanowire with rectangular section.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
if space=='momentum':
Nx, Ny, Nz = N[0], N[1], N[2]
m=len(U_in[:,0,0])
n_eig=len(U_in[0,:,0])
n_k=len(U_in[0,0,:])
if BdG=='no':
U_out = np.empty([2*Nx*Ny*Nz,int(n_eig),n_k],dtype=complex)
elif BdG=='yes':
U_out = np.empty([4*Nx*Ny*Nz,int(n_eig),n_k],dtype=complex)
Ly, Lz = dis[1]*Ny, dis[2]*Nz
y, z = np.linspace(-float(Ly)/2,float(Ly)/2,Ny), np.linspace(-float(Lz)/2,float(Lz)/2,Nz)
a0=float(Ly)/2
b0=a0*np.sin(np.pi/3)*(Lz/Ly)
l=0
if BdG=='no':
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
U_out[2*(k+(j+i*Ny)*Nz),:,:]=U_in[l,:,:]
U_out[2*(k+(j+i*Ny)*Nz)+1,:,:]=U_in[l+1,:,:]
l=l+2
else:
U_out[2*(k+(j+i*Ny)*Nz),:,:]=np.zeros((n_eig,n_k))
U_out[2*(k+(j+i*Ny)*Nz)+1,:,:]=np.zeros((n_eig,n_k))
elif BdG=='yes':
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0)) ):
U_out[2*(k+(j+i*Ny)*Nz),:,:]=U_in[l,:,:]
U_out[2*(k+(j+i*Ny)*Nz)+1,:,:]=U_in[l+1,:,:]
U_out[2*(k+(j+i*Ny)*Nz)+2*Nx*Ny*Nz,:,:]=U_in[l+int(m/2),:,:]
U_out[2*(k+(j+i*Ny)*Nz)+1+2*Nx*Ny*Nz,:,:]=U_in[l+1+int(m/2),:,:]
l=l+2
else:
U_out[2*(k+(j+i*Ny)*Nz),:,:]=np.zeros((n_eig,n_k))
U_out[2*(k+(j+i*Ny)*Nz)+1,:,:]=np.zeros((n_eig,n_k))
U_out[2*(k+(j+i*Ny)*Nz)+2*Nx*Ny*Nz,:,:]=np.zeros((n_eig,n_k))
U_out[2*(k+(j+i*Ny)*Nz)+1+2*Nx*Ny*Nz,:,:]=np.zeros((n_eig,n_k))
elif space=='position':
Nx, Ny, Nz = N[0], N[1], N[2]
m=len(U_in[:,0])
n_eig=len(U_in[0,:])
if BdG=='no':
U_out = np.empty([2*Nx*Ny*Nz,int(n_eig)],dtype=complex)
elif BdG=='yes':
U_out = np.empty([4*Nx*Ny*Nz,int(n_eig)],dtype=complex)
Ly, Lz = dis[1]*Ny, dis[2]*Nz
y, z = np.linspace(-float(Ly)/2,float(Ly)/2,Ny), np.linspace(-float(Lz)/2,float(Lz)/2,Nz)
a0=float(Ly)/2
b0=a0*np.sin(np.pi/3)*(Lz/Ly)
if scipy.sparse.issparse(U_in):
U_in=U_in.todense()
l=0
if BdG=='no':
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0))):
U_out[2*(k+(j+i*Ny)*Nz),:]=U_in[l,:]
U_out[2*(k+(j+i*Ny)*Nz)+1,:]=U_in[l+1,:]
l=l+2
else:
U_out[2*(k+(j+i*Ny)*Nz),:]=np.zeros((n_eig))
U_out[2*(k+(j+i*Ny)*Nz)+1,:]=np.zeros((n_eig))
elif BdG=='yes':
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
if (between(z[k], (-b0,b0)) and between(z[k],(2*b0/a0*y[j]-2*b0,-2*b0/a0*y[j]+2*b0)) and between(z[k],(-2*b0/a0*y[j]-2*b0,2*b0/a0*y[j]+2*b0))):
U_out[2*(k+(j+i*Ny)*Nz),:]=U_in[l,:]
U_out[2*(k+(j+i*Ny)*Nz)+1,:]=U_in[l+1,:]
U_out[2*(k+(j+i*Ny)*Nz)+2*Nx*Ny*Nz,:]=U_in[l+int(m/2),:]
U_out[2*(k+(j+i*Ny)*Nz)+1+2*Nx*Ny*Nz,:]=U_in[l+1+int(m/2),:]
l=l+2
else:
U_out[2*(k+(j+i*Ny)*Nz),:]=np.zeros((n_eig))
U_out[2*(k+(j+i*Ny)*Nz)+1,:]=np.zeros((n_eig))
U_out[2*(k+(j+i*Ny)*Nz)+2*Nx*Ny*Nz,:]=np.zeros((n_eig))
U_out[2*(k+(j+i*Ny)*Nz)+1+2*Nx*Ny*Nz,:]=np.zeros((n_eig))
return (U_out)
#%%
def H_rec2shape(H,shape,N,dis,BdG='no',output='H',m=0):
"""
Transform a Hamiltonian of a nanwoire with rectangular cross-section to a
nanowire with a different one.
Parameters
----------
H: arr
Hamiltonian with rectangular section.
shape: arr or str
Shape of the section. It can be a (Nx,Ny,Nz) or (Ny,Nz) array,
where each 0 element means that the corresponding site is not
part of the section, while 1 means it is; or it can be 'hexagonal',
what means that the section must be an hexagonal shape.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: {'yes','no'}
Whether the Hamiltonian has BdG symmetry.
output: {'H','m'}
Either to return the Hamiltonian (output='H') or the number of sites
of the discretized Hamiltonian with the desired shape
(output='m').
m: int
Number of sites of the discretized Hamiltonian with the desired
shape. If m=0, m is computed.
Returns
-------
Depends on the parameter output.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
if np.isscalar(shape) and shape=='hexagonal':
shape=np.ones(N)
shape=mask_hexagonal(shape,np.linspace(-N[1]*dis[1]/2,N[1]*dis[1]/2,N[1]),np.linspace(-N[2]*dis[2]/2,N[2]*dis[2]/2,N[2]),x=np.linspace(0,N[0]*dis[0],N[0]),change=0)
shape=shape.flatten()
if m==0:
m=len(shape[shape==1])
if BdG=='no':
m=m*2
elif BdG=='yes':
m=m*4
if scipy.sparse.issparse(H):
sparse='yes'
else:
sparse='no'
if (output=='H'):
if BdG=='no':
if sparse=='yes':
H_del=scipy.sparse.dok_matrix((m,2*np.prod(N)),dtype=complex)
else:
H_del=np.zeros((m,2*np.prod(N)),dtype=complex)
elif BdG=='yes':
if sparse=='yes':
H_del=scipy.sparse.dok_matrix((m,4*np.prod(N)),dtype=complex)
else:
H_del=np.zeros((m,4*np.prod(N)),dtype=complex)
j=0
for i in range(np.prod(N)):
if shape[i]==1:
H_del[j,2*i],H_del[j+1,2*i+1] = 1, 1
if BdG=='yes':
H_del[j+int(m/2),2*i+2*int(np.prod(N))],H_del[j+1+int(m/2),2*i+1+2*int(np.prod(N))] = 1, 1
j+=2
H=H_del.dot(H.dot(H_del.transpose()))
return (H)
elif (output=='m'):
return (m)
#%%
def U_rec2shape(U_in,shape,N,dis,BdG='no',m=0):
"""
Transform a wavefunction of a nanwoire with rectangular cross-section to a
nanowire with a different one, erasing to this end the elements of the
wavefunction outside the section of the wire.
Parameters
----------
U_in: arr
Wavefunction of a nanowire with rectangular section.
shape: arr or str
Shape of the section. It can be a (Nx,Ny,Nz) or (Ny,Nz) array,
where each np.nan element means that the corresponding site is not
part of the section; or it can be 'hexagonal', what means that the
section must be an hexagonal shape.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: str
Whether the Hamiltonian has BdG symmetry.
m: int
Number of sites of the discretized Hamiltonian with the desired
shape. If m=0, m is computed.
Returns
-------
U: arr
Wavefunction of a nanowire with hexagonal section.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
n_eig=np.shape(U_in)[1]
if m==0:
m=len(shape[shape==1])
if BdG=='no':
m=m*2
elif BdG=='yes':
m=m*4
if scipy.sparse.issparse(U_in):
sparse='yes'
U_in=U_in.todense()
else:
sparse='no'
if np.isscalar(shape) and shape=='hexagonal':
shape=np.ones(N)
shape=mask_hexagonal(shape,np.linspace(-N[1]*dis[1]/2,N[1]*dis[1]/2,N[1]),np.linspace(-N[2]*dis[2]/2,N[2]*dis[2]/2,N[2]),x=np.linspace(0,N[0]*dis[0],N[0]),change=0)
shape=shape.flatten()
shape=np.repeat(shape,2)
if BdG=='yes':
shape=np.tile(shape,2)
U=np.zeros((m,n_eig),dtype=complex)
U=U_in[shape==1,:]
if sparse=='yes':
U=scipy.sparse.dok_matrix(U)
return (U)
#%%
def U_shape2rec(U_in,shape,N,dis,BdG='no'):
"""
Transform a wavefunction of a nanwoire with an arbitrary cross-section to a
nanowire with an rectangular one, filling with zeros the new elements
outside the hexagonal section of the wire.
Parameters
----------
U_in: arr
Wavefunction of a nanowire with hexagonal section.
shape: arr or str
Shape of the section. It can be a (Nx,Ny,Nz) or (Ny,Nz) array,
where each np.nan element means that the corresponding site is not
part of the section; or it can be 'hexagonal', what means that the
section must be an hexagonal shape.
N: arr
Number of sites in each direction.
dis: arr
Discretization in each direction.
BdG: str
Whether the Hamiltonian has BdG symmetry.
space: str
Whether the wavefunction is in position space or momentum.
Returns
-------
U: arr
Wavefunction of a nanowire with rectangular section.
"""
if len(N)==2:
N=np.array([1,N[0],N[1]])
dis=np.array([0,dis[0],dis[1]])
n_eig=len(U_in[0,:])
if np.isscalar(shape) and shape=='hexagonal':
shape=np.ones(N)
shape=mask_hexagonal(shape,np.linspace(-N[1]*dis[1]/2,N[1]*dis[1]/2,N[1]),np.linspace(-N[2]*dis[2]/2,N[2]*dis[2]/2,N[2]),x=np.linspace(0,N[0]*dis[0],N[0]),change=0)
shape=shape.flatten()
shape=np.repeat(shape,2)
if BdG=='yes':
shape=np.tile(shape,2)
if scipy.sparse.issparse(U_in):
sparse='yes'
U_in=U_in.todense()
else:
sparse='no'
if BdG=='no':
U_out = np.zeros((2*np.prod(N),int(n_eig)),dtype=complex)
elif BdG=='yes':
U_out = np.zeros((4*np.prod(N),int(n_eig)),dtype=complex)
U_out[shape==1,:]=U_in
if sparse=='yes':
U_out=scipy.sparse.dok_matrix(U_out)
return (U_out)
#%% ############################# Spectrum
#%%
def prob(U,N,BdG='yes'):
"""
Obtains the probability density of a given wavefunction.
Parameters
----------
U: arr
Wavefunction in a 1D array.
N: int or arr
Number of sites. Each element of N[i] is the number of sites along
the direction i. If N is int, then there is just one dimension.
BdG: {'yes','no'}
Whether the wavefunction U is written in the BdG formalism.
Returns
-------
P: arr
Probability density of U with the same dimension than N.
"""
P=np.zeros(N)
if BdG=='no':
P=(np.abs(U[0::2])**2+np.abs(U[1::2])**2).reshape(N)
elif BdG=='yes':
P=(np.abs(U[0:2*np.prod(N):2])**2+np.abs(U[1:2*np.prod(N):2])**2+np.abs(U[2*np.prod(N)::2])**2+np.abs(U[2*np.prod(N)+1::2])**2).reshape(N)
return (P)
#%%
def Qtot(E,U,kT):
"""
Computes the total charge in the system.
Parameters
----------
E: scalar or arr
Energies.
U: arr
Eigenstates corresponding to each energy.
kT: scalar
Temperature (in units of energy).
Returns
-------
Qtot: scalar
Total charge in the system.
"""
den=np.dot(U,np.dot(np.diag(1/(1+np.exp(E/kT))),np.transpose(U)))
Qtot=np.sum(np.diag(den)[0:int(len(E)/2)])
return Qtot
#%%
def QM(Uodd,Ueven):
"""
Computes the Majorana charge (wavefunction overlap).
Parameters
----------
Uodd: arr
Eigenstate of the odd-parity Majorana state.
Uevev: arr
Eigenstate of the even-parity Majorana state.
Returns
-------
QM: scalar
Majorana charge (overlap between U_L and U_R).
"""
QM = np.absolute(np.dot(Uodd+Ueven, -1j*(Uodd-Ueven)))
return QM
#%%
def Density_Matrix(E,U,kT):
"""
Computes the density matrix of the system.
Parameters
----------
E: scalar or arr
Energies.
U: arr
Eigenstates corresponding to each energy.
kT: scalar
Temperature (in units of energy).
Returns
-------
den: arr
Density matrix of the system.
"""
den = np.dot(U, np.dot(np.diag(1 / (1 + np.exp(E / kT))), np.transpose(U)))
return den
#%%
def Density(E,U,N,kT):
"""
Computes the charge density of the system.
Parameters
----------
E: arr
Energies.
U: arr
Eigenstates.
N: arr
Number of sites in each direction.
kT: scalar
Temperature (in units of energy).
Returns
-------
den: arr (3D)
Charge density in each site..
"""
np.seterr(over='ignore')
if np.ndim(N)==1:
Nx=N[0]
Ny=N[1]
Nz=N[2]
n_eig=len(E)
den=np.zeros((Nx,Ny,Nz))
for i in range(Nx):
for j in range(Ny):
for k in range(Nz):
for m in range(n_eig):
den[i,j,k]=den[i,j,k]+(np.abs(U[2*(k+(i*Ny+j)*Nz),m])**2+np.abs(U[2*(k+(i*Ny+j)*Nz)+1,m])**2)*(1 / (1 + np.exp(E[m] / kT)))
#den = np.dot(U, np.transpose(U))
elif np.ndim(N)==0:
Nx=N
n_eig=len(E)
den=np.zeros((Nx))
for i in range(Nx):
for m in range(n_eig):
den[i]=den[i]+(np.abs(U[2*i,m])**2+np.abs(U[2*i+1,m])**2)*(1 / (1 + np.exp(E[m] / kT)))
#den = np.dot(U, np.transpose(U))
return den
#%%
def Density_momentum(E,U,k,N,kT):
"""
Charge densisty of an infnite system in one direction.
Parameters
----------
E: arr
Energies.
U: arr
Eigenstates.
k: arr
Momentum vector.
N: arr
Number of sites in each direction.
kT: scalar
Temperature (in units of energy).
Returns
-------
den: arr (2D)
Charge density in each site.
"""
Nx=N[0]
Ny=N[1]
Nz=N[2]
n_eig=len(E)
if np.ndim(U)==3:
den=np.zeros((Nx,Ny,Nz))
for i_x in range(Nx):
for i_y in range(Ny):
for i_z in range(Nz):
for i_E in range(n_eig):
den[i_x,i_y,i_z]=den[i_x,i_y,i_z]+(np.abs(U[int(2*(i_z+(i_y+i_x*Ny)*Nz)),i_E,0])**2+np.abs(U[int(2*(i_z+(i_y+i_x*Ny)*Nz))+1,i_E,0])**2)*denfromDOS(k,E[i_E,:],kT)
elif np.ndim(U)==2:
Nx=1
den=np.zeros((Ny,Nz))
i_x=0
for i_y in range(Ny):
for i_z in range(Nz):
for i_E in range(n_eig):
den[i_y,i_z]=den[i_y,i_z]+(np.abs(U[int(2*(i_z+(i_y+i_x*Ny)*Nz)),i_E])**2+np.abs(U[int(2*(i_z+(i_y+i_x*Ny)*Nz))+1,i_E])**2)*denfromDOS(k,E[i_E,:],kT)
return den
#%%
def k_F(mu,aR,Vz,m_eff=0.023):
"""
Find the Fermi momentum for a 1D infinite nanowire.
Parameters
----------
mu: scalar or arr
Chemical potential.
aR: scalar or arr
Spin-orbit coupling.
Vz: scalar or arr
Zeeman splitting.
m_eff: scalar or str
Effective mass.
Returns
-------
k_F: scalar or arr
Fermi momentum.
"""
if m_eff=='InAs':
m_eff=0.023
elif m_eff=='InSb':
m_eff=0.015
m=constants.m_e*m_eff
hbar=constants.hbar
mu,aR,Vz=mu*1e-3*constants.e,aR*1e-12*constants.e,Vz*1e-3*constants.e
kSO=m*aR/hbar**2
kZ=np.sqrt(2*m*Vz)/hbar
kmu_p=2*m*mu/hbar**2
kF=np.zeros(2)
kF[0]=np.sqrt(2*kSO**2+kmu_p+np.sqrt(4*kSO**4+kZ**4+4*kmu_p*kSO**2))
kF[1]=np.sqrt(2*kSO**2+kmu_p-np.sqrt(4*kSO**4+kZ**4+4*kmu_p*kSO**2))
kF=kF*1e-9
return (kF)
#%%
def DOS(k,E):
"""
Density of states of a 1D infinite nanowire.
Parameters
----------
k: arr
momentum vector.
E: arr
Energies.
Returns
-------
DOS: arr
Density of states.
"""
DOS=np.abs(np.gradient(E,k))**(-1)/np.pi
DOS[0]=0
return(DOS)
#%%
def denfromDOS(k,E,kT):
"""
1D charge denisty of an infinite nanowire.
Parameters
----------
k: arr
momentum vector.
E: arr
Energies (in units of energy).
Returns
-------
DOS: arr
Density of states.
"""
np.seterr(over='ignore')
dos=DOS(k,E)
den=0
for i in range(len(E)-1):
den=den+dos[i]*(E[i+1]-E[i])*(1 / (1 + np.exp(E[i] / kT)))
if not(np.abs(k[0])==np.abs(k[-1])):
den=den*2
return (den)
#%%
def LDOS(P_n,E_n,E_sample,a_0=0.0):
"""
Local density of states as a function of the energies E_sample.
Parameters
----------
P_n: arr
Probability density of the wavefunction at a given point for
different eigensates.
E_n: arr
Corresponding energies.
E_sample: arr
Energies in which the LDOS is evaluated.
a_0: float
Dirac delta characteristic length. If a_0=0 perfect Dirac delta is
used, while otherwise it is used an analytical expression for the
Delta with a characteristic width.
Returns
-------
LDOS: arr
Local density of states for a given energies.
"""
n_n=len(E_n)
n_out=len(E_sample)
LDOS=np.zeros(n_out)
if a_0==0.0:
for i in range(n_out-1):
for j in range(n_n):
if (E_sample[i+1]>=E_n[j]) and (E_sample[i]<=E_n[j]):
LDOS[i]=LDOS[i]+P_n[j]
return(LDOS)
else:
if a_0=='none':
a_0=np.abs(E_sample[0]-E_sample[1])*4
def Dirac_delta(E,En,a_0):
return np.exp(-((E-En)/a_0)**2)/(np.sqrt(np.pi)*np.abs(a_0))
for i in range(n_out):
for j in range(n_n):
LDOS[i]=LDOS[i]+P_n[j]*Dirac_delta(E_sample[i],E_n[j],a_0)
return (LDOS)
#%%
def dIdV(LDOS,E_sample,kT):
"""
Differential conductance for a given energies E_sample.
Parameters
----------
LDOS: arr
Local density of states computed using Functions.LDOS.
E_sample: arr
Energies in which the dIdV (and LDOS) is evaluated.
kT: float
Temperature (in units of energy).
Returns
-------
dIdV: arr
Differential conductance for a given energies.
"""
def sech(x):
return 1.0/np.cosh(x)
n=len(E_sample)
dIdV=np.zeros(n)
for i in range(n):
for j in range(n):
dIdV[i]=dIdV[i]+LDOS[j]*sech((E_sample[i]-E_sample[j])/(2*kT))**2
return (dIdV)
#%% ############################# Others
#%%
def Chern_number(H_k,k_vec,N):
"""
Computes the Chern number of a 1D Hamiltonian in k-space.
Parameters
----------
H_k: arr
1D Hamiltonian in k-space. Each element H_k[:,:,i] is the
Hamiltonian evaluated at k_vec[i].
k_vec: arr
Momentum vector of the first Brillouin zone in which the
Hamiltonian is evaluated.
N: int
Number of sites in which the unit cell of the Hamiltonian is
discretized.
Returns
-------
Ch: int
Chern number of the given 1D Hamiltonian.
"""
Gamma=np.zeros((4*N,4*N),dtype=complex)
for i in range(N):
Gamma[2*i:2*i+2,2*i+2*N:2*i+2*N+2]=np.array([[1,0],[0,1]])
Gamma[2*i+2*N:2*i+2*N+2,2*i:2*i+2]=np.array([[1,0],[0,1]])
Ch=np.sign(pf.pfaffian(np.dot(Gamma,H_k[:,:,int((len(k_vec)-1)/2)])))*np.sign(pf.pfaffian(np.dot(Gamma,H_k[:,:,int(len(k_vec)-1)])))
return (Ch)
#%%
def rho_acc(x,y,z,den_acc_in,n_lattice,r_lattice,superlattice_type='none'):
"""
Computes the superficial charge density of a nanowire with hexagonal
section.
Parameters
----------
x,y,z: arr
Positions of the mesh of the nanowire section.
den_acc_in: scalar
Magnitude of the accumulation layer.
n_lattice: int
Number of superlattice cells.
r_lattice: float
Partial coverage of the SC.
superlattice_type: str
Whether the superlattice is on top, at the bottom, or there is no
superlattice (none).
Returns
-------
rho_acc: arr
Charge density inside the wire due to the charge accumulation layer.
"""
Nx, Ny, Nz = len(x), len(y), len(z)
Lx, Ly, Lz = x[Nx-1], y[Ny-1]*2, z[Nz-1]*2
a0=Ly/2
b0=a0*np.sin(np.pi/3)
dis=np.array([np.abs(x[0]-x[1]),np.abs(y[0]-y[1]),np.abs(z[0]-z[1])])
L_SC, L_0=Lx/n_lattice*r_lattice, Lx/n_lattice*(1-r_lattice)
den_acc_out=np.zeros((Nx,Ny,Nz))
if superlattice_type=='top':
den_acc_out[:,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,-b0)]=np.ones((Nx,arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
for j in range(Nx):
for i in range(n_lattice+1):
if (x[j]>=L_SC/2+i*(L_SC+L_0)) and (x[j]<=L_SC/2+L_0+i*(L_SC+L_0)):
den_acc_out[j,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,b0)]=np.ones((arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
elif superlattice_type=='bottom':
den_acc_out[:,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,b0)]=np.ones((Nx,arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
for j in range(Nx):
for i in range(n_lattice+1):
if (x[j]>=L_SC/2+i*(L_SC+L_0)) and (x[j]<=L_SC/2+L_0+i*(L_SC+L_0)):
den_acc_out[j,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,-b0)]=np.ones((arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
elif superlattice_type=='none':
den_acc_out[:,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,-b0)+1]=np.ones((Nx,arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
den_acc_out[:,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,b0)-1]=np.ones((Nx,arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
else:
for j in range(Nx):
for i in range(n_lattice+1):
if (x[j]>=L_SC/2+i*(L_SC+L_0)) and (x[j]<=L_SC/2+L_0+i*(L_SC+L_0)):
den_acc_out[j,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,-b0)]=np.ones((arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
den_acc_out[j,arg_isclose(y,-a0/2):arg_isclose(y,a0/2)+1,arg_isclose(z,b0)]=np.ones((arg_isclose(y,a0/2)-arg_isclose(y,-a0/2)+1))*den_acc_in
for k in range(Nz):
if (z[k]>=-b0) and (z[k]<=0):
den_acc_out[:,arg_isclose(2*b0/a0*y-2*b0,z[k]-dis[2])+1,k]=np.ones(Nx)*den_acc_in
den_acc_out[:,arg_isclose(-2*b0/a0*y-2*b0,z[k]-dis[2])-1,k]=np.ones(Nx)*den_acc_in
elif (z[k]<=b0) and (z[k]>=0):
den_acc_out[:,arg_isclose(2*b0/a0*y+2*b0,z[k]+dis[2])-1,k]=np.ones(Nx)*den_acc_in
den_acc_out[:,arg_isclose(-2*b0/a0*y+2*b0,z[k]+dis[2])+1,k]=np.ones(Nx)*den_acc_in
return (den_acc_out)
| [
"numpy.prod",
"numpy.sqrt",
"numpy.random.rand",
"numpy.argsort",
"numpy.array",
"numpy.sin",
"numpy.gradient",
"numpy.arange",
"numpy.repeat",
"numpy.isscalar",
"numpy.ndim",
"numpy.exp",
"numpy.linspace",
"numpy.dot",
"numpy.concatenate",
"numpy.meshgrid",
"numpy.abs",
"numpy.til... | [((1494, 1518), 'numpy.seterr', 'np.seterr', ([], {'over': '"""ignore"""'}), "(over='ignore')\n", (1503, 1518), True, 'import numpy as np\n'), ((1523, 1549), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (1532, 1549), True, 'import numpy as np\n'), ((2929, 2956), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (2938, 2956), True, 'import numpy as np\n'), ((7974, 7988), 'numpy.isscalar', 'np.isscalar', (['U'], {}), '(U)\n', (7985, 7988), True, 'import numpy as np\n'), ((10334, 10348), 'numpy.isscalar', 'np.isscalar', (['k'], {}), '(k)\n', (10345, 10348), True, 'import numpy as np\n'), ((23219, 23233), 'numpy.isscalar', 'np.isscalar', (['x'], {}), '(x)\n', (23230, 23233), True, 'import numpy as np\n'), ((25248, 25266), 'numpy.array', 'np.array', (["['wire']"], {}), "(['wire'])\n", (25256, 25266), True, 'import numpy as np\n'), ((25296, 25308), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (25304, 25308), True, 'import numpy as np\n'), ((25318, 25330), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (25326, 25330), True, 'import numpy as np\n'), ((27229, 27245), 'numpy.isscalar', 'np.isscalar', (['W_w'], {}), '(W_w)\n', (27240, 27245), True, 'import numpy as np\n'), ((27577, 27595), 'numpy.zeros', 'np.zeros', (['(Ny, Nz)'], {}), '((Ny, Nz))\n', (27585, 27595), True, 'import numpy as np\n'), ((33181, 33254), 'numpy.array', 'np.array', (['[(N[0] - 1) * dis[0], (N[1] - 1) * dis[1], (N[2] - 1) * dis[2]]'], {}), '([(N[0] - 1) * dis[0], (N[1] - 1) * dis[1], (N[2] - 1) * dis[2]])\n', (33189, 33254), True, 'import numpy as np\n'), ((33333, 33359), 'numpy.zeros', 'np.zeros', (['N[1:]'], {'dtype': 'int'}), '(N[1:], dtype=int)\n', (33341, 33359), True, 'import numpy as np\n'), ((34688, 34699), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (34696, 34699), True, 'import numpy as np\n'), ((51544, 51563), 'numpy.repeat', 'np.repeat', (['shape', '(2)'], {}), '(shape, 2)\n', (51553, 51563), True, 'import numpy as np\n'), ((51624, 51659), 'numpy.zeros', 'np.zeros', (['(m, n_eig)'], {'dtype': 'complex'}), '((m, n_eig), dtype=complex)\n', (51632, 51659), True, 'import numpy as np\n'), ((53348, 53367), 'numpy.repeat', 'np.repeat', (['shape', '(2)'], {}), '(shape, 2)\n', (53357, 53367), True, 'import numpy as np\n'), ((54531, 54542), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (54539, 54542), True, 'import numpy as np\n'), ((56877, 56901), 'numpy.seterr', 'np.seterr', ([], {'over': '"""ignore"""'}), "(over='ignore')\n", (56886, 56901), True, 'import numpy as np\n'), ((59934, 59945), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (59942, 59945), True, 'import numpy as np\n'), ((60887, 60911), 'numpy.seterr', 'np.seterr', ([], {'over': '"""ignore"""'}), "(over='ignore')\n", (60896, 60911), True, 'import numpy as np\n'), ((62005, 62020), 'numpy.zeros', 'np.zeros', (['n_out'], {}), '(n_out)\n', (62013, 62020), True, 'import numpy as np\n'), ((63231, 63242), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (63239, 63242), True, 'import numpy as np\n'), ((64118, 64157), 'numpy.zeros', 'np.zeros', (['(4 * N, 4 * N)'], {'dtype': 'complex'}), '((4 * N, 4 * N), dtype=complex)\n', (64126, 64157), True, 'import numpy as np\n'), ((65620, 65642), 'numpy.zeros', 'np.zeros', (['(Nx, Ny, Nz)'], {}), '((Nx, Ny, Nz))\n', (65628, 65642), True, 'import numpy as np\n'), ((8404, 8417), 'numpy.argsort', 'np.argsort', (['E'], {}), '(E)\n', (8414, 8417), True, 'import numpy as np\n'), ((8911, 8924), 'numpy.argsort', 'np.argsort', (['E'], {}), '(E)\n', (8921, 8924), True, 'import numpy as np\n'), ((9360, 9372), 'numpy.ndim', 'np.ndim', (['vec'], {}), '(vec)\n', (9367, 9372), True, 'import numpy as np\n'), ((11340, 11359), 'numpy.concatenate', 'np.concatenate', (['arg'], {}), '(arg)\n', (11354, 11359), True, 'import numpy as np\n'), ((12508, 12525), 'numpy.abs', 'np.abs', (['(vec - val)'], {}), '(vec - val)\n', (12514, 12525), True, 'import numpy as np\n'), ((13747, 13779), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {'indexing': '"""ij"""'}), "(x, y, indexing='ij')\n", (13758, 13779), True, 'import numpy as np\n'), ((22076, 22088), 'numpy.ndim', 'np.ndim', (['phi'], {}), '(phi)\n', (22083, 22088), True, 'import numpy as np\n'), ((22114, 22154), 'numpy.gradient', 'np.gradient', (['phi', 'dis[0]', 'dis[1]', 'dis[2]'], {}), '(phi, dis[0], dis[1], dis[2])\n', (22125, 22154), True, 'import numpy as np\n'), ((22168, 22190), 'numpy.array', 'np.array', (['[Ex, Ey, Ez]'], {}), '([Ex, Ey, Ez])\n', (22176, 22190), True, 'import numpy as np\n'), ((27121, 27181), 'numpy.linspace', 'np.linspace', (['(-(Ny - 1) * dis_y / 2)', '((Ny - 1) * dis_y / 2)', 'Ny'], {}), '(-(Ny - 1) * dis_y / 2, (Ny - 1) * dis_y / 2, Ny)\n', (27132, 27181), True, 'import numpy as np\n'), ((27169, 27229), 'numpy.linspace', 'np.linspace', (['(-(Nz - 1) * dis_z / 2)', '((Nz - 1) * dis_z / 2)', 'Nz'], {}), '(-(Nz - 1) * dis_z / 2, (Nz - 1) * dis_z / 2, Nz)\n', (27180, 27229), True, 'import numpy as np\n'), ((27490, 27505), 'numpy.array', 'np.array', (["['0']"], {}), "(['0'])\n", (27498, 27505), True, 'import numpy as np\n'), ((27548, 27563), 'numpy.array', 'np.array', (["['0']"], {}), "(['0'])\n", (27556, 27563), True, 'import numpy as np\n'), ((32261, 32289), 'numpy.tile', 'np.tile', (['fun_out', '(Nx, 1, 1)'], {}), '(fun_out, (Nx, 1, 1))\n', (32268, 32289), True, 'import numpy as np\n'), ((33253, 33291), 'numpy.linspace', 'np.linspace', (['(-L[1] / 2)', '(L[1] / 2)', 'N[1]'], {}), '(-L[1] / 2, L[1] / 2, N[1])\n', (33264, 33291), True, 'import numpy as np\n'), ((33287, 33325), 'numpy.linspace', 'np.linspace', (['(-L[2] / 2)', '(L[2] / 2)', 'N[2]'], {}), '(-L[2] / 2, L[2] / 2, N[2])\n', (33298, 33325), True, 'import numpy as np\n'), ((35879, 35904), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (35887, 35904), True, 'import numpy as np\n'), ((35915, 35944), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (35923, 35944), True, 'import numpy as np\n'), ((39784, 39809), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (39792, 39809), True, 'import numpy as np\n'), ((39820, 39849), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (39828, 39849), True, 'import numpy as np\n'), ((40159, 40173), 'numpy.shape', 'np.shape', (['U_in'], {}), '(U_in)\n', (40167, 40173), True, 'import numpy as np\n'), ((40218, 40253), 'numpy.zeros', 'np.zeros', (['(m, n_eig)'], {'dtype': 'complex'}), '((m, n_eig), dtype=complex)\n', (40226, 40253), True, 'import numpy as np\n'), ((42230, 42255), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (42238, 42255), True, 'import numpy as np\n'), ((42266, 42295), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (42274, 42295), True, 'import numpy as np\n'), ((48177, 48202), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (48185, 48202), True, 'import numpy as np\n'), ((48213, 48242), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (48221, 48242), True, 'import numpy as np\n'), ((48253, 48271), 'numpy.isscalar', 'np.isscalar', (['shape'], {}), '(shape)\n', (48264, 48271), True, 'import numpy as np\n'), ((48310, 48320), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (48317, 48320), True, 'import numpy as np\n'), ((50905, 50930), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (50913, 50930), True, 'import numpy as np\n'), ((50941, 50970), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (50949, 50970), True, 'import numpy as np\n'), ((50980, 50994), 'numpy.shape', 'np.shape', (['U_in'], {}), '(U_in)\n', (50988, 50994), True, 'import numpy as np\n'), ((51267, 51285), 'numpy.isscalar', 'np.isscalar', (['shape'], {}), '(shape)\n', (51278, 51285), True, 'import numpy as np\n'), ((51324, 51334), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (51331, 51334), True, 'import numpy as np\n'), ((51596, 51613), 'numpy.tile', 'np.tile', (['shape', '(2)'], {}), '(shape, 2)\n', (51603, 51613), True, 'import numpy as np\n'), ((52965, 52990), 'numpy.array', 'np.array', (['[1, N[0], N[1]]'], {}), '([1, N[0], N[1]])\n', (52973, 52990), True, 'import numpy as np\n'), ((53001, 53030), 'numpy.array', 'np.array', (['[0, dis[0], dis[1]]'], {}), '([0, dis[0], dis[1]])\n', (53009, 53030), True, 'import numpy as np\n'), ((53071, 53089), 'numpy.isscalar', 'np.isscalar', (['shape'], {}), '(shape)\n', (53082, 53089), True, 'import numpy as np\n'), ((53128, 53138), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (53135, 53138), True, 'import numpy as np\n'), ((53400, 53417), 'numpy.tile', 'np.tile', (['shape', '(2)'], {}), '(shape, 2)\n', (53407, 53417), True, 'import numpy as np\n'), ((55829, 55873), 'numpy.dot', 'np.dot', (['(Uodd + Ueven)', '(-1.0j * (Uodd - Ueven))'], {}), '(Uodd + Ueven, -1.0j * (Uodd - Ueven))\n', (55835, 55873), True, 'import numpy as np\n'), ((56914, 56924), 'numpy.ndim', 'np.ndim', (['N'], {}), '(N)\n', (56921, 56924), True, 'import numpy as np\n'), ((57015, 57037), 'numpy.zeros', 'np.zeros', (['(Nx, Ny, Nz)'], {}), '((Nx, Ny, Nz))\n', (57023, 57037), True, 'import numpy as np\n'), ((58345, 58355), 'numpy.ndim', 'np.ndim', (['U'], {}), '(U)\n', (58352, 58355), True, 'import numpy as np\n'), ((58372, 58394), 'numpy.zeros', 'np.zeros', (['(Nx, Ny, Nz)'], {}), '((Nx, Ny, Nz))\n', (58380, 58394), True, 'import numpy as np\n'), ((59876, 59895), 'numpy.sqrt', 'np.sqrt', (['(2 * m * Vz)'], {}), '(2 * m * Vz)\n', (59883, 59895), True, 'import numpy as np\n'), ((64218, 64244), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (64226, 64244), True, 'import numpy as np\n'), ((64285, 64311), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (64293, 64311), True, 'import numpy as np\n'), ((65444, 65461), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (65450, 65461), True, 'import numpy as np\n'), ((1567, 1588), 'numpy.exp', 'np.exp', (['((E - mu) / kT)'], {}), '((E - mu) / kT)\n', (1573, 1588), True, 'import numpy as np\n'), ((3617, 3640), 'numpy.nan_to_num', 'np.nan_to_num', (['den_e', '(0)'], {}), '(den_e, 0)\n', (3630, 3640), True, 'import numpy as np\n'), ((4001, 4024), 'numpy.nan_to_num', 'np.nan_to_num', (['den_e', '(0)'], {}), '(den_e, 0)\n', (4014, 4024), True, 'import numpy as np\n'), ((10417, 10446), 'numpy.arange', 'np.arange', (['init', 'N'], {'step': 'step'}), '(init, N, step=step)\n', (10426, 10446), True, 'import numpy as np\n'), ((10445, 10474), 'numpy.arange', 'np.arange', (['init', 'N'], {'step': 'step'}), '(init, N, step=step)\n', (10454, 10474), True, 'import numpy as np\n'), ((11108, 11120), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (11116, 11120), True, 'import numpy as np\n'), ((11122, 11134), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (11130, 11134), True, 'import numpy as np\n'), ((11191, 11220), 'numpy.append', 'np.append', (['index_1', 'arg[i][0]'], {}), '(index_1, arg[i][0])\n', (11200, 11220), True, 'import numpy as np\n'), ((11242, 11271), 'numpy.append', 'np.append', (['index_2', 'arg[i][1]'], {}), '(index_2, arg[i][1])\n', (11251, 11271), True, 'import numpy as np\n'), ((13599, 13637), 'numpy.linspace', 'np.linspace', (['(-L[1] / 2)', '(L[1] / 2)', 'N[0]'], {}), '(-L[1] / 2, L[1] / 2, N[0])\n', (13610, 13637), True, 'import numpy as np\n'), ((13633, 13671), 'numpy.linspace', 'np.linspace', (['(-L[0] / 2)', '(L[0] / 2)', 'N[1]'], {}), '(-L[0] / 2, L[0] / 2, N[1])\n', (13644, 13671), True, 'import numpy as np\n'), ((22008, 22027), 'numpy.abs', 'np.abs', (['(x[1] - x[0])'], {}), '(x[1] - x[0])\n', (22014, 22027), True, 'import numpy as np\n'), ((22026, 22045), 'numpy.abs', 'np.abs', (['(y[1] - y[0])'], {}), '(y[1] - y[0])\n', (22032, 22045), True, 'import numpy as np\n'), ((22044, 22063), 'numpy.abs', 'np.abs', (['(z[1] - z[0])'], {}), '(z[1] - z[0])\n', (22050, 22063), True, 'import numpy as np\n'), ((22204, 22216), 'numpy.ndim', 'np.ndim', (['phi'], {}), '(phi)\n', (22211, 22216), True, 'import numpy as np\n'), ((22238, 22270), 'numpy.gradient', 'np.gradient', (['phi', 'dis[1]', 'dis[2]'], {}), '(phi, dis[1], dis[2])\n', (22249, 22270), True, 'import numpy as np\n'), ((22285, 22303), 'numpy.array', 'np.array', (['[Ey, Ez]'], {}), '([Ey, Ez])\n', (22293, 22303), True, 'import numpy as np\n'), ((24015, 24033), 'numpy.zeros', 'np.zeros', (['(Ny, Nz)'], {}), '((Ny, Nz))\n', (24023, 24033), True, 'import numpy as np\n'), ((24626, 24643), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (24632, 24643), True, 'import numpy as np\n'), ((27322, 27339), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (27328, 27339), True, 'import numpy as np\n'), ((27360, 27376), 'numpy.isscalar', 'np.isscalar', (['W_w'], {}), '(W_w)\n', (27371, 27376), True, 'import numpy as np\n'), ((36143, 36160), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (36149, 36160), True, 'import numpy as np\n'), ((40125, 40142), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (40131, 40142), True, 'import numpy as np\n'), ((40697, 40732), 'numpy.zeros', 'np.zeros', (['(m, n_eig)'], {'dtype': 'complex'}), '((m, n_eig), dtype=complex)\n', (40705, 40732), True, 'import numpy as np\n'), ((48356, 48412), 'numpy.linspace', 'np.linspace', (['(-N[1] * dis[1] / 2)', '(N[1] * dis[1] / 2)', 'N[1]'], {}), '(-N[1] * dis[1] / 2, N[1] * dis[1] / 2, N[1])\n', (48367, 48412), True, 'import numpy as np\n'), ((48403, 48459), 'numpy.linspace', 'np.linspace', (['(-N[2] * dis[2] / 2)', '(N[2] * dis[2] / 2)', 'N[2]'], {}), '(-N[2] * dis[2] / 2, N[2] * dis[2] / 2, N[2])\n', (48414, 48459), True, 'import numpy as np\n'), ((49272, 49282), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (49279, 49282), True, 'import numpy as np\n'), ((51370, 51426), 'numpy.linspace', 'np.linspace', (['(-N[1] * dis[1] / 2)', '(N[1] * dis[1] / 2)', 'N[1]'], {}), '(-N[1] * dis[1] / 2, N[1] * dis[1] / 2, N[1])\n', (51381, 51426), True, 'import numpy as np\n'), ((51417, 51473), 'numpy.linspace', 'np.linspace', (['(-N[2] * dis[2] / 2)', '(N[2] * dis[2] / 2)', 'N[2]'], {}), '(-N[2] * dis[2] / 2, N[2] * dis[2] / 2, N[2])\n', (51428, 51473), True, 'import numpy as np\n'), ((53174, 53230), 'numpy.linspace', 'np.linspace', (['(-N[1] * dis[1] / 2)', '(N[1] * dis[1] / 2)', 'N[1]'], {}), '(-N[1] * dis[1] / 2, N[1] * dis[1] / 2, N[1])\n', (53185, 53230), True, 'import numpy as np\n'), ((53221, 53277), 'numpy.linspace', 'np.linspace', (['(-N[2] * dis[2] / 2)', '(N[2] * dis[2] / 2)', 'N[2]'], {}), '(-N[2] * dis[2] / 2, N[2] * dis[2] / 2, N[2])\n', (53232, 53277), True, 'import numpy as np\n'), ((55310, 55325), 'numpy.transpose', 'np.transpose', (['U'], {}), '(U)\n', (55322, 55325), True, 'import numpy as np\n'), ((55344, 55356), 'numpy.diag', 'np.diag', (['den'], {}), '(den)\n', (55351, 55356), True, 'import numpy as np\n'), ((56376, 56391), 'numpy.transpose', 'np.transpose', (['U'], {}), '(U)\n', (56388, 56391), True, 'import numpy as np\n'), ((57404, 57414), 'numpy.ndim', 'np.ndim', (['N'], {}), '(N)\n', (57411, 57414), True, 'import numpy as np\n'), ((57470, 57482), 'numpy.zeros', 'np.zeros', (['Nx'], {}), '(Nx)\n', (57478, 57482), True, 'import numpy as np\n'), ((58737, 58747), 'numpy.ndim', 'np.ndim', (['U'], {}), '(U)\n', (58744, 58747), True, 'import numpy as np\n'), ((58777, 58795), 'numpy.zeros', 'np.zeros', (['(Ny, Nz)'], {}), '((Ny, Nz))\n', (58785, 58795), True, 'import numpy as np\n'), ((59979, 60033), 'numpy.sqrt', 'np.sqrt', (['(4 * kSO ** 4 + kZ ** 4 + 4 * kmu_p * kSO ** 2)'], {}), '(4 * kSO ** 4 + kZ ** 4 + 4 * kmu_p * kSO ** 2)\n', (59986, 60033), True, 'import numpy as np\n'), ((60052, 60106), 'numpy.sqrt', 'np.sqrt', (['(4 * kSO ** 4 + kZ ** 4 + 4 * kmu_p * kSO ** 2)'], {}), '(4 * kSO ** 4 + kZ ** 4 + 4 * kmu_p * kSO ** 2)\n', (60059, 60106), True, 'import numpy as np\n'), ((61066, 61078), 'numpy.abs', 'np.abs', (['k[0]'], {}), '(k[0])\n', (61072, 61078), True, 'import numpy as np\n'), ((61080, 61093), 'numpy.abs', 'np.abs', (['k[-1]'], {}), '(k[-1])\n', (61086, 61093), True, 'import numpy as np\n'), ((63186, 63196), 'numpy.cosh', 'np.cosh', (['x'], {}), '(x)\n', (63193, 63196), True, 'import numpy as np\n'), ((65478, 65497), 'numpy.abs', 'np.abs', (['(x[0] - x[1])'], {}), '(x[0] - x[1])\n', (65484, 65497), True, 'import numpy as np\n'), ((65496, 65515), 'numpy.abs', 'np.abs', (['(y[0] - y[1])'], {}), '(y[0] - y[1])\n', (65502, 65515), True, 'import numpy as np\n'), ((65514, 65533), 'numpy.abs', 'np.abs', (['(z[0] - z[1])'], {}), '(z[0] - z[1])\n', (65520, 65533), True, 'import numpy as np\n'), ((4437, 4470), 'numpy.nan_to_num', 'np.nan_to_num', (['(den_hh + den_lh)', '(0)'], {}), '(den_hh + den_lh, 0)\n', (4450, 4470), True, 'import numpy as np\n'), ((5232, 5265), 'numpy.nan_to_num', 'np.nan_to_num', (['(den_hh + den_lh)', '(0)'], {}), '(den_hh + den_lh, 0)\n', (5245, 5265), True, 'import numpy as np\n'), ((8065, 8078), 'numpy.argsort', 'np.argsort', (['E'], {}), '(E)\n', (8075, 8078), True, 'import numpy as np\n'), ((8543, 8556), 'numpy.argsort', 'np.argsort', (['E'], {}), '(E)\n', (8553, 8556), True, 'import numpy as np\n'), ((10505, 10538), 'numpy.arange', 'np.arange', (['init', '(N - k)'], {'step': 'step'}), '(init, N - k, step=step)\n', (10514, 10538), True, 'import numpy as np\n'), ((13688, 13707), 'numpy.abs', 'np.abs', (['(x[1] - x[0])'], {}), '(x[1] - x[0])\n', (13694, 13707), True, 'import numpy as np\n'), ((13706, 13725), 'numpy.abs', 'np.abs', (['(y[1] - y[0])'], {}), '(y[1] - y[0])\n', (13712, 13725), True, 'import numpy as np\n'), ((13869, 13880), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (13877, 13880), True, 'import numpy as np\n'), ((13882, 13893), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (13890, 13893), True, 'import numpy as np\n'), ((15123, 15146), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (15132, 15146), True, 'import numpy as np\n'), ((22318, 22330), 'numpy.ndim', 'np.ndim', (['phi'], {}), '(phi)\n', (22325, 22330), True, 'import numpy as np\n'), ((22348, 22369), 'numpy.gradient', 'np.gradient', (['phi', 'dis'], {}), '(phi, dis)\n', (22359, 22369), True, 'import numpy as np\n'), ((23384, 23401), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (23390, 23401), True, 'import numpy as np\n'), ((23966, 23983), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (23972, 23983), True, 'import numpy as np\n'), ((27423, 27440), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (27429, 27440), True, 'import numpy as np\n'), ((32194, 32211), 'numpy.isnan', 'np.isnan', (['fun_out'], {}), '(fun_out)\n', (32202, 32211), True, 'import numpy as np\n'), ((36472, 36518), 'numpy.zeros', 'np.zeros', (['(m, 2 * Nx * Ny * Nz)'], {'dtype': 'complex'}), '((m, 2 * Nx * Ny * Nz), dtype=complex)\n', (36480, 36518), True, 'import numpy as np\n'), ((38360, 38372), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (38368, 38372), True, 'import numpy as np\n'), ((42814, 42831), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (42820, 42831), True, 'import numpy as np\n'), ((48452, 48487), 'numpy.linspace', 'np.linspace', (['(0)', '(N[0] * dis[0])', 'N[0]'], {}), '(0, N[0] * dis[0], N[0])\n', (48463, 48487), True, 'import numpy as np\n'), ((51466, 51501), 'numpy.linspace', 'np.linspace', (['(0)', '(N[0] * dis[0])', 'N[0]'], {}), '(0, N[0] * dis[0], N[0])\n', (51477, 51501), True, 'import numpy as np\n'), ((53270, 53305), 'numpy.linspace', 'np.linspace', (['(0)', '(N[0] * dis[0])', 'N[0]'], {}), '(0, N[0] * dis[0], N[0])\n', (53281, 53305), True, 'import numpy as np\n'), ((60471, 60488), 'numpy.gradient', 'np.gradient', (['E', 'k'], {}), '(E, k)\n', (60482, 60488), True, 'import numpy as np\n'), ((62302, 62335), 'numpy.abs', 'np.abs', (['(E_sample[0] - E_sample[1])'], {}), '(E_sample[0] - E_sample[1])\n', (62308, 62335), True, 'import numpy as np\n'), ((62399, 62429), 'numpy.exp', 'np.exp', (['(-((E - En) / a_0) ** 2)'], {}), '(-((E - En) / a_0) ** 2)\n', (62405, 62429), True, 'import numpy as np\n'), ((67627, 67638), 'numpy.ones', 'np.ones', (['Nx'], {}), '(Nx)\n', (67634, 67638), True, 'import numpy as np\n'), ((67722, 67733), 'numpy.ones', 'np.ones', (['Nx'], {}), '(Nx)\n', (67729, 67733), True, 'import numpy as np\n'), ((5484, 5507), 'numpy.nan_to_num', 'np.nan_to_num', (['den_e', '(0)'], {}), '(den_e, 0)\n', (5497, 5507), True, 'import numpy as np\n'), ((5869, 5902), 'numpy.nan_to_num', 'np.nan_to_num', (['(den_hh + den_lh)', '(0)'], {}), '(den_hh + den_lh, 0)\n', (5882, 5902), True, 'import numpy as np\n'), ((6291, 6314), 'numpy.nan_to_num', 'np.nan_to_num', (['den_e', '(0)'], {}), '(den_e, 0)\n', (6304, 6314), True, 'import numpy as np\n'), ((7058, 7091), 'numpy.nan_to_num', 'np.nan_to_num', (['(den_hh + den_lh)', '(0)'], {}), '(den_hh + den_lh, 0)\n', (7071, 7091), True, 'import numpy as np\n'), ((10535, 10568), 'numpy.arange', 'np.arange', (['init', '(N - k)'], {'step': 'step'}), '(init, N - k, step=step)\n', (10544, 10568), True, 'import numpy as np\n'), ((10631, 10664), 'numpy.arange', 'np.arange', (['init', '(N + k)'], {'step': 'step'}), '(init, N + k, step=step)\n', (10640, 10664), True, 'import numpy as np\n'), ((13918, 13929), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (13926, 13929), True, 'import numpy as np\n'), ((13930, 13941), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (13938, 13941), True, 'import numpy as np\n'), ((15161, 15172), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (15169, 15172), True, 'import numpy as np\n'), ((15174, 15185), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (15182, 15185), True, 'import numpy as np\n'), ((24476, 24493), 'numpy.isnan', 'np.isnan', (['fun_out'], {}), '(fun_out)\n', (24484, 24493), True, 'import numpy as np\n'), ((25136, 25153), 'numpy.isnan', 'np.isnan', (['fun_out'], {}), '(fun_out)\n', (25144, 25153), True, 'import numpy as np\n'), ((37146, 37192), 'numpy.zeros', 'np.zeros', (['(m, 4 * Nx * Ny * Nz)'], {'dtype': 'complex'}), '((m, 4 * Nx * Ny * Nz), dtype=complex)\n', (37154, 37192), True, 'import numpy as np\n'), ((45033, 45050), 'numpy.sin', 'np.sin', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (45039, 45050), True, 'import numpy as np\n'), ((53584, 53594), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (53591, 53594), True, 'import numpy as np\n'), ((62425, 62439), 'numpy.sqrt', 'np.sqrt', (['np.pi'], {}), '(np.pi)\n', (62432, 62439), True, 'import numpy as np\n'), ((62440, 62451), 'numpy.abs', 'np.abs', (['a_0'], {}), '(a_0)\n', (62446, 62451), True, 'import numpy as np\n'), ((67855, 67866), 'numpy.ones', 'np.ones', (['Nx'], {}), '(Nx)\n', (67862, 67866), True, 'import numpy as np\n'), ((67950, 67961), 'numpy.ones', 'np.ones', (['Nx'], {}), '(Nx)\n', (67957, 67961), True, 'import numpy as np\n'), ((8148, 8175), 'numpy.abs', 'np.abs', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8154, 8175), True, 'import numpy as np\n'), ((8184, 8212), 'numpy.sign', 'np.sign', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8191, 8212), True, 'import numpy as np\n'), ((8655, 8682), 'numpy.abs', 'np.abs', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8661, 8682), True, 'import numpy as np\n'), ((8691, 8719), 'numpy.sign', 'np.sign', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8698, 8719), True, 'import numpy as np\n'), ((10599, 10632), 'numpy.arange', 'np.arange', (['init', '(N + k)'], {'step': 'step'}), '(init, N + k, step=step)\n', (10608, 10632), True, 'import numpy as np\n'), ((14727, 14758), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (14733, 14758), True, 'import numpy as np\n'), ((14902, 14933), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j + 1])'], {}), '(ym[i, j] - ym[i, j + 1])\n', (14908, 14933), True, 'import numpy as np\n'), ((15210, 15221), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (15218, 15221), True, 'import numpy as np\n'), ((15222, 15233), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (15230, 15233), True, 'import numpy as np\n'), ((16489, 16500), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (16497, 16500), True, 'import numpy as np\n'), ((16502, 16513), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (16510, 16513), True, 'import numpy as np\n'), ((53671, 53681), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (53678, 53681), True, 'import numpy as np\n'), ((54577, 54592), 'numpy.abs', 'np.abs', (['U[0::2]'], {}), '(U[0::2])\n', (54583, 54592), True, 'import numpy as np\n'), ((54596, 54611), 'numpy.abs', 'np.abs', (['U[1::2]'], {}), '(U[1::2])\n', (54602, 54611), True, 'import numpy as np\n'), ((55295, 55309), 'numpy.exp', 'np.exp', (['(E / kT)'], {}), '(E / kT)\n', (55301, 55309), True, 'import numpy as np\n'), ((56358, 56372), 'numpy.exp', 'np.exp', (['(E / kT)'], {}), '(E / kT)\n', (56364, 56372), True, 'import numpy as np\n'), ((61026, 61043), 'numpy.exp', 'np.exp', (['(E[i] / kT)'], {}), '(E[i] / kT)\n', (61032, 61043), True, 'import numpy as np\n'), ((8279, 8306), 'numpy.abs', 'np.abs', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8285, 8306), True, 'import numpy as np\n'), ((8315, 8343), 'numpy.sign', 'np.sign', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8322, 8343), True, 'import numpy as np\n'), ((8786, 8813), 'numpy.abs', 'np.abs', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8792, 8813), True, 'import numpy as np\n'), ((8822, 8850), 'numpy.sign', 'np.sign', (['(E[0] + E[n_eig - 1])'], {}), '(E[0] + E[n_eig - 1])\n', (8829, 8850), True, 'import numpy as np\n'), ((14818, 14849), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (14824, 14849), True, 'import numpy as np\n'), ((14993, 15024), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j - 1])'], {}), '(ym[i, j] - ym[i, j - 1])\n', (14999, 15024), True, 'import numpy as np\n'), ((16027, 16058), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (16033, 16058), True, 'import numpy as np\n'), ((16202, 16233), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j + 1])'], {}), '(ym[i, j] - ym[i, j + 1])\n', (16208, 16233), True, 'import numpy as np\n'), ((16538, 16549), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (16546, 16549), True, 'import numpy as np\n'), ((16550, 16561), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (16558, 16561), True, 'import numpy as np\n'), ((43412, 43434), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (43420, 43434), True, 'import numpy as np\n'), ((43493, 43515), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (43501, 43515), True, 'import numpy as np\n'), ((48880, 48890), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (48887, 48890), True, 'import numpy as np\n'), ((48962, 48972), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (48969, 48972), True, 'import numpy as np\n'), ((14481, 14512), 'numpy.abs', 'np.abs', (['(ym[i, j + 1] - ym[i, j])'], {}), '(ym[i, j + 1] - ym[i, j])\n', (14487, 14512), True, 'import numpy as np\n'), ((14509, 14540), 'numpy.abs', 'np.abs', (['(ym[i, j - 1] - ym[i, j])'], {}), '(ym[i, j - 1] - ym[i, j])\n', (14515, 14540), True, 'import numpy as np\n'), ((14613, 14644), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (14619, 14644), True, 'import numpy as np\n'), ((14641, 14672), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (14647, 14672), True, 'import numpy as np\n'), ((16118, 16149), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (16124, 16149), True, 'import numpy as np\n'), ((16293, 16324), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j - 1])'], {}), '(ym[i, j] - ym[i, j - 1])\n', (16299, 16324), True, 'import numpy as np\n'), ((17176, 17207), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (17182, 17207), True, 'import numpy as np\n'), ((17351, 17382), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j + 1])'], {}), '(ym[i, j] - ym[i, j + 1])\n', (17357, 17382), True, 'import numpy as np\n'), ((44267, 44289), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (44275, 44289), True, 'import numpy as np\n'), ((44348, 44370), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (44356, 44370), True, 'import numpy as np\n'), ((44438, 44460), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (44446, 44460), True, 'import numpy as np\n'), ((44530, 44552), 'numpy.zeros', 'np.zeros', (['(n_eig, n_k)'], {}), '((n_eig, n_k))\n', (44538, 44552), True, 'import numpy as np\n'), ((45693, 45708), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (45701, 45708), True, 'import numpy as np\n'), ((45768, 45783), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (45776, 45783), True, 'import numpy as np\n'), ((49095, 49105), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (49102, 49105), True, 'import numpy as np\n'), ((49177, 49187), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (49184, 49187), True, 'import numpy as np\n'), ((15781, 15812), 'numpy.abs', 'np.abs', (['(ym[i, j + 1] - ym[i, j])'], {}), '(ym[i, j + 1] - ym[i, j])\n', (15787, 15812), True, 'import numpy as np\n'), ((15809, 15840), 'numpy.abs', 'np.abs', (['(ym[i, j - 1] - ym[i, j])'], {}), '(ym[i, j - 1] - ym[i, j])\n', (15815, 15840), True, 'import numpy as np\n'), ((15913, 15944), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (15919, 15944), True, 'import numpy as np\n'), ((15941, 15972), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (15947, 15972), True, 'import numpy as np\n'), ((17267, 17298), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (17273, 17298), True, 'import numpy as np\n'), ((17442, 17473), 'numpy.abs', 'np.abs', (['(ym[i, j] - ym[i, j - 1])'], {}), '(ym[i, j] - ym[i, j - 1])\n', (17448, 17473), True, 'import numpy as np\n'), ((38728, 38747), 'numpy.append', 'np.append', (['sites', 'm'], {}), '(sites, m)\n', (38737, 38747), True, 'import numpy as np\n'), ((46519, 46534), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (46527, 46534), True, 'import numpy as np\n'), ((46594, 46609), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (46602, 46609), True, 'import numpy as np\n'), ((46678, 46693), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (46686, 46693), True, 'import numpy as np\n'), ((46764, 46779), 'numpy.zeros', 'np.zeros', (['n_eig'], {}), '(n_eig)\n', (46772, 46779), True, 'import numpy as np\n'), ((57579, 57598), 'numpy.abs', 'np.abs', (['U[2 * i, m]'], {}), '(U[2 * i, m])\n', (57585, 57598), True, 'import numpy as np\n'), ((57599, 57622), 'numpy.abs', 'np.abs', (['U[2 * i + 1, m]'], {}), '(U[2 * i + 1, m])\n', (57605, 57622), True, 'import numpy as np\n'), ((57632, 57649), 'numpy.exp', 'np.exp', (['(E[m] / kT)'], {}), '(E[m] / kT)\n', (57638, 57649), True, 'import numpy as np\n'), ((16930, 16961), 'numpy.abs', 'np.abs', (['(ym[i, j + 1] - ym[i, j])'], {}), '(ym[i, j + 1] - ym[i, j])\n', (16936, 16961), True, 'import numpy as np\n'), ((16958, 16989), 'numpy.abs', 'np.abs', (['(ym[i, j - 1] - ym[i, j])'], {}), '(ym[i, j - 1] - ym[i, j])\n', (16964, 16989), True, 'import numpy as np\n'), ((17062, 17093), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i - 1, j])'], {}), '(xm[i, j] - xm[i - 1, j])\n', (17068, 17093), True, 'import numpy as np\n'), ((17090, 17121), 'numpy.abs', 'np.abs', (['(xm[i, j] - xm[i + 1, j])'], {}), '(xm[i, j] - xm[i + 1, j])\n', (17096, 17121), True, 'import numpy as np\n'), ((57222, 57263), 'numpy.abs', 'np.abs', (['U[2 * (k + (i * Ny + j) * Nz), m]'], {}), '(U[2 * (k + (i * Ny + j) * Nz), m])\n', (57228, 57263), True, 'import numpy as np\n'), ((57256, 57301), 'numpy.abs', 'np.abs', (['U[2 * (k + (i * Ny + j) * Nz) + 1, m]'], {}), '(U[2 * (k + (i * Ny + j) * Nz) + 1, m])\n', (57262, 57301), True, 'import numpy as np\n'), ((57303, 57320), 'numpy.exp', 'np.exp', (['(E[m] / kT)'], {}), '(E[m] / kT)\n', (57309, 57320), True, 'import numpy as np\n'), ((49444, 49454), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (49451, 49454), True, 'import numpy as np\n'), ((49488, 49498), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (49495, 49498), True, 'import numpy as np\n'), ((3518, 3535), 'numpy.abs', 'np.abs', (['(phi + E_F)'], {}), '(phi + E_F)\n', (3524, 3535), True, 'import numpy as np\n'), ((3728, 3750), 'numpy.abs', 'np.abs', (['(phi + E_F + Vz)'], {}), '(phi + E_F + Vz)\n', (3734, 3750), True, 'import numpy as np\n'), ((16661, 16681), 'numpy.random.rand', 'np.random.rand', (['N[0]'], {}), '(N[0])\n', (16675, 16681), True, 'import numpy as np\n'), ((16708, 16728), 'numpy.random.rand', 'np.random.rand', (['N[0]'], {}), '(N[0])\n', (16722, 16728), True, 'import numpy as np\n'), ((54736, 54746), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (54743, 54746), True, 'import numpy as np\n'), ((54766, 54776), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (54773, 54776), True, 'import numpy as np\n'), ((3896, 3918), 'numpy.abs', 'np.abs', (['(phi + E_F - Vz)'], {}), '(phi + E_F - Vz)\n', (3902, 3918), True, 'import numpy as np\n'), ((4154, 4180), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F)'], {}), '(-phi - E_gap - E_F)\n', (4160, 4180), True, 'import numpy as np\n'), ((4326, 4352), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F)'], {}), '(-phi - E_gap - E_F)\n', (4332, 4352), True, 'import numpy as np\n'), ((4567, 4598), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F - Vz)'], {}), '(-phi - E_gap - E_F - Vz)\n', (4573, 4598), True, 'import numpy as np\n'), ((4930, 4961), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F - Vz)'], {}), '(-phi - E_gap - E_F - Vz)\n', (4936, 4961), True, 'import numpy as np\n'), ((20365, 20382), 'numpy.tan', 'np.tan', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (20371, 20382), True, 'import numpy as np\n'), ((20399, 20416), 'numpy.tan', 'np.tan', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (20405, 20416), True, 'import numpy as np\n'), ((54676, 54686), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (54683, 54686), True, 'import numpy as np\n'), ((54707, 54717), 'numpy.prod', 'np.prod', (['N'], {}), '(N)\n', (54714, 54717), True, 'import numpy as np\n'), ((4752, 4783), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F + Vz)'], {}), '(-phi - E_gap - E_F + Vz)\n', (4758, 4783), True, 'import numpy as np\n'), ((5115, 5146), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F + Vz)'], {}), '(-phi - E_gap - E_F + Vz)\n', (5121, 5146), True, 'import numpy as np\n'), ((5383, 5400), 'numpy.abs', 'np.abs', (['(phi + E_F)'], {}), '(phi + E_F)\n', (5389, 5400), True, 'import numpy as np\n'), ((5584, 5610), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F)'], {}), '(-phi - E_gap - E_F)\n', (5590, 5610), True, 'import numpy as np\n'), ((5756, 5782), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F)'], {}), '(-phi - E_gap - E_F)\n', (5762, 5782), True, 'import numpy as np\n'), ((6016, 6038), 'numpy.abs', 'np.abs', (['(phi + E_F + Vz)'], {}), '(phi + E_F + Vz)\n', (6022, 6038), True, 'import numpy as np\n'), ((6391, 6422), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F - Vz)'], {}), '(-phi - E_gap - E_F - Vz)\n', (6397, 6422), True, 'import numpy as np\n'), ((6754, 6785), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F - Vz)'], {}), '(-phi - E_gap - E_F - Vz)\n', (6760, 6785), True, 'import numpy as np\n'), ((6184, 6206), 'numpy.abs', 'np.abs', (['(phi + E_F - Vz)'], {}), '(phi + E_F - Vz)\n', (6190, 6206), True, 'import numpy as np\n'), ((6576, 6607), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F + Vz)'], {}), '(-phi - E_gap - E_F + Vz)\n', (6582, 6607), True, 'import numpy as np\n'), ((6939, 6970), 'numpy.abs', 'np.abs', (['(-phi - E_gap - E_F + Vz)'], {}), '(-phi - E_gap - E_F + Vz)\n', (6945, 6970), True, 'import numpy as np\n'), ((20642, 20663), 'numpy.cos', 'np.cos', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20648, 20663), True, 'import numpy as np\n'), ((20667, 20688), 'numpy.sin', 'np.sin', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20673, 20688), True, 'import numpy as np\n'), ((20707, 20728), 'numpy.sin', 'np.sin', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20713, 20728), True, 'import numpy as np\n'), ((20732, 20753), 'numpy.cos', 'np.cos', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20738, 20753), True, 'import numpy as np\n'), ((20835, 20856), 'numpy.cos', 'np.cos', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20841, 20856), True, 'import numpy as np\n'), ((20860, 20881), 'numpy.sin', 'np.sin', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20866, 20881), True, 'import numpy as np\n'), ((20909, 20930), 'numpy.sin', 'np.sin', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20915, 20930), True, 'import numpy as np\n'), ((20934, 20955), 'numpy.cos', 'np.cos', (['(np.pi / 3 * l)'], {}), '(np.pi / 3 * l)\n', (20940, 20955), True, 'import numpy as np\n')] |
#%%
import pytest
import numpy as np
from natural_bm import dbm
import natural_bm.backend as B
from natural_bm.utils_testing import nnet_for_testing
#%%
def test_prep_topology():
topology_dict = {0: {1}}
pairs, topology_input_dict = dbm.prep_topology(topology_dict)
assert pairs == [(0, 1)]
assert topology_input_dict == {1: {0}}
topology_dict = {0: {1}, 1: {2}}
pairs, topology_input_dict = dbm.prep_topology(topology_dict)
assert pairs == [(0, 1), (1, 2)]
assert topology_input_dict == {1: {0}, 2: {1}}
topology_dict = {0: {1, 3}, 1: {2}, 2: {3}}
pairs, topology_input_dict = dbm.prep_topology(topology_dict)
assert pairs == [(0, 1), (0, 3), (1, 2), (2, 3)]
assert topology_input_dict == {1: {0}, 2: {1}, 3: {0, 2}}
#%%
def test_prep_topology_fail():
topology_dict = {0: {1, 2}, 1: {2}}
with pytest.raises(Exception) as e_info:
pairs, topology_input_dict = dbm.prep_topology(topology_dict)
#%%
@pytest.mark.parametrize('nnet_type', ['rbm', 'dbm', 'dbm_complex'],
ids=['rbm', 'dbm', 'dbm_complex'])
def test_dbm_init(nnet_type):
nnet = nnet_for_testing(nnet_type)
layers = nnet.layers
synapses = nnet.synapses
parts = layers + synapses
weights = []
for lay in layers:
weights.append(lay.b)
for syn in synapses:
weights.append(syn.W)
assert nnet.parts == parts
assert nnet.trainable_weights == weights
assert nnet.non_trainable_weights == []
#%%
def _dbm_prep(nnet_type):
mbs = 6
nnet = nnet_for_testing(nnet_type)
x = B.variable(np.zeros((mbs, nnet.layer_size_list[0])))
return nnet, x
#%%
@pytest.mark.parametrize('nnet_type', ['rbm', 'dbm', 'dbm_complex'],
ids=['rbm', 'dbm', 'dbm_complex'])
@pytest.mark.parametrize('beta', [None, 0.5, 1.0], ids=['None', '0.5', '1.0'])
def test_dbm_prop(nnet_type, beta):
nnet, x = _dbm_prep(nnet_type)
if beta is None:
prob_ls = nnet.propup(x)
else:
prob_ls = nnet.propup(x, beta=beta)
assert len(prob_ls) == len(nnet.layer_size_list)
#%%
@pytest.mark.parametrize('nnet_type', ['rbm', 'dbm', 'dbm_complex'],
ids=['rbm', 'dbm', 'dbm_complex'])
@pytest.mark.parametrize('beta', [0.0, 1.0], ids=['0.0', '1.0'])
@pytest.mark.parametrize('constant', [None, 0, 1], ids=['None', '0', '1'])
def test_dbm_probability(nnet_type, beta, constant):
nnet, x = _dbm_prep(nnet_type)
constant_ls = []
if constant is not None:
constant_ls += [constant]
# tests
input_ls = nnet.propup(x, beta=beta)
output_even_ls = nnet.prob_even_given_odd(input_ls, beta=beta, constant=constant_ls)
output_odd_ls = nnet.prob_odd_given_even(input_ls, beta=beta, constant=constant_ls)
assert len(output_even_ls) == len(input_ls)
assert len(output_odd_ls) == len(input_ls)
#%%
@pytest.mark.parametrize('nnet_type', ['rbm', 'dbm', 'dbm_complex'],
ids=['rbm', 'dbm', 'dbm_complex'])
@pytest.mark.parametrize('beta', [0.0, 1.0], ids=['0.0', '1.0'])
@pytest.mark.parametrize('propup', [True, False], ids=['True', 'False'])
@pytest.mark.parametrize('fe_type', ['fe', 'fe_odd', 'fe_even'],
ids=['fe', 'fe_odd', 'fe_even'])
def test_free_energy(nnet_type, beta, propup, fe_type):
nnet, x = _dbm_prep(nnet_type)
if propup:
input_ls = nnet.propup(x, beta=beta)
else:
input_ls = x
if fe_type == 'fe':
fe = nnet.free_energy(input_ls, beta=beta)
elif fe_type == 'fe_odd':
fe = nnet.free_energy_sumover_odd(input_ls, beta=beta)
elif fe_type == 'fe_even':
fe = nnet.free_energy_sumover_even(input_ls, beta=beta)
assert B.eval(fe).shape == B.eval(x.shape)[0]
#%% Main
if __name__ == '__main__':
pytest.main([__file__])
| [
"natural_bm.utils_testing.nnet_for_testing",
"natural_bm.dbm.prep_topology",
"pytest.main",
"pytest.mark.parametrize",
"numpy.zeros",
"pytest.raises",
"natural_bm.backend.eval"
] | [((974, 1081), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nnet_type"""', "['rbm', 'dbm', 'dbm_complex']"], {'ids': "['rbm', 'dbm', 'dbm_complex']"}), "('nnet_type', ['rbm', 'dbm', 'dbm_complex'], ids=[\n 'rbm', 'dbm', 'dbm_complex'])\n", (997, 1081), False, 'import pytest\n'), ((1677, 1784), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nnet_type"""', "['rbm', 'dbm', 'dbm_complex']"], {'ids': "['rbm', 'dbm', 'dbm_complex']"}), "('nnet_type', ['rbm', 'dbm', 'dbm_complex'], ids=[\n 'rbm', 'dbm', 'dbm_complex'])\n", (1700, 1784), False, 'import pytest\n'), ((1806, 1883), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""beta"""', '[None, 0.5, 1.0]'], {'ids': "['None', '0.5', '1.0']"}), "('beta', [None, 0.5, 1.0], ids=['None', '0.5', '1.0'])\n", (1829, 1883), False, 'import pytest\n'), ((2129, 2236), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nnet_type"""', "['rbm', 'dbm', 'dbm_complex']"], {'ids': "['rbm', 'dbm', 'dbm_complex']"}), "('nnet_type', ['rbm', 'dbm', 'dbm_complex'], ids=[\n 'rbm', 'dbm', 'dbm_complex'])\n", (2152, 2236), False, 'import pytest\n'), ((2258, 2321), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""beta"""', '[0.0, 1.0]'], {'ids': "['0.0', '1.0']"}), "('beta', [0.0, 1.0], ids=['0.0', '1.0'])\n", (2281, 2321), False, 'import pytest\n'), ((2323, 2396), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""constant"""', '[None, 0, 1]'], {'ids': "['None', '0', '1']"}), "('constant', [None, 0, 1], ids=['None', '0', '1'])\n", (2346, 2396), False, 'import pytest\n'), ((2908, 3015), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""nnet_type"""', "['rbm', 'dbm', 'dbm_complex']"], {'ids': "['rbm', 'dbm', 'dbm_complex']"}), "('nnet_type', ['rbm', 'dbm', 'dbm_complex'], ids=[\n 'rbm', 'dbm', 'dbm_complex'])\n", (2931, 3015), False, 'import pytest\n'), ((3037, 3100), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""beta"""', '[0.0, 1.0]'], {'ids': "['0.0', '1.0']"}), "('beta', [0.0, 1.0], ids=['0.0', '1.0'])\n", (3060, 3100), False, 'import pytest\n'), ((3102, 3173), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""propup"""', '[True, False]'], {'ids': "['True', 'False']"}), "('propup', [True, False], ids=['True', 'False'])\n", (3125, 3173), False, 'import pytest\n'), ((3175, 3275), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fe_type"""', "['fe', 'fe_odd', 'fe_even']"], {'ids': "['fe', 'fe_odd', 'fe_even']"}), "('fe_type', ['fe', 'fe_odd', 'fe_even'], ids=['fe',\n 'fe_odd', 'fe_even'])\n", (3198, 3275), False, 'import pytest\n'), ((244, 276), 'natural_bm.dbm.prep_topology', 'dbm.prep_topology', (['topology_dict'], {}), '(topology_dict)\n', (261, 276), False, 'from natural_bm import dbm\n'), ((420, 452), 'natural_bm.dbm.prep_topology', 'dbm.prep_topology', (['topology_dict'], {}), '(topology_dict)\n', (437, 452), False, 'from natural_bm import dbm\n'), ((627, 659), 'natural_bm.dbm.prep_topology', 'dbm.prep_topology', (['topology_dict'], {}), '(topology_dict)\n', (644, 659), False, 'from natural_bm import dbm\n'), ((1143, 1170), 'natural_bm.utils_testing.nnet_for_testing', 'nnet_for_testing', (['nnet_type'], {}), '(nnet_type)\n', (1159, 1170), False, 'from natural_bm.utils_testing import nnet_for_testing\n'), ((1557, 1584), 'natural_bm.utils_testing.nnet_for_testing', 'nnet_for_testing', (['nnet_type'], {}), '(nnet_type)\n', (1573, 1584), False, 'from natural_bm.utils_testing import nnet_for_testing\n'), ((3838, 3861), 'pytest.main', 'pytest.main', (['[__file__]'], {}), '([__file__])\n', (3849, 3861), False, 'import pytest\n'), ((861, 885), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (874, 885), False, 'import pytest\n'), ((934, 966), 'natural_bm.dbm.prep_topology', 'dbm.prep_topology', (['topology_dict'], {}), '(topology_dict)\n', (951, 966), False, 'from natural_bm import dbm\n'), ((1604, 1644), 'numpy.zeros', 'np.zeros', (['(mbs, nnet.layer_size_list[0])'], {}), '((mbs, nnet.layer_size_list[0]))\n', (1612, 1644), True, 'import numpy as np\n'), ((3757, 3767), 'natural_bm.backend.eval', 'B.eval', (['fe'], {}), '(fe)\n', (3763, 3767), True, 'import natural_bm.backend as B\n'), ((3777, 3792), 'natural_bm.backend.eval', 'B.eval', (['x.shape'], {}), '(x.shape)\n', (3783, 3792), True, 'import natural_bm.backend as B\n')] |
import numpy as np
import pandas as pd
import RecSysALS
import RecSysKNN
import RecSysNMF
from RecSysExampleData20Items import RecSysExampleData20Items
class ArticleAntidoteData():
def __init__(self, n_users, n_movies, top_users, top_movies, l, theta, k):
self.n_users = n_users
self.n_movies = n_movies
self.top_users = top_users
self.top_movies = top_movies
self.l = l
self.theta = theta
self.k = k
###################################################################################################################
# function to read the data
def read_movieitems(self, n_users, n_movies, top_users, top_movies, data_dir):
# get ratings
df = pd.read_table('{}/ratings.dat'.format(data_dir),names=['UserID','MovieID','Rating','Timestamp'], sep='::', engine='python')
# create a dataframe with movie IDs on the rows and user IDs on the columns
ratings = df.pivot(index='MovieID', columns='UserID', values='Rating')
movies = pd.read_table('{}/movies.dat'.format(data_dir), names=['MovieID', 'Title', 'Genres'], sep='::', engine='python', encoding = "ISO-8859-1")
user_info = pd.read_table('{}/users.dat'.format(data_dir), names=['UserID','Gender','Age','Occupation','Zip-code'], sep='::', engine='python', encoding = "ISO-8859-1")
user_info = user_info.rename(index=user_info['UserID'])[['Gender','Age','Occupation','Zip-code']]
# put movie titles as index on rows
movieSeries = pd.Series(list(movies['Title']), index=movies['MovieID'])
ratings = ratings.rename(index=movieSeries)
# read movie genres
movie_genres = pd.Series(list(movies['Genres']),index=movies['Title'])
movie_genres = movie_genres.apply(lambda s:s.split('|'))
if top_movies:
# select the top n_movies with the highest number of ratings
num_ratings = (~ratings.isnull()).sum(axis=1) # quantitative ratings for each movie: Movie 1: 4, Movie 2: 5, Movie 3: 2 ...
rows = num_ratings.nlargest(n_movies) # quantitative ratings for each movie (n_movies) sorted: Movie 7: 6, Movie 2: 5, Movie 1: 4 ...
ratings = ratings.loc[rows.index] # matrix[n_movies rows , original columns]; before [original rows x original columns]
if top_users:
# select the top n_users with the highest number of ratings
num_ratings = (~ratings.isnull()).sum(axis=0) # quantitative ratings made by each user: User 1: 5, User 2: 5, User 3: 5, ...
cols = num_ratings.nlargest(n_users) # quantitative evaluations by each user (n_users) sorted: User 1: 5, User 2: 5, User 3: 5, ...
ratings = ratings[cols.index] # matrix [n_movies rows , original columns]; before [n_movies rows , original columns] (just updated the index)
else:
# select the first n_users from the matrix
cols = ratings.columns[0:n_users]
ratings = ratings[cols] # matrix [n_movies rows , n_users columns]; before [n_movies rows , original columns]
ratings = ratings.T # transposed: matrix [n_users rows x n_movies columns];
return ratings, movie_genres, user_info
###################################################################################################################
# compute_X_est:
def compute_X_est(self, X, algorithm='RecSysALS', data_dir="Data/Movie20Items"):
if(algorithm == 'RecSysALS'):
# factorization parameters
rank = 1 # before 20
lambda_ = 1 # before 20 - ridge regularizer parameter
# initiate a recommender system of type ALS (Alternating Least Squares)
RS = RecSysALS.als_RecSysALS(rank,lambda_)
X_est,error = RS.fit_model(X)
elif(algorithm == 'RecSysKNN'):
RecSysKNN
elif(algorithm == 'RecSysNMF'):
RecSysNMF
elif(algorithm == 'RecSysExampleAntidoteData20Items'):
RS = RecSysExampleData20Items()
X_est, movie_genres, user_info = RecSysExampleData20Items.read_movieitems(40, 20, False, False, data_dir)
#X_est, movie_genres, user_info = RS.read_movieitems(40, 20, False, False, "recsys-antidote/data/Movie20Items")
else:
RecSysNMF
return X_est
#######################################################################################################################
class Polarization():
def evaluate(self, X_est):
#print("def evaluate(self, X_est):")
#print("X_est")
#print(X_est)
return X_est.var(axis=0,ddof=0).mean()
def gradient(self, X_est):
"""
Returns the gradient of the divergence utility defined on the
estimated ratings of the original users.
The output is an n by d matrix which is flatten.
"""
D = X_est - X_est.mean()
G = D.values
return G
#######################################################################################################################
class IndividualLossVariance():
def __init__(self, X, omega, axis):
self.axis = axis
self.omega = omega
self.X = X.mask(~omega)
self.omega_user = omega.sum(axis=axis)
def get_losses(self, X_est):
X = self.X
X_est = X_est.mask(~self.omega)
E = (X_est - X).pow(2)
losses = E.mean(axis=self.axis)
return losses
def evaluate(self, X_est):
losses = self.get_losses(X_est)
var = losses.values.var()
return var
def gradient(self, X_est):
"""
Returns the gradient of the utility.
The output is an n by d matrix which is flatten.
"""
X = self.X
X_est = X_est.mask(~self.omega)
diff = X_est - X
if self.axis == 0:
diff = diff.T
losses = self.get_losses(X_est)
B = losses - losses.mean()
C = B.divide(self.omega_user)
D = diff.multiply(C,axis=0)
G = D.fillna(0).values
if self.axis == 0:
G = G.T
return G
#######################################################################################################################
class GroupLossVariance():
def __init__(self, X, omega, G, axis):
self.X = X
self.omega = omega
self.G = G
self.axis = axis
if self.axis == 0:
self.X = self.X.T
self.omega = self.omega.T
self.group_id ={}
for group in self.G: #G [user1, user2, user3, user4]
for user in G[group]:
self.group_id[user] = group
self.omega_group = {}
for group in self.G:
self.omega_group[group] = (~self.X.mask(~self.omega).loc[self.G[group]].isnull()).sum().sum()
omega_user = {}
for user in self.X.index:
omega_user[user] = self.omega_group[self.group_id[user]]
self.omega_user = pd.Series(omega_user)
def get_losses(self, X_est):
if self.axis == 0:
X_est = X_est.T
X = self.X.mask(~self.omega)
X_est = X_est.mask(~self.omega)
E = (X_est - X).pow(2)
if not E.shape == X.shape:
print ('dimension error')
return
losses = {}
for group in self.G:
losses[group] = np.nanmean(E.loc[self.G[group]].values)
losses = pd.Series(losses)
return losses
def evaluate(self, X_est):
losses = self.get_losses(X_est)
var = losses.values.var()
return var
def gradient(self, X_est):
"""
Returns the gradient of the utility.
The output is an n by d matrix which is flatten.
"""
group_losses = self.get_losses(X_est)
#n_group = len(self.G)
X = self.X.mask(~self.omega)
if self.axis == 0:
X_est = X_est.T
X_est = X_est.mask(~self.omega)
diff = X_est - X
if not diff.shape == X.shape:
print ('dimension error')
return
user_group_losses ={}
for user in X.index:
user_group_losses[user] = group_losses[self.group_id[user]]
losses = pd.Series(user_group_losses)
B = losses - group_losses.mean()
C = B.divide(self.omega_user)
#C = (4.0/n_group) * C
D = diff.multiply(C,axis=0)
G = D.fillna(0).values
if self.axis == 0:
G = G.T
return G | [
"pandas.Series",
"numpy.nanmean",
"RecSysExampleData20Items.RecSysExampleData20Items.read_movieitems",
"RecSysALS.als_RecSysALS",
"RecSysExampleData20Items.RecSysExampleData20Items"
] | [((7170, 7191), 'pandas.Series', 'pd.Series', (['omega_user'], {}), '(omega_user)\n', (7179, 7191), True, 'import pandas as pd\n'), ((7636, 7653), 'pandas.Series', 'pd.Series', (['losses'], {}), '(losses)\n', (7645, 7653), True, 'import pandas as pd\n'), ((8472, 8500), 'pandas.Series', 'pd.Series', (['user_group_losses'], {}), '(user_group_losses)\n', (8481, 8500), True, 'import pandas as pd\n'), ((3811, 3849), 'RecSysALS.als_RecSysALS', 'RecSysALS.als_RecSysALS', (['rank', 'lambda_'], {}), '(rank, lambda_)\n', (3834, 3849), False, 'import RecSysALS\n'), ((7579, 7618), 'numpy.nanmean', 'np.nanmean', (['E.loc[self.G[group]].values'], {}), '(E.loc[self.G[group]].values)\n', (7589, 7618), True, 'import numpy as np\n'), ((4097, 4123), 'RecSysExampleData20Items.RecSysExampleData20Items', 'RecSysExampleData20Items', ([], {}), '()\n', (4121, 4123), False, 'from RecSysExampleData20Items import RecSysExampleData20Items\n'), ((4169, 4241), 'RecSysExampleData20Items.RecSysExampleData20Items.read_movieitems', 'RecSysExampleData20Items.read_movieitems', (['(40)', '(20)', '(False)', '(False)', 'data_dir'], {}), '(40, 20, False, False, data_dir)\n', (4209, 4241), False, 'from RecSysExampleData20Items import RecSysExampleData20Items\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 12 12:05:47 2020
@author: Samyak
"""
#==============================================================================
# REGRESSION MODEL - PREDICTING PRICE OF PRE OWNED CARS
#==============================================================================
import numpy as np
import pandas as pd
import seaborn as sns
#setting graph size
sns.set(rc = {"figure.figsize": (10, 8)})
# Reading Data and getting info about data
data_price = pd.read_csv("cars_sampled.csv")
cars = data_price.copy()
cars.info()
cars.describe()
# To set float values upto 3 decimal places
pd.set_option("display.float_format", lambda x: "%.3f" % x)
cars.describe()
# Dropping unwanted columns
cols = ["name", "dateCrawled", "dateCreated", "postalCode", "lastSeen"]
cars = cars.drop(columns = cols, axis =1)
#Removing duplicates from the data
cars.drop_duplicates(keep="first", inplace=True)
cars.isnull().sum()
# varialbe Yearof Registration
yearwise = cars["yearOfRegistration"].value_counts().sort_index()
cars["yearOfRegistration"].describe()
sum(cars["yearOfRegistration"] > 2018)
sum(cars["yearOfRegistration"] < 1950)
sns.regplot(x="yearOfRegistration", y="price", scatter=True, fit_reg=False, data=cars)
# Removing Null values
cars = cars.dropna(axis = 0)
cars.isnull().sum()
# varialbe price
price_count = cars["price"].value_counts().sort_index()
cars["price"].describe()
sum(cars["price"] > 150000)
sum(cars["price"] < 100)
sns.distplot(cars["price"])
# varialbe PowerPS
power_count = cars["powerPS"].value_counts().sort_index()
cars["powerPS"].describe()
sum(cars["powerPS"] > 500)
sum(cars["powerPS"] < 10)
sns.boxplot(cars["powerPS"])
sns.regplot(x="powerPS", y="price", scatter=True, fit_reg=False, data=cars)
#Ranging the data to make it more usefull
cars = cars[
(cars.yearOfRegistration >= 1950)
& (cars.yearOfRegistration <= 2018)
& (cars.price <= 150000)
& (cars.price >= 100)
& (cars.powerPS <= 500)
& (cars.powerPS >= 10)
]
cars["monthOfRegistration"] /= 12
#Adding Age
cars["Age"] = (2018-cars["yearOfRegistration"])+cars["monthOfRegistration"]
cars["Age"] = round(cars["Age"], 2)
cars["Age"].describe()
#Since age is deployed therefor removing
cols1 = ["yearOfRegistration", "monthOfRegistration"]
cars = cars.drop(columns = cols1, axis = 1)
cars1 = cars.copy()
#Vissualizing Parameters after narrowing the range form dataframe
#Age
sns.distplot(cars["Age"])
sns.boxplot(y=cars["Age"])
sns.regplot(x="Age", y="price", scatter=True, fit_reg=False, data=cars1)
#price
sns.distplot(cars["price"])
sns.boxplot(y=cars["price"])
#poweerPS
sns.distplot(cars["powerPS"])
sns.boxplot(y=cars["powerPS"])
sns.regplot(x="powerPS", y="price", scatter=True, fit_reg=False, data=cars1)
#=============================================================================
#Comparing and Analyzing each and every varaible with price
#And removing Insignificant columns
#=============================================================================
#seller
cars["seller"].value_counts()
pd.crosstab(cars["seller"], columns="count", normalize=True)
sns.countplot(x="seller", data=cars1)
sns.boxplot(x="seller", y="price", data=cars1)
#Fewer cars have commercial which is innsignificant
#does not affect price as seen in boxplot
cars1 = cars1.drop(columns=["seller"], axis=1)
#offerType
cars["offerType"].value_counts()
pd.crosstab(cars["offerType"], columns="count", normalize=True)
sns.countplot(x="offerType", data=cars1)
sns.boxplot(x="offerType", y="price", data=cars1)
#does not affect price as seen in boxplot
cars1 = cars1.drop(columns=["offerType"], axis=1)
#abtest
cars["abtest"].value_counts()
pd.crosstab(cars["abtest"], columns="count", normalize=True)
sns.countplot(x="abtest", data=cars1)
sns.boxplot(x="abtest", y="price", data=cars1)
#does not affect price as seen in boxplot
cars1 = cars1.drop(columns=["abtest"], axis=1)
#vehicleType
cars["vehicleType"].value_counts()
pd.crosstab(cars["vehicleType"], columns="count", normalize=True)
sns.countplot(x="vehicleType", data=cars1)
sns.boxplot(x="vehicleType", y="price", data=cars1)
#affecting the price
#gearbox
cars["gearbox"].value_counts()
pd.crosstab(cars["gearbox"], columns="count", normalize=True)
sns.countplot(x="gearbox", data=cars1)
sns.boxplot(x="gearbox", y="price", data=cars1)
#affecting the price
#model
cars["model"].value_counts()
pd.crosstab(cars["model"], columns="count", normalize=True)
#affecting the price
#kilometer
cars["kilometer"].value_counts()
pd.crosstab(cars["kilometer"], columns="count", normalize=True)
sns.countplot(x="kilometer", data=cars1)
sns.boxplot(x="kilometer", y="price", data=cars1)
#affecting the price
#fuelType
cars["fuelType"].value_counts()
pd.crosstab(cars["fuelType"], columns="count", normalize=True)
sns.countplot(x="fuelType", data=cars1)
sns.boxplot(x="fuelType", y="price", data=cars1)
#affecting the price
#brand
cars["brand"].value_counts()
pd.crosstab(cars["brand"], columns="count", normalize=True)
sns.countplot(x="brand", data=cars1)
sns.boxplot(x="price", y="brand", data=cars1)
#affecting the price
#notRepairedDamage
cars["notRepairedDamage"].value_counts()
pd.crosstab(cars["notRepairedDamage"], columns="count", normalize=True)
sns.countplot(x="notRepairedDamage", data=cars1)
sns.boxplot(x="notRepairedDamage", y="price", data=cars1)
#cars wihich have repaired their damage have significantly more value
#============================================================================
# CORRELATION
#===========================================================================
cars_select = cars.select_dtypes(exclude=[object])
corelation = cars_select.corr()
round(corelation, 3)
cars_select.corr().loc[:, "price"].abs().sort_values(ascending=False)[1:]
# powerPS have some decent affect on the price i.e 58%
cars1.describe()
#==============================================================================
# BUILDING ML MODEL
#==============================================================================
cars2 = cars1.copy()
#converting categorical variable in 0/1 format or dummy format
cars2 = pd.get_dummies(cars1, drop_first=True)
#==============================IMPORTING LIBRARIES=============================
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
#Seprating the values for Linear Regression Model
x1 = cars2.drop(["price"], axis = "columns", inplace = False )
y1 = cars2["price"]
#plotting the variable price
prices = pd.DataFrame({"1. Before": y1, "2. After":np.log(y1)})
prices.hist()
#Transforming file as a loarithmic value
y1 = np.log(y1)
#splittting the training and testing data
x_train, x_test, y_train, y_test = train_test_split(x1, y1, test_size = 0.3, random_state=0)
#findin mean value on test data
test_mean = np.mean(y_test)
print(test_mean)
test_mean = np.repeat(test_mean, len(y_test))
print(test_mean)
#Root mean squared value error
rmse = np.sqrt(mean_squared_error(y_test, test_mean))
print(rmse)
linear_reg = LinearRegression(fit_intercept = True)
model_fit = linear_reg.fit(x_train, y_train)
cars_prediction = linear_reg.predict(x_test)
#MSE and RMSE for predictive values
mse1 = mean_squared_error(y_test, cars_prediction)
rmse1 = np.sqrt(mse1)
print(mse1)
print(rmse1)
# R SQUARED VALUE
r2_test = model_fit.score(x_test, y_test)
r2_train = model_fit.score(x_train, y_train)
print(r2_test, r2_train)
#Regression Diaagnostic - Residual plot analysis
reiduals = y_test - cars_prediction
sns.regplot(x=cars_prediction, y=reiduals, fit_reg=False, scatter=True)
reiduals.describe()
#=============================================================================
# RANDOM FOREST MODEL
#=============================================================================
rf = RandomForestRegressor(n_estimators=100, max_features="auto",
max_depth=100, min_samples_split=10,
min_samples_leaf=4, random_state=1)
model_rf = rf.fit(x_train, y_train)
rf_prediction = rf.predict(x_test)
#MSE and RMSE for predictive values
mse1 = mean_squared_error(y_test, rf_prediction)
rmse1 = np.sqrt(mse1)
print(mse1)
print(rmse1)
# R SQUARED VALUE
r2_test = model_rf.score(x_test, y_test)
r2_train = model_rf.score(x_train, y_train)
print(r2_test, r2_train)
# END
| [
"numpy.mean",
"seaborn.set",
"seaborn.regplot",
"numpy.sqrt",
"sklearn.ensemble.RandomForestRegressor",
"pandas.read_csv",
"seaborn.distplot",
"sklearn.model_selection.train_test_split",
"numpy.log",
"pandas.crosstab",
"pandas.set_option",
"seaborn.boxplot",
"pandas.get_dummies",
"sklearn.... | [((385, 424), 'seaborn.set', 'sns.set', ([], {'rc': "{'figure.figsize': (10, 8)}"}), "(rc={'figure.figsize': (10, 8)})\n", (392, 424), True, 'import seaborn as sns\n'), ((484, 515), 'pandas.read_csv', 'pd.read_csv', (['"""cars_sampled.csv"""'], {}), "('cars_sampled.csv')\n", (495, 515), True, 'import pandas as pd\n'), ((615, 674), 'pandas.set_option', 'pd.set_option', (['"""display.float_format"""', "(lambda x: '%.3f' % x)"], {}), "('display.float_format', lambda x: '%.3f' % x)\n", (628, 674), True, 'import pandas as pd\n'), ((1154, 1244), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""yearOfRegistration"""', 'y': '"""price"""', 'scatter': '(True)', 'fit_reg': '(False)', 'data': 'cars'}), "(x='yearOfRegistration', y='price', scatter=True, fit_reg=False,\n data=cars)\n", (1165, 1244), True, 'import seaborn as sns\n'), ((1466, 1493), 'seaborn.distplot', 'sns.distplot', (["cars['price']"], {}), "(cars['price'])\n", (1478, 1493), True, 'import seaborn as sns\n'), ((1652, 1680), 'seaborn.boxplot', 'sns.boxplot', (["cars['powerPS']"], {}), "(cars['powerPS'])\n", (1663, 1680), True, 'import seaborn as sns\n'), ((1681, 1756), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""powerPS"""', 'y': '"""price"""', 'scatter': '(True)', 'fit_reg': '(False)', 'data': 'cars'}), "(x='powerPS', y='price', scatter=True, fit_reg=False, data=cars)\n", (1692, 1756), True, 'import seaborn as sns\n'), ((2417, 2442), 'seaborn.distplot', 'sns.distplot', (["cars['Age']"], {}), "(cars['Age'])\n", (2429, 2442), True, 'import seaborn as sns\n'), ((2443, 2469), 'seaborn.boxplot', 'sns.boxplot', ([], {'y': "cars['Age']"}), "(y=cars['Age'])\n", (2454, 2469), True, 'import seaborn as sns\n'), ((2470, 2542), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""Age"""', 'y': '"""price"""', 'scatter': '(True)', 'fit_reg': '(False)', 'data': 'cars1'}), "(x='Age', y='price', scatter=True, fit_reg=False, data=cars1)\n", (2481, 2542), True, 'import seaborn as sns\n'), ((2551, 2578), 'seaborn.distplot', 'sns.distplot', (["cars['price']"], {}), "(cars['price'])\n", (2563, 2578), True, 'import seaborn as sns\n'), ((2579, 2607), 'seaborn.boxplot', 'sns.boxplot', ([], {'y': "cars['price']"}), "(y=cars['price'])\n", (2590, 2607), True, 'import seaborn as sns\n'), ((2619, 2648), 'seaborn.distplot', 'sns.distplot', (["cars['powerPS']"], {}), "(cars['powerPS'])\n", (2631, 2648), True, 'import seaborn as sns\n'), ((2649, 2679), 'seaborn.boxplot', 'sns.boxplot', ([], {'y': "cars['powerPS']"}), "(y=cars['powerPS'])\n", (2660, 2679), True, 'import seaborn as sns\n'), ((2680, 2756), 'seaborn.regplot', 'sns.regplot', ([], {'x': '"""powerPS"""', 'y': '"""price"""', 'scatter': '(True)', 'fit_reg': '(False)', 'data': 'cars1'}), "(x='powerPS', y='price', scatter=True, fit_reg=False, data=cars1)\n", (2691, 2756), True, 'import seaborn as sns\n'), ((3051, 3111), 'pandas.crosstab', 'pd.crosstab', (["cars['seller']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['seller'], columns='count', normalize=True)\n", (3062, 3111), True, 'import pandas as pd\n'), ((3112, 3149), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""seller"""', 'data': 'cars1'}), "(x='seller', data=cars1)\n", (3125, 3149), True, 'import seaborn as sns\n'), ((3150, 3196), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""seller"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='seller', y='price', data=cars1)\n", (3161, 3196), True, 'import seaborn as sns\n'), ((3383, 3446), 'pandas.crosstab', 'pd.crosstab', (["cars['offerType']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['offerType'], columns='count', normalize=True)\n", (3394, 3446), True, 'import pandas as pd\n'), ((3447, 3487), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""offerType"""', 'data': 'cars1'}), "(x='offerType', data=cars1)\n", (3460, 3487), True, 'import seaborn as sns\n'), ((3488, 3537), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""offerType"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='offerType', y='price', data=cars1)\n", (3499, 3537), True, 'import seaborn as sns\n'), ((3669, 3729), 'pandas.crosstab', 'pd.crosstab', (["cars['abtest']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['abtest'], columns='count', normalize=True)\n", (3680, 3729), True, 'import pandas as pd\n'), ((3730, 3767), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""abtest"""', 'data': 'cars1'}), "(x='abtest', data=cars1)\n", (3743, 3767), True, 'import seaborn as sns\n'), ((3768, 3814), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""abtest"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='abtest', y='price', data=cars1)\n", (3779, 3814), True, 'import seaborn as sns\n'), ((3953, 4018), 'pandas.crosstab', 'pd.crosstab', (["cars['vehicleType']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['vehicleType'], columns='count', normalize=True)\n", (3964, 4018), True, 'import pandas as pd\n'), ((4019, 4061), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""vehicleType"""', 'data': 'cars1'}), "(x='vehicleType', data=cars1)\n", (4032, 4061), True, 'import seaborn as sns\n'), ((4062, 4113), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""vehicleType"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='vehicleType', y='price', data=cars1)\n", (4073, 4113), True, 'import seaborn as sns\n'), ((4176, 4237), 'pandas.crosstab', 'pd.crosstab', (["cars['gearbox']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['gearbox'], columns='count', normalize=True)\n", (4187, 4237), True, 'import pandas as pd\n'), ((4238, 4276), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""gearbox"""', 'data': 'cars1'}), "(x='gearbox', data=cars1)\n", (4251, 4276), True, 'import seaborn as sns\n'), ((4277, 4324), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""gearbox"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='gearbox', y='price', data=cars1)\n", (4288, 4324), True, 'import seaborn as sns\n'), ((4383, 4442), 'pandas.crosstab', 'pd.crosstab', (["cars['model']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['model'], columns='count', normalize=True)\n", (4394, 4442), True, 'import pandas as pd\n'), ((4509, 4572), 'pandas.crosstab', 'pd.crosstab', (["cars['kilometer']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['kilometer'], columns='count', normalize=True)\n", (4520, 4572), True, 'import pandas as pd\n'), ((4573, 4613), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""kilometer"""', 'data': 'cars1'}), "(x='kilometer', data=cars1)\n", (4586, 4613), True, 'import seaborn as sns\n'), ((4614, 4663), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""kilometer"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='kilometer', y='price', data=cars1)\n", (4625, 4663), True, 'import seaborn as sns\n'), ((4728, 4790), 'pandas.crosstab', 'pd.crosstab', (["cars['fuelType']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['fuelType'], columns='count', normalize=True)\n", (4739, 4790), True, 'import pandas as pd\n'), ((4791, 4830), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""fuelType"""', 'data': 'cars1'}), "(x='fuelType', data=cars1)\n", (4804, 4830), True, 'import seaborn as sns\n'), ((4831, 4879), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""fuelType"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='fuelType', y='price', data=cars1)\n", (4842, 4879), True, 'import seaborn as sns\n'), ((4938, 4997), 'pandas.crosstab', 'pd.crosstab', (["cars['brand']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['brand'], columns='count', normalize=True)\n", (4949, 4997), True, 'import pandas as pd\n'), ((4998, 5034), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""brand"""', 'data': 'cars1'}), "(x='brand', data=cars1)\n", (5011, 5034), True, 'import seaborn as sns\n'), ((5035, 5080), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""price"""', 'y': '"""brand"""', 'data': 'cars1'}), "(x='price', y='brand', data=cars1)\n", (5046, 5080), True, 'import seaborn as sns\n'), ((5163, 5234), 'pandas.crosstab', 'pd.crosstab', (["cars['notRepairedDamage']"], {'columns': '"""count"""', 'normalize': '(True)'}), "(cars['notRepairedDamage'], columns='count', normalize=True)\n", (5174, 5234), True, 'import pandas as pd\n'), ((5235, 5283), 'seaborn.countplot', 'sns.countplot', ([], {'x': '"""notRepairedDamage"""', 'data': 'cars1'}), "(x='notRepairedDamage', data=cars1)\n", (5248, 5283), True, 'import seaborn as sns\n'), ((5284, 5341), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""notRepairedDamage"""', 'y': '"""price"""', 'data': 'cars1'}), "(x='notRepairedDamage', y='price', data=cars1)\n", (5295, 5341), True, 'import seaborn as sns\n'), ((6109, 6147), 'pandas.get_dummies', 'pd.get_dummies', (['cars1'], {'drop_first': '(True)'}), '(cars1, drop_first=True)\n', (6123, 6147), True, 'import pandas as pd\n'), ((6721, 6731), 'numpy.log', 'np.log', (['y1'], {}), '(y1)\n', (6727, 6731), True, 'import numpy as np\n'), ((6810, 6865), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x1', 'y1'], {'test_size': '(0.3)', 'random_state': '(0)'}), '(x1, y1, test_size=0.3, random_state=0)\n', (6826, 6865), False, 'from sklearn.model_selection import train_test_split\n'), ((6913, 6928), 'numpy.mean', 'np.mean', (['y_test'], {}), '(y_test)\n', (6920, 6928), True, 'import numpy as np\n'), ((7122, 7158), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (7138, 7158), False, 'from sklearn.linear_model import LinearRegression\n'), ((7297, 7340), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test', 'cars_prediction'], {}), '(y_test, cars_prediction)\n', (7315, 7340), False, 'from sklearn.metrics import mean_squared_error\n'), ((7349, 7362), 'numpy.sqrt', 'np.sqrt', (['mse1'], {}), '(mse1)\n', (7356, 7362), True, 'import numpy as np\n'), ((7607, 7678), 'seaborn.regplot', 'sns.regplot', ([], {'x': 'cars_prediction', 'y': 'reiduals', 'fit_reg': '(False)', 'scatter': '(True)'}), '(x=cars_prediction, y=reiduals, fit_reg=False, scatter=True)\n', (7618, 7678), True, 'import seaborn as sns\n'), ((7886, 8023), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {'n_estimators': '(100)', 'max_features': '"""auto"""', 'max_depth': '(100)', 'min_samples_split': '(10)', 'min_samples_leaf': '(4)', 'random_state': '(1)'}), "(n_estimators=100, max_features='auto', max_depth=100,\n min_samples_split=10, min_samples_leaf=4, random_state=1)\n", (7907, 8023), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((8191, 8232), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test', 'rf_prediction'], {}), '(y_test, rf_prediction)\n', (8209, 8232), False, 'from sklearn.metrics import mean_squared_error\n'), ((8241, 8254), 'numpy.sqrt', 'np.sqrt', (['mse1'], {}), '(mse1)\n', (8248, 8254), True, 'import numpy as np\n'), ((7057, 7094), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_test', 'test_mean'], {}), '(y_test, test_mean)\n', (7075, 7094), False, 'from sklearn.metrics import mean_squared_error\n'), ((6647, 6657), 'numpy.log', 'np.log', (['y1'], {}), '(y1)\n', (6653, 6657), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from src.models.text_classifier import run_model_on_file
from src.models.text_classifier import TextClassifier
from utils import get_conf_labels as get_conf_labels
from utils.bootstrap import my_bootstrap
from utils.get_pars_data import get_par_data
from utils.clean_n_split import clean_n_split
def par_runner(all_par_data,data_path,model_path,mails_num,min_confidence,model_name,user_id):
name = model_name
i = -1
true_data = all_par_data.loc[all_par_data['label_id'] == 1.]
false_data = all_par_data.loc[all_par_data['label_id'] == 0.]
while len(true_data) > 0:
i += 1
mails_remain = len(np.unique(true_data['document_id']))
if mails_remain <= mails_num:
mails_num = mails_remain
par_data = get_par_data(data_path, model_path, true_data, name, min_confidence, mails_num, user_id)
if i == 0:
full_par_data = par_data
else:
full_par_data = pd.concat([full_par_data, par_data], ignore_index=True)
full_par_data = pd.concat([full_par_data, false_data], ignore_index=True)
return full_par_data
if __name__ == '__main__':
data_path = r'C:\develop\code\semi-supervised-text-classification\data'
model_path = r'C:\develop\code\semi-supervised-text-classification\data\results\ml_model_'
full_data = pd.read_csv(r'C:\develop\code\semi-supervised-text-classification\data\enron_no_head.csv')
all_par_data = clean_n_split(full_data)
# Hyper parm
mails_num = 20
min_confidence = 0.85
model_name = '0'
user_id = 2
full_par_data = par_runner(all_par_data, data_path, model_path, mails_num, min_confidence, model_name, user_id)
true_data = all_par_data.loc[all_par_data['label_id'] == 1.]
false_data = all_par_data.loc[all_par_data['label_id'] == 0.]
while len(true_data) > 0:
i +=1
mails_remain = len(np.unique(true_data['document_id']))
if mails_remain<=mails_num:
mails_num = mails_remain
par_data = get_par_data(data_path,model_path,true_data,model_name,min_confidence,mails_num,user_id)
if i==0:
full_par_data = par_data
else:
full_par_data = pd.concat([full_par_data,par_data],ignore_index=True)
full_par_data = pd.concat([full_par_data,false_data],ignore_index=True)
print('a') | [
"numpy.unique",
"pandas.read_csv",
"utils.clean_n_split.clean_n_split",
"pandas.concat",
"utils.get_pars_data.get_par_data"
] | [((1111, 1168), 'pandas.concat', 'pd.concat', (['[full_par_data, false_data]'], {'ignore_index': '(True)'}), '([full_par_data, false_data], ignore_index=True)\n', (1120, 1168), True, 'import pandas as pd\n'), ((1411, 1515), 'pandas.read_csv', 'pd.read_csv', (['"""C:\\\\develop\\\\code\\\\semi-supervised-text-classification\\\\data\\\\enron_no_head.csv"""'], {}), "(\n 'C:\\\\develop\\\\code\\\\semi-supervised-text-classification\\\\data\\\\enron_no_head.csv'\n )\n", (1422, 1515), True, 'import pandas as pd\n'), ((1521, 1545), 'utils.clean_n_split.clean_n_split', 'clean_n_split', (['full_data'], {}), '(full_data)\n', (1534, 1545), False, 'from utils.clean_n_split import clean_n_split\n'), ((2359, 2416), 'pandas.concat', 'pd.concat', (['[full_par_data, false_data]'], {'ignore_index': '(True)'}), '([full_par_data, false_data], ignore_index=True)\n', (2368, 2416), True, 'import pandas as pd\n'), ((846, 938), 'utils.get_pars_data.get_par_data', 'get_par_data', (['data_path', 'model_path', 'true_data', 'name', 'min_confidence', 'mails_num', 'user_id'], {}), '(data_path, model_path, true_data, name, min_confidence,\n mails_num, user_id)\n', (858, 938), False, 'from utils.get_pars_data import get_par_data\n'), ((2098, 2196), 'utils.get_pars_data.get_par_data', 'get_par_data', (['data_path', 'model_path', 'true_data', 'model_name', 'min_confidence', 'mails_num', 'user_id'], {}), '(data_path, model_path, true_data, model_name, min_confidence,\n mails_num, user_id)\n', (2110, 2196), False, 'from utils.get_pars_data import get_par_data\n'), ((714, 749), 'numpy.unique', 'np.unique', (["true_data['document_id']"], {}), "(true_data['document_id'])\n", (723, 749), True, 'import numpy as np\n'), ((1034, 1089), 'pandas.concat', 'pd.concat', (['[full_par_data, par_data]'], {'ignore_index': '(True)'}), '([full_par_data, par_data], ignore_index=True)\n', (1043, 1089), True, 'import pandas as pd\n'), ((1968, 2003), 'numpy.unique', 'np.unique', (["true_data['document_id']"], {}), "(true_data['document_id'])\n", (1977, 2003), True, 'import numpy as np\n'), ((2284, 2339), 'pandas.concat', 'pd.concat', (['[full_par_data, par_data]'], {'ignore_index': '(True)'}), '([full_par_data, par_data], ignore_index=True)\n', (2293, 2339), True, 'import pandas as pd\n')] |
import numpy as np
def generate_noise(size, beta):
white_noise = np.random.randn(*size)
white_noise_fft = np.fft.fftn(white_noise)
ndims = len(size)
freq_along_axis = []
for axis in range(ndims):
freq_along_axis.append(np.fft.fftfreq(size[axis]))
grids = np.meshgrid(*freq_along_axis)
sum_of_squares = 0
for grid in grids:
sum_of_squares += grid**2
freqs = np.sqrt(sum_of_squares)
origin = (0,) * ndims
freqs[origin] += 1e-8 # DC component
filter = 1/np.power(freqs, beta)
colored_fft = white_noise_fft * filter.T
colored_noise = np.fft.ifftn(colored_fft)
return np.abs(colored_noise)
| [
"numpy.abs",
"numpy.sqrt",
"numpy.power",
"numpy.fft.fftfreq",
"numpy.fft.fftn",
"numpy.meshgrid",
"numpy.fft.ifftn",
"numpy.random.randn"
] | [((75, 97), 'numpy.random.randn', 'np.random.randn', (['*size'], {}), '(*size)\n', (90, 97), True, 'import numpy as np\n'), ((120, 144), 'numpy.fft.fftn', 'np.fft.fftn', (['white_noise'], {}), '(white_noise)\n', (131, 144), True, 'import numpy as np\n'), ((294, 323), 'numpy.meshgrid', 'np.meshgrid', (['*freq_along_axis'], {}), '(*freq_along_axis)\n', (305, 323), True, 'import numpy as np\n'), ((416, 439), 'numpy.sqrt', 'np.sqrt', (['sum_of_squares'], {}), '(sum_of_squares)\n', (423, 439), True, 'import numpy as np\n'), ((615, 640), 'numpy.fft.ifftn', 'np.fft.ifftn', (['colored_fft'], {}), '(colored_fft)\n', (627, 640), True, 'import numpy as np\n'), ((653, 674), 'numpy.abs', 'np.abs', (['colored_noise'], {}), '(colored_noise)\n', (659, 674), True, 'import numpy as np\n'), ((527, 548), 'numpy.power', 'np.power', (['freqs', 'beta'], {}), '(freqs, beta)\n', (535, 548), True, 'import numpy as np\n'), ((253, 279), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['size[axis]'], {}), '(size[axis])\n', (267, 279), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
import math
import numpy as np
from collections import Counter
def createDataSet():
X = []
Y = []
filename = 'credit.txt'
temp_X = []
data = np.genfromtxt(filename, delimiter=None,dtype=str)
for n in range(1, len(data)):
Y.append(data[n][6])
X_row = []
for p in range(0, len(data[0])-1):
X_row.append(data[n][p])
temp_X.append(data[n][p])
X.append(X_row)
X = np.array(X)
Y = np.array(Y)
X = X.T
dataSet = X
labels = Y
# change to discrete values
return dataSet, labels
# 计算香农熵
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVec in dataSet: # the the number of unique elements and their occurance
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
for key in labelCounts:
prob = float(labelCounts[key]) / numEntries
shannonEnt -= prob * math.log(prob, 2) # log base 2
return shannonEnt
# 按特征和特征值划分数据集
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis] # chop out axis used for splitting
reducedFeatVec.extend(featVec[axis + 1:])
retDataSet.append(reducedFeatVec) # 这里注意extend和append的区别
return retDataSet
# ID3决策树分类算法
def chooseBestFeatureToSplitID3(dataSet):
numFeatures = len(dataSet[0]) - 1 # myDat[0]表示第一行数据, the last column is used for the labels
baseEntropy = calcShannonEnt(dataSet)
bestInfoGain = 0.0
bestFeature = -1
for i in range(numFeatures): # iterate over all the features
featList = [example[i] for example in dataSet] # featList是每一列的所有值,是一个列表
uniqueVals = set(featList) # 集合中每个值互不相同
newEntropy = 0.0
for value in uniqueVals:
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet) / float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy # calculate the info gain; ie reduction in entropy
if (infoGain > bestInfoGain): # compare this to the best gain so far
bestInfoGain = infoGain # if better than current best, set to best
bestFeature = i
return bestFeature # returns an integer
# 当所有特征都用完的时候投票决定分类
def majorityCnt(classList):
classCount = {}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
# ID3构建树
def createTreeID3(dataSet, labels):
classList = [example[-1] for example in dataSet] # 创建类标签
if classList.count(classList[0]) == len(classList):
return classList[0] # 如果所有类标签完全相同则停止,直接返回该类标签
if len(dataSet[0]) == 1: # 遍历完了所有的标签仍然不能将数据集划分为仅包含唯一类别的分组
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplitID3(dataSet) # 最佳分类特征的下标
bestFeatLabel = labels[bestFeat] # 最佳分类特征的名字
myTree = {bestFeatLabel: {}} # 创建
del (labels[bestFeat]) # 从label里删掉这个最佳特征,创建迭代的label列表
featValues = [example[bestFeat] for example in dataSet] # 这个最佳特征对应的所有值
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:] # copy all of labels, so trees don't mess up existing labels
myTree[bestFeatLabel][value] = createTreeID3(splitDataSet(dataSet, bestFeat, value), subLabels)
return myTree
if __name__ == "__main__":
dataSet, labels = createDataSet()
print(createTreeID3(dataSet,labels)) | [
"numpy.array",
"numpy.genfromtxt",
"math.log"
] | [((204, 254), 'numpy.genfromtxt', 'np.genfromtxt', (['filename'], {'delimiter': 'None', 'dtype': 'str'}), '(filename, delimiter=None, dtype=str)\n', (217, 254), True, 'import numpy as np\n'), ((486, 497), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (494, 497), True, 'import numpy as np\n'), ((506, 517), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (514, 517), True, 'import numpy as np\n'), ((1091, 1108), 'math.log', 'math.log', (['prob', '(2)'], {}), '(prob, 2)\n', (1099, 1108), False, 'import math\n')] |
import math
import quaternion
import numpy as np
from plyfile import PlyData, PlyElement
def write_ply(points, filename, text=True):
""" input: Nx3, write points to filename as PLY format. """
points = [(points[i,0], points[i,1], points[i,2]) for i in range(points.shape[0])]
vertex = np.array(points, dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')])
el = PlyElement.describe(vertex, 'vertex', comments=['vertices'])
PlyData([el], text=text).write(filename)
def random_sampling(pc, num_sample, replace=None, return_choices=False):
""" Input is NxC, output is num_samplexC
"""
if replace is None: replace = (pc.shape[0]<num_sample)
choices = np.random.choice(pc.shape[0], num_sample, replace=replace)
if return_choices:
return pc[choices], choices
else:
return pc[choices]
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return roll_x, pitch_y, yaw_z # in radians
def make_M_from_tqs(t, q, s):
q = np.quaternion(q[0], q[1], q[2], q[3])
T = np.eye(4)
T[0:3, 3] = t
R = np.eye(4)
R[0:3, 0:3] = quaternion.as_rotation_matrix(q)
S = np.eye(4)
S[0:3, 0:3] = np.diag(s)
M = T.dot(R).dot(S)
return M
def flip_axis_to_camera(pc):
''' Flip X-right,Y-forward,Z-up to X-right,Y-down,Z-forward
Input and output are both (N,3) array
'''
pc2 = np.copy(pc)
pc2[...,[0,1,2]] = pc2[...,[0,2,1]] # cam X,Y,Z = depth X,-Z,Y
pc2[...,1] *= -1
return pc2
def flip_axis_to_depth(pc):
pc2 = np.copy(pc)
pc2[...,[0,1,2]] = pc2[...,[0,2,1]] # depth X,Y,Z = cam X,Z,-Y
pc2[...,2] *= -1
return pc2
def in_hull(p, hull, check):
from scipy.spatial import Delaunay
if not isinstance(hull,Delaunay):
hull = Delaunay(hull)
return hull.find_simplex(p)>=0
def extract_pc_in_box3d(pc, box3d, check):
''' pc: (N,3), box3d: (8,3)
Order of indices:
(3)-----(2)
/ | / |
(4)-+---(1) |
| (7)---+-(6)
| / | /
(8)-----(5)
-: l (x)
|: h (y)
/: w (z)
'''
box3d_roi_inds = in_hull(pc[:,0:3], box3d, check)
return pc[box3d_roi_inds,:], box3d_roi_inds
def roty(t):
"""Rotation about the y-axis."""
c = np.cos(t)
s = np.sin(t)
return np.array([[c, 0, s],
[0, 1, 0],
[-s, 0, c]])
def rotate_aligned_boxes(centers, lengths, rot_mat):
# centers, lengths = input_boxes[:,0:3], input_boxes[:,3:6]
new_centers = np.dot(centers, np.transpose(rot_mat))
dx, dy = lengths[:,0]/2.0, lengths[:,1]/2.0
new_x = np.zeros((dx.shape[0], 4))
new_y = np.zeros((dx.shape[0], 4))
for i, crnr in enumerate([(-1,-1), (1, -1), (1, 1), (-1, 1)]):
crnrs = np.zeros((dx.shape[0], 3))
crnrs[:,0] = crnr[0]*dx
crnrs[:,1] = crnr[1]*dy
crnrs = np.dot(crnrs, np.transpose(rot_mat))
new_x[:,i] = crnrs[:,0]
new_y[:,i] = crnrs[:,1]
new_dx = 2.0*np.max(new_x, 1)
new_dy = 2.0*np.max(new_y, 1)
new_lengths = np.stack((new_dx, new_dy, lengths[:,2]), axis=1)
# return np.concatenate([new_centers, new_lengths], axis=1)
return new_centers, new_lengths
def filter_dominant_cls(points, sem_cls, not_cared_id):
'''
args:
points: (N, 3)
sem_cls: (N, 1)
returns:
dom_points: (M, 3)
'''
cls_book = {'max_total': 0, 'dominant': 0}
for cls_id in np.unique(sem_cls):
if cls_id in not_cared_id:
continue
cls_sum = np.sum(np.where(sem_cls == cls_id)[0])
if cls_sum > cls_book['max_total']:
cls_book['dominant'] = cls_id
cls_book['max_total'] = cls_sum
choices = np.where(sem_cls == cls_book['dominant'])[0]
return points[choices], choices
def get_3d_box_rotated(box_size, rot_mat, padding=None):
''' @<NAME>, KAIST
box_size is array(l,w,h), heading_angle is radius clockwise from pos x axis, center is xyz of box center
output (8,3) array for 3D box cornders
Similar to utils/compute_orientation_3d
Order of indices:
(3)-----(2)
/ | / |
(4)-+---(1) |
| (7)---+-(6)
| / | /
(8)-----(5)
-: l (x)
|: h (y)
/: w (z)
args:
box_size: float (3)
rot_mat: float (4, 4)
returns:
corners_3d: float (8, 3)
'''
R = rot_mat # (4, 4)
l,h,w = box_size * 2
x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2];
y_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2];
z_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2];
hcoord = np.ones(8, dtype=np.float32)
corners_3d = np.vstack([x_corners,y_corners,z_corners, hcoord])
if padding:
p = padding
corners_3d[0:1, :] += [p, p, -p, -p, p, p, -p, -p]
corners_3d[1:2, :] += [p, p, p, p, -p, -p, -p, -p]
corners_3d[2:3, :] += [p, -p, -p, p, p, -p, -p, p]
corners_3d = np.dot(R, corners_3d)
corners_3d = np.transpose(corners_3d)
corners_3d = corners_3d[:, :3]
assert(corners_3d.shape[0] * corners_3d.shape[1] == 24)
return corners_3d
def batch_get_3d_box_rotated(box_size, rot_mat):
''' box_size: [x1,x2,...,xn,3] => (B, 3)
heading_angle: [x1,x2,...,xn,4,4] => (B, 4, 4)
center: [x1,x2,...,xn,3] => (B, 3)
Return:
[x1,x3,...,xn,8,3] => (B, 8, 3)
'''
input_shape = box_size.shape[0] # B
R = rot_mat # (B, 4, 4)
l = np.expand_dims(box_size[...,0], -1) # [x1,...,xn,1]
w = np.expand_dims(box_size[...,1], -1)
h = np.expand_dims(box_size[...,2], -1)
corners_3d = np.zeros(tuple(list(input_shape)+[8,3]))
corners_3d[...,:,0] = np.concatenate((l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2, 1), -1)
corners_3d[...,:,1] = np.concatenate((h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2, 1), -1)
corners_3d[...,:,2] = np.concatenate((w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2, 1), -1)
tlist = [i for i in range(len(input_shape))]
tlist += [len(input_shape)+1, len(input_shape)]
corners_3d = np.matmul(corners_3d, np.transpose(R, tuple(tlist)))
assert(corners_3d.shape[1] * corners_3d.shape[2] == 24)
return corners_3d
def get_3d_box(box_size, heading_angle, center):
''' box_size is array(l,w,h), heading_angle is radius clockwise from pos x axis, center is xyz of box center
output (8,3) array for 3D box cornders
Similar to utils/compute_orientation_3d
'''
R = roty(heading_angle)
l,w,h = box_size
x_corners = [l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2];
y_corners = [h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2];
z_corners = [w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2];
corners_3d = np.dot(R, np.vstack([x_corners,y_corners,z_corners]))
corners_3d[0,:] = corners_3d[0,:] + center[0];
corners_3d[1,:] = corners_3d[1,:] + center[1];
corners_3d[2,:] = corners_3d[2,:] + center[2];
corners_3d = np.transpose(corners_3d)
return corners_3d
def nms_3d_faster_samecls(boxes, overlap_threshold, old_type=False):
x1 = boxes[:,0]
y1 = boxes[:,1]
z1 = boxes[:,2]
x2 = boxes[:,3]
y2 = boxes[:,4]
z2 = boxes[:,5]
score = boxes[:,6]
cls = boxes[:,7]
area = (x2-x1)*(y2-y1)*(z2-z1)
I = np.argsort(score)
pick = []
while (I.size!=0):
last = I.size
i = I[-1]
pick.append(i)
xx1 = np.maximum(x1[i], x1[I[:last-1]])
yy1 = np.maximum(y1[i], y1[I[:last-1]])
zz1 = np.maximum(z1[i], z1[I[:last-1]])
xx2 = np.minimum(x2[i], x2[I[:last-1]])
yy2 = np.minimum(y2[i], y2[I[:last-1]])
zz2 = np.minimum(z2[i], z2[I[:last-1]])
cls1 = cls[i]
cls2 = cls[I[:last-1]]
l = np.maximum(0, xx2-xx1)
w = np.maximum(0, yy2-yy1)
h = np.maximum(0, zz2-zz1)
if old_type:
o = (l*w*h)/area[I[:last-1]]
else:
inter = l*w*h
o = inter / (area[i] + area[I[:last-1]] - inter)
o = o * (cls1==cls2)
I = np.delete(I, np.concatenate(([last-1], np.where(o>overlap_threshold)[0])))
return pick
| [
"numpy.argsort",
"numpy.array",
"numpy.sin",
"numpy.where",
"numpy.max",
"numpy.stack",
"numpy.dot",
"numpy.vstack",
"plyfile.PlyElement.describe",
"numpy.concatenate",
"numpy.maximum",
"numpy.eye",
"numpy.ones",
"numpy.random.choice",
"math.atan2",
"numpy.cos",
"numpy.quaternion",
... | [((299, 362), 'numpy.array', 'np.array', (['points'], {'dtype': "[('x', 'f4'), ('y', 'f4'), ('z', 'f4')]"}), "(points, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')])\n", (307, 362), True, 'import numpy as np\n'), ((371, 431), 'plyfile.PlyElement.describe', 'PlyElement.describe', (['vertex', '"""vertex"""'], {'comments': "['vertices']"}), "(vertex, 'vertex', comments=['vertices'])\n", (390, 431), False, 'from plyfile import PlyData, PlyElement\n'), ((678, 736), 'numpy.random.choice', 'np.random.choice', (['pc.shape[0]', 'num_sample'], {'replace': 'replace'}), '(pc.shape[0], num_sample, replace=replace)\n', (694, 736), True, 'import numpy as np\n'), ((1215, 1233), 'math.atan2', 'math.atan2', (['t0', 't1'], {}), '(t0, t1)\n', (1225, 1233), False, 'import math\n'), ((1356, 1369), 'math.asin', 'math.asin', (['t2'], {}), '(t2)\n', (1365, 1369), False, 'import math\n'), ((1458, 1476), 'math.atan2', 'math.atan2', (['t3', 't4'], {}), '(t3, t4)\n', (1468, 1476), False, 'import math\n'), ((1570, 1607), 'numpy.quaternion', 'np.quaternion', (['q[0]', 'q[1]', 'q[2]', 'q[3]'], {}), '(q[0], q[1], q[2], q[3])\n', (1583, 1607), True, 'import numpy as np\n'), ((1616, 1625), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1622, 1625), True, 'import numpy as np\n'), ((1652, 1661), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1658, 1661), True, 'import numpy as np\n'), ((1680, 1712), 'quaternion.as_rotation_matrix', 'quaternion.as_rotation_matrix', (['q'], {}), '(q)\n', (1709, 1712), False, 'import quaternion\n'), ((1721, 1730), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (1727, 1730), True, 'import numpy as np\n'), ((1749, 1759), 'numpy.diag', 'np.diag', (['s'], {}), '(s)\n', (1756, 1759), True, 'import numpy as np\n'), ((1954, 1965), 'numpy.copy', 'np.copy', (['pc'], {}), '(pc)\n', (1961, 1965), True, 'import numpy as np\n'), ((2109, 2120), 'numpy.copy', 'np.copy', (['pc'], {}), '(pc)\n', (2116, 2120), True, 'import numpy as np\n'), ((2857, 2866), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (2863, 2866), True, 'import numpy as np\n'), ((2875, 2884), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (2881, 2884), True, 'import numpy as np\n'), ((2896, 2940), 'numpy.array', 'np.array', (['[[c, 0, s], [0, 1, 0], [-s, 0, c]]'], {}), '([[c, 0, s], [0, 1, 0], [-s, 0, c]])\n', (2904, 2940), True, 'import numpy as np\n'), ((3242, 3268), 'numpy.zeros', 'np.zeros', (['(dx.shape[0], 4)'], {}), '((dx.shape[0], 4))\n', (3250, 3268), True, 'import numpy as np\n'), ((3281, 3307), 'numpy.zeros', 'np.zeros', (['(dx.shape[0], 4)'], {}), '((dx.shape[0], 4))\n', (3289, 3307), True, 'import numpy as np\n'), ((3703, 3752), 'numpy.stack', 'np.stack', (['(new_dx, new_dy, lengths[:, 2])'], {'axis': '(1)'}), '((new_dx, new_dy, lengths[:, 2]), axis=1)\n', (3711, 3752), True, 'import numpy as np\n'), ((4135, 4153), 'numpy.unique', 'np.unique', (['sem_cls'], {}), '(sem_cls)\n', (4144, 4153), True, 'import numpy as np\n'), ((5388, 5416), 'numpy.ones', 'np.ones', (['(8)'], {'dtype': 'np.float32'}), '(8, dtype=np.float32)\n', (5395, 5416), True, 'import numpy as np\n'), ((5434, 5486), 'numpy.vstack', 'np.vstack', (['[x_corners, y_corners, z_corners, hcoord]'], {}), '([x_corners, y_corners, z_corners, hcoord])\n', (5443, 5486), True, 'import numpy as np\n'), ((5721, 5742), 'numpy.dot', 'np.dot', (['R', 'corners_3d'], {}), '(R, corners_3d)\n', (5727, 5742), True, 'import numpy as np\n'), ((5760, 5784), 'numpy.transpose', 'np.transpose', (['corners_3d'], {}), '(corners_3d)\n', (5772, 5784), True, 'import numpy as np\n'), ((6276, 6312), 'numpy.expand_dims', 'np.expand_dims', (['box_size[..., 0]', '(-1)'], {}), '(box_size[..., 0], -1)\n', (6290, 6312), True, 'import numpy as np\n'), ((6336, 6372), 'numpy.expand_dims', 'np.expand_dims', (['box_size[..., 1]', '(-1)'], {}), '(box_size[..., 1], -1)\n', (6350, 6372), True, 'import numpy as np\n'), ((6380, 6416), 'numpy.expand_dims', 'np.expand_dims', (['box_size[..., 2]', '(-1)'], {}), '(box_size[..., 2], -1)\n', (6394, 6416), True, 'import numpy as np\n'), ((6500, 6587), 'numpy.concatenate', 'np.concatenate', (['(l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2, 1)', '(-1)'], {}), '((l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2,\n 1), -1)\n', (6514, 6587), True, 'import numpy as np\n'), ((6587, 6674), 'numpy.concatenate', 'np.concatenate', (['(h / 2, h / 2, h / 2, h / 2, -h / 2, -h / 2, -h / 2, -h / 2, 1)', '(-1)'], {}), '((h / 2, h / 2, h / 2, h / 2, -h / 2, -h / 2, -h / 2, -h / 2,\n 1), -1)\n', (6601, 6674), True, 'import numpy as np\n'), ((6674, 6761), 'numpy.concatenate', 'np.concatenate', (['(w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2, 1)', '(-1)'], {}), '((w / 2, -w / 2, -w / 2, w / 2, w / 2, -w / 2, -w / 2, w / 2,\n 1), -1)\n', (6688, 6761), True, 'import numpy as np\n'), ((7718, 7742), 'numpy.transpose', 'np.transpose', (['corners_3d'], {}), '(corners_3d)\n', (7730, 7742), True, 'import numpy as np\n'), ((8048, 8065), 'numpy.argsort', 'np.argsort', (['score'], {}), '(score)\n', (8058, 8065), True, 'import numpy as np\n'), ((2347, 2361), 'scipy.spatial.Delaunay', 'Delaunay', (['hull'], {}), '(hull)\n', (2355, 2361), False, 'from scipy.spatial import Delaunay\n'), ((3147, 3168), 'numpy.transpose', 'np.transpose', (['rot_mat'], {}), '(rot_mat)\n', (3159, 3168), True, 'import numpy as np\n'), ((3404, 3430), 'numpy.zeros', 'np.zeros', (['(dx.shape[0], 3)'], {}), '((dx.shape[0], 3))\n', (3412, 3430), True, 'import numpy as np\n'), ((3630, 3646), 'numpy.max', 'np.max', (['new_x', '(1)'], {}), '(new_x, 1)\n', (3636, 3646), True, 'import numpy as np\n'), ((3664, 3680), 'numpy.max', 'np.max', (['new_y', '(1)'], {}), '(new_y, 1)\n', (3670, 3680), True, 'import numpy as np\n'), ((4417, 4458), 'numpy.where', 'np.where', (["(sem_cls == cls_book['dominant'])"], {}), "(sem_cls == cls_book['dominant'])\n", (4425, 4458), True, 'import numpy as np\n'), ((7504, 7548), 'numpy.vstack', 'np.vstack', (['[x_corners, y_corners, z_corners]'], {}), '([x_corners, y_corners, z_corners])\n', (7513, 7548), True, 'import numpy as np\n'), ((8181, 8216), 'numpy.maximum', 'np.maximum', (['x1[i]', 'x1[I[:last - 1]]'], {}), '(x1[i], x1[I[:last - 1]])\n', (8191, 8216), True, 'import numpy as np\n'), ((8229, 8264), 'numpy.maximum', 'np.maximum', (['y1[i]', 'y1[I[:last - 1]]'], {}), '(y1[i], y1[I[:last - 1]])\n', (8239, 8264), True, 'import numpy as np\n'), ((8277, 8312), 'numpy.maximum', 'np.maximum', (['z1[i]', 'z1[I[:last - 1]]'], {}), '(z1[i], z1[I[:last - 1]])\n', (8287, 8312), True, 'import numpy as np\n'), ((8325, 8360), 'numpy.minimum', 'np.minimum', (['x2[i]', 'x2[I[:last - 1]]'], {}), '(x2[i], x2[I[:last - 1]])\n', (8335, 8360), True, 'import numpy as np\n'), ((8373, 8408), 'numpy.minimum', 'np.minimum', (['y2[i]', 'y2[I[:last - 1]]'], {}), '(y2[i], y2[I[:last - 1]])\n', (8383, 8408), True, 'import numpy as np\n'), ((8421, 8456), 'numpy.minimum', 'np.minimum', (['z2[i]', 'z2[I[:last - 1]]'], {}), '(z2[i], z2[I[:last - 1]])\n', (8431, 8456), True, 'import numpy as np\n'), ((8521, 8545), 'numpy.maximum', 'np.maximum', (['(0)', '(xx2 - xx1)'], {}), '(0, xx2 - xx1)\n', (8531, 8545), True, 'import numpy as np\n'), ((8556, 8580), 'numpy.maximum', 'np.maximum', (['(0)', '(yy2 - yy1)'], {}), '(0, yy2 - yy1)\n', (8566, 8580), True, 'import numpy as np\n'), ((8591, 8615), 'numpy.maximum', 'np.maximum', (['(0)', '(zz2 - zz1)'], {}), '(0, zz2 - zz1)\n', (8601, 8615), True, 'import numpy as np\n'), ((436, 460), 'plyfile.PlyData', 'PlyData', (['[el]'], {'text': 'text'}), '([el], text=text)\n', (443, 460), False, 'from plyfile import PlyData, PlyElement\n'), ((3525, 3546), 'numpy.transpose', 'np.transpose', (['rot_mat'], {}), '(rot_mat)\n', (3537, 3546), True, 'import numpy as np\n'), ((4236, 4263), 'numpy.where', 'np.where', (['(sem_cls == cls_id)'], {}), '(sem_cls == cls_id)\n', (4244, 4263), True, 'import numpy as np\n'), ((8859, 8890), 'numpy.where', 'np.where', (['(o > overlap_threshold)'], {}), '(o > overlap_threshold)\n', (8867, 8890), True, 'import numpy as np\n')] |
#!/usr/bin/env python3.5
import argparse
import logging
import time
import cv2
import numpy as np
import tensorflow as tf
from tf_pose import common
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
import datetime
from threading import Thread
import pickle
import io
# This file(run_webcam.py) is heavily changed to capture
# and store standard pose data for further machine learning
class WebcamVideoStream:
def __init__(self, capture):
# initialize the video camera stream and read the first frame
# from the stream
self.stream = capture
(self.grabbed, self.frame) = self.stream.read()
# initialize the variable used to indicate if the thread should
# be stopped
self.stopped = False
def start(self):
# start the thread to read frames from the video stream
Thread(target=self.update, args=()).start()
return self
def update(self):
# keep looping infinitely until the thread is stopped
while True:
# if the thread indicator variable is set, stop the thread
if self.stopped:
return
# otherwise, read the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# return the frame most recently read
return self.frame
def stop(self):
# indicate that the thread should be stopped
self.stopped = True
# define binery data
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
# define integer data
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# define float data
def _float32_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
logger = logging.getLogger('TfPoseEstimator-WebCam')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
def textCountdown(t, mString):
progressBar = '>>>>>>>>>'
while t:
print(progressBar + mString + str(t))
time.sleep(1)
t -= 1
progressBar += '>>>>>>>>>'
def captureImage(recordTypeNum, recording_time,recording_interval, vs, imageList):
recordTypes = ['000 GOOD MOVES 000','111 BAD MOVES 111']
recordTypeString = recordTypes[recordTypeNum]
textCountdown(3, 'Capture session' + recordTypeString +' start in :' )
start_time = time.time()
while True:
if ((time.time() - start_time) >= recording_time):
print('Time up!')
break
else:
image = vs.read()
group_index =int(np.floor((time.time() - start_time)/recording_interval))
print('adding image to group:' + str(group_index) )
imageList[group_index] += [image]
# cv2.putText(image,str(len(HumanFrames)),(10, 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('tf-pose-estimation result', image)
image = None
if cv2.waitKey(1) == 27:
break
cv2.waitKey(10)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='tf-pose-estimation realtime webcam')
parser.add_argument('--camera', type=int, default=0)
parser.add_argument('--resize', type=str, default='304x224',
help='if provided, resize images before they are processed. default=0x0, Recommends : 432x368 or 656x368 or 1312x736 ')
parser.add_argument('--resize-out-ratio', type=float, default=4.0,
help='if provided, resize heatmaps before they are post-processed. default=1.0')
parser.add_argument('--model', type=str, default='mobilenet_thin', help='cmu / mobilenet_thin')
parser.add_argument('--show-process', type=bool, default=False,
help='for debug purpose, if enabled, speed for inference is dropped.')
args = parser.parse_args()
logger.debug('initialization %s : %s' % (args.model, get_graph_path(args.model)))
w, h = model_wh(args.resize)
if w > 0 and h > 0:
e = TfPoseEstimator(get_graph_path(args.model), target_size=(w, h))
else:
e = TfPoseEstimator(get_graph_path(args.model), target_size=(432, 368))
logger.debug('cam read+')
cam = cv2.VideoCapture(args.camera)
print("WebcamVideoStream instance 'vs' is created")
vs = WebcamVideoStream(cam).start()
#frameNumber = 0
goodSampleSize = 5
badSampleSize = 5
recording_time = 4.0
recording_interval = 0.2
groupNumber = np.floor(recording_time / recording_interval)
imageSetGood = []
imageSetBad = []
dataSet = []
exerciseName = 'torsoTwist'
for i in range(int(groupNumber)):
imageSetGood.append([])
for i in range(int(groupNumber)):
imageSetBad.append([])
for i in range(int(groupNumber)):
dataSet.append([])
# label for good moves:0 / bad moves: 1
labelSet=[]
for i in range(int(groupNumber)):
labelSet.append([])
body = []
timeRatio = []
#process time of pose estimation with current setting is about 0.125 sec/frame
#frameLimit = int(round(recording_time/0.125))
#print('Limit of frame number is:' + str(frameLimit))
#Target exercises:In situ high knee / wood chop / Plank*40Sec
print(exerciseName +', left *1 right *1 ,recording time=' + str(recording_time) + 'Secs')
for i in range(goodSampleSize):
captureImage(0,recording_time,recording_interval,vs,imageSetGood)
for i in range(badSampleSize):
captureImage(1, recording_time, recording_interval, vs, imageSetBad)
for i in range(int(groupNumber)):
print('processing Good Sample of group number:' +str(i))
for image in imageSetGood[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
#print(humans)
if ((humans != []) & (len(humans)==1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(0)
#imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
#cv2.imshow("process result", imageC)
imageC = None
#cv2.waitKey(5)
for i in range(int(groupNumber)):
print('processing Bad sample of group number:' + str(i))
for image in imageSetBad[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
#print(humans)
if ((humans != []) & (len(humans) == 1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(1)
#imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
#cv2.imshow("process result", imageC)
imageC = None
#cv2.waitKey(5)
#Free memory space for better processing speed
del imageSetGood
del imageSetBad
print('image set flushed!!')
#Restart imageSets
imageSetGood = []
imageSetBad = []
for i in range(int(groupNumber)):
imageSetGood.append([])
for i in range(int(groupNumber)):
imageSetBad.append([])
print(exerciseName+', left *1 right *1 ,recording time=' + str(recording_time) + 'Secs')
for i in range(goodSampleSize):
captureImage(0, recording_time, recording_interval, vs, imageSetGood)
for i in range(badSampleSize):
captureImage(1, recording_time, recording_interval, vs, imageSetBad)
for i in range(int(groupNumber)):
print('processing Good Sample of group number:' + str(i))
for image in imageSetGood[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
#print(humans)
if ((humans != []) & (len(humans) == 1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(0)
# imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
# cv2.imshow("process result", imageC)
imageC = None
# cv2.waitKey(5)
for i in range(int(groupNumber)):
print('processing Bad sample of group number:' + str(i))
for image in imageSetBad[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
#print(humans)
if ((humans != []) & (len(humans) == 1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(1)
# imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
# cv2.imshow("process result", imageC)
imageC = None
# cv2.waitKey(5)
# Free memory space for better processing speed
del imageSetGood
del imageSetBad
print('image set flushed!!')
# Restart imageSets
imageSetGood = []
imageSetBad = []
for i in range(int(groupNumber)):
imageSetGood.append([])
for i in range(int(groupNumber)):
imageSetBad.append([])
print(exerciseName+', left *1 right *1 ,recording time=' + str(recording_time) + 'Secs')
for i in range(goodSampleSize):
captureImage(0, recording_time, recording_interval, vs, imageSetGood)
for i in range(badSampleSize):
captureImage(1, recording_time, recording_interval, vs, imageSetBad)
for i in range(int(groupNumber)):
print('processing Good Sample of group number:' + str(i))
for image in imageSetGood[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
# print(humans)
if ((humans != []) & (len(humans) == 1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(0)
# imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
# cv2.imshow("process result", imageC)
imageC = None
# cv2.waitKey(5)
for i in range(int(groupNumber)):
print('processing Bad sample of group number:' + str(i))
for image in imageSetBad[i]:
temp = []
imageC = image.copy()
humans = e.inference(imageC, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
# print(humans)
if ((humans != []) & (len(humans) == 1)):
for human in humans:
for j in range(common.CocoPart.Background.value):
if j not in human.body_parts.keys():
temp.append(0.0)
temp.append(0.0)
continue
body_part = human.body_parts[j]
coord = [body_part.x, body_part.y]
temp.append(coord[0])
temp.append(coord[1])
dataSet[i].append(temp)
labelSet[i].append(1)
# imageC = TfPoseEstimator.draw_humans(imageC, humans, imgcopy=False)
# cv2.imshow("process result", imageC)
imageC = None
# cv2.waitKey(5)
print(dataSet)
print(labelSet)
print(np.shape(dataSet))
print(np.shape(labelSet))
output = open( exerciseName+'Data3.pkl', 'wb')
pickle.dump(dataSet, output)
output.close()
output = open(exerciseName+'Label3.pkl', 'wb')
pickle.dump(labelSet, output)
output.close()
pkl_file = open(exerciseName+'Data3.pkl', 'rb')
highKneeData = pickle.load(pkl_file)
pkl_file.close()
print(highKneeData)
pkl_file = open(exerciseName + 'Label3.pkl', 'rb')
highKneeLabel = pickle.load(pkl_file)
pkl_file.close()
print(highKneeLabel)
cv2.destroyAllWindows()
vs.stop()
| [
"logging.getLogger",
"logging.StreamHandler",
"time.sleep",
"tensorflow.train.Int64List",
"cv2.imshow",
"cv2.destroyAllWindows",
"tf_pose.networks.model_wh",
"argparse.ArgumentParser",
"tf_pose.networks.get_graph_path",
"tensorflow.train.FloatList",
"cv2.waitKey",
"numpy.floor",
"pickle.load... | [((1889, 1932), 'logging.getLogger', 'logging.getLogger', (['"""TfPoseEstimator-WebCam"""'], {}), "('TfPoseEstimator-WebCam')\n", (1906, 1932), False, 'import logging\n'), ((1969, 1992), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1990, 1992), False, 'import logging\n'), ((2032, 2105), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s"""'], {}), "('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')\n", (2049, 2105), False, 'import logging\n'), ((14720, 14743), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (14741, 14743), False, 'import cv2\n'), ((2635, 2646), 'time.time', 'time.time', ([], {}), '()\n', (2644, 2646), False, 'import time\n'), ((3333, 3406), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""tf-pose-estimation realtime webcam"""'}), "(description='tf-pose-estimation realtime webcam')\n", (3356, 3406), False, 'import argparse\n'), ((4243, 4264), 'tf_pose.networks.model_wh', 'model_wh', (['args.resize'], {}), '(args.resize)\n', (4251, 4264), False, 'from tf_pose.networks import get_graph_path, model_wh\n'), ((4495, 4524), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.camera'], {}), '(args.camera)\n', (4511, 4524), False, 'import cv2\n'), ((4762, 4807), 'numpy.floor', 'np.floor', (['(recording_time / recording_interval)'], {}), '(recording_time / recording_interval)\n', (4770, 4807), True, 'import numpy as np\n'), ((14283, 14311), 'pickle.dump', 'pickle.dump', (['dataSet', 'output'], {}), '(dataSet, output)\n', (14294, 14311), False, 'import pickle\n'), ((14387, 14416), 'pickle.dump', 'pickle.dump', (['labelSet', 'output'], {}), '(labelSet, output)\n', (14398, 14416), False, 'import pickle\n'), ((14508, 14529), 'pickle.load', 'pickle.load', (['pkl_file'], {}), '(pkl_file)\n', (14519, 14529), False, 'import pickle\n'), ((14651, 14672), 'pickle.load', 'pickle.load', (['pkl_file'], {}), '(pkl_file)\n', (14662, 14672), False, 'import pickle\n'), ((2284, 2297), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2294, 2297), False, 'import time\n'), ((14178, 14195), 'numpy.shape', 'np.shape', (['dataSet'], {}), '(dataSet)\n', (14186, 14195), True, 'import numpy as np\n'), ((14207, 14225), 'numpy.shape', 'np.shape', (['labelSet'], {}), '(labelSet)\n', (14215, 14225), True, 'import numpy as np\n'), ((1595, 1628), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (1613, 1628), True, 'import tensorflow as tf\n'), ((1720, 1753), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[value]'}), '(value=[value])\n', (1738, 1753), True, 'import tensorflow as tf\n'), ((1845, 1876), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': 'value'}), '(value=value)\n', (1863, 1876), True, 'import tensorflow as tf\n'), ((3133, 3179), 'cv2.imshow', 'cv2.imshow', (['"""tf-pose-estimation result"""', 'image'], {}), "('tf-pose-estimation result', image)\n", (3143, 3179), False, 'import cv2\n'), ((3276, 3291), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (3287, 3291), False, 'import cv2\n'), ((4317, 4343), 'tf_pose.networks.get_graph_path', 'get_graph_path', (['args.model'], {}), '(args.model)\n', (4331, 4343), False, 'from tf_pose.networks import get_graph_path, model_wh\n'), ((4403, 4429), 'tf_pose.networks.get_graph_path', 'get_graph_path', (['args.model'], {}), '(args.model)\n', (4417, 4429), False, 'from tf_pose.networks import get_graph_path, model_wh\n'), ((898, 933), 'threading.Thread', 'Thread', ([], {'target': 'self.update', 'args': '()'}), '(target=self.update, args=())\n', (904, 933), False, 'from threading import Thread\n'), ((2677, 2688), 'time.time', 'time.time', ([], {}), '()\n', (2686, 2688), False, 'import time\n'), ((3220, 3234), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3231, 3234), False, 'import cv2\n'), ((4203, 4229), 'tf_pose.networks.get_graph_path', 'get_graph_path', (['args.model'], {}), '(args.model)\n', (4217, 4229), False, 'from tf_pose.networks import get_graph_path, model_wh\n'), ((2855, 2866), 'time.time', 'time.time', ([], {}), '()\n', (2864, 2866), False, 'import time\n')] |
# -*- coding: utf-8 -*-
"""Tests for the models.model_api of hydromt."""
import os
from os.path import join, isfile
import xarray as xr
import numpy as np
from affine import Affine
import logging
from pyflwdir import core_d8
import hydromt
from hydromt import raster
from hydromt.models import MODELS
from hydromt.models.model_api import Model
__all__ = ["TestModel"]
logger = logging.getLogger(__name__)
class TestModel(Model):
_NAME = "testname"
_CONF = "test.ini"
_GEOMS = {}
_MAPS = {"elevtn": "dem", "flwdir": "ldd", "basins": "basins", "mask": "mask"}
_FOLDERS = ["data"]
def __init__(
self, root=None, mode="w", config_fn=None, data_libs=None, logger=logger
):
super().__init__(
root=root,
mode=mode,
config_fn=config_fn,
data_libs=data_libs,
logger=logger,
)
def setup_basemaps(self, region, res=0.5, crs=4326, add_geom=False):
_maps = {
"elevtn": {"func": _rand_float, "nodata": -9999.0},
"flwdir": {"func": _rand_d8, "nodata": core_d8._mv},
"mask": {"func": _rand_msk, "nodata": -1},
"basins": {"func": _rand_msk, "nodata": -1},
}
ds_base = _create_staticmaps(_maps, region["bbox"], res)
self.set_crs(crs)
rmdict = {k: v for k, v in self._MAPS.items() if k in ds_base.data_vars}
self.set_staticmaps(ds_base.rename(rmdict))
if add_geom:
self.set_staticgeoms(self.region, "region")
def setup_param(self, name, value):
nodatafloat = -999
da_param = xr.where(self.staticmaps[self._MAPS["basins"]], value, nodatafloat)
da_param.raster.set_nodata(nodatafloat)
da_param = da_param.rename(name)
self.set_staticmaps(da_param)
def read_staticmaps(self):
fn = join(self.root, "staticmaps.nc")
if not self._write:
self._staticmaps = xr.Dataset()
if fn is not None and isfile(fn):
self.logger.info(f"Read staticmaps from {fn}")
ds = xr.open_dataset(fn, mask_and_scale=False).load()
ds.close()
self.set_staticmaps(ds)
def write_staticmaps(self):
if not self._write:
raise IOError("Model opened in read-only mode")
ds_out = self.staticmaps
fn = join(self.root, "staticmaps.nc")
self.logger.info(f"Write staticmaps to {fn}")
ds_out.to_netcdf(fn)
def _rand_float(shape, dtype=np.float32):
return np.random.rand(*shape).astype(dtype)
def _rand_d8(shape):
d8 = core_d8._ds.ravel()
return d8.flat[np.random.randint(d8.size, size=shape)]
def _rand_msk(shape):
mks = np.array([0, 1, 2], dtype=np.int8)
return mks[np.random.randint(mks.size, size=shape)]
def _create_staticmaps(_maps, bbox, res):
w, s, e, n = bbox
shape = (6, 10)
transform = Affine(res, w, e, s, res, n)
data_vars = {n: (_maps[n]["func"](shape), _maps[n]["nodata"]) for n in _maps}
ds = raster.RasterDataset.from_numpy(data_vars=data_vars, transform=transform)
ds.raster.set_crs(4326)
return ds
| [
"logging.getLogger",
"numpy.random.rand",
"hydromt.raster.RasterDataset.from_numpy",
"os.path.join",
"xarray.Dataset",
"os.path.isfile",
"numpy.array",
"numpy.random.randint",
"xarray.where",
"affine.Affine",
"xarray.open_dataset",
"pyflwdir.core_d8._ds.ravel"
] | [((381, 408), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (398, 408), False, 'import logging\n'), ((2596, 2615), 'pyflwdir.core_d8._ds.ravel', 'core_d8._ds.ravel', ([], {}), '()\n', (2613, 2615), False, 'from pyflwdir import core_d8\n'), ((2709, 2743), 'numpy.array', 'np.array', (['[0, 1, 2]'], {'dtype': 'np.int8'}), '([0, 1, 2], dtype=np.int8)\n', (2717, 2743), True, 'import numpy as np\n'), ((2902, 2930), 'affine.Affine', 'Affine', (['res', 'w', 'e', 's', 'res', 'n'], {}), '(res, w, e, s, res, n)\n', (2908, 2930), False, 'from affine import Affine\n'), ((3022, 3095), 'hydromt.raster.RasterDataset.from_numpy', 'raster.RasterDataset.from_numpy', ([], {'data_vars': 'data_vars', 'transform': 'transform'}), '(data_vars=data_vars, transform=transform)\n', (3053, 3095), False, 'from hydromt import raster\n'), ((1617, 1684), 'xarray.where', 'xr.where', (["self.staticmaps[self._MAPS['basins']]", 'value', 'nodatafloat'], {}), "(self.staticmaps[self._MAPS['basins']], value, nodatafloat)\n", (1625, 1684), True, 'import xarray as xr\n'), ((1858, 1890), 'os.path.join', 'join', (['self.root', '"""staticmaps.nc"""'], {}), "(self.root, 'staticmaps.nc')\n", (1862, 1890), False, 'from os.path import join, isfile\n'), ((2356, 2388), 'os.path.join', 'join', (['self.root', '"""staticmaps.nc"""'], {}), "(self.root, 'staticmaps.nc')\n", (2360, 2388), False, 'from os.path import join, isfile\n'), ((2635, 2673), 'numpy.random.randint', 'np.random.randint', (['d8.size'], {'size': 'shape'}), '(d8.size, size=shape)\n', (2652, 2673), True, 'import numpy as np\n'), ((2759, 2798), 'numpy.random.randint', 'np.random.randint', (['mks.size'], {'size': 'shape'}), '(mks.size, size=shape)\n', (2776, 2798), True, 'import numpy as np\n'), ((1950, 1962), 'xarray.Dataset', 'xr.Dataset', ([], {}), '()\n', (1960, 1962), True, 'import xarray as xr\n'), ((1993, 2003), 'os.path.isfile', 'isfile', (['fn'], {}), '(fn)\n', (1999, 2003), False, 'from os.path import join, isfile\n'), ((2527, 2549), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (2541, 2549), True, 'import numpy as np\n'), ((2081, 2122), 'xarray.open_dataset', 'xr.open_dataset', (['fn'], {'mask_and_scale': '(False)'}), '(fn, mask_and_scale=False)\n', (2096, 2122), True, 'import xarray as xr\n')] |
import datetime
import random
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn as nn
from absl import app, flags, logging
from loguru import logger
from scipy import stats
from sklearn import metrics, model_selection
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from torch.utils.tensorboard import SummaryWriter
import config
import dataset
import engine
from model import BERTBaseUncased
from utils import categorical_accuracy, label_decoder, label_encoder
matplotlib.rcParams['interactive'] == True
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
writer = SummaryWriter()
logger.add("experiment.log")
flags.DEFINE_boolean('features', True, "")
flags.DEFINE_string('test_file', None, "")
flags.DEFINE_string('model_path', None, "")
FLAGS = flags.FLAGS
def main(_):
test_file = config.EVAL_PROC
model_path = config.MODEL_PATH
if FLAGS.test_file:
test_file = FLAGS.test_file
if FLAGS.model_path:
model_path = FLAGS.model_path
df_test = pd.read_fwf(test_file)
logger.info(f"Bert Model: {config.BERT_PATH}")
logger.info(
f"Current date and time :{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ")
logger.info(f"Test file: {test_file}")
logger.info(f"Test size : {len(df_test):.4f}")
trg = []
for i in range(len(df_test.values)):
trg.append(0)
test_dataset = dataset.BERTDataset(
review=df_test.values,
target=trg
)
test_data_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=config.VALID_BATCH_SIZE,
num_workers=3
)
device = config.device
model = BERTBaseUncased(config.DROPOUT)
model.load_state_dict(torch.load(
model_path, map_location=torch.device(device)))
model.to(device)
outputs, extracted_features = engine.predict_fn(
test_data_loader, model, device, extract_features=FLAGS.features)
df_test["predicted"] = outputs
# save file
df_test.to_csv('predictions.csv', header=None, index=False)
if __name__ == "__main__":
app.run(main)
| [
"torch.manual_seed",
"torch.utils.tensorboard.SummaryWriter",
"loguru.logger.add",
"engine.predict_fn",
"loguru.logger.info",
"random.seed",
"absl.flags.DEFINE_boolean",
"model.BERTBaseUncased",
"absl.app.run",
"datetime.datetime.now",
"numpy.random.seed",
"dataset.BERTDataset",
"torch.utils... | [((633, 650), 'random.seed', 'random.seed', (['SEED'], {}), '(SEED)\n', (644, 650), False, 'import random\n'), ((651, 671), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (665, 671), True, 'import numpy as np\n'), ((672, 695), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (689, 695), False, 'import torch\n'), ((696, 724), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (718, 724), False, 'import torch\n'), ((777, 792), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (790, 792), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((793, 821), 'loguru.logger.add', 'logger.add', (['"""experiment.log"""'], {}), "('experiment.log')\n", (803, 821), False, 'from loguru import logger\n'), ((823, 865), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""features"""', '(True)', '""""""'], {}), "('features', True, '')\n", (843, 865), False, 'from absl import app, flags, logging\n'), ((866, 908), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""test_file"""', 'None', '""""""'], {}), "('test_file', None, '')\n", (885, 908), False, 'from absl import app, flags, logging\n'), ((909, 952), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""model_path"""', 'None', '""""""'], {}), "('model_path', None, '')\n", (928, 952), False, 'from absl import app, flags, logging\n'), ((1194, 1216), 'pandas.read_fwf', 'pd.read_fwf', (['test_file'], {}), '(test_file)\n', (1205, 1216), True, 'import pandas as pd\n'), ((1222, 1268), 'loguru.logger.info', 'logger.info', (['f"""Bert Model: {config.BERT_PATH}"""'], {}), "(f'Bert Model: {config.BERT_PATH}')\n", (1233, 1268), False, 'from loguru import logger\n'), ((1382, 1420), 'loguru.logger.info', 'logger.info', (['f"""Test file: {test_file}"""'], {}), "(f'Test file: {test_file}')\n", (1393, 1420), False, 'from loguru import logger\n'), ((1573, 1627), 'dataset.BERTDataset', 'dataset.BERTDataset', ([], {'review': 'df_test.values', 'target': 'trg'}), '(review=df_test.values, target=trg)\n', (1592, 1627), False, 'import dataset\n'), ((1674, 1771), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'config.VALID_BATCH_SIZE', 'num_workers': '(3)'}), '(test_dataset, batch_size=config.\n VALID_BATCH_SIZE, num_workers=3)\n', (1701, 1771), False, 'import torch\n'), ((1842, 1873), 'model.BERTBaseUncased', 'BERTBaseUncased', (['config.DROPOUT'], {}), '(config.DROPOUT)\n', (1857, 1873), False, 'from model import BERTBaseUncased\n'), ((2024, 2112), 'engine.predict_fn', 'engine.predict_fn', (['test_data_loader', 'model', 'device'], {'extract_features': 'FLAGS.features'}), '(test_data_loader, model, device, extract_features=FLAGS.\n features)\n', (2041, 2112), False, 'import engine\n'), ((2265, 2278), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (2272, 2278), False, 'from absl import app, flags, logging\n'), ((1945, 1965), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (1957, 1965), False, 'import torch\n'), ((1320, 1343), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1341, 1343), False, 'import datetime\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import math
mpl.rcParams['text.usetex'] = True
def plotPD(data1, label1, data2, label2, fname):
max1 = np.amax(data1)
max2 = np.amax(data2)
maxx = 1.1*max(max1, max2)
data1[data1[:,1] == -1, 1] = maxx
data2[data2[:,1] == -1, 1] = maxx
plt.scatter(data1[:,0], data1[:,1], marker = '+', alpha=0.85, color='tab:blue', label=label1)
plt.scatter(data2[:,0], data2[:,1], marker = 'o' , alpha=0.6, label = label2\
, facecolors='none', edgecolors='tab:red', linewidths=2)
ax = plt.gca()
#ax.set_yticks([maxx])
#ax.set_yticklabels([r'$\infty$'], fontsize=20)
plt.hlines(maxx, xmin=0, xmax=maxx, ls='--', alpha=0.3, color='black')
plt.plot([0, maxx], [0, maxx], ls='--', alpha=0.5, color='black')
plt.xlabel('birth', fontsize=24)
plt.ylabel('death', fontsize=24)
plt.tight_layout()
plt.legend()
plt.legend(prop={'size': 20})
#plt.show()
plt.savefig('figures/'+fname+'.png', format='png')
plt.savefig('figures/'+fname+'.pdf', format='pdf')
plt.cla()
plt.clf()
dirr = 'Datasets/ripser_PD_results/'
datasets = ['Dragon', 'Fract', 'o3', 'torus4']
label1 = 'Ripser'
label2 = 'Dory'
data1 = np.loadtxt(dirr+'ripsdragon.txt', delimiter=',')
data2 = np.loadtxt('Datasets/Dragon/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripsdragonH1')
data1 = np.loadtxt(dirr+'ripsfract.txt', delimiter=',')
data2 = np.loadtxt('Datasets/Fract/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripsfractH1')
data1 = np.loadtxt(dirr+'ripsfractH2.txt', delimiter=',')
data2 = np.loadtxt('Datasets/Fract/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripsfractH2')
data1 = np.loadtxt(dirr+'ripso3.txt', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripso3H1')
data1 = np.loadtxt(dirr+'ripso3H2.txt', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripso3H2')
data1 = np.loadtxt(dirr+'ripstorus4.txt', delimiter=',')
data2 = np.loadtxt('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripstorusH1')
data1 = np.loadtxt(dirr+'ripstorus4H2.txt', delimiter=',')
data2 = np.loadtxt('Datasets/torus4/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='ripstorusH2')
label1 = 'Gudhi'
label2 = 'Dory'
data1 = np.loadtxt('Datasets/o3/Gudhi_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='Gudhio3H1')
data1 = np.loadtxt('Datasets/o3/Gudhi_H2.csv', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='Gudhio3H2')
data1 = np.loadtxt('Datasets/torus4/Gudhi_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='GudhitorusH1')
data1 = np.loadtxt('Datasets/torus4/Gudhi_H2.csv', delimiter=',')
data2 = np.loadtxt('Datasets/torus4/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='GudhitorusH2')
label1 = 'Eirene'
label2 = 'Dory'
data1 = np.loadtxt('Datasets/Dragon/Eirene_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/Dragon/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='EirenedragonH1')
data1 = np.loadtxt('Datasets/Fract/Eirene_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/Fract/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='EirenefractH1')
data1 = np.loadtxt('Datasets/Fract/Eirene_H2.csv', delimiter=',')
data2 = np.loadtxt('Datasets/Fract/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='EirenefractH2')
data1 = np.loadtxt('Datasets/o3/Eirene_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='Eireneo3H1')
data1 = np.loadtxt('Datasets/o3/Eirene_H2.csv', delimiter=',')
data2 = np.loadtxt('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='Eireneo3H2')
data1 = np.loadtxt('Datasets/torus4/Eirene_H1.csv', delimiter=',')
data2 = np.loadtxt('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')
plotPD(data1, label1, data2, label2, fname='EirenetorusH1')
| [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.cla",
"matplotlib.pyplot.hlines",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.tight_layout",
"numpy.loadtxt",
... | [((1441, 1491), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripsdragon.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripsdragon.txt', delimiter=',')\n", (1451, 1491), True, 'import numpy as np\n'), ((1498, 1563), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Dragon/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Dragon/DoryH1_pers_data.txt', delimiter=',')\n", (1508, 1563), True, 'import numpy as np\n'), ((1633, 1682), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripsfract.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripsfract.txt', delimiter=',')\n", (1643, 1682), True, 'import numpy as np\n'), ((1689, 1753), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Fract/DoryH1_pers_data.txt', delimiter=',')\n", (1699, 1753), True, 'import numpy as np\n'), ((1822, 1873), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripsfractH2.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripsfractH2.txt', delimiter=',')\n", (1832, 1873), True, 'import numpy as np\n'), ((1880, 1944), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Fract/DoryH2_pers_data.txt', delimiter=',')\n", (1890, 1944), True, 'import numpy as np\n'), ((2013, 2059), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripso3.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripso3.txt', delimiter=',')\n", (2023, 2059), True, 'import numpy as np\n'), ((2066, 2127), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')\n", (2076, 2127), True, 'import numpy as np\n'), ((2193, 2241), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripso3H2.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripso3H2.txt', delimiter=',')\n", (2203, 2241), True, 'import numpy as np\n'), ((2248, 2309), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')\n", (2258, 2309), True, 'import numpy as np\n'), ((2375, 2425), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripstorus4.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripstorus4.txt', delimiter=',')\n", (2385, 2425), True, 'import numpy as np\n'), ((2432, 2497), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')\n", (2442, 2497), True, 'import numpy as np\n'), ((2565, 2617), 'numpy.loadtxt', 'np.loadtxt', (["(dirr + 'ripstorus4H2.txt')"], {'delimiter': '""","""'}), "(dirr + 'ripstorus4H2.txt', delimiter=',')\n", (2575, 2617), True, 'import numpy as np\n'), ((2624, 2689), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/torus4/DoryH2_pers_data.txt', delimiter=',')\n", (2634, 2689), True, 'import numpy as np\n'), ((2791, 2844), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/Gudhi_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/o3/Gudhi_H1.csv', delimiter=',')\n", (2801, 2844), True, 'import numpy as np\n'), ((2853, 2914), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')\n", (2863, 2914), True, 'import numpy as np\n'), ((2981, 3034), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/Gudhi_H2.csv"""'], {'delimiter': '""","""'}), "('Datasets/o3/Gudhi_H2.csv', delimiter=',')\n", (2991, 3034), True, 'import numpy as np\n'), ((3043, 3104), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')\n", (3053, 3104), True, 'import numpy as np\n'), ((3171, 3228), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/Gudhi_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/torus4/Gudhi_H1.csv', delimiter=',')\n", (3181, 3228), True, 'import numpy as np\n'), ((3237, 3302), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')\n", (3247, 3302), True, 'import numpy as np\n'), ((3371, 3428), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/Gudhi_H2.csv"""'], {'delimiter': '""","""'}), "('Datasets/torus4/Gudhi_H2.csv', delimiter=',')\n", (3381, 3428), True, 'import numpy as np\n'), ((3437, 3502), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/torus4/DoryH2_pers_data.txt', delimiter=',')\n", (3447, 3502), True, 'import numpy as np\n'), ((3607, 3665), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Dragon/Eirene_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/Dragon/Eirene_H1.csv', delimiter=',')\n", (3617, 3665), True, 'import numpy as np\n'), ((3674, 3739), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Dragon/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Dragon/DoryH1_pers_data.txt', delimiter=',')\n", (3684, 3739), True, 'import numpy as np\n'), ((3810, 3867), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/Eirene_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/Fract/Eirene_H1.csv', delimiter=',')\n", (3820, 3867), True, 'import numpy as np\n'), ((3876, 3940), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Fract/DoryH1_pers_data.txt', delimiter=',')\n", (3886, 3940), True, 'import numpy as np\n'), ((4010, 4067), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/Eirene_H2.csv"""'], {'delimiter': '""","""'}), "('Datasets/Fract/Eirene_H2.csv', delimiter=',')\n", (4020, 4067), True, 'import numpy as np\n'), ((4076, 4140), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/Fract/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/Fract/DoryH2_pers_data.txt', delimiter=',')\n", (4086, 4140), True, 'import numpy as np\n'), ((4210, 4264), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/Eirene_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/o3/Eirene_H1.csv', delimiter=',')\n", (4220, 4264), True, 'import numpy as np\n'), ((4273, 4334), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH1_pers_data.txt', delimiter=',')\n", (4283, 4334), True, 'import numpy as np\n'), ((4402, 4456), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/Eirene_H2.csv"""'], {'delimiter': '""","""'}), "('Datasets/o3/Eirene_H2.csv', delimiter=',')\n", (4412, 4456), True, 'import numpy as np\n'), ((4465, 4526), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/o3/DoryH2_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/o3/DoryH2_pers_data.txt', delimiter=',')\n", (4475, 4526), True, 'import numpy as np\n'), ((4594, 4652), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/Eirene_H1.csv"""'], {'delimiter': '""","""'}), "('Datasets/torus4/Eirene_H1.csv', delimiter=',')\n", (4604, 4652), True, 'import numpy as np\n'), ((4661, 4726), 'numpy.loadtxt', 'np.loadtxt', (['"""Datasets/torus4/DoryH1_pers_data.txt"""'], {'delimiter': '""","""'}), "('Datasets/torus4/DoryH1_pers_data.txt', delimiter=',')\n", (4671, 4726), True, 'import numpy as np\n'), ((199, 213), 'numpy.amax', 'np.amax', (['data1'], {}), '(data1)\n', (206, 213), True, 'import numpy as np\n'), ((229, 243), 'numpy.amax', 'np.amax', (['data2'], {}), '(data2)\n', (236, 243), True, 'import numpy as np\n'), ((389, 487), 'matplotlib.pyplot.scatter', 'plt.scatter', (['data1[:, 0]', 'data1[:, 1]'], {'marker': '"""+"""', 'alpha': '(0.85)', 'color': '"""tab:blue"""', 'label': 'label1'}), "(data1[:, 0], data1[:, 1], marker='+', alpha=0.85, color=\n 'tab:blue', label=label1)\n", (400, 487), True, 'import matplotlib.pyplot as plt\n'), ((491, 624), 'matplotlib.pyplot.scatter', 'plt.scatter', (['data2[:, 0]', 'data2[:, 1]'], {'marker': '"""o"""', 'alpha': '(0.6)', 'label': 'label2', 'facecolors': '"""none"""', 'edgecolors': '"""tab:red"""', 'linewidths': '(2)'}), "(data2[:, 0], data2[:, 1], marker='o', alpha=0.6, label=label2,\n facecolors='none', edgecolors='tab:red', linewidths=2)\n", (502, 624), True, 'import matplotlib.pyplot as plt\n'), ((671, 680), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (678, 680), True, 'import matplotlib.pyplot as plt\n'), ((776, 846), 'matplotlib.pyplot.hlines', 'plt.hlines', (['maxx'], {'xmin': '(0)', 'xmax': 'maxx', 'ls': '"""--"""', 'alpha': '(0.3)', 'color': '"""black"""'}), "(maxx, xmin=0, xmax=maxx, ls='--', alpha=0.3, color='black')\n", (786, 846), True, 'import matplotlib.pyplot as plt\n'), ((855, 920), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, maxx]', '[0, maxx]'], {'ls': '"""--"""', 'alpha': '(0.5)', 'color': '"""black"""'}), "([0, maxx], [0, maxx], ls='--', alpha=0.5, color='black')\n", (863, 920), True, 'import matplotlib.pyplot as plt\n'), ((938, 970), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""birth"""'], {'fontsize': '(24)'}), "('birth', fontsize=24)\n", (948, 970), True, 'import matplotlib.pyplot as plt\n'), ((979, 1011), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""death"""'], {'fontsize': '(24)'}), "('death', fontsize=24)\n", (989, 1011), True, 'import matplotlib.pyplot as plt\n'), ((1029, 1047), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1045, 1047), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1068), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1066, 1068), True, 'import matplotlib.pyplot as plt\n'), ((1086, 1115), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'prop': "{'size': 20}"}), "(prop={'size': 20})\n", (1096, 1115), True, 'import matplotlib.pyplot as plt\n'), ((1154, 1208), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + fname + '.png')"], {'format': '"""png"""'}), "('figures/' + fname + '.png', format='png')\n", (1165, 1208), True, 'import matplotlib.pyplot as plt\n'), ((1213, 1267), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + fname + '.pdf')"], {'format': '"""pdf"""'}), "('figures/' + fname + '.pdf', format='pdf')\n", (1224, 1267), True, 'import matplotlib.pyplot as plt\n'), ((1281, 1290), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (1288, 1290), True, 'import matplotlib.pyplot as plt\n'), ((1299, 1308), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1306, 1308), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
"""
Helper functions and classes for general use.
"""
from __future__ import division
from functools import partial, update_wrapper
from time import localtime, strftime
import numpy as np
from numpy.linalg import norm
import rospy
from geometry_msgs.msg import Point, PoseStamped, Quaternion
from sensor_msgs.msg import Image
from std_msgs.msg import Header
import tf
d2r = np.deg2rad
r2d = np.rad2deg
EULER_CONVENTION = "rxyz"
def unit_vector(v):
"""
Change the length of the vector to unity in the same direction.
Parameters
----------
v : array-like
A vector to be normalized.
Returns
-------
np.ndarray
The normalized vector, or the original vector if it has a length of 0.
"""
norm = np.linalg.norm(v)
if norm:
return v / norm
else:
return np.asarray(v)
# noinspection PyPep8Naming
class memoize(object):
def __init__(self, func):
self.func = func
update_wrapper(self, func)
def __get__(self, instance, owner):
if instance is None:
return self.func
return partial(self, instance)
def __call__(self, *args, **kwargs):
obj = args[0]
try:
cache = obj.__cache__
except AttributeError:
cache = obj.__cache__ = {}
key = (self.func, args[1:], frozenset(kwargs.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kwargs)
return res
class Pose(object):
"""
Convenience wrapper for PoseStamped.
Parameters
----------
pose_stamped : PoseStamped
The pose message.
Attributes
----------
pose_stamped : PoseStamped
The pose message.
position : np.ndarray
The x, y, and z coordinates contained in the pose.
orientation : np.ndarray
The x, y, z, and w quaternion contained in the pose.
header : Header
The header from the pose message
"""
def __init__(self, pose_stamped):
self.pose_stamped = pose_stamped
self.position, self.orientation = self._components(self.pose_stamped)
self.header = self.pose_stamped.header
def rel_position(self, pose, rotation_matrix=None):
"""
Calculate the relative position with another pose, with local reference.
Parameters
----------
pose : Pose
The target pose.
rotation_matrix : Optional[np.ndarray]
The rotation matrix to use. If not provided, the rotation matrix of
the current pose is used.
Returns
-------
np.ndarray
The x, y, z relative positions.
"""
if rotation_matrix is None:
rotation_matrix = Quat.rotation_matrix(self.orientation)
return rotation_matrix.dot(pose.position - self.position)
def rel_euler(self, pose):
"""
Calculate the relative angle with another pose.
Parameters
----------
pose : Pose
The target pose.
Returns
-------
np.ndarray
The relative angle as Euler, in the order of pitch, roll, yaw.
"""
return Quat.to_euler(Quat.rel_rotation(pose.orientation,
self.orientation))
def distance(self, pose):
"""
Calculate the distance to another pose.
Parameters
----------
pose : Pose
The target pose.
Returns
-------
float
The distance to the target pose.
"""
return norm(pose.position - self.position)
@staticmethod
def _components(pose_stamped):
"""
Return the position and orientation of a PoseStamped as numpy arrays.
Parameters
----------
pose_stamped : Pose(WithCovariance)?(Stamped)?
The pose to be decomposed.
Returns
-------
position : np.ndarray
The x, y, and z coordinates contained in the pose.
orientation : np.ndarray
The x, y, z, and w quaternion contained in the pose.
"""
position = np.array([pose_stamped.pose.position.x,
pose_stamped.pose.position.y,
pose_stamped.pose.position.z])
orientation = np.array([pose_stamped.pose.orientation.x,
pose_stamped.pose.orientation.y,
pose_stamped.pose.orientation.z,
pose_stamped.pose.orientation.w])
return position, orientation
@classmethod
def from_components(cls, position, orientation, sequence=0):
"""
Generate a Pose from its components.
Parameters
----------
position : Sequence[float]
The x, y, and z coordinates of the pose.
orientation : Sequence[float]
The x, y, z, and w quaternion of the pose.
sequence : Optional[int]
The sequence number of the pose.
Returns
-------
Pose
The generated pose.
"""
return cls(cls.generate_stamped(position, orientation, sequence))
@staticmethod
def generate_stamped(position, orientation, sequence=0):
"""
Generate a PoseStamped from its components.
Parameters
----------
position : Sequence[float]
The x, y, and z coordinates of the pose.
orientation : Sequence[float]
The x, y, z, and w quaternion of the pose.
sequence : Optional[int]
The sequence number of the pose.
Returns
-------
PoseStamped
The generated pose.
"""
pose_stamped = PoseStamped()
pose_stamped.header.seq = sequence
try:
pose_stamped.header.stamp = rospy.Time.now()
except rospy.exceptions.ROSInitException:
pass
pose_stamped.pose.position = Point(*position)
pose_stamped.pose.orientation = Quaternion(*orientation)
return pose_stamped
def __repr__(self):
return "<Pose ({position}, {orientation})>".format(
position=self.position.tolist(),
orientation=self.orientation.tolist(),
time=self.header.stamp)
def __str__(self):
return "<Pose ({position}, {orientation}): {time}>".format(
position=self.position.tolist(),
orientation=self.orientation.tolist(),
time=self.header.stamp)
class Frame(object):
"""
Encapsulate an image and the pose it was taken in.
Parameters
----------
pose_stamped : PoseStamped
The pose of the drone when the image was taken.
image : Image
The image that was taken.
Attributes
----------
pose_stamped : PoseStamped
The raw pose message of the drone at which the image was taken.
pose : Pose
The pose of the drone at which the image was taken.
rotation_matrix : np.ndarray
The rotation matrix of the frame orientation.
image : Image
The image that was taken.
stamp : rospy.rostime.Time
The timestamp of the pose.
stamp_str : str
The timestamp of the pose, in human readable format.
"""
def __init__(self, pose_stamped, image):
self.pose_stamped = pose_stamped
self.pose = Pose(pose_stamped)
self.rotation_matrix = Quat.rotation_matrix(self.pose.orientation)
self.image = image
self.stamp = self.pose.header.stamp
self.stamp_str = strftime("%Y-%m-%d %H:%M:%S",
localtime(self.stamp.to_time()))
@memoize
def rel_position(self, pose):
"""
Calculate the relative position with another pose, with local reference.
Parameters
----------
pose : Pose
The target pose.
Returns
-------
np.ndarray
The x, y, z relative positions.
"""
return self.pose.rel_position(pose,
rotation_matrix=self.rotation_matrix)
@memoize
def rel_euler(self, pose):
"""
Calculate the relative angle with another pose.
Parameters
----------
pose : Pose
The target pose.
Returns
-------
np.ndarray
The relative angle as Euler, in the order of pitch, roll, yaw.
"""
return self.pose.rel_euler(pose)
@memoize
def distance(self, pose):
"""
Calculate the distance to another pose.
Parameters
----------
pose : Pose
The target pose.
Returns
-------
float
The distance to the target pose.
"""
return self.pose.distance(pose)
def __repr__(self):
return "<Frame({pose})>".format(pose=self.pose)
class Fov(object):
"""
Field of view methods.
"""
@staticmethod
def d2v(fov_diagonal, aspect_ratio=4 / 3):
"""
Convert a diagonal field of view to vertical.
Parameters
----------
fov_diagonal : float
The diagonal field of view.
aspect_ratio: Optional[float]
The aspect ratio of the display. Default is 4:3.
Returns
-------
float
The vertical field of view.
"""
ratio_diagonal = np.sqrt(1 + aspect_ratio**2)
return 2 * r2d(np.arctan(np.tan(d2r(fov_diagonal) / 2)
/ ratio_diagonal))
@staticmethod
def v2h(fov_vertical, aspect_ratio=4 / 3):
"""
Convert a vertical field of view to horizontal.
Parameters
----------
fov_vertical : float
The vertical field of view.
aspect_ratio: Optional[float]
The aspect ratio of the display. Default is 4:3.
Returns
-------
float
The horizontal field of view.
"""
return 2 * r2d(np.arctan(np.tan(d2r(fov_vertical) / 2) * aspect_ratio))
class Quat(object):
"""
Quaternion methods.
"""
@staticmethod
def to_euler(quaternion):
"""
Change a quaternion to an Euler angle representation.
Parameters
----------
quaternion : np.ndarray
A quaternion in the order of x, y, z, w.
Returns
-------
np.ndarray
The Euler angle, in the order of pitch, roll, yaw.
"""
# noinspection PyUnresolvedReferences
return tf.transformations.euler_from_quaternion(quaternion,
EULER_CONVENTION)
@staticmethod
def to_axis(quaternion):
"""
Change a quaternion to an axis-angle representation.
Parameters
----------
quaternion : np.ndarray
A quaternion in the order of x, y, z, w.
Notes
-----
θ is in degrees rather than radians, for ease of integration in OpenGL.
Returns
-------
tuple
The angle in axis-angle representation, with the order of θ, x, y,
z. θ is in degrees.
"""
x, y, z, w = unit_vector(quaternion)
angle = r2d(2 * np.arccos(w))
if angle == 0:
axis_x = 1
axis_y = axis_z = 0
elif angle % 180 == 0:
axis_x, axis_y, axis_z = x, y, z
else:
axis_x = x / np.sqrt(1 - w**2)
axis_y = y / np.sqrt(1 - w**2)
axis_z = z / np.sqrt(1 - w**2)
return angle, axis_x, axis_y, axis_z
@staticmethod
def product(a, b):
"""
Find the product of two quaternions.
Parameters
----------
a : Sequence[float]
A quaternion, in the order of x, y, z, w
b : Sequence[float]
A quaternion, in the order of x, y, z, w
Returns
-------
np.ndarray
A quaternion, in the order of x, y, z, w
"""
imaginary_part = a[3] * b[:3] + b[3] * a[:3] + np.cross(a[:3], b[:3])
real_part = a[3] * b[3] - np.dot(a[:3], b[:3])
return np.append(imaginary_part, real_part)
@staticmethod
def inverse(quaternion):
"""
Return the inverse of a quaternion
Parameters
----------
quaternion : Sequence[float]
A quaternion, in the order of x, y, z, w
Returns
-------
np.ndarray
The inverse of the quaternion.
"""
return (quaternion * np.array([-1, -1, -1, 1])
/ np.linalg.norm(quaternion)**2)
@staticmethod
def rel_rotation(a, b):
"""
Find the quaternion which produces a rotation from `a` to `b`.
Parameters
----------
a : Sequence[float]
A quaternion, in the order of x, y, z, w
b : Sequence[float]
A quaternion, in the order of x, y, z, w
Returns
-------
np.ndarray
A quaternion, in the order of x, y, z, w
"""
return Quat.product(unit_vector(a), Quat.inverse(unit_vector(b)))
@staticmethod
def rotation_matrix(quaternion):
"""
Create the rotation matrix of a quaternion.
Parameters
----------
quaternion : np.ndarray
A quaternion in the order of x, y, z, w.
Returns
-------
np.ndarray
A 3x3 rotation matrix representing the quaternion.
References
----------
.. [1] Wikipedia, Rotation Matrix.
https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
"""
x, y, z, w = quaternion
n = sum(quaternion**2)
if n == 0:
return np.identity(3)
s = 2 / n
wx = s * w * x
wy = s * w * y
wz = s * w * z
xx = s * x * x
xy = s * x * y
xz = s * x * z
yy = s * y * y
yz = s * y * z
zz = s * z * z
return np.array([[1 - (yy + zz), xy - wz, wy],
[wz, 1 - (xx + zz), yz - wx],
[xz - wy, yz + wx, 1 - (xx + yy)]])
| [
"tf.transformations.euler_from_quaternion",
"numpy.identity",
"numpy.sqrt",
"numpy.cross",
"numpy.arccos",
"numpy.asarray",
"numpy.append",
"numpy.array",
"rospy.Time.now",
"geometry_msgs.msg.Point",
"functools.partial",
"geometry_msgs.msg.PoseStamped",
"geometry_msgs.msg.Quaternion",
"num... | [((779, 796), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (793, 796), True, 'import numpy as np\n'), ((859, 872), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (869, 872), True, 'import numpy as np\n'), ((989, 1015), 'functools.update_wrapper', 'update_wrapper', (['self', 'func'], {}), '(self, func)\n', (1003, 1015), False, 'from functools import partial, update_wrapper\n'), ((1130, 1153), 'functools.partial', 'partial', (['self', 'instance'], {}), '(self, instance)\n', (1137, 1153), False, 'from functools import partial, update_wrapper\n'), ((3679, 3714), 'numpy.linalg.norm', 'norm', (['(pose.position - self.position)'], {}), '(pose.position - self.position)\n', (3683, 3714), False, 'from numpy.linalg import norm\n'), ((4248, 4352), 'numpy.array', 'np.array', (['[pose_stamped.pose.position.x, pose_stamped.pose.position.y, pose_stamped.\n pose.position.z]'], {}), '([pose_stamped.pose.position.x, pose_stamped.pose.position.y,\n pose_stamped.pose.position.z])\n', (4256, 4352), True, 'import numpy as np\n'), ((4430, 4576), 'numpy.array', 'np.array', (['[pose_stamped.pose.orientation.x, pose_stamped.pose.orientation.y,\n pose_stamped.pose.orientation.z, pose_stamped.pose.orientation.w]'], {}), '([pose_stamped.pose.orientation.x, pose_stamped.pose.orientation.y,\n pose_stamped.pose.orientation.z, pose_stamped.pose.orientation.w])\n', (4438, 4576), True, 'import numpy as np\n'), ((5873, 5886), 'geometry_msgs.msg.PoseStamped', 'PoseStamped', ([], {}), '()\n', (5884, 5886), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((6105, 6121), 'geometry_msgs.msg.Point', 'Point', (['*position'], {}), '(*position)\n', (6110, 6121), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((6162, 6186), 'geometry_msgs.msg.Quaternion', 'Quaternion', (['*orientation'], {}), '(*orientation)\n', (6172, 6186), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((9596, 9626), 'numpy.sqrt', 'np.sqrt', (['(1 + aspect_ratio ** 2)'], {}), '(1 + aspect_ratio ** 2)\n', (9603, 9626), True, 'import numpy as np\n'), ((10761, 10831), 'tf.transformations.euler_from_quaternion', 'tf.transformations.euler_from_quaternion', (['quaternion', 'EULER_CONVENTION'], {}), '(quaternion, EULER_CONVENTION)\n', (10801, 10831), False, 'import tf\n'), ((12406, 12442), 'numpy.append', 'np.append', (['imaginary_part', 'real_part'], {}), '(imaginary_part, real_part)\n', (12415, 12442), True, 'import numpy as np\n'), ((14298, 14407), 'numpy.array', 'np.array', (['[[1 - (yy + zz), xy - wz, wy], [wz, 1 - (xx + zz), yz - wx], [xz - wy, yz +\n wx, 1 - (xx + yy)]]'], {}), '([[1 - (yy + zz), xy - wz, wy], [wz, 1 - (xx + zz), yz - wx], [xz -\n wy, yz + wx, 1 - (xx + yy)]])\n', (14306, 14407), True, 'import numpy as np\n'), ((5983, 5999), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (5997, 5999), False, 'import rospy\n'), ((12313, 12335), 'numpy.cross', 'np.cross', (['a[:3]', 'b[:3]'], {}), '(a[:3], b[:3])\n', (12321, 12335), True, 'import numpy as np\n'), ((12370, 12390), 'numpy.dot', 'np.dot', (['a[:3]', 'b[:3]'], {}), '(a[:3], b[:3])\n', (12376, 12390), True, 'import numpy as np\n'), ((14038, 14052), 'numpy.identity', 'np.identity', (['(3)'], {}), '(3)\n', (14049, 14052), True, 'import numpy as np\n'), ((11482, 11494), 'numpy.arccos', 'np.arccos', (['w'], {}), '(w)\n', (11491, 11494), True, 'import numpy as np\n'), ((12812, 12837), 'numpy.array', 'np.array', (['[-1, -1, -1, 1]'], {}), '([-1, -1, -1, 1])\n', (12820, 12837), True, 'import numpy as np\n'), ((12856, 12882), 'numpy.linalg.norm', 'np.linalg.norm', (['quaternion'], {}), '(quaternion)\n', (12870, 12882), True, 'import numpy as np\n'), ((11690, 11709), 'numpy.sqrt', 'np.sqrt', (['(1 - w ** 2)'], {}), '(1 - w ** 2)\n', (11697, 11709), True, 'import numpy as np\n'), ((11733, 11752), 'numpy.sqrt', 'np.sqrt', (['(1 - w ** 2)'], {}), '(1 - w ** 2)\n', (11740, 11752), True, 'import numpy as np\n'), ((11776, 11795), 'numpy.sqrt', 'np.sqrt', (['(1 - w ** 2)'], {}), '(1 - w ** 2)\n', (11783, 11795), True, 'import numpy as np\n')] |
"""
let's be simple
"""
import os
import sys
sys.path.append("../../../../")
import swhlab
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
import time
class ABF2(swhlab.ABF):
def simple(self,plotToo=True):
# RMS percentile
perRMS=75
perPSC=100-perRMS
percentileUp=100-perPSC/2
percentileDown=perPSC/2
# get moving window baseline subtracted data
X,Y=self.sweepX2,self.sweepY
Y[:.5*self.pointsPerSec]=np.nan
# figure out what our noise floor should be
noise=np.empty(len(Y))
noise[:]=np.nan
noiseUp=np.copy(noise)
noiseDown=np.copy(noise)
pad=self.pointsPerMs*50
for i in range(len(noise)):
if len(Y[i-pad:i+pad]):
noiseUp[i]=np.percentile(Y[i-pad:i+pad],percentileUp)
noiseDown[i]=np.percentile(Y[i-pad:i+pad],percentileDown)
noiseCenter=np.nanmean([noiseUp,noiseDown],axis=0)
noiseCenterPoint=np.nanmean(noiseCenter)
Y=Y-noiseCenter
realData=Y[.5*self.pointsPerSec:]
fracAbove=len(np.where(realData>(np.nanmean(noiseUp)-noiseCenterPoint))[0])/len(realData)
fracBelow=len(np.where(realData<(np.nanmean(noiseDown)-noiseCenterPoint))[0])/len(realData)
# create the plot
if plotToo:
plt.figure(figsize=(15,5))
plt.title("above / below = %.02f%% / %.02f%%"%(fracAbove*100,fracBelow*100))
plt.plot(X,Y,alpha=.5)
plt.axhline(0,color='k',lw=2)
plt.axhline(np.nanmean(noiseUp)-noiseCenterPoint,color='r',lw=2)
plt.axhline(np.nanmean(noiseDown)-noiseCenterPoint,color='r',lw=2)
plt.margins(0,.1)
plt.show()
return fracAbove,fracBelow
if __name__=="__main__":
#abfPath=r"X:\Data\2P01\2016\2016-09-01 PIR TGOT"
abfPath=r"C:\Users\scott\Documents\important\demodata"
abf=ABF2(os.path.join(abfPath,"16d14036.abf"))
#abf=ABF2(os.path.join(abfPath,"16d16007.abf"))
# above,below=np.empty(abf.sweeps),np.empty(abf.sweeps)
# for sweep in abf.setsweeps():
# print("analyzing sweep %d of %d"%(sweep,abf.sweeps))
# above[sweep],below[sweep]=abf.simple(plotToo=False)
#
# np.save("above.npy",above)
# np.save("below.npy",below)
above,below=np.load("above.npy"),np.load("below.npy")
plt.figure(figsize=(15,10))
plt.plot(np.arange(abf.sweeps)*abf.sweepLength,above,'b-')
plt.plot(np.arange(abf.sweeps)*abf.sweepLength,below,'r-')
plt.show()
#abf.setsweep(100)
#abf.setsweep(266)
#abf.simple()
print("DONE") | [
"numpy.copy",
"numpy.arange",
"matplotlib.pyplot.plot",
"os.path.join",
"matplotlib.pyplot.axhline",
"numpy.nanmean",
"matplotlib.pyplot.figure",
"numpy.percentile",
"matplotlib.pyplot.title",
"numpy.load",
"sys.path.append",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.show"
] | [((46, 77), 'sys.path.append', 'sys.path.append', (['"""../../../../"""'], {}), "('../../../../')\n", (61, 77), False, 'import sys\n'), ((2468, 2496), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (2478, 2496), True, 'import matplotlib.pyplot as plt\n'), ((2626, 2636), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2634, 2636), True, 'import matplotlib.pyplot as plt\n'), ((667, 681), 'numpy.copy', 'np.copy', (['noise'], {}), '(noise)\n', (674, 681), True, 'import numpy as np\n'), ((700, 714), 'numpy.copy', 'np.copy', (['noise'], {}), '(noise)\n', (707, 714), True, 'import numpy as np\n'), ((983, 1023), 'numpy.nanmean', 'np.nanmean', (['[noiseUp, noiseDown]'], {'axis': '(0)'}), '([noiseUp, noiseDown], axis=0)\n', (993, 1023), True, 'import numpy as np\n'), ((1047, 1070), 'numpy.nanmean', 'np.nanmean', (['noiseCenter'], {}), '(noiseCenter)\n', (1057, 1070), True, 'import numpy as np\n'), ((2009, 2046), 'os.path.join', 'os.path.join', (['abfPath', '"""16d14036.abf"""'], {}), "(abfPath, '16d14036.abf')\n", (2021, 2046), False, 'import os\n'), ((2417, 2437), 'numpy.load', 'np.load', (['"""above.npy"""'], {}), "('above.npy')\n", (2424, 2437), True, 'import numpy as np\n'), ((2438, 2458), 'numpy.load', 'np.load', (['"""below.npy"""'], {}), "('below.npy')\n", (2445, 2458), True, 'import numpy as np\n'), ((1411, 1438), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 5)'}), '(figsize=(15, 5))\n', (1421, 1438), True, 'import matplotlib.pyplot as plt\n'), ((1450, 1537), 'matplotlib.pyplot.title', 'plt.title', (["('above / below = %.02f%% / %.02f%%' % (fracAbove * 100, fracBelow * 100))"], {}), "('above / below = %.02f%% / %.02f%%' % (fracAbove * 100, fracBelow *\n 100))\n", (1459, 1537), True, 'import matplotlib.pyplot as plt\n'), ((1539, 1564), 'matplotlib.pyplot.plot', 'plt.plot', (['X', 'Y'], {'alpha': '(0.5)'}), '(X, Y, alpha=0.5)\n', (1547, 1564), True, 'import matplotlib.pyplot as plt\n'), ((1576, 1607), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(0)'], {'color': '"""k"""', 'lw': '(2)'}), "(0, color='k', lw=2)\n", (1587, 1607), True, 'import matplotlib.pyplot as plt\n'), ((1774, 1793), 'matplotlib.pyplot.margins', 'plt.margins', (['(0)', '(0.1)'], {}), '(0, 0.1)\n', (1785, 1793), True, 'import matplotlib.pyplot as plt\n'), ((1804, 1814), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1812, 1814), True, 'import matplotlib.pyplot as plt\n'), ((2509, 2530), 'numpy.arange', 'np.arange', (['abf.sweeps'], {}), '(abf.sweeps)\n', (2518, 2530), True, 'import numpy as np\n'), ((2572, 2593), 'numpy.arange', 'np.arange', (['abf.sweeps'], {}), '(abf.sweeps)\n', (2581, 2593), True, 'import numpy as np\n'), ((846, 893), 'numpy.percentile', 'np.percentile', (['Y[i - pad:i + pad]', 'percentileUp'], {}), '(Y[i - pad:i + pad], percentileUp)\n', (859, 893), True, 'import numpy as np\n'), ((918, 967), 'numpy.percentile', 'np.percentile', (['Y[i - pad:i + pad]', 'percentileDown'], {}), '(Y[i - pad:i + pad], percentileDown)\n', (931, 967), True, 'import numpy as np\n'), ((1630, 1649), 'numpy.nanmean', 'np.nanmean', (['noiseUp'], {}), '(noiseUp)\n', (1640, 1649), True, 'import numpy as np\n'), ((1707, 1728), 'numpy.nanmean', 'np.nanmean', (['noiseDown'], {}), '(noiseDown)\n', (1717, 1728), True, 'import numpy as np\n'), ((1187, 1206), 'numpy.nanmean', 'np.nanmean', (['noiseUp'], {}), '(noiseUp)\n', (1197, 1206), True, 'import numpy as np\n'), ((1285, 1306), 'numpy.nanmean', 'np.nanmean', (['noiseDown'], {}), '(noiseDown)\n', (1295, 1306), True, 'import numpy as np\n')] |
import numpy as np
def shift_mutation(perm):
"""
Performs a shift mutation on a permutation
"""
n = len(perm)
i = np.random.choice(n, 2, replace = False)
i = np.sort(i)
i0 = i[0]
i1 = i[1]
perm = np.concatenate((perm[i1:], perm[i0:i1], perm[:i0][::-1]))
return perm
def swap_mutation(perm, *args):
"""
Performs a swap mutation on a permutation
"""
n = len(perm)
i = np.random.choice(n, 2, replace = False)
perm[i] = perm[i[::-1]]
return perm
def reverse_mutation(perm, *args):
"""
Performs a reverse mutation on a permutation
"""
n = len(perm) - 1
i = np.random.choice(n, 1)[0]
perm[i:i+2] = perm[i:i+2][::-1]
return perm
def swap_primes_mutation(sub, perm, black_list, scale, n):
"""
Performs a swap mutation on a permutation.
Cities on the black list have a higher chance of being swapped with cities not on the blacklist,
if the former are on tenth steps.
Not used in the final project, it led to no improvement. Maybe a bug?
"""
l = len(perm)
cids = sub[:, 0].astype(int)
# boolean mask of city ids, ordered by the permutation, on the black list
bool_mask = black_list[cids[perm]]
# index of tenth steps:
# starting from 8, as this will be used for paths not starting from 0, but that will be prefixed with 0
tenths = np.arange(8, l, 10)
# -- computation of probability of selecting the first batch of cities
# the boolean mask becomes a binary string (the 1s are cities on the black list)
p1 = bool_mask.astype(int)
# The 1s corresponding to cities on the black list are assigned a higher weight
p1[tenths] *= scale
# every other city is assigned a small weight
p1[p1 == 0] = 1
# the weights are normalized to become probabilities
p1 = (p1 / sum(p1))
# n cities are selected, according to their weight
idx1 = np.random.choice(np.arange(l), n, replace=False, p=p1)
# -- computation of probabilities of selecting the second batch of cities
# negation of the first boolean mask, i.e., cities not on the black list, typed as a binary array
p2 = (~bool_mask).astype(int)
# The 1s corresponding to cities not on the black list and that are not tenth steps are assigned a higher weight
p2[np.delete(np.arange(l), tenths)] *= scale
# every other city is assigned a small weight
p2[p2 == 0] = 1
# cities selected in the first batch are assigned a 0 probability, so that there will not be doubles
p2[idx1] = 0
# the weights are normalized to become probabilities
p2 = (p2 / sum(p2))
# n cities are selected according to this new probabilies
idx2 = np.random.choice(np.arange(l), n, replace=False, p=p2)
# the cities are swapped
newperm = perm.copy()
newperm[idx1] = perm[idx2]
newperm[idx2] = perm[idx1]
return newperm
def reverse_primes_mutation(sub, perm, black_list, scale, n):
"""
Performs a swap mutation on a permutation.
Cities on the black list have a higher chance of being with cities not on the blacklist,
if the former are on tenth steps
"""
l = len(perm)
cids = sub[:, 0].astype(int)
# boolean mask of cities on the black list
bool_mask1 = black_list[cids[perm]]
# boolean mask of cities whose successor in the route is not on the black list
bool_mask2 = ~np.roll(bool_mask1, -1)
# conjunction of the two boolean masks:
# cities on the black list whose successor is not on the black list
bool_mask = bool_mask1 & bool_mask2
# index of tenth steps:
# starting from 8, as this will be used for paths not starting from 0, but that will be prefixed with 0
tenths = np.arange(8, l, 10)
# the boolean mask becomes a binary array
p1 = bool_mask.astype(int)
# 1s, corresponding to cities on the black list whose successor is not on the black list, are given a higher weight
p1[tenths] *= scale
# every other city is given a smaller weight
p1[p1 == 0] = 1
# if n > 1, some indices are set as 0 in order to not make overlapping reverses
if n > 1:
p1[np.arange(1, l, 2)] = 0
# the last element of the weight list is deleted,
# as the corresponding city does not have a successor to be swapped with
p1 = p1[:-1]
# the weights are normalized to become probabilities
p1 = (p1 / sum(p1))
# n cities are selected according to this probability
i = np.random.choice(np.arange(l - 1), n, replace=False, p=p1)
# the n cities selected are swapped with their successor
newperm = perm.copy()
newperm[i] = perm[i + 1]
newperm[i + 1] = perm[i]
return newperm
def SA(array, fit_fun, mut_fun, black_list, scale, n_to_mute,
maxIter = np.inf, maxIterNoChange=200, tmin=0.01, alpha=0.999,
perm_init=None, t_init=1000, verbose=False):
"""
Simple implementation of the SA algorithm
:param array: array, in our case the cities array
:param fit_fun: fitness function
:param mut_fun: mutation function
:param black_list: black list
:param scale: scale to assign a higher weight to cities in the black list
:param n_to_mute: how many elements should be mutated
:param maxIter: max number of iteration, np.inf by default to run until convergence
:param maxIterNoChange: max number of iterations for convergence
:param tmin: min temperature
:param alpha: constant to update temperature
:param perm_init: initial permutation
:param t_init: initial temperature
:param verbose: if True, the progress of the algorithm is printed
:return: best permutation found
"""
# initialize solution
if perm_init is None:
perm = np.random.permutation(range(1, len(array)))
else:
perm = perm_init.copy()
# init temperature
tem = t_init
dist = fit_fun(perm, array, black_list) # objective function
best_dist = dist # init best dist
best_perm = perm.copy() # init best permutation
citer = 0
iterNoChange = 0
while tem >= tmin:
# mutate
newperm = mut_fun(array, perm, black_list, scale, n_to_mute)
dist_new = fit_fun(newperm, array, black_list)
if dist_new <= best_dist:
perm = newperm
dist = dist_new
best_dist = dist
best_perm = perm.copy()
iterNoChange = 0
elif np.exp((dist - dist_new) / tem) > np.random.uniform():
dist = dist_new
perm = newperm
iterNoChange = 0
# update traces
tem *= alpha
if (citer % 100 == 0) and verbose:
print('Iter: {}, IterNoChange: {}, Current: {}, Best: {}'.format(citer, iterNoChange, dist, best_dist))
citer += 1
iterNoChange += 1
if (iterNoChange >= maxIterNoChange) or (citer >= maxIter):
break
return best_perm
| [
"numpy.roll",
"numpy.random.choice",
"numpy.sort",
"numpy.exp",
"numpy.concatenate",
"numpy.random.uniform",
"numpy.arange"
] | [((136, 173), 'numpy.random.choice', 'np.random.choice', (['n', '(2)'], {'replace': '(False)'}), '(n, 2, replace=False)\n', (152, 173), True, 'import numpy as np\n'), ((184, 194), 'numpy.sort', 'np.sort', (['i'], {}), '(i)\n', (191, 194), True, 'import numpy as np\n'), ((234, 291), 'numpy.concatenate', 'np.concatenate', (['(perm[i1:], perm[i0:i1], perm[:i0][::-1])'], {}), '((perm[i1:], perm[i0:i1], perm[:i0][::-1]))\n', (248, 291), True, 'import numpy as np\n'), ((430, 467), 'numpy.random.choice', 'np.random.choice', (['n', '(2)'], {'replace': '(False)'}), '(n, 2, replace=False)\n', (446, 467), True, 'import numpy as np\n'), ((1381, 1400), 'numpy.arange', 'np.arange', (['(8)', 'l', '(10)'], {}), '(8, l, 10)\n', (1390, 1400), True, 'import numpy as np\n'), ((3723, 3742), 'numpy.arange', 'np.arange', (['(8)', 'l', '(10)'], {}), '(8, l, 10)\n', (3732, 3742), True, 'import numpy as np\n'), ((646, 668), 'numpy.random.choice', 'np.random.choice', (['n', '(1)'], {}), '(n, 1)\n', (662, 668), True, 'import numpy as np\n'), ((1936, 1948), 'numpy.arange', 'np.arange', (['l'], {}), '(l)\n', (1945, 1948), True, 'import numpy as np\n'), ((2718, 2730), 'numpy.arange', 'np.arange', (['l'], {}), '(l)\n', (2727, 2730), True, 'import numpy as np\n'), ((3393, 3416), 'numpy.roll', 'np.roll', (['bool_mask1', '(-1)'], {}), '(bool_mask1, -1)\n', (3400, 3416), True, 'import numpy as np\n'), ((4481, 4497), 'numpy.arange', 'np.arange', (['(l - 1)'], {}), '(l - 1)\n', (4490, 4497), True, 'import numpy as np\n'), ((2323, 2335), 'numpy.arange', 'np.arange', (['l'], {}), '(l)\n', (2332, 2335), True, 'import numpy as np\n'), ((4143, 4161), 'numpy.arange', 'np.arange', (['(1)', 'l', '(2)'], {}), '(1, l, 2)\n', (4152, 4161), True, 'import numpy as np\n'), ((6418, 6449), 'numpy.exp', 'np.exp', (['((dist - dist_new) / tem)'], {}), '((dist - dist_new) / tem)\n', (6424, 6449), True, 'import numpy as np\n'), ((6452, 6471), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (6469, 6471), True, 'import numpy as np\n')] |
from collections import defaultdict
from typing import Dict
from matplotlib.animation import FuncAnimation
import matplotlib.gridspec as gs
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pandas as pd
def plot_infection_history(
g: nx.Graph,
pos: Dict[int, np.ndarray],
stats: pd.DataFrame,
outfile: str,
cumulative=False):
"""
Create an animation of the infection spread through the graph
Paramaters:
g: nx.Graph
pos: Dict[int, np.ndarray]
Node positions. Call e.g. nx.spring_layout
stats: pd.DataFrame
Contagion run statistics
cumulative:
Plot all infections rather than only currently infected
"""
fig = plt.figure(figsize=(16, 9))
spec = gs.GridSpec(ncols=2, nrows=1, figure=fig, width_ratios=[3, 2])
spec2 = gs.GridSpecFromSubplotSpec(2, 1, subplot_spec=spec[1])
ax1 = fig.add_subplot(spec[0])
ax2 = fig.add_subplot(spec2[0])
ax3 = fig.add_subplot(spec2[1])
max_val = 0
for node in g:
if "is_infected" in g.nodes[node]["history"]:
state_history = g.nodes[node]["history"]["is_infected"]
max_val = max(max_val, state_history[0][0])
ax2.set_xlim(0, max_val)
ax2.set_ylim(0, max(stats["is_recovered"])*1.1)
ax2.set_xlabel("Time")
ax2.set_ylabel("Infected")
ax3.set_ylabel("Infected")
pcol = nx.draw_networkx_nodes(
g,
pos,
nodelist=list(g.nodes),
node_color="lightgrey",
node_size=10,
ax=ax1)
line, = ax2.plot([], [], ls="-", lw=2, color="r")
line2, = ax2.plot([], [], ls="-", lw=2, color="lightgreen")
def update(t):
node_cols = []
inf_by = defaultdict(int)
for node in g:
col = "lightgrey"
if "is_infected" in g.nodes[node]["history"]:
state_history = g.nodes[node]["history"]["is_infected"]
if cumulative:
if state_history[0][0] <= t:
col = "r"
else:
if ((state_history[0][0] <= t) and
((len(state_history) == 1) or
(state_history[1][0] > t))):
if (("traced" in g.nodes[node]["history"] )
and (min(g.nodes[node]["history"]["traced"]) <= t)):
col = "darkorange"
else:
col = "r"
if ((len(state_history) == 2) and
(state_history[1][0] <= t)):
if ((("traced" in g.nodes[node]["history"])
and (min(g.nodes[node]["history"]["traced"]) <=
state_history[1][0]))
or "symptomatic" in g.nodes[node]["history"]):
col = "darkgreen"
else:
col = "purple"
if "infected_by" in g.nodes[node]["history"]:
if state_history[0][0] <= t:
inf_by[g.nodes[node]["history"]["infected_by"]] += 1
node_cols.append(col)
pcol.set_facecolor(node_cols)
pcol.set_alpha(0.8)
line.set_data(np.arange(t), stats["is_infected"][:t])
line2.set_data(np.arange(t), stats["is_recovered"][:t])
if inf_by:
inf_by = {k: v for k, v in
sorted(
inf_by.items(),
key=lambda item: item[1],
reverse=True)}
min_len = min(10, len(inf_by))
ax3.clear()
ax3.bar(np.arange(min_len), list(inf_by.values())[:min_len])
ax3.set_xticks(np.arange(min_len))
ax3.set_xticklabels(list(inf_by.keys())[:min_len])
ax3.set_ylabel("Num infected")
return pcol, line, line2
anim = FuncAnimation(
fig,
update,
frames=np.arange(0, max_val),
interval=200,
blit=False)
anim.save(outfile)
| [
"matplotlib.pyplot.figure",
"matplotlib.gridspec.GridSpec",
"collections.defaultdict",
"matplotlib.gridspec.GridSpecFromSubplotSpec",
"numpy.arange"
] | [((773, 800), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (783, 800), True, 'import matplotlib.pyplot as plt\n'), ((812, 874), 'matplotlib.gridspec.GridSpec', 'gs.GridSpec', ([], {'ncols': '(2)', 'nrows': '(1)', 'figure': 'fig', 'width_ratios': '[3, 2]'}), '(ncols=2, nrows=1, figure=fig, width_ratios=[3, 2])\n', (823, 874), True, 'import matplotlib.gridspec as gs\n'), ((887, 941), 'matplotlib.gridspec.GridSpecFromSubplotSpec', 'gs.GridSpecFromSubplotSpec', (['(2)', '(1)'], {'subplot_spec': 'spec[1]'}), '(2, 1, subplot_spec=spec[1])\n', (913, 941), True, 'import matplotlib.gridspec as gs\n'), ((1774, 1790), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1785, 1790), False, 'from collections import defaultdict\n'), ((3383, 3395), 'numpy.arange', 'np.arange', (['t'], {}), '(t)\n', (3392, 3395), True, 'import numpy as np\n'), ((3446, 3458), 'numpy.arange', 'np.arange', (['t'], {}), '(t)\n', (3455, 3458), True, 'import numpy as np\n'), ((4102, 4123), 'numpy.arange', 'np.arange', (['(0)', 'max_val'], {}), '(0, max_val)\n', (4111, 4123), True, 'import numpy as np\n'), ((3792, 3810), 'numpy.arange', 'np.arange', (['min_len'], {}), '(min_len)\n', (3801, 3810), True, 'import numpy as np\n'), ((3872, 3890), 'numpy.arange', 'np.arange', (['min_len'], {}), '(min_len)\n', (3881, 3890), True, 'import numpy as np\n')] |
"""Pi-kalman"""
import numpy as np
from typing import Tuple
class LinearGaussianStateSpaceModel(object):
""" Minimal implementation of a linear gaussian (LG) state space model (SSM)
A (stationary) linear gaussian state space model is defined as:
z' = A * z + B * U + 𝛆 (transition model)
y' = C * z' + 𝛅 (observation model)
𝛆 ~ 𝒩(0, Q)
𝛅 ~ 𝒩(0, R)
So that,
ℙ(z'| z) ~ 𝒩(A * z + B * U, Q)
ℙ(y' | z') ~ 𝒩(C * z', R)
Where ℙ indicates the probability of an event, 𝒩 denotes the normal
(gaussian) distribution, and the ' symbol indicates the next time step.
i.e. z is at time t and z' is at time t + 1.
The generative process for this model proceeds as follows; we start with a
latent state z which describes the system at time t. From z, we can directly
sample an observation y also at time t. To iterate the system, we transition
from z to z' at time t + 1 allowing us to then sample y' at time t + 1.
The equivalent probabilistic graphical model (PGM) is shown below:
```
z_1 -> z_2 -> ... -> z_t -> z_T
| | | | |
y_1 y_2 ... y_t y_T
```
We can continue in this fashion to sample y_1, ..., y_T. Alternatively, if
we observe y_1, ..., y_T as data, we can make inference about z_1, ..., z_T.
References:
https://arxiv.org/pdf/1204.0375.pdf
https://probml.github.io/pml-book/
Notes:
``Linear gaussian state space model`` is synonymous with a
``linear dynamical system``. An algorithm which performs estimation on
an ``LG-SSM`` is known as the ``Kalman Filter Algorithm``.
"""
def __init__(self,
A: np.ndarray,
B: np.ndarray,
C: np.ndarray,
U: np.ndarray,
Q: np.ndarray,
R: np.ndarray):
"""
Args:
A: nxn transition matrix
B: input effect matrix
C: observation matrix
U: control input
Q: transition noise covariance matrix
R: observation noise covariance matrix
"""
self.A = A
self.C = C
self.B = B
self.U = U
self.Q = Q
self.R = R
def prediction_step(self,
X: np.ndarray,
P: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
""" Runs a prediction step in the kalman filter.
To update the latent state z' and its mean X'|X and covariance P'|P from
initial state z and a sequence of observations y_{1:t-1} we use the law
of total probability and the definitions of the conditional
distributions of z'| y_{1:t-1}, u, z and the prior distribution of
z | X, P where X and P are the mean and covariance of z respectively.
```
ℙ(z' | y_{1:t-1}, u) = ∫ ℙ(z' | y_{1:t-1}, u, z) * ℙ(z | X, P) * dz (1)
= ∫ ℙ(z' | u, z) * ℙ(z | X, P) dz (2)
= ∫ 𝒩(z'; A * z + B * U, Q) * 𝒩(z; X, P) dz (3)
= 𝒩(z'; X'|X, P'|P) (4)
X'|X = A * X + B * U
P'|P = A * P * A^T + Q
```
And we have used law of total probability in eqn (1), independence of z'
y_{1:t-1} conditioned on z in eqn (2), conditional dist. assumptions in
eqn (3) and the Normal-Normal conjugacy property in eqn (4).
Args:
X: mean state estimate of the previous step (t - 1).
P: state covariance of previous step (t - 1).
Returns:
X'|X: predicted mean state estimate at time t without measurement
P'|P: predicted state covariance at time t without measurement
"""
X = np.dot(self.A, X) + np.dot(self.B, self.U)
P = np.dot(self.A, np.dot(P, self.A.T)) + self.Q
return X, P
def measurement_step(self,
X: np.ndarray,
P: np.ndarray,
Y: np.ndarray) -> Tuple[np.ndarray, np.ndarray, Tuple]:
""" Runs a measurement update step in the kalman filter.
Args:
X'|X: predicted mean state estimate at time t without measurement
P'|P: predicted state covariance at time t without measurement
Y: observed value at time t
Returns:
X': predicted mean state estimate at time t with measurement
P': predicted state covariance at time t with measurement
Y_hat, S: params for posterior predictive distribution:
ℙ(Y'| Y, U) ~ 𝒩(Y'; Y_hat, S)
= 𝒩(C * X, C * P * C^T + R)
"""
Y_hat = np.dot(self.C, X)
S = np.dot(self.C, np.dot(P, self.C.T)) + self.R
K = np.dot(P, np.dot(self.C.T, np.linalg.inv(S)))
r = Y - Y_hat
X = X + np.dot(K, r)
P = P - np.dot(K, np.dot(self.C, P)) # FIXME: References differ...
# P = P - dot(K, dot(S, K.T))
return X, P, (Y_hat, S)
def posterior_predictive(self, Y_hat, S):
# TODO: What will one step predictions show?
return None
def offline_update(
self,
X: np.ndarray,
P: np.ndarray,
Y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Prediction and measurement steps for an offline Kalman filter.
Notes:
Wraps the `online_update` function over the input `Y`.
Args:
X: mean state estimate of the previous step (t - 1).
P: state covariance of previous step (t - 1).
Y: observed value at time t
Returns:
X_sequence: predicted mean state estimate at times 1,...,T
"""
n, _ = Y.shape
X_list = []
for i in range(n):
Y_i = Y[i:i+1, :].T
X, P, _ = self.online_update(X, P, Y_i)
X_list.append(X)
X_sequence = np.concatenate(X_list, axis=-1)
return X_sequence
def online_update(self, X: np.ndarray, P: np.ndarray, Y: np.ndarray):
"""Prediction and measurement step for an online Kalman filter step.
Args:
X: mean state estimate of the previous step (t - 1).
P: state covariance of previous step (t - 1).
Y: observed value at time t
Returns:
X': predicted mean state estimate at time t with measurement
P': predicted state covariance at time t with measurement
Y_hat, S: params for posterior predictive distribution
"""
X, P = self.prediction_step(X, P)
X, P, params = self.measurement_step(X, P, Y)
Y_post = self.posterior_predictive(*params)
return X, P, Y_post
class GPSTracker(LinearGaussianStateSpaceModel):
""" GPS Tracker application as a Linear Gaussian State Space Model.
Implements a Linear Gaussian State Space Model for n-dimensional tracking.
Review on a LG-SSM is as follows:
z' = A * z + B * U + 𝛆 (transition model)
y' = C * z' + 𝛅 (observation model)
𝛆 ~ 𝒩(0, Q)
𝛅 ~ 𝒩(0, R)
And,
ℙ(z'| z) ~ 𝒩(A * z + B * U, Q)
ℙ(y' | z') ~ 𝒩(C * z', R)
Latent states (z) will represent both positions and velocities and
the observations (y) only need positions. Specifically for 2-dimensions:
```
z = [x_coord, y_coord, x_velocity, y_velocity]
y = [x_coord, y_coord]
A = [[1, 0, dt, 0],
[0, 1, 0, dt],
[0, 0, 1, 0],
[0, 0, 0, 1]]
C = [[1, 0, 0, 0],
[0, 1, 0, 0]]
Q = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]
R = [[1, 0],
[0, 1]]
```
"""
def __init__(self,
obs_dim: int = 2,
dt: float = 0.1):
# Double the latent dimension to include both speed and position
latent_dim = 2 * obs_dim
self.__observation_dimension = obs_dim
self.__latent_dimension = latent_dim
# last latent state plus a dead reckoning from the previous velocity
A = np.eye(latent_dim) + np.diag([dt] * obs_dim, k=obs_dim)
# no control inputs
B = np.eye(latent_dim)
U = np.zeros((latent_dim, 1))
# Reduce the 2 * obs_dim, latent_dim to just obs_dim
C = np.eye(latent_dim)[:obs_dim, :]
# identity noise
Q = np.eye(latent_dim)
R = np.eye(obs_dim)
super(GPSTracker, self).__init__(A=A, B=B, C=C, U=U, Q=Q, R=R)
@property
def latent_dimension(self):
return self.__latent_dimension
@property
def observation_dimension(self):
return self.__observation_dimension
def print_latent_state(self, X: np.ndarray) -> None:
print(f'coords: \n'
f'{X[:self.observation_dimension]}')
print(f'velocities: \n'
f'{X[self.observation_dimension:]}')
def __repr__(self):
return """
---------------------
State Equation:
---------------------
z' = A * z + B * U + 𝒩(0, Q) \n
A: \n {} \n
B: \n {} \n
U: \n {} \n
Q: \n {} \n
---------------------
Observation Equation:
---------------------
y' = C * z' + 𝒩(0, R)
C: \n {} \n
R: \n {}
""".format(self.A, self.B, self.U, self.Q, self.C, self.R).\
replace(' ', '')
| [
"numpy.eye",
"numpy.diag",
"numpy.dot",
"numpy.zeros",
"numpy.linalg.inv",
"numpy.concatenate"
] | [((4891, 4908), 'numpy.dot', 'np.dot', (['self.C', 'X'], {}), '(self.C, X)\n', (4897, 4908), True, 'import numpy as np\n'), ((6142, 6173), 'numpy.concatenate', 'np.concatenate', (['X_list'], {'axis': '(-1)'}), '(X_list, axis=-1)\n', (6156, 6173), True, 'import numpy as np\n'), ((8417, 8435), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (8423, 8435), True, 'import numpy as np\n'), ((8448, 8473), 'numpy.zeros', 'np.zeros', (['(latent_dim, 1)'], {}), '((latent_dim, 1))\n', (8456, 8473), True, 'import numpy as np\n'), ((8618, 8636), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (8624, 8636), True, 'import numpy as np\n'), ((8649, 8664), 'numpy.eye', 'np.eye', (['obs_dim'], {}), '(obs_dim)\n', (8655, 8664), True, 'import numpy as np\n'), ((3958, 3975), 'numpy.dot', 'np.dot', (['self.A', 'X'], {}), '(self.A, X)\n', (3964, 3975), True, 'import numpy as np\n'), ((3978, 4000), 'numpy.dot', 'np.dot', (['self.B', 'self.U'], {}), '(self.B, self.U)\n', (3984, 4000), True, 'import numpy as np\n'), ((5062, 5074), 'numpy.dot', 'np.dot', (['K', 'r'], {}), '(K, r)\n', (5068, 5074), True, 'import numpy as np\n'), ((8320, 8338), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (8326, 8338), True, 'import numpy as np\n'), ((8341, 8375), 'numpy.diag', 'np.diag', (['([dt] * obs_dim)'], {'k': 'obs_dim'}), '([dt] * obs_dim, k=obs_dim)\n', (8348, 8375), True, 'import numpy as np\n'), ((8548, 8566), 'numpy.eye', 'np.eye', (['latent_dim'], {}), '(latent_dim)\n', (8554, 8566), True, 'import numpy as np\n'), ((4028, 4047), 'numpy.dot', 'np.dot', (['P', 'self.A.T'], {}), '(P, self.A.T)\n', (4034, 4047), True, 'import numpy as np\n'), ((4936, 4955), 'numpy.dot', 'np.dot', (['P', 'self.C.T'], {}), '(P, self.C.T)\n', (4942, 4955), True, 'import numpy as np\n'), ((5005, 5021), 'numpy.linalg.inv', 'np.linalg.inv', (['S'], {}), '(S)\n', (5018, 5021), True, 'import numpy as np\n'), ((5101, 5118), 'numpy.dot', 'np.dot', (['self.C', 'P'], {}), '(self.C, P)\n', (5107, 5118), True, 'import numpy as np\n')] |
import numpy as np
class KMeans:
def __init__(self, k, dataset):
self.dataset = dataset
self.k = k
self.centroids = []
# Randomly choose centroids
self.randomize_centroids()
@staticmethod
def distance(point, centroid):
return np.linalg.norm(point-centroid)
@property
def predicted(self):
return np.array([self.predict(p) for p in self.dataset])
def randomize_centroids(self):
self.centroids = self.dataset[np.random.choice(len(self.dataset), self.k, replace=False), :]
def get_prepared(self):
return zip(self.dataset, self.predicted)
def get_points_in_clusters(self):
return [self.dataset[np.where(self.predicted == c)] for c in range(self.k)]
def error(self):
distances = [self.distance(point, self.centroids[int(cluster)]) for point, cluster in self.get_prepared()]
return 1 / len(self.dataset) * sum(distances)
def predict(self, point):
return int(np.argmin([self.distance(point, centroid) for centroid in self.centroids]))
def train(self, epochs=50):
minimal_error = np.inf
minimal_centroids = self.centroids
for e in range(epochs):
self.randomize_centroids()
self.update_centroids()
if self.error() < minimal_error:
minimal_centroids = self.centroids
minimal_error = self.error()
self.centroids = minimal_centroids
def update_centroids(self):
predicted = None
while (predicted is None) or (not all(predicted == self.predicted)):
predicted = self.predicted
self.centroids = list(map(lambda x: np.sum(x, axis=0) / (len(x) or 1), self.get_points_in_clusters()))
| [
"numpy.where",
"numpy.sum",
"numpy.linalg.norm"
] | [((291, 323), 'numpy.linalg.norm', 'np.linalg.norm', (['(point - centroid)'], {}), '(point - centroid)\n', (305, 323), True, 'import numpy as np\n'), ((710, 739), 'numpy.where', 'np.where', (['(self.predicted == c)'], {}), '(self.predicted == c)\n', (718, 739), True, 'import numpy as np\n'), ((1705, 1722), 'numpy.sum', 'np.sum', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1711, 1722), True, 'import numpy as np\n')] |
import sys
import math
import copy
import functools
from scipy.stats import binom
import numpy as np
import matplotlib.pyplot as plt
import collections as col
import scipy.optimize
nan = float("nan")
minf = float("-inf")
def is_smth_near(profile, v1, rng=2):
"""
Return index of something near if something exists near the target position. Else return None.
:param profile: list(int) - profile
:param v1: int - target place
:param rng: int - how far to search from target
:return: int/None - either a place where we have found something or None
"""
# fill the search space
to_search = [v1]
for i in range(1, rng + 1):
to_search.extend([v1 - i, v1 + i])
# search the search space
for i in to_search:
if 0 <= i < len(profile) and profile[i] != 0:
return i
return None
def good_for_sampling(sample, v1, v2, profiles, single=False, extract_all=False):
"""
Tests if the sample is good for training purposes.
:param sample: str - sample name
:param v1: int - allele 1
:param v2: int - allele 2
:param profiles: pd.DataFrame - profile (counts of STRs)
:param single: bool - extract single allele samples
:param extract_all: bool - extract all samples (found in profiles)
:return: bool - if the samples are "good"
"""
if sample not in profiles.index:
return False
try:
v1 = int(v1)
except ValueError:
v1 = 0
try:
v2 = int(v2)
except ValueError:
v2 = 0
if v1 not in profiles.columns or v2 not in profiles.columns:
return False
if is_smth_near(profiles.loc[sample], v1) is None or is_smth_near(profiles.loc[sample], v2) is None:
return False
if v1 == 0 and v2 == 0:
return False
if extract_all:
return True
elif single:
if v2 == 0:
v2 = v1
return v1 == v2
else:
ret = max(v2, v1) - min(v2, v1) > 1
# print("Good for sampling:", sample, v1, v2, ret, profiles.loc[sample])
return ret
def split_profile(sample, v1, v2, profiles, verbose=False):
"""
Split profiles into 2 each for corresponding allele.
:param sample: str - sample name
:param v1: int - allele 1
:param v2: int - allele 2
:param profiles: pd.DataFrame - profiles
:param verbose: bool - be verbose?
:return: tuple(ndarray, ndarray) - arrays for both alleles
"""
def fill_array(src, loc):
"""
Copy non-empty sub-array from src starting at loc.
:param src: ndarray - source array
:param loc: int - starting position
:return: ndarray - array with slice of src array around loc position
"""
dst = np.zeros_like(src)
dst[loc] = src[loc]
i = loc + 1
while i < len(src) and src[i] > 0:
dst[i] = src[i]
i += 1
i = loc - 1
while i >= 0 and src[i] > 0:
dst[i] = src[i]
i -= 1
return dst
# fill partial arrays:
test_array = np.array(profiles.loc[sample])
v1 = is_smth_near(profiles.loc[sample], v1)
v2 = 0 if v2 == 0 else is_smth_near(profiles.loc[sample], v2)
if v1 is None:
print("ERROR: this should not happen")
exit(-1)
left = fill_array(test_array, v1)
if v2 == v1 or v2 == 0 or v2 is None:
right = []
else:
right = fill_array(test_array, v2)
# check if ok:
if sum(test_array) - sum(left) - sum(right) != 0:
if verbose:
print("Sample %20s: (%2d, %2d) - %5d outliers detected..." % (sample, v1, v2, sum(test_array) - sum(left) - sum(right)), file=sys.stderr,
end=" " if sum(test_array) - sum(left) - sum(right) < 0 else "\n")
if sum(test_array) - sum(left) - sum(right) < 0:
right[:(v1 + v2) // 2] = 0
left[(v1 + v2) // 2:] = 0
if verbose:
print("Recounting...\nSample %20s: (%2d, %2d) - %5d outliers detected..." % (sample, v1, v2, sum(test_array) - sum(left) - sum(right)), file=sys.stderr)
# return both arrays
return left, right
def write_params(file_desc, model_params, read_drop_params, read_drop_params_rel, fit_function, print_all=False):
"""
Write trained parameters to output.
:param file_desc: file descriptor - where to write to
:param model_params: 4-tuple(floats) - parameters of fit_function
:param read_drop_params: 2-tuple(floats) - parameters for linear read count drop model absolute
:param read_drop_params_rel: 2-tuple(floats) - parameters for linear read count drop model relative
:param fit_function: function - error function for model distributions
:param print_all: bool - whether to print all parameters in the end in computer-friendly output
:return: None
"""
strings = {"linear": "%f + %f * x" % (model_params[0], model_params[1]), "const": "%f" % (model_params[0]), "n2": "%f + %f * x + %f * x * x" % (model_params[0], model_params[1], model_params[2]),
"exp": "%f + %f * exp(%f * x)" % (model_params[0], model_params[1], model_params[2])}
print("Model parameters:", file=file_desc)
print("\tfunction: %s" % fit_function, file=file_desc)
print("\tdeletes: %s" % strings[fit_function], file=file_desc)
print("\tinserts: linear with parameter %f" % model_params[3], file=file_desc)
print("Read loss parameters (absolute):", file=file_desc)
print("\tfunction: linear", file=file_desc)
print("\tread count drop: %f - %f * x" % (read_drop_params[0], -read_drop_params[1]), file=file_desc)
print("Read loss parameters (relative):", file=file_desc)
print("\tfunction: linear", file=file_desc)
print("\tread count drop: %f - %f * x" % (read_drop_params_rel[0], -read_drop_params_rel[1]), file=file_desc)
if print_all:
all_params = np.hstack((model_params, read_drop_params[:2], read_drop_params_rel[:2]))
print("All parameters:", file=file_desc)
print("\t%g %g %g %g %g %g %g %g" % tuple(all_params), file=file_desc)
def extract_alleles(sample, true_values, profiles, verbose=False):
"""
Splits sample into 1 or 2 subsamples for training
:param sample: int - sample number
:param true_values: pd.DataFrame - true values of alleles
:param profiles: ndarray - profile (counts of STRs)
:param verbose: bool - be verbose?
:return: dict{int: ndarray} - true_values to corresponding sub-profiles
"""
v1, v2 = true_values.get_value(index=sample, col=0), true_values.get_value(index=sample, col=1)
# get subprofiles
left, right = split_profile(sample, v1, v2, profiles, verbose)
# construct dict
d = {v1: left}
if len(right) != 0:
d[v2] = right
return d
def combine_distribs(deletes, inserts):
"""
Combine insert and delete models/distributions
:param deletes: ndarray - delete distribution
:param inserts: ndarray - insert distribution
:return: ndarray - combined array of the same length
"""
# how much to fill?
to_fill = sum(deletes == 0.0) + 1
while to_fill < len(inserts) and inserts[to_fill] > 0.0001:
to_fill += 1
# create the end array
len_del = len(deletes)
end_distr = np.zeros_like(deletes, dtype=float)
# fill it!
for i, a in enumerate(inserts[:to_fill]):
# print i,a,(deletes*a)[:len_del-i]
end_distr[i:] += (deletes * a)[:len_del - i]
# print("end_distr", end_distr[:3], deletes[:3], inserts[:3])
return end_distr
def norm_profiles(all_profiles):
"""
Normalize profiles dictionary
:param all_profiles: list(dict{int:ndarray}) - list of all profiles
:return: list(dict{int:ndarray}) - normalized all_profiles
"""
res = copy.deepcopy(all_profiles)
for td in res:
for k, v in td.items():
if sum(v) == 0:
print("divided by 0.", sum(v), v, k, td[k])
else:
td[k] = v / float(sum(v))
return res
def const_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Constant rate function.
:param n: int - allele number (unused)
:param p1: float - constant parameter
:param p2: float - linear parameter (unused)
:param p3: float - additional parameter (unused)
:return: float - p1
"""
return p1
def linear_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Linear rate function.
:param n: int - allele number
:param p1: float - constant parameter
:param p2: float - linear parameter
:param p3: float - additional parameter (unused)
:return: float - p1 + p2 * n
"""
return p1 + p2 * n
def relative_read_drop_train_linear(a, p1=0.0, p2=1.0, p3=1.0):
"""
Ratio of linear functions for relative read drop quantification.
:param a: (list(int), list(int)) - allele numbers
:param p1: float - constant parameter
:param p2: float - linear parameter
:return: float - ratio of the two linear functions
"""
a1, a2 = a
return np.array([linear_rate(aa1, p1, p2) / linear_rate(aa2, p1, p2) for aa1, aa2 in zip(a1, a2)])
def n2_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Quadratic rate function.
:param n: int - allele number
:param p1: float - constant parameter
:param p2: float - linear parameter
:param p3: float - quadratic parameter
:return: float - p1 + p2 * n + p3 * n * n
"""
return p1 + p2 * n + p3 * n * n
def exp_rate(n, p1=0.0, p2=1.0, p3=1.0):
"""
Exponential rate function.
:param n: int - allele number
:param p1: float - constant parameter
:param p2: float - linear parameter
:param p3: float - exponential parameter
:return: float - p1 + p2 * e^(p3 * n)
"""
return p1 + p2 * math.exp(p3 * n)
def clip(value, minimal, maximal):
"""
Clips value to range <minimal, maximal>
:param value: ? - value
:param minimal: ? - minimal value
:param maximal: ? - maximal value
:return: ? - clipped value
"""
return min(max(minimal, value), maximal)
def model_full(rng, model_params, n, rate_func=linear_rate):
"""
Create binomial model for both deletes and inserts of STRs
:param rng: ndarray - range of distribution
:param model_params: 4-tuple - parameters for inserts and deletes
:param n: int - target allele number
:param rate_func: function - rate function for deletes
:return: ndarray - combined distribution
"""
p1, p2, p3, q = model_params
deletes = binom.pmf(rng, n, clip(1 - rate_func(n, p1, p2, p3), 0.0, 1.0))
inserts = binom.pmf(rng, n, q)
return combine_distribs(deletes, inserts)
def model_template(rng, model_params, rate_func=linear_rate):
"""
Partial function for model creation.
:param rng: ndarray - range of distribution
:param model_params: 4-tuple - parameters for inserts and deletes
:param rate_func: function - rate function for deletes
:return: partial function with only 1 parameter - n - target allele number
"""
return functools.partial(model_full, rng, model_params, rate_func=rate_func)
def likelihood_multinomial(model_d, true_nums):
"""
Calculates likelihood P(model_d | true_nums). (sum(t(x))!/ (sum(t(x)))! )*prod(m(x)^t)
:param model_d: ndarray - model distribution
:param true_nums: ndarray - true distribution
:return: float - log-likelihood of generation of the true distribution out of the model distribution according to multinomial
"""
res = likelihood_simple(model_d, true_nums)
res += math.log(math.factorial(np.sum(true_nums)))
res -= np.sum(map(lambda x: math.log(math.factorial(x)), true_nums))
return minf if np.isnan(res) else res
def likelihood_simple(model_d, true_d):
"""
Calculates likelihood P(model_d | true_nums)
:param model_d: ndarray - model distribution
:param true_d: ndarray - true distribution
:return: float - log-likelihood of generation of the true distribution out of the model distribution
"""
res = sum(map(lambda m, t: 0.0 if t == 0.0 else (minf if m == 0.0 else t * math.log(m)), zip(model_d, true_d)))
return minf if np.isnan(res) else res
def likelihood(model_tmp, samples):
"""
Calculated likelihood for all samples
:param model_tmp: partial function - model template with current parameters
:param samples: list(dict{int:ndarray}) - all profiles
:return: float - log likelihood of current model summed on all samples
"""
loglike = 0.0
for true_dict in samples:
for k, v in true_dict.items():
md = model_tmp(k)
loglike += likelihood_multinomial(md, v) / np.sum(v)
# loglike += likelihood_one(md, v) / sum(v)
return loglike
def comparison(params, samples, rate_func):
"""
Get minus log likelihood of model specified with params on all samples
:param params: 4-tuple - model parameters
:param samples: list(dict{int:ndarray}) - all profiles
:param rate_func: function - rate function for deletes
:return: float - -log likelihood
"""
x = np.arange(len(samples[0].values()[0]))
model_tmp = model_template(x, params, rate_func)
return -likelihood(model_tmp, samples)
def display(model_tmp, samples, filename, min_allele=4):
"""
Generates a file with model vs true distribution comparison
:param model_tmp: partial function - model template with current parameters
:param samples: list(dict{int:ndarray}) - all profiles
:param filename: str - filename prefix to write model comparison to
:param min_allele: int - lowest allele to display
:return: None
"""
data = []
for true_dict in samples:
for k, v in true_dict.items():
data.append((k, v))
data = sorted(data, key=lambda xx: xx[0])
data = list(filter(lambda xx: xx[0] >= min_allele, data))
x = np.arange(len(data[0][1]))
for i, (k, v) in enumerate(data):
md = model_tmp(k)
plt.figure()
plt.plot(x, md * sum(v), "r-")
plt.plot(x, v, "b-")
plt.title(k)
last_dot = filename.rfind('.')
filename_curr = "%s%03d%s" % (filename[:last_dot], i, filename[last_dot:])
plt.savefig(filename_curr)
plt.close()
def count_occurrences(samples, len_repeating=1):
"""
Count read counts and relative read counts.
:param samples: list(dict{int:ndarray}) - all profiles
:param len_repeating: int - length of the STR
:return: defaultdict(list), defaultdict(list) - read counts and relative read counts
"""
numbers = col.defaultdict(list)
numbers_prop = col.defaultdict(list)
for td in samples:
num_v1 = 0
allele_v1 = 0
for k, v in td.items():
numbers[k * len_repeating].append(sum(v))
# we found second allele
if allele_v1 != 0 and k != 0 and k != allele_v1:
allele_v2 = k
num_v2 = sum(v)
if allele_v2 != 0:
if allele_v2 < allele_v1:
allele_v1, allele_v2 = allele_v2, allele_v1
num_v1, num_v2 = num_v2, num_v1
numbers_prop[(allele_v1 * len_repeating, allele_v2 * len_repeating)].append(num_v1 / float(num_v2))
# first allele
if allele_v1 == 0:
allele_v1 = k
num_v1 = sum(v)
return numbers, numbers_prop
def plot_occurrences(x, y, filename, read_drop_params):
"""
Plot read counts into file.
:param x: list - x coordinate to plot
:param y: list - y coordinate to plot
:param filename: str - filename where to plot to
:param read_drop_params: 2-tuple(floats) - parameters for linear read count drop model
:return: None
"""
plt.figure()
plt.plot(x, y, "r.")
v_lin_rate = np.vectorize(linear_rate)
plt.plot(x, v_lin_rate(x, *read_drop_params), "g-")
plt.savefig(filename)
plt.close()
def flatten(numbers):
"""
Flatten the read count dictionary into arrays for curve fitting.
:param numbers: defaultdict(list) - read counts
:return: list, list - list of allele numbers and list of corresponding read counts
"""
x = []
y = []
for k, v in numbers.items():
y.extend(v)
x.extend([k] * len(v))
return x, y
def train_read_drop_abs(nums):
"""
Train the read drop parameters of a linear drop.
:param nums: defaultdict(list) - read counts
:return: list(2) - parameters of linear read drop function
"""
params_read_drop = None
x, y = flatten(nums)
v_lin_err = np.vectorize(linear_rate)
try:
params_read_drop, _ = scipy.optimize.curve_fit(v_lin_err, x, y, (0., 1.), maxfev=20000)
except scipy.optimize.OptimizeWarning:
pass
return params_read_drop
def train_read_drop_rel(nums):
"""
Train the read drop parameters of a linear drop.
:param nums: defaultdict(list) - read counts
:return: list(2) - parameters of linear read drop function
"""
params_read_drop = None
x, y = flatten(nums)
# p1 = 1.0
# p2 = (1-c)/(c*a2-a1)
p2 = [(1 - c) / (c * a2 - a1) for c, (a1, a2) in zip(y, x)]
return 1.0, np.mean(p2)
def train_read_drop_rel2(nums):
"""
Train the read drop parameters of a linear drop.
:param nums: defaultdict(list) - read counts
:return: list(2) - parameters of linear read drop function
"""
params_read_drop = None
x, y = flatten(nums)
x = list(map(lambda a: a[0] / float(a[1]), x))
print(x, y)
v_lin_err = np.vectorize(linear_rate)
try:
params_read_drop, _ = scipy.optimize.curve_fit(v_lin_err, x, y, (0.0, 1.0), maxfev=20000)
except scipy.optimize.OptimizeWarning:
pass
return params_read_drop
def train_read_drop_rel3(nums):
"""
Train the read drop parameters of a linear drop.
:param nums: defaultdict(list) - read counts
:return: list(2) - parameters of linear read drop function
"""
params_read_drop = None
x, y = flatten(nums)
x = list(map(list, zip(*x)))
# v_rdl_err = np.vectorize(relative_read_drop_train_linear)
try:
params_read_drop, _ = scipy.optimize.curve_fit(relative_read_drop_train_linear, x, y, (0.1, 0.9), maxfev=20000)
except scipy.optimize.OptimizeWarning:
pass
return params_read_drop
| [
"numpy.hstack",
"math.log",
"numpy.array",
"copy.deepcopy",
"math.exp",
"numpy.mean",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.savefig",
"math.factorial",
"numpy.isnan",
"matplotlib.pyplot.title",
"numpy.vectorize",
"scipy.stats.binom.pmf",
"numpy.sum",
"... | [((3064, 3094), 'numpy.array', 'np.array', (['profiles.loc[sample]'], {}), '(profiles.loc[sample])\n', (3072, 3094), True, 'import numpy as np\n'), ((7255, 7290), 'numpy.zeros_like', 'np.zeros_like', (['deletes'], {'dtype': 'float'}), '(deletes, dtype=float)\n', (7268, 7290), True, 'import numpy as np\n'), ((7768, 7795), 'copy.deepcopy', 'copy.deepcopy', (['all_profiles'], {}), '(all_profiles)\n', (7781, 7795), False, 'import copy\n'), ((10564, 10584), 'scipy.stats.binom.pmf', 'binom.pmf', (['rng', 'n', 'q'], {}), '(rng, n, q)\n', (10573, 10584), False, 'from scipy.stats import binom\n'), ((11019, 11088), 'functools.partial', 'functools.partial', (['model_full', 'rng', 'model_params'], {'rate_func': 'rate_func'}), '(model_full, rng, model_params, rate_func=rate_func)\n', (11036, 11088), False, 'import functools\n'), ((14572, 14593), 'collections.defaultdict', 'col.defaultdict', (['list'], {}), '(list)\n', (14587, 14593), True, 'import collections as col\n'), ((14613, 14634), 'collections.defaultdict', 'col.defaultdict', (['list'], {}), '(list)\n', (14628, 14634), True, 'import collections as col\n'), ((15787, 15799), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15797, 15799), True, 'import matplotlib.pyplot as plt\n'), ((15804, 15824), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""r."""'], {}), "(x, y, 'r.')\n", (15812, 15824), True, 'import matplotlib.pyplot as plt\n'), ((15842, 15867), 'numpy.vectorize', 'np.vectorize', (['linear_rate'], {}), '(linear_rate)\n', (15854, 15867), True, 'import numpy as np\n'), ((15928, 15949), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (15939, 15949), True, 'import matplotlib.pyplot as plt\n'), ((15954, 15965), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15963, 15965), True, 'import matplotlib.pyplot as plt\n'), ((16620, 16645), 'numpy.vectorize', 'np.vectorize', (['linear_rate'], {}), '(linear_rate)\n', (16632, 16645), True, 'import numpy as np\n'), ((17591, 17616), 'numpy.vectorize', 'np.vectorize', (['linear_rate'], {}), '(linear_rate)\n', (17603, 17616), True, 'import numpy as np\n'), ((2738, 2756), 'numpy.zeros_like', 'np.zeros_like', (['src'], {}), '(src)\n', (2751, 2756), True, 'import numpy as np\n'), ((5866, 5939), 'numpy.hstack', 'np.hstack', (['(model_params, read_drop_params[:2], read_drop_params_rel[:2])'], {}), '((model_params, read_drop_params[:2], read_drop_params_rel[:2]))\n', (5875, 5939), True, 'import numpy as np\n'), ((11671, 11684), 'numpy.isnan', 'np.isnan', (['res'], {}), '(res)\n', (11679, 11684), True, 'import numpy as np\n'), ((12137, 12150), 'numpy.isnan', 'np.isnan', (['res'], {}), '(res)\n', (12145, 12150), True, 'import numpy as np\n'), ((13964, 13976), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13974, 13976), True, 'import matplotlib.pyplot as plt\n'), ((14024, 14044), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'v', '"""b-"""'], {}), "(x, v, 'b-')\n", (14032, 14044), True, 'import matplotlib.pyplot as plt\n'), ((14053, 14065), 'matplotlib.pyplot.title', 'plt.title', (['k'], {}), '(k)\n', (14062, 14065), True, 'import matplotlib.pyplot as plt\n'), ((14198, 14224), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename_curr'], {}), '(filename_curr)\n', (14209, 14224), True, 'import matplotlib.pyplot as plt\n'), ((14233, 14244), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14242, 14244), True, 'import matplotlib.pyplot as plt\n'), ((17228, 17239), 'numpy.mean', 'np.mean', (['p2'], {}), '(p2)\n', (17235, 17239), True, 'import numpy as np\n'), ((9740, 9756), 'math.exp', 'math.exp', (['(p3 * n)'], {}), '(p3 * n)\n', (9748, 9756), False, 'import math\n'), ((11559, 11576), 'numpy.sum', 'np.sum', (['true_nums'], {}), '(true_nums)\n', (11565, 11576), True, 'import numpy as np\n'), ((12642, 12651), 'numpy.sum', 'np.sum', (['v'], {}), '(v)\n', (12648, 12651), True, 'import numpy as np\n'), ((11620, 11637), 'math.factorial', 'math.factorial', (['x'], {}), '(x)\n', (11634, 11637), False, 'import math\n'), ((12081, 12092), 'math.log', 'math.log', (['m'], {}), '(m)\n', (12089, 12092), False, 'import math\n')] |
#! /usr/bin/env python
from __future__ import absolute_import, division, print_function
import argparse
import logging
import os
import numpy as np
import re
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)-5.5s %(name)-20.20s %(levelname)-7.7s %(message)s",
datefmt="%H:%M",
level=logging.INFO,
)
def shuffle_and_combine(dir, input_samples, output_sample, regex=False):
logger.info("Starting shuffling and combining")
logger.info(" Folder: %s", dir)
logger.info(" Input samples: %s", input_samples[0])
for sample in input_samples[1:]:
logger.info(" %s", sample)
logger.info(" Output sample: %s", output_sample)
logger.info(" Regular expressions: %s", regex)
# Path and filenames
folder = "{}/data/samples/".format(dir)
filenames = ["theta", "theta_alt", "x", "t_xz", "t_xz_alt", "log_r_xz", "log_r_xz_alt", "z"]
# Parse regular expressions
if regex:
input_expressions = input_samples
input_samples = []
for expr in input_expressions:
logging.debug(
"Parsing regex %s in folder %s", "x_(" + expr + ")\.npy", folder
)
regex = re.compile("x_(" + expr + ")\.npy")
for root, _, files in os.walk(folder):
for file in files:
if regex.match(file):
input_sample = file[2:-4]
if input_sample in input_samples:
logging.debug(
" Input sample %s already in list", input_sample
)
continue
logging.debug(" Found input sample %s", input_sample)
input_samples.append(input_sample)
if len(input_samples) == 0:
logging.warning(" No matching input samples found!")
return
# Combine samples
n_samples = None
permutation = None
for filename in filenames:
# Load individual files
try:
individuals = [
np.load(folder + "/" + filename + "_" + input_sample + ".npy")
for input_sample in input_samples
]
except FileNotFoundError:
logger.info(
"Object %s does not exist for (some of the) input samples", filename
)
continue
# Combine
try:
combined = np.concatenate(individuals, axis=0)
except ValueError:
logging.warning(
"Object %s: individual results do not have matching shapes!", filename
)
for input_sample, individual in zip(input_samples, individuals):
logging.warning(
" %s: %s has shape %s", input_sample, filename, individual.shape
)
continue
logger.info(
"Combined %s %s files, combined shape: %s",
len(individuals),
filename,
combined.shape,
)
# Shuffle
if n_samples is None or permutation is None:
n_samples = combined.shape[0]
permutation = np.random.permutation(n_samples)
else:
if n_samples != combined.shape[0]:
logging.error("Inconsistent shapes!")
raise RuntimeError("Inconsistent shapes!")
combined = combined[permutation]
logger.info("Shuffled combined %s results", filename)
# Save
try:
np.save(folder + "/" + filename + "_" + output_sample + ".npy", combined)
np.savez_compressed(
folder + "/" + filename + "_" + output_sample + ".npz", combined
)
except FileExistsError:
logging.warning(
"File %s already exists, cannot save results!",
folder + "/" + filename + "_" + output_sample + ".npy",
)
continue
logger.info(
"Saved file %s", folder + "/" + filename + "_" + output_sample + ".npy"
)
def remove_infs_and_nans(folder, filenames, input_sample):
data = []
out_filenames = []
for filename in filenames:
try:
data.append(np.load(folder + "/" + filename + "_" + input_sample + ".npy"))
out_filenames.append(
folder + "/" + filename + "_" + input_sample + "_cleaned.npy"
)
except FileNotFoundError:
pass
cut = None
for array in data:
this_cut = np.all(np.isfinite(array.reshape(array.shape[0], -1)), axis=1)
if cut is None:
cut = this_cut
else:
cut = np.logical_and(cut, this_cut)
n_pass = np.sum(cut, dtype=np.int)
n_fail = len(cut) - n_pass
logger.info(
"Cleaning up *_%s.npy: %s samples pass, %s samples removed",
folder,
input_sample,
n_pass,
n_fail,
)
for array, out_filename in zip(data, out_filenames):
cleaned_array = array[cut]
np.save(out_filename, cleaned_array)
def parse_args():
# Parse arguments
parser = argparse.ArgumentParser(
description="Combines multiple separate simulated samples"
)
parser.add_argument("output", help='Combined sample label (like "train" or "test")')
parser.add_argument(
"inputs",
nargs="+",
help='Individual input sample labels (like "train0 train1 train2"). If '
"option --regex is set, inputs can be regular expressions.",
)
parser.add_argument(
"--regex", action="store_true", help="Allows regular expressions in inputs"
)
parser.add_argument(
"--dir",
type=str,
default=".",
help="Directory. Samples will be looked for / saved in the data/samples subfolder.",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
shuffle_and_combine(args.dir, args.inputs, args.output, args.regex)
logger.info("All done! Have a nice day!")
| [
"logging.getLogger",
"logging.basicConfig",
"logging.debug",
"argparse.ArgumentParser",
"re.compile",
"numpy.logical_and",
"os.walk",
"logging.warning",
"numpy.sum",
"numpy.concatenate",
"numpy.savez_compressed",
"numpy.load",
"logging.error",
"numpy.save",
"numpy.random.permutation"
] | [((170, 197), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (187, 197), False, 'import logging\n'), ((198, 335), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)-5.5s %(name)-20.20s %(levelname)-7.7s %(message)s"""', 'datefmt': '"""%H:%M"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)-5.5s %(name)-20.20s %(levelname)-7.7s %(message)s', datefmt\n ='%H:%M', level=logging.INFO)\n", (217, 335), False, 'import logging\n'), ((4821, 4846), 'numpy.sum', 'np.sum', (['cut'], {'dtype': 'np.int'}), '(cut, dtype=np.int)\n', (4827, 4846), True, 'import numpy as np\n'), ((5233, 5321), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Combines multiple separate simulated samples"""'}), "(description=\n 'Combines multiple separate simulated samples')\n", (5256, 5321), False, 'import argparse\n'), ((5141, 5177), 'numpy.save', 'np.save', (['out_filename', 'cleaned_array'], {}), '(out_filename, cleaned_array)\n', (5148, 5177), True, 'import numpy as np\n'), ((1122, 1207), 'logging.debug', 'logging.debug', (['"""Parsing regex %s in folder %s"""', "('x_(' + expr + ')\\\\.npy')", 'folder'], {}), "('Parsing regex %s in folder %s', 'x_(' + expr + ')\\\\.npy', folder\n )\n", (1135, 1207), False, 'import logging\n'), ((1253, 1289), 're.compile', 're.compile', (["('x_(' + expr + ')\\\\.npy')"], {}), "('x_(' + expr + ')\\\\.npy')\n", (1263, 1289), False, 'import re\n'), ((1324, 1339), 'os.walk', 'os.walk', (['folder'], {}), '(folder)\n', (1331, 1339), False, 'import os\n'), ((1907, 1960), 'logging.warning', 'logging.warning', (['""" No matching input samples found!"""'], {}), "(' No matching input samples found!')\n", (1922, 1960), False, 'import logging\n'), ((2530, 2565), 'numpy.concatenate', 'np.concatenate', (['individuals'], {'axis': '(0)'}), '(individuals, axis=0)\n', (2544, 2565), True, 'import numpy as np\n'), ((3265, 3297), 'numpy.random.permutation', 'np.random.permutation', (['n_samples'], {}), '(n_samples)\n', (3286, 3297), True, 'import numpy as np\n'), ((3617, 3690), 'numpy.save', 'np.save', (["(folder + '/' + filename + '_' + output_sample + '.npy')", 'combined'], {}), "(folder + '/' + filename + '_' + output_sample + '.npy', combined)\n", (3624, 3690), True, 'import numpy as np\n'), ((3703, 3792), 'numpy.savez_compressed', 'np.savez_compressed', (["(folder + '/' + filename + '_' + output_sample + '.npz')", 'combined'], {}), "(folder + '/' + filename + '_' + output_sample + '.npz',\n combined)\n", (3722, 3792), True, 'import numpy as np\n'), ((4777, 4806), 'numpy.logical_and', 'np.logical_and', (['cut', 'this_cut'], {}), '(cut, this_cut)\n', (4791, 4806), True, 'import numpy as np\n'), ((2169, 2231), 'numpy.load', 'np.load', (["(folder + '/' + filename + '_' + input_sample + '.npy')"], {}), "(folder + '/' + filename + '_' + input_sample + '.npy')\n", (2176, 2231), True, 'import numpy as np\n'), ((2605, 2696), 'logging.warning', 'logging.warning', (['"""Object %s: individual results do not have matching shapes!"""', 'filename'], {}), "('Object %s: individual results do not have matching shapes!',\n filename)\n", (2620, 2696), False, 'import logging\n'), ((3375, 3412), 'logging.error', 'logging.error', (['"""Inconsistent shapes!"""'], {}), "('Inconsistent shapes!')\n", (3388, 3412), False, 'import logging\n'), ((3863, 3986), 'logging.warning', 'logging.warning', (['"""File %s already exists, cannot save results!"""', "(folder + '/' + filename + '_' + output_sample + '.npy')"], {}), "('File %s already exists, cannot save results!', folder +\n '/' + filename + '_' + output_sample + '.npy')\n", (3878, 3986), False, 'import logging\n'), ((4332, 4394), 'numpy.load', 'np.load', (["(folder + '/' + filename + '_' + input_sample + '.npy')"], {}), "(folder + '/' + filename + '_' + input_sample + '.npy')\n", (4339, 4394), True, 'import numpy as np\n'), ((2816, 2903), 'logging.warning', 'logging.warning', (['""" %s: %s has shape %s"""', 'input_sample', 'filename', 'individual.shape'], {}), "(' %s: %s has shape %s', input_sample, filename, individual\n .shape)\n", (2831, 2903), False, 'import logging\n'), ((1744, 1798), 'logging.debug', 'logging.debug', (['""" Found input sample %s"""', 'input_sample'], {}), "(' Found input sample %s', input_sample)\n", (1757, 1798), False, 'import logging\n'), ((1555, 1619), 'logging.debug', 'logging.debug', (['""" Input sample %s already in list"""', 'input_sample'], {}), "(' Input sample %s already in list', input_sample)\n", (1568, 1619), False, 'import logging\n')] |
import os
import random
import torch
import numpy as np
def seed_torch(seed=0):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
seed_torch(9)
class attention_params(torch.nn.Module):
def __init__(self, N):
super(attention_params, self).__init__()
self.alpha = torch.nn.Parameter(torch.ones(N)/N)
self.softmax = torch.nn.Softmax(dim=-1)
def forward(self, idx):
probs = self.softmax(self.alpha)
return probs[idx] | [
"torch.manual_seed",
"torch.nn.Softmax",
"random.seed",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.ones"
] | [((86, 103), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (97, 103), False, 'import random\n'), ((153, 173), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (167, 173), True, 'import numpy as np\n'), ((178, 201), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (195, 201), False, 'import torch\n'), ((206, 234), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (228, 234), False, 'import torch\n'), ((498, 522), 'torch.nn.Softmax', 'torch.nn.Softmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (514, 522), False, 'import torch\n'), ((458, 471), 'torch.ones', 'torch.ones', (['N'], {}), '(N)\n', (468, 471), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
@author: jzh
"""
import numpy as np, keras.backend as K
import tensorflow as tf
from keras.optimizers import Adam
from keras.layers import Input
from keras.models import Model
from src.VAE import get_gcn, get_gcn_vae_id, get_gcn_vae_exp
from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change
from src.get_mesh import get_mesh
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh, ArpackNoConvergence
from src.mesh import V2M2
ref_name = 'data/disentangle/Mean_Face.obj'
'''
GCN code was inspired by https://github.com/tkipf/keras-gcn
'''
def get_general_laplacian(adj):
return (sp.diags(np.power(np.array(adj.sum(1)), 1).flatten(), 0) - adj) * sp.diags(np.power(np.array(adj.sum(1)), -1).flatten(), 0)
def normalize_adj(adj, symmetric=True):
if symmetric:
d = sp.diags(np.power(np.array(adj.sum(1)), -0.5).flatten(), 0)
a_norm = adj.dot(d).transpose().dot(d).tocsr()
else:
d = sp.diags(np.power(np.array(adj.sum(1)), -1).flatten(), 0)
a_norm = d.dot(adj).tocsr()
return a_norm
def normalized_laplacian(adj, symmetric=True):
adj_normalized = normalize_adj(adj, symmetric)
laplacian = (sp.eye(adj.shape[0], dtype=np.float32)) - adj_normalized
return laplacian
def preprocess_adj(adj, symmetric=True):
adj = adj + sp.eye(adj.shape[0])
adj = normalize_adj(adj, symmetric)
return adj
def rescale_laplacian(laplacian):
try:
print('Calculating largest eigenvalue of normalized graph Laplacian...')
largest_eigval = (eigsh(laplacian, 1, which='LM', return_eigenvectors=False))[0]
except ArpackNoConvergence:
print('Eigenvalue calculation did not converge! Using largest_eigval=2 instead.')
largest_eigval = 2
scaled_laplacian = 2.0 / largest_eigval * laplacian - sp.eye(laplacian.shape[0])
return scaled_laplacian
def chebyshev_polynomial(X, k):
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices."""
print(('Calculating Chebyshev polynomials up to order {}...').format(k))
T_k = list()
T_k.append(sp.eye(X.shape[0]).tocsr())
T_k.append(X)
def chebyshev_recurrence(T_k_minus_one, T_k_minus_two, X):
X_ = sp.csr_matrix(X, copy=True)
return 2 * X_.dot(T_k_minus_one) - T_k_minus_two
for i in range(2, k + 1):
T_k.append(chebyshev_recurrence(T_k[-1], T_k[-2], X))
T_k = [i.astype(np.float32) for i in T_k]
return T_k
class gcn_dis_model(object):
def __init__(self, input_dim, prefix, suffix, lr, load, feature_dim=9, latent_dim_id=50, latent_dim_exp=25, kl_weight=0.000005,weight_decay = 0.00001, batch_size=1, MAX_DEGREE=2):
self.input_dim = input_dim
self.prefix = prefix
self.suffix = suffix
self.load = load
self.latent_dim_id = latent_dim_id
self.latent_dim_exp = latent_dim_exp
self.feature_dim = feature_dim
self.v = int(input_dim / feature_dim)
self.hidden_dim = 300
self.lr = lr
self.kl_weight = K.variable(kl_weight)
self.M_list = np.load(('data/{}/max_data.npy').format(self.prefix))
self.m_list = np.load(('data/{}/min_data.npy').format(self.prefix))
self.batch_size = batch_size
self.weight_decay = K.variable(weight_decay)
self.build_model(MAX_DEGREE)
class disentangle_model_vae_id(gcn_dis_model):
def build_model(self, MAX_DEGREE):
SYM_NORM = True
A = sp.load_npz(('data/{}/FWH_adj_matrix.npz').format(self.prefix))
L = normalized_laplacian(A, SYM_NORM)
T_k = chebyshev_polynomial(rescale_laplacian(L), MAX_DEGREE)
support = MAX_DEGREE + 1
self.kl_loss, self.encoder, self.decoder, self.gcn_vae_id = get_gcn_vae_id(T_k, support, batch_size=self.batch_size, feature_dim=self.feature_dim, v=self.v, input_dim=self.input_dim, latent_dim = self.latent_dim_id)
self.neutral_face = Input(shape=(self.input_dim,))
real = self.gcn_vae_id.get_input_at(0)
ratio = K.variable(self.M_list - self.m_list)
if self.feature_dim == 9:
self.id_loss = K.mean(K.abs((self.neutral_face - self.gcn_vae_id(real)) * ratio))/1.8
else:
ori_mesh = K.reshape(((self.neutral_face - self.gcn_vae_id(real)) * ratio), (self.batch_size, -1, 3))
self.id_loss = K.mean(K.sqrt(K.sum(K.square(ori_mesh) ,axis=-1)))/1.8
weights = self.gcn_vae_id.trainable_weights#+[self.scalar]
self.regularization_loss = 0
for w in weights:
#print(w)
if self.feature_dim == 9:
self.regularization_loss += self.weight_decay* K.sum(K.square(w))
else:
self.regularization_loss += 0.00002* K.sum(K.square(w))
self.loss = self.id_loss + self.kl_weight * self.kl_loss + self.regularization_loss
self.opt = Adam(lr=self.lr)
training_updates = (self.opt).get_updates(weights, [], self.loss)
self.train_func = K.function([real, self.neutral_face], [self.id_loss, self.loss, self.kl_loss, self.regularization_loss], training_updates)
self.test_func = K.function([real, self.neutral_face], [self.id_loss, self.loss, self.kl_loss, self.regularization_loss])
if self.load:
self.load_models()
def save_models(self):
self.gcn_vae_id.save_weights(('model/gcn_vae_id_model/gcn_vae_id{}{}.h5').format(self.prefix, self.suffix))
self.encoder.save_weights(('model/gcn_vae_id_model/encoder_id_{}{}.h5').format(self.prefix, self.suffix))
self.decoder.save_weights(('model/gcn_vae_id_model/decoder_id_{}{}.h5').format(self.prefix, self.suffix))
def load_models(self):
self.gcn_vae_id.load_weights(('model/gcn_vae_id_model/gcn_vae_id{}{}.h5').format(self.prefix, self.suffix))
def code_bp(self, epoch):
#test_array = np.vstack(batch_change(np.fromfile('data/disentangle/real_data/{}.dat'.format(i))) for i in range(287))
test_array = np.load('data/{}/test_data.npy'.format(self.prefix))[47*np.arange(10)]
frt = np.loadtxt('src/front_part_v.txt', dtype = int)
mask = np.zeros(11510)
mask[frt] = 1
normalize_fromfile(test_array, self.M_list, self.m_list)
num = 0
target_feature = test_array[num:num+1]
#x = [0,2,6,7,8]
K.set_learning_phase(0)
start = self.encoder.predict(target_feature, batch_size = self.batch_size)
code = K.variable(start[0])
target_feature_holder = Input(shape=(self.input_dim, ))
mask = K.variable(np.repeat(mask, 9))
ratio = K.variable(self.M_list - self.m_list)
cross_id = K.variable(np.tile(np.array([1,0,0,1,0,1,0,0,0]), 11510))
target = self.decoder(code)
loss = K.mean(K.abs(ratio*(target - target_feature_holder)))/1.8
lr = self.lr
for circle in range(10):
training_updates = (Adam(lr=lr)).get_updates([code], [], loss)
bp_func = K.function([target_feature_holder], [loss, target], training_updates)
for i in range(epoch):
err, result_mesh = bp_func([target_feature])
print('Epoch: {}, loss: {}'.format(i,err))
lr = input('learning rate change? ')
lr = float(lr)
if lr == 0:
break
start_norm = self.decoder.predict(start[0],batch_size = self.batch_size)
start_id = denormalize_fromfile(start_norm, self.M_list, self.m_list)
result_id = denormalize_fromfile(result_mesh, self.M_list, self.m_list)
denormalize_fromfile(target_feature, self.M_list, self.m_list)
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
V2M2(get_mesh(ref_name, data_recover(start_id)), 'data/mesh/start_id.obj')
V2M2(get_mesh(ref_name, data_recover(result_id)), 'data/mesh/result_id.obj')
V2M2(get_mesh(ref_name, data_recover(target_feature)), 'data/mesh/target_id.obj')
def train(self, epoch):
def get_interpolate_data(prefix, num = 2000):
if prefix == 'disentangle':
#interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/real_data/{}.dat'.format(prefix, i))) for i in range(num))
interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i))) for i in range(num))
else:
interpolate_data = np.vstack(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i)) for i in range(num))
mean_inter = np.mean(interpolate_data, axis = 0)
interpolate_data = interpolate_data - mean_inter
return interpolate_data
inter_array = get_interpolate_data(self.prefix, 4000)
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))
test_array = np.load(('data/{}/test_data.npy').format(self.prefix))
mean_exp = np.load(('data/{}/MeanFace_data.npy').format(self.prefix))
normalize_fromfile(test_array, self.M_list, self.m_list)
normalize_fromfile(mean_exp, self.M_list, self.m_list)
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(inter_array, self.M_list, self.m_list)
ITS = data_array.shape[0]//self.batch_size
log = np.zeros((epoch*ITS,))
test_log = np.zeros((epoch*ITS,))
constant_list = np.arange(data_array.shape[0])
inter_list = np.arange(inter_array.shape[0])
display_step = 50
for i in range(epoch):
np.random.shuffle(constant_list)
np.random.shuffle(inter_list)
# for index, j in enumerate(constant_list):
for index, j in enumerate(zip(*[iter(constant_list)]*self.batch_size)):
# l = np.random.randint(0, 47)
l = np.random.randint(0,47,self.batch_size)
inter_sample = np.random.randint(0,inter_array.shape[0],self.batch_size)
#l = 1
j = np.array(j)
C_exp = j % 47
C_neutral = j - C_exp
people_with_emotion = data_array[j]
people_neutral_face = data_array[C_neutral]
C_int = inter_list[(index*self.batch_size) %inter_array.shape[0]: (index * self.batch_size)%inter_array.shape[0]+self.batch_size]
inter_people = inter_array[C_int]
m = np.random.randint(0, 47, inter_people.shape[0])
inter_people_emotion = inter_people + mean_exp[m] + 0.9*(self.M_list + self.m_list)/(self.M_list - self.m_list)
K.set_learning_phase(1)
K.set_value(self.opt.lr, self.lr*10)
err_re_inter, err_total_inter, err_kl, err_regular = self.train_func([inter_people_emotion, inter_people])
K.set_value(self.opt.lr, self.lr*0.1)
err_re_emoti, err_total_emoti, err_kl, err_regular = self.train_func([people_with_emotion, people_neutral_face])
err_re = err_re_emoti#(err_re_inter + err_re_emoti)/2
err_total = (err_total_inter + err_total_emoti)/2
k = np.random.randint(0, 10*47,self.batch_size)
test_emotion = test_array[k]
test_neutral = test_array[k-(k%47)]
K.set_learning_phase(0)
eval_re, eval_total, eval_kl, eval_regular = self.test_func([test_emotion, test_neutral])
if index%display_step == 0:
print(('Epoch: {:3}, total_loss: {:8.4f}, re_loss: {:8.4f}, kl_loss: {:8.4f}, regular: {:8.4f}, eval: {:8.4f}, eval_re: {:8.4f}, eval_kl: {:8.4f}').format(i, err_total, err_re, err_kl, err_regular, eval_total, eval_re, eval_kl))
log[i*ITS + index] += err_re
test_log[i*ITS + index] += eval_re
np.save('log', log)
np.save('testlog', test_log)
self.save_models()
def special_train(self, epoch):
def get_interpolate_data(prefix, num = 2000):
if prefix == 'disentangle':
#interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/real_data/{}.dat'.format(prefix, i))) for i in range(num))
interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i))) for i in range(num))
else:
interpolate_data = np.vstack(np.fromfile('data/{}/real_data/{}.dat'.format(prefix, i)) for i in range(num))
mean_inter = np.mean(interpolate_data, axis = 0)
interpolate_data = interpolate_data - mean_inter
return interpolate_data
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))[47*np.arange(140)]
test_array = np.load(('data/{}/test_data.npy').format(self.prefix))[47*np.arange(10)]
inter_array = get_interpolate_data(self.prefix)
normalize_fromfile(inter_array, self.M_list, self.m_list)
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(test_array, self.M_list, self.m_list)
data_array = np.concatenate([data_array, inter_array])
log = np.zeros((epoch,))
test_log = np.zeros((epoch,))
constant_list = np.arange(data_array.shape[0])
display_step = 50
for i in range(epoch):
np.random.shuffle(constant_list)
for index, j in enumerate(zip(*[iter(constant_list)]*self.batch_size)):
test_idx = np.random.randint(0,10,self.batch_size)
test_emotion = test_array[test_idx]
people_with_emotion = data_array[np.array(j)]
K.set_learning_phase(1)
err_re, err_total, err_kl, err_regular = self.train_func([people_with_emotion, people_with_emotion])
K.set_learning_phase(0)
eval_re, eval_total, eval_kl, eval_regular = self.test_func([test_emotion, test_emotion])
if index%display_step == 0:
print(('Epoch: {:3}, total_loss: {:8.4f}, re_loss: {:8.4f}, kl_loss: {:8.4f}, regular: {:8.4f}, eval: {:8.4f}, eval_re: {:8.4f}, eval_kl: {:8.4f}').format(i, err_total, err_re, err_kl, err_regular, eval_total, eval_re, eval_kl))
log[i] += err_total
test_log[i] += eval_total
np.save('log', log)
np.save('testlog', test_log)
self.save_models()
def test(self, limit=5, filename='test', people_id=142):
data = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
err_re, err_total, err_kl, _ = self.test_func([data_array[24:25], data_array[:1]])
print(err_re)
feature_id = denormalize_fromfile(self.gcn_vae_id.predict(data_array, batch_size=self.batch_size), self.M_list, self.m_list)
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
for i in (0, 1, 2, 22, 24, 25, 37, 39):
V2M2(get_mesh(ref_name, data_recover(feature_id[i])), ('data/mesh/id_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(data[i])), ('data/mesh/ori_{}_{}.obj').format(self.prefix, i))
class disentangle_model_vae_exp(gcn_dis_model):
def build_model(self, MAX_DEGREE):
SYM_NORM = True
A = sp.load_npz(('data/{}/FWH_adj_matrix.npz').format(self.prefix))
L = normalized_laplacian(A, SYM_NORM)
T_k = chebyshev_polynomial(rescale_laplacian(L), MAX_DEGREE)
support = MAX_DEGREE + 1
self.kl_loss, self.encoder, self.decoder, self.gcn_vae_exp = get_gcn_vae_exp(T_k, support, batch_size=self.batch_size, feature_dim=self.feature_dim, v=self.v, input_dim=self.input_dim, latent_dim = self.latent_dim_exp)
self.mean_exp = Input(shape=(self.input_dim,))
real = self.gcn_vae_exp.get_input_at(0)
ratio = K.variable(self.M_list - self.m_list)
# L2 when xyz, L1 when rimd
if self.feature_dim == 9:
#self.away_loss = 0.001/K.mean(K.abs(0.9*s- ( self.gcn_vae_exp(real)) * ratio))
self.exp_loss = K.mean(K.abs((self.mean_exp - self.gcn_vae_exp(real)) * ratio )) / 1.8 #+ self.away_loss
else:
self.exp_loss = K.mean(K.square((self.mean_exp - self.gcn_vae_exp(real)) * ratio )) * 100
self.loss = self.exp_loss + self.kl_weight * self.kl_loss
weights = self.gcn_vae_exp.trainable_weights
training_updates = (Adam(lr=self.lr)).get_updates(weights, [], self.loss)
self.train_func = K.function([real, self.mean_exp], [self.exp_loss, self.loss, self.kl_loss], training_updates)
self.test_func = K.function([real, self.mean_exp], [self.exp_loss, self.loss, self.kl_loss])
if self.load:
self.load_models()
def save_models(self):
self.gcn_vae_exp.save_weights(('model/gcn_vae_exp_model/gcn_vae_exp{}{}.h5').format(self.prefix, self.suffix))
self.encoder.save_weights(('model/gcn_vae_exp_model/encoder_exp_{}{}.h5').format(self.prefix, self.suffix))
self.decoder.save_weights(('model/gcn_vae_exp_model/decoder_exp_{}{}.h5').format(self.prefix, self.suffix))
def load_models(self):
self.gcn_vae_exp.load_weights(('model/gcn_vae_exp_model/gcn_vae_exp{}{}.h5').format(self.prefix, self.suffix))
def train(self, epoch):
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))
test_array = np.load(('data/{}/test_data.npy').format(self.prefix))
mean_exp = np.load(('data/{}/MeanFace_data.npy').format(self.prefix))
normalize_fromfile(mean_exp, self.M_list, self.m_list)
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(test_array, self.M_list, self.m_list)
log = np.zeros((epoch,))
test_log = np.zeros((epoch,))
constant_list = np.arange(6580)
for i in range(epoch):
k = np.random.randint(1, 11)
test_emotion = test_array[k * 47 - 47:k * 47]
np.random.shuffle(constant_list)
for j in constant_list:
l = np.random.randint(0, 47)
C_exp = j % 47
people_with_emotion = data_array[j:j + 1]
exp = mean_exp[C_exp:C_exp+1]
err_re, err_total, err_kl = self.train_func([people_with_emotion, exp])
eval_re, eval_total, eval_kl = self.test_func([test_emotion[l:l + 1], mean_exp[l:l+1]])
print(('Epoch: {:3}, people: {:4}, total_loss: {:8.6f}, re_loss: {:8.6f}, kl_loss: {:8.4f}, eval: {:8.6f}, eval_re: {:8.6f}, eval_kl: {:8.4f}').format(i, j, err_total, err_re, err_kl, eval_total, eval_re, eval_kl))
log[i] += err_total
test_log[i] += eval_total
np.save('log', log)
np.save('testlog', test_log)
self.save_models()
def test(self, limit=5, filename='test', people_id=142):
data = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
feature_exp = denormalize_fromfile(self.gcn_vae_exp.predict(data_array, batch_size=self.batch_size), self.M_list, self.m_list)
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
for i in (0, 1, 2, 22, 37, 39):
V2M2(get_mesh(ref_name, data_recover(feature_exp[i])), ('data/mesh/exp_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(data[i])), ('data/mesh/ori_{}_{}.obj').format(self.prefix, i))
def test_fusion(self, id_net):
filename = 'test'
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
os.mkdir('data/mesh/id')
os.mkdir('data/mesh/exp')
os.mkdir('data/mesh/rec')
os.mkdir('data/mesh/ori')
for people_id in range(141, 151):
os.mkdir(('data/mesh/id/Feature{}').format(people_id))
os.mkdir(('data/mesh/exp/Feature{}').format(people_id))
os.mkdir(('data/mesh/rec/Feature{}').format(people_id))
os.mkdir(('data/mesh/ori/Feature{}').format(people_id))
data = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
feature_id = denormalize_fromfile(id_net.decoder.predict(id_net.encoder.predict(data_array, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
feature_exp = denormalize_fromfile(self.decoder.predict(self.encoder.predict(data_array, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
for i in range(47):
V2M2(get_mesh(ref_name, data_recover(data[i])), ('data/mesh/ori/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(data[i]-feature_id[i])), ('data/mesh/id/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_exp[i])), ('data/mesh/exp/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_exp[i] + data[i]-feature_id[i])), ('data/mesh/rec/Feature{}/{}.obj').format(people_id, i))
def test_training_pose(self, id_net, fusion_net):
from src.measurement import write_align_mesh
filename = '/raid/jzh/alignpose/RimdFeature1024/gathered_feature'
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
os.mkdir('data/mesh/exp')
os.mkdir('data/mesh/id')
os.mkdir('data/mesh/rec_plus')
os.mkdir('data/mesh/rec_fusion')
for people_id in range(141, 151):
os.mkdir(('data/mesh/exp/Feature{}').format(people_id))
os.mkdir(('data/mesh/id/Feature{}').format(people_id))
os.mkdir(('data/mesh/rec_plus/Feature{}').format(people_id))
os.mkdir(('data/mesh/rec_fusion/Feature{}').format(people_id))
data = np.load(('{}/Feature{}.npy').format(filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
#norm_id = data_array -id_net.decoder.predict(id_net.encoder.predict(data_array, batch_size=self.batch_size)[0],batch_size=self.batch_size) - 0.9*( self.M_list+ self.m_list)/( self.M_list- self.m_list)
norm_id =id_net.gcn_vae_id.predict(data_array, batch_size=self.batch_size)
norm_exp = self.decoder.predict(self.encoder.predict(data_array, batch_size=self.batch_size)[0],batch_size=self.batch_size)
norm_rec = fusion_net.gcn_comp.predict([norm_id, norm_exp],batch_size = self.batch_size)+ 0.9*( self.M_list+ self.m_list)/( self.M_list- self.m_list)
feature_id = denormalize_fromfile(norm_id, self.M_list, self.m_list)
feature_exp = denormalize_fromfile(norm_exp, self.M_list, self.m_list)
feature_rec = denormalize_fromfile(norm_rec, self.M_list, self.m_list)
for i in range(20):
V2M2(get_mesh(ref_name, data_recover(feature_exp[i])), ('data/mesh/exp/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_id[i])), ('data/mesh/id/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_id[i] + feature_exp[i])), ('data/mesh/rec_plus/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_rec[i])), ('data/mesh/rec_fusion/Feature{}/{}.obj').format(people_id, i))
write_align_mesh(('data/mesh/rec_plus/Feature{}/{}.obj').format(people_id, i),'/raid/jzh/alignpose/Tester_{}/AlignPose/pose_{}.obj'.format(people_id, i),('data/mesh/rec_fusion/Feature{}/aligned_{}.obj').format(people_id, i))
write_align_mesh(('data/mesh/rec_fusion/Feature{}/{}.obj').format(people_id, i),'/raid/jzh/alignpose/Tester_{}/AlignPose/pose_{}.obj'.format(people_id, i),('data/mesh/rec_plus/Feature{}/aligned_{}.obj').format(people_id, i))
def test_change(self, id_net):
from src.measurement import write_align_mesh
filename = '/raid/jzh/alignpose/RimdFeature1024/gathered_feature'
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
data_array141 = np.load(('{}/Feature{}.npy').format(filename, 141))
data_array142 = np.load(('{}/Feature{}.npy').format(filename, 142))
data141 = data_array141.copy()
data142 = data_array142.copy()
normalize_fromfile(data_array141, self.M_list, self.m_list)
normalize_fromfile(data_array142, self.M_list, self.m_list)
feature_id_141 = denormalize_fromfile(id_net.decoder.predict(id_net.encoder.predict(data_array141, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
feature_exp_141 = denormalize_fromfile(self.decoder.predict(self.encoder.predict(data_array141, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
feature_id_142 = denormalize_fromfile(id_net.decoder.predict(id_net.encoder.predict(data_array142, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
feature_exp_142 = denormalize_fromfile(self.decoder.predict(self.encoder.predict(data_array142, batch_size=self.batch_size)[0],batch_size=self.batch_size), self.M_list, self.m_list)
for i in range(20):
V2M2(get_mesh(ref_name, data_recover(data141[0] - feature_id_141[0] + feature_exp_142[i])), ('data/mesh/141_id_142_exp_{}.obj'.format(i)))
V2M2(get_mesh(ref_name, data_recover(data142[0] - feature_id_142[0] + feature_exp_141[i])), ('data/mesh/142_id_141_exp_{}.obj'.format(i)))
write_align_mesh('data/mesh/141_id_142_exp_{}.obj'.format(i),'/raid/jzh/alignpose/Tester_{}/AlignPose/pose_{}.obj'.format(141, i),'data/mesh/alighed_141_id_142_exp_{}.obj'.format(i))
write_align_mesh('data/mesh/142_id_141_exp_{}.obj'.format(i),'/raid/jzh/alignpose/Tester_{}/AlignPose/pose_{}.obj'.format(142, i),'data/mesh/alighed_142_id_141_exp_{}.obj'.format(i))
class gcn_model(object):
def __init__(self, input_dim, prefix, suffix, lr, load, feature_dim=9, batch_size=1, MAX_DEGREE=1):
self.input_dim = input_dim
self.prefix = prefix
self.suffix = suffix
self.lr = lr
self.load = load
self.M_list = np.load(('data/{}/max_data.npy').format(self.prefix))
self.m_list = np.load(('data/{}/min_data.npy').format(self.prefix))
self.batch_size = batch_size
self.feature_dim = feature_dim
self.v = int(input_dim / feature_dim)
ratio = K.variable(self.M_list - self.m_list)
s = K.variable(self.m_list + self.M_list)
SYM_NORM = True
A = sp.load_npz(('data/{}/FWH_adj_matrix.npz').format(self.prefix))
L = normalized_laplacian(A, SYM_NORM)
T_k = chebyshev_polynomial(rescale_laplacian(L), MAX_DEGREE)
support = MAX_DEGREE + 1
self.gcn_comp = get_gcn(T_k, support, batch_size=self.batch_size, feature_dim=self.feature_dim, v=self.v, input_dim=self.input_dim)
self.real = Input(shape=(self.input_dim,))
self.neutral_face = Input(shape=(self.input_dim,))
self.mean_exp = Input(shape=(self.input_dim,))
if feature_dim == 9:
self.loss = K.mean(K.abs((self.real - self.gcn_comp([self.neutral_face, self.mean_exp])) * ratio - 0.9 * s))
else:
self.loss = K.mean(K.square((self.real - self.gcn_comp([self.neutral_face, self.mean_exp])) * ratio- 0.9 * s))
self.weights = self.gcn_comp.trainable_weights
#print(self.weights)
self.training_updates = (Adam(lr=lr)).get_updates(self.weights, [], self.loss)
self.train_func = K.function([self.real, self.mean_exp, self.neutral_face], [self.loss], self.training_updates)
self.test_func = K.function([self.real, self.mean_exp, self.neutral_face], [self.loss])
if not load:
self.load_models()
def save_models(self):
self.gcn_comp.save_weights(('model/gcn_comp_{}{}.h5').format(self.prefix, self.suffix))
def load_models(self):
#self.gcn_comp.load_weights(('model/gcn_comp_{}{}.h5').format(self.prefix, self.suffix))
self.gcn_comp.load_weights(('model/gcn_comp_{}{}.h5').format(self.prefix, 'fusion_rimd'))
def train(self, epoch):
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))
mean_exp = np.load(('data/{}/MeanFace_data.npy').format(self.prefix))
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(mean_exp, self.M_list, self.m_list)
log = np.zeros((epoch,))
test_log = np.zeros((epoch,))
batch_size = self.batch_size
train_people_num = 130
constant_list = np.arange(train_people_num * 47)
for i in range(epoch):
k = np.random.randint(1, 11)
test_emotion = data_array[train_people_num * 47 + k * 47 - 47:train_people_num * 47 + k * 47]
np.random.shuffle(constant_list)
for j in range(int(train_people_num * 47 / batch_size)):
batch_index = constant_list[j * batch_size:j * batch_size + batch_size]
exp_index = batch_index % 47
neutral_index = batch_index - exp_index
people_with_emotion = data_array[batch_index]
people_neutral_face = data_array[neutral_index]
people_exp = mean_exp[exp_index]
err_total = self.train_func([people_with_emotion, people_exp, people_neutral_face])
if err_total[0] > 0.04:
for _ in range(5):
err_total =self.train_func([people_with_emotion, people_exp, people_neutral_face])
if err_total[0] > 0.06:
print('bad data')
for _ in range(10):
err_total =self.train_func([people_with_emotion, people_exp, people_neutral_face])
t = np.random.randint(1, 46)
eval_total = self.test_func([test_emotion[t:t+self.batch_size], mean_exp[t:t+self.batch_size], np.repeat(test_emotion[:1], self.batch_size, axis=0)])
print(('Epoch: {:3}, people: {:4}, total_loss: {:8.6f}, eval: {:8.6f}').format(i, j, err_total[0], eval_total[0]))
log[i] += err_total[0]
test_log[i] += eval_total[0]
np.save('test_log', test_log)
np.save('log', log)
self.save_models()
def train_fusion(self, id_net, exp_net, epoch):
def get_interpolate_data(prefix, num = 2000):
if prefix == 'disentangle':
interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i))) for i in range(num))
else:
interpolate_data = np.vstack(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i)) for i in range(num))
mean_inter = np.mean(interpolate_data, axis = 0)
interpolate_data = interpolate_data - mean_inter
return interpolate_data
def reshape_feature(x):
return K.reshape(x, (self.batch_size, -1, 3))
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))
test_array = np.load(('data/{}/test_data.npy').format(self.prefix))
mean_exp = np.load(('data/{}/MeanFace_data.npy').format(self.prefix))
inter_array = get_interpolate_data(self.prefix)
normalize_fromfile(inter_array, self.M_list, self.m_list)
normalize_fromfile(test_array, self.M_list, self.m_list)
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(mean_exp, self.M_list, self.m_list)
data_array = np.concatenate([data_array, mean_exp, inter_array])
train_people_num = data_array.shape[0]
log = np.zeros((epoch * train_people_num,))
test_log = np.zeros((epoch * train_people_num,))
batch_size = self.batch_size
constant_list = np.arange(train_people_num)
id_mesh = id_net.decoder(id_net.encoder(self.real)[0])
exp_mesh = exp_net.decoder(exp_net.encoder(self.real)[0])
rec_mesh = self.gcn_comp([id_mesh,exp_mesh])
ratio = K.variable(self.M_list - self.m_list)
s = K.variable(self.M_list + self.m_list)
self.regularization_loss = 0
for w in self.weights:
#print(w)
if self.feature_dim == 9:
self.regularization_loss += 0.00001* K.sum(K.abs(w))
else:
self.regularization_loss += 0.00001* K.sum(K.square(w))
if self.feature_dim == 9:
loss_func = K.mean(K.abs((self.real - rec_mesh)* ratio - 0.9* s))+ self.regularization_loss
else:
loss_func = K.mean(K.sqrt(K.sum(K.square(reshape_feature((self.real - rec_mesh)* ratio - 0.9* s)) ,axis=-1)))/1.8+ self.regularization_loss
training_updates = (Adam(lr=self.lr)).get_updates(self.weights, [], loss_func)
train_function = K.function([self.real], [loss_func, self.regularization_loss], training_updates)
test_function = K.function([self.real], [loss_func, self.regularization_loss])
display_step = 50
for i in range(epoch):
np.random.shuffle(constant_list)
for j in range(int(train_people_num/batch_size)):
batch_index = constant_list[j * batch_size:j * batch_size + batch_size]
#exp_index = batch_index % 47
#neutral_index = batch_index - exp_index
people_with_emotion = data_array[batch_index]
#people_neutral_face = data_array[neutral_index]
#people_exp = mean_exp[exp_index]
k = np.random.randint(test_array.shape[0])
test_emotion = test_array[k :k + 1]
err_total = train_function([people_with_emotion])
eval_total = test_function([test_emotion])
log[i*train_people_num + j] += err_total[0]
test_log[i*train_people_num + j] += eval_total[0]
if j%display_step ==0:
print(('Epoch: {:3}, people: {:4}, total_loss: {:8.6f}, regular_loss: {:8.6f}, eval: {:8.6f}').format(i, j, err_total[0],err_total[1], eval_total[0]))
np.save('testlog', test_log)
np.save('log', log)
np.save('testlog', test_log)
np.save('log', log)
self.save_models()
def end_to_end(self, id_net, exp_net, epoch):
#---------------------
# future part
#---------------------
ratio = K.variable(self.M_list - self.m_list)
s = K.variable(self.m_list + self.M_list)
# id operator
def I(z):
return id_net.decoder(id_net.encoder(z)[2])
def E(z):
return exp_net.decoder(exp_net.encoder(z)[2])
def F(y,x):
return self.gcn_comp([y,x])
def reshape_feature(x):
return K.reshape(x, (self.batch_size, -1, 3))
#ori_mesh = K.reshape(((self.neutral_face - self.gcn_vae_id(real)) * ratio), (self.batch_size, -1, 3))
#self.id_loss = K.mean(K.sqrt(K.sum(K.square(ori_mesh) ,axis=-1)))/1.8
'''
1. I(z_{i,k}) - y_i = 0
2. E(z_{i,k}) - x_k = 0
3. E(I(z_{i,k})) = I(E(z_{i,k})) = 0
4. F(E(z_{i,k}),I(z_{i,k}) - z_{i,k} = 0
'''
z = self.real
x = self.mean_exp
y = self.neutral_face
if self.feature_dim == 9:
loss_id = K.mean(K.abs((I(z) - y)*ratio))+ id_net.kl_weight * id_net.kl_loss
loss_exp = K.mean(K.abs((E(z) - x)*ratio))+ exp_net.kl_weight * exp_net.kl_loss
loss_disentangle = K.mean(K.abs(E(I(z))*ratio + 0.9*s)) + K.mean(K.abs(I(E(z))*ratio + 0.9*s))
loss_rec = K.mean(K.abs(F(I(z),E(z))*ratio+ 0.9*s - z*ratio))
else:
loss_id = K.mean(K.sqrt(K.sum(K.square(reshape_feature((I(z) - y)*ratio)) ,axis=-1)))/1.8 + id_net.kl_weight * id_net.kl_loss
loss_exp = K.mean(K.sqrt(K.sum(K.square(reshape_feature((E(z) - x)*ratio)) ,axis=-1)))/1.8+ exp_net.kl_weight * exp_net.kl_loss
loss_disentangle = K.mean(K.sqrt(K.sum(K.square(reshape_feature(E(I(z))*ratio + 0.9*s)) ,axis=-1)))/1.8 + K.mean(K.sqrt(K.sum(K.square(reshape_feature(I(E(z))*ratio + 0.9*s)) ,axis=-1)))/1.8
loss_rec = K.mean(K.sqrt(K.sum(K.square(reshape_feature(F(I(z),E(z))*ratio+ 0.9*s - z*ratio)) ,axis=-1)))/1.8
weights_I = id_net.encoder.trainable_weights + id_net.decoder.trainable_weights
weights_E = exp_net.encoder.trainable_weights + exp_net.decoder.trainable_weights
weights_F = self.gcn_comp.trainable_weights
regular_loss = 0
for weight in weights_I:
if self.feature_dim == 9:
regular_loss += 0.00003*K.sum(K.square(weight))
else:
regular_loss += 0.00003*K.sum(K.square(weight))
for weight in weights_E:
if self.feature_dim == 9:
regular_loss += 0.000001*K.sum(K.square(weight))
else:
regular_loss += 0.000001*K.sum(K.square(weight))
for weight in weights_F:
if self.feature_dim == 9:
regular_loss += 0.00001* K.sum(K.square(weight))
else:
regular_loss += 0.00001* K.sum(K.square(weight))
total_loss = loss_id + loss_exp + loss_disentangle + loss_rec + regular_loss
our_model = Model(z,[I(z), E(z), F(I(z),E(z))])
def load_models():
our_model.load_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def save_models():
our_model.save_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
id_z = id_net.encoder.get_input_at(0)
exp_z = exp_net.encoder.get_input_at(0)
if self.load:
load_models()
training_updates = (Adam(lr=self.lr)).get_updates(weights_I+weights_E+weights_F, [], total_loss)
train_func = K.function([id_z, exp_z, z, x, y], [total_loss, loss_id, loss_exp, loss_disentangle, loss_rec,regular_loss], training_updates)
test_func = K.function([id_z, exp_z, z, x, y], [total_loss, loss_id, loss_exp, loss_disentangle, loss_rec])
def get_interpolate_data(prefix, num = 2000):
if prefix == 'disentangle':
interpolate_data = np.vstack(batch_change(np.fromfile('data/{}/real_data/{}.dat'.format(prefix, i))) for i in range(num))
else:
interpolate_data = np.vstack(np.fromfile('data/{}/Interpolated_results/interpolated_{}.dat'.format(prefix, i)) for i in range(num))
mean_inter = np.mean(interpolate_data, axis = 0)
interpolate_data = interpolate_data - mean_inter
return interpolate_data
data_array = np.load(('data/{}/train_data.npy').format(self.prefix))
test_array = np.load(('data/{}/test_data.npy').format(self.prefix))
mean_exp = np.load(('data/{}/MeanFace_data.npy').format(self.prefix))
inter_array = get_interpolate_data(self.prefix,1)
normalize_fromfile(inter_array, self.M_list, self.m_list)
normalize_fromfile(test_array, self.M_list, self.m_list)
normalize_fromfile(data_array, self.M_list, self.m_list)
normalize_fromfile(mean_exp, self.M_list, self.m_list)
data_array = np.concatenate([data_array, mean_exp, inter_array])
train_people_num = data_array.shape[0]
log = np.zeros((epoch * train_people_num,))
test_log = np.zeros((epoch * train_people_num,))
display_step = 50
constant_list = np.arange(train_people_num)
for i in range(epoch):
k = np.random.randint(1, 11)
test_emotion = test_array[k * 47 - 47: k * 47]
np.random.shuffle(constant_list)
for j in range(train_people_num):
batch_index = constant_list[j]
if batch_index < 141*47:
exp_index = batch_index % 47
neutral_index = batch_index - exp_index
else:
exp_index = 0
neutral_index = batch_index
people_with_emotion = data_array[batch_index:batch_index+1]
people_neutral_face = data_array[neutral_index:neutral_index +1]
people_exp = mean_exp[exp_index:exp_index+1]
err_total, err_id, err_exp, err_dis, err_rec, err_regular = train_func([people_with_emotion,people_with_emotion,people_with_emotion, people_exp, people_neutral_face])
t = np.random.randint(0, 46)
eval_total, eval_id, eval_exp, eval_dis, eval_rec = test_func([test_emotion[t:t+1],test_emotion[t:t+1],test_emotion[t:t+1], mean_exp[t:t+1], test_emotion[:1]])
if j%display_step == 0:
print(('Epoch: {:3}, people: {:4}, total_loss: {:8.6f}, eval: {:8.6f}').format(i, j, err_total, eval_total))
print('ERROR: id: {:8.6f}, exp:{:8.6f}, disentangle: {:8.6f}, rec:{:8.6f}, regular: {:8.6f}'.format(err_id, err_exp, err_dis, err_rec, err_regular))
print('EVAL: id: {:8.6f}, exp:{:8.6f}, disentangle: {:8.6f}, rec:{:8.6f}'.format( eval_id, eval_exp, eval_dis, eval_rec))
log[i] += err_total
test_log[i] += eval_total
np.save('test_log', test_log)
np.save('log', log)
save_models()
def test(self, id_net, exp_net, filename='test', people_id=142):
# id operator
def I(z):
return id_net.decoder(id_net.encoder(z)[2])
def E(z):
return exp_net.decoder(exp_net.encoder(z)[2])
def F(y,x):
return self.gcn_comp([y,x])
'''
1. I(z_{i,k}) - y_i = 0
2. E(z_{i,k}) - x_k = 0
3. E(I(z_{i,k})) = I(E(z_{i,k})) = 0
4. F(E(z_{i,k}),I(z_{i,k}) - z_{i,k} = 0
'''
z = self.real
our_model = Model(z,[I(z), E(z), F(I(z),E(z))])
def load_models():
our_model.load_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def save_models():
our_model.save_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
if self.load:
load_models()
#self.load_models()
data = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
exp_code = exp_net.encoder.predict(data_array, batch_size = self.batch_size)[0]
id_code = id_net.encoder.predict(data_array, batch_size = self.batch_size)[0]
norm_exp = exp_net.decoder.predict(exp_code, batch_size = self.batch_size)
norm_id = id_net.decoder.predict(id_code, batch_size = self.batch_size)
feature_rec = denormalize_fromfile((self.gcn_comp.predict([norm_id, norm_exp], batch_size=self.batch_size)+ 0.9 * (self.m_list + self.M_list) / (self.M_list - self.m_list)) , self.M_list, self.m_list)
feature_exp = denormalize_fromfile(norm_exp , self.M_list, self.m_list)
feature_id = denormalize_fromfile(norm_id , self.M_list, self.m_list)
feature_plus = feature_exp + feature_id
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
for i in (0, 1, 2, 22, 37, 39):
V2M2(get_mesh(ref_name, data_recover(feature_rec[i])), ('data/mesh/rec_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(data[i])), ('data/mesh/ori_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(feature_plus[i])), ('data/mesh/plus_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(feature_exp[i])), ('data/mesh/exp_{}_{}.obj').format(self.prefix, i))
V2M2(get_mesh(ref_name, data_recover(feature_id[i])), ('data/mesh/id_{}_{}.obj').format(self.prefix, i))
def test_change(self, id_net, exp_net, filename='test', people_id=142):
# id operator
def I(z):
return id_net.decoder(id_net.encoder(z)[2])
def E(z):
return exp_net.decoder(exp_net.encoder(z)[2])
def F(y,x):
return self.gcn_comp([y,x])
'''
1. I(z_{i,k}) - y_i = 0
2. E(z_{i,k}) - x_k = 0
3. E(I(z_{i,k})) = I(E(z_{i,k})) = 0
4. F(E(z_{i,k}),I(z_{i,k}) - z_{i,k} = 0
'''
z = self.real
our_model = Model(z,[I(z), E(z), F(I(z),E(z))])
def load_models():
our_model.load_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def save_models():
our_model.save_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
if self.load:
load_models()
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
os.mkdir('data/mesh/people')
os.mkdir('data/mesh/transfer')
data_array141 = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, 141))
data_array142 = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, 142))
data142 = data_array142.copy()
normalize_fromfile(data_array141, self.M_list, self.m_list)
normalize_fromfile(data_array142, self.M_list, self.m_list)
exp_code = exp_net.encoder.predict(data_array142, batch_size = self.batch_size)[0]
id_code = id_net.encoder.predict(data_array141, batch_size = self.batch_size)[0]
bias = 0.9 * (self.m_list + self.M_list) / (self.M_list - self.m_list)
norm_exp = exp_net.decoder.predict(exp_code, batch_size = self.batch_size)
norm_id = id_net.decoder.predict(id_code, batch_size = self.batch_size)
id_used = np.repeat(norm_id[0:1], 47, axis = 0)
norm_transfer = self.gcn_comp.predict([id_used, norm_exp], batch_size = self.batch_size) + bias
feature_id_141 = denormalize_fromfile(id_used, self.M_list, self.m_list)
feature_exp_142 = denormalize_fromfile(norm_exp, self.M_list, self.m_list)
feature_transfer = denormalize_fromfile(norm_transfer, self.M_list, self.m_list)
key_frames = (0,1,2,22,37,39,2,1,23,12)
inter = 20
for index,i in enumerate(key_frames[:-1]):
for j in range(inter):
transfer_feature = (1-j/(inter - 1))*feature_transfer[key_frames[index]] + j/(inter-1)*feature_transfer[key_frames[index + 1]]
people_feature = (1-j/(inter - 1))*data142[key_frames[index]] + j/(inter - 1)*data142[key_frames[index + 1]]
V2M2(get_mesh(ref_name, data_recover(people_feature)), ('data/mesh/people/exp_{}_frame_{}.obj').format(index, j))
V2M2(get_mesh(ref_name, data_recover(transfer_feature)), ('data/mesh/transfer/exp_{}_frame_{}.obj').format(index, j))
def test_whole(self, id_net, exp_net, filename = 'test',people_id = 141):
# id operator
def I(z):
return id_net.decoder(id_net.encoder(z)[2])
def E(z):
return exp_net.decoder(exp_net.encoder(z)[2])
def F(y,x):
return self.gcn_comp([y,x])
'''
1. I(z_{i,k}) - y_i = 0
2. E(z_{i,k}) - x_k = 0
3. E(I(z_{i,k})) = I(E(z_{i,k})) = 0
4. F(E(z_{i,k}),I(z_{i,k}) - z_{i,k} = 0
'''
z = self.real
our_model = Model(z,[I(z), E(z), F(I(z),E(z))])
def load_models():
our_model.load_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def save_models():
our_model.save_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
if self.load:
load_models()
def get_optimized_mesh(target_feature, epoch = 50, lr = 0.4):
id_start = id_net.encoder.predict(target_feature)
exp_start = exp_net.encoder.predict(target_feature)
id_code = K.variable(id_start[0])
exp_code = K.variable(exp_start[0])
target_feature_holder = Input(shape=(self.input_dim, ))
target_id = id_net.decoder(id_code)
target_exp = exp_net.decoder(exp_code)
target_plus = target_id + target_exp
target_rec = self.gcn_comp([target_id, target_exp])
ratio = K.variable(self.M_list - self.m_list)
s = K.variable(self.M_list + self.m_list)
plus_loss = K.mean(K.abs(ratio*( target_feature_holder - target_plus) - 0.9*s))/1.8
rec_loss = K.mean(K.abs(ratio*( target_feature_holder - target_rec) - 0.9*s))/1.8
training_updates_plus = (Adam(lr=lr)).get_updates([id_code, exp_code], [], plus_loss)
training_updates_rec = (Adam(lr=lr)).get_updates([id_code, exp_code], [], rec_loss)
bp_func_plus = K.function([target_feature_holder], [plus_loss, target_plus], training_updates_plus)
bp_func_rec = K.function([target_feature_holder], [rec_loss, target_rec], training_updates_rec)
for i in range(epoch):
err, result_mesh_plus = bp_func_plus([target_feature])
print('Plus Error:{}'.format(err))
for i in range(epoch):
err, result_mesh_rec = bp_func_rec([target_feature])
print('Rec Error:{}'.format(err))
return result_mesh_plus, result_mesh_rec
import shutil, os
# commit following lines for the second test
###
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
os.mkdir('data/mesh/id')
os.mkdir('data/mesh/exp')
os.mkdir('data/mesh/rec')
os.mkdir('data/mesh/ori')
os.mkdir('data/mesh/plus')
os.mkdir('data/mesh/bp_plus')
os.mkdir('data/mesh/bp_rec')
###
# commit above lines for the second test
for people_id in range(people_id, people_id+1):
os.mkdir(('data/mesh/id/Feature{}').format(people_id))
os.mkdir(('data/mesh/exp/Feature{}').format(people_id))
os.mkdir(('data/mesh/rec/Feature{}').format(people_id))
os.mkdir(('data/mesh/ori/Feature{}').format(people_id))
os.mkdir(('data/mesh/plus/Feature{}').format(people_id))
os.mkdir(('data/mesh/bp_plus/Feature{}').format(people_id))
os.mkdir(('data/mesh/bp_rec/Feature{}').format(people_id))
#data = np.load(('{}/Feature{}.npy').format(filename, people_id))
data = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, filename, people_id))
data_array = data.copy()
normalize_fromfile(data_array, self.M_list, self.m_list)
exp_code = exp_net.encoder.predict(data_array, batch_size = self.batch_size)[0]
id_code = id_net.encoder.predict(data_array, batch_size = self.batch_size)[0]
norm_exp = exp_net.decoder.predict(exp_code, batch_size = self.batch_size)
norm_id = id_net.decoder.predict(id_code, batch_size = self.batch_size)
feature_rec = denormalize_fromfile((self.gcn_comp.predict([norm_id, norm_exp], batch_size=self.batch_size)+ 0.9 * (self.m_list + self.M_list) / (self.M_list - self.m_list)) , self.M_list, self.m_list)
feature_exp = denormalize_fromfile(norm_exp , self.M_list, self.m_list)
feature_id = denormalize_fromfile(norm_id , self.M_list, self.m_list)
f_plus = np.zeros_like(feature_rec)
f_rec = np.zeros_like(feature_rec)
bias = 0.9 * (self.m_list + self.M_list) / (self.M_list - self.m_list)
for i in range(47):
f_plus_i, f_rec_i = get_optimized_mesh(data_array[i:i+1])
f_plus[i] = f_plus_i + bias
f_rec[i] = f_rec_i+ bias
bp_plus = denormalize_fromfile(f_plus , self.M_list, self.m_list)
bp_rec = denormalize_fromfile(f_rec , self.M_list, self.m_list)
for i in range(47):
V2M2(get_mesh(ref_name, data_recover(bp_plus[i])), ('data/mesh/bp_plus/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(bp_rec[i])), ('data/mesh/bp_rec/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(data[i])), ('data/mesh/ori/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_rec[i])), ('data/mesh/rec/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_id[i])), ('data/mesh/id/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_exp[i])), ('data/mesh/exp/Feature{}/{}.obj').format(people_id, i))
V2M2(get_mesh(ref_name, data_recover(feature_exp[i] + feature_id[i])), ('data/mesh/plus/Feature{}/{}.obj').format(people_id, i))
def test_interpolation(self, id_net, exp_net):
exp_1 = batch_change(np.fromfile('/home/jzh/CVPR2019/Exploring/extrapolated_144.dat')).reshape(1,-1)
exp_2 = batch_change(np.fromfile('/home/jzh/CVPR2019/Exploring/extrapolated_167.dat')).reshape(1,-1)
id_1 = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, 'whole', 43))[:1]
id_2 = np.load(('data/{}/{}_data/Feature{}.npy').format(self.prefix, 'whole', 134))[:1]
normalize_fromfile(exp_1, self.M_list, self.m_list)
normalize_fromfile(exp_2, self.M_list, self.m_list)
normalize_fromfile(id_1, self.M_list, self.m_list)
normalize_fromfile(id_2, self.M_list, self.m_list)
# id operator
def I(z):
return id_net.decoder(id_net.encoder(z)[2])
def E(z):
return exp_net.decoder(exp_net.encoder(z)[2])
def F(y,x):
return self.gcn_comp([y,x])
'''
1. I(z_{i,k}) - y_i = 0
2. E(z_{i,k}) - x_k = 0
3. E(I(z_{i,k})) = I(E(z_{i,k})) = 0
4. F(E(z_{i,k}),I(z_{i,k}) - z_{i,k} = 0
'''
z = self.real
our_model = Model(z,[I(z), E(z), F(I(z),E(z))])
code_id = Input(shape = (50,))
code_exp = Input(shape = (25,))
corespondent_mesh = self.gcn_comp([id_net.decoder(code_id),exp_net.decoder(code_exp)])
code2mesh = Model([code_id, code_exp], corespondent_mesh)
def load_models():
our_model.load_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def save_models():
our_model.save_weights(('model/our_model/our_model{}{}.h5').format(self.prefix, self.suffix))
def get_optimized_code(target_feature, epoch = 50, lr = 0.5):
id_start = id_net.encoder.predict(target_feature)
exp_start = exp_net.encoder.predict(target_feature)
id_code = K.variable(id_start[0])
exp_code = K.variable(exp_start[0])
target_feature_holder = Input(shape=(self.input_dim, ))
target_id = id_net.decoder(id_code)
target_exp = exp_net.decoder(exp_code)
target_rec = self.gcn_comp([target_id, target_exp])
ratio = K.variable(self.M_list - self.m_list)
s = K.variable(self.M_list + self.m_list)
rec_loss = K.mean(K.abs(ratio*( target_feature_holder - target_rec) - 0.9*s))/1.8
training_updates_rec = (Adam(lr=lr)).get_updates([id_code, exp_code], [], rec_loss)
bp_func_rec = K.function([target_feature_holder], [rec_loss, target_rec, id_code, exp_code], training_updates_rec)
for i in range(epoch):
err, result_mesh_rec, code_id, code_exp = bp_func_rec([target_feature])
print('Rec Error:{}'.format(err))
return result_mesh_rec, code_id, code_exp
if self.load:
load_models()
import shutil, os
shutil.rmtree('data/mesh')
os.mkdir('data/mesh')
_, _, exp_code_1 = get_optimized_code(exp_1)
_, _, exp_code_2 = get_optimized_code(exp_2)
_, id_code_1, _ = get_optimized_code(id_1)
_, id_code_2, _ = get_optimized_code(id_2)
bias = 0.9 * (self.m_list + self.M_list) / (self.M_list - self.m_list)
n = 20
for id_go in range(-2,n+1):
for exp_go in range(-2,n+1):
new_code_id = id_go/(n-1)*id_code_1 + (1 - id_go/(n-1))*id_code_2
new_code_exp = exp_go/(n-1)*exp_code_1 + (1 - exp_go/(n-1))*exp_code_2
norm_rec = code2mesh.predict([new_code_id, new_code_exp],batch_size = self.batch_size) + bias
feature_rec = denormalize_fromfile(norm_rec , self.M_list, self.m_list)
V2M2(get_mesh(ref_name, data_recover(feature_rec[0])), ('data/mesh/id_{}_exp_{}.obj').format(id_go, exp_go))
if __name__ == '__main__':
start = True
| [
"numpy.fromfile",
"keras.backend.reshape",
"numpy.array",
"src.data_utils.normalize_fromfile",
"src.data_utils.data_recover",
"src.data_utils.denormalize_fromfile",
"numpy.save",
"numpy.arange",
"numpy.mean",
"numpy.repeat",
"scipy.sparse.eye",
"src.VAE.get_gcn",
"scipy.sparse.linalg.eigen.a... | [((1270, 1308), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {'dtype': 'np.float32'}), '(adj.shape[0], dtype=np.float32)\n', (1276, 1308), True, 'import scipy.sparse as sp\n'), ((1410, 1430), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (1416, 1430), True, 'import scipy.sparse as sp\n'), ((1920, 1946), 'scipy.sparse.eye', 'sp.eye', (['laplacian.shape[0]'], {}), '(laplacian.shape[0])\n', (1926, 1946), True, 'import scipy.sparse as sp\n'), ((2342, 2369), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['X'], {'copy': '(True)'}), '(X, copy=True)\n', (2355, 2369), True, 'import scipy.sparse as sp\n'), ((3208, 3229), 'keras.backend.variable', 'K.variable', (['kl_weight'], {}), '(kl_weight)\n', (3218, 3229), True, 'import numpy as np, keras.backend as K\n'), ((3451, 3475), 'keras.backend.variable', 'K.variable', (['weight_decay'], {}), '(weight_decay)\n', (3461, 3475), True, 'import numpy as np, keras.backend as K\n'), ((3928, 4091), 'src.VAE.get_gcn_vae_id', 'get_gcn_vae_id', (['T_k', 'support'], {'batch_size': 'self.batch_size', 'feature_dim': 'self.feature_dim', 'v': 'self.v', 'input_dim': 'self.input_dim', 'latent_dim': 'self.latent_dim_id'}), '(T_k, support, batch_size=self.batch_size, feature_dim=self.\n feature_dim, v=self.v, input_dim=self.input_dim, latent_dim=self.\n latent_dim_id)\n', (3942, 4091), False, 'from src.VAE import get_gcn, get_gcn_vae_id, get_gcn_vae_exp\n'), ((4113, 4143), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (4118, 4143), False, 'from keras.layers import Input\n'), ((4209, 4246), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (4219, 4246), True, 'import numpy as np, keras.backend as K\n'), ((5113, 5129), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr'}), '(lr=self.lr)\n', (5117, 5129), False, 'from keras.optimizers import Adam\n'), ((5232, 5359), 'keras.backend.function', 'K.function', (['[real, self.neutral_face]', '[self.id_loss, self.loss, self.kl_loss, self.regularization_loss]', 'training_updates'], {}), '([real, self.neutral_face], [self.id_loss, self.loss, self.\n kl_loss, self.regularization_loss], training_updates)\n', (5242, 5359), True, 'import numpy as np, keras.backend as K\n'), ((5381, 5490), 'keras.backend.function', 'K.function', (['[real, self.neutral_face]', '[self.id_loss, self.loss, self.kl_loss, self.regularization_loss]'], {}), '([real, self.neutral_face], [self.id_loss, self.loss, self.\n kl_loss, self.regularization_loss])\n', (5391, 5490), True, 'import numpy as np, keras.backend as K\n'), ((6341, 6386), 'numpy.loadtxt', 'np.loadtxt', (['"""src/front_part_v.txt"""'], {'dtype': 'int'}), "('src/front_part_v.txt', dtype=int)\n", (6351, 6386), True, 'import numpy as np, keras.backend as K\n'), ((6405, 6420), 'numpy.zeros', 'np.zeros', (['(11510)'], {}), '(11510)\n', (6413, 6420), True, 'import numpy as np, keras.backend as K\n'), ((6453, 6509), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (6471, 6509), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((6610, 6633), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (6630, 6633), True, 'import numpy as np, keras.backend as K\n'), ((6734, 6754), 'keras.backend.variable', 'K.variable', (['start[0]'], {}), '(start[0])\n', (6744, 6754), True, 'import numpy as np, keras.backend as K\n'), ((6790, 6820), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (6795, 6820), False, 'from keras.layers import Input\n'), ((6888, 6925), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (6898, 6925), True, 'import numpy as np, keras.backend as K\n'), ((7746, 7804), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['start_norm', 'self.M_list', 'self.m_list'], {}), '(start_norm, self.M_list, self.m_list)\n', (7766, 7804), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((7826, 7885), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['result_mesh', 'self.M_list', 'self.m_list'], {}), '(result_mesh, self.M_list, self.m_list)\n', (7846, 7885), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((7895, 7957), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['target_feature', 'self.M_list', 'self.m_list'], {}), '(target_feature, self.M_list, self.m_list)\n', (7915, 7957), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((7996, 8022), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (8009, 8022), False, 'import shutil, os\n'), ((8032, 8053), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (8040, 8053), False, 'import shutil, os\n'), ((9408, 9464), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (9426, 9464), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((9474, 9528), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['mean_exp', 'self.M_list', 'self.m_list'], {}), '(mean_exp, self.M_list, self.m_list)\n', (9492, 9528), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((9538, 9594), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (9556, 9594), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((9604, 9661), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['inter_array', 'self.M_list', 'self.m_list'], {}), '(inter_array, self.M_list, self.m_list)\n', (9622, 9661), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((9731, 9755), 'numpy.zeros', 'np.zeros', (['(epoch * ITS,)'], {}), '((epoch * ITS,))\n', (9739, 9755), True, 'import numpy as np, keras.backend as K\n'), ((9774, 9798), 'numpy.zeros', 'np.zeros', (['(epoch * ITS,)'], {}), '((epoch * ITS,))\n', (9782, 9798), True, 'import numpy as np, keras.backend as K\n'), ((9822, 9852), 'numpy.arange', 'np.arange', (['data_array.shape[0]'], {}), '(data_array.shape[0])\n', (9831, 9852), True, 'import numpy as np, keras.backend as K\n'), ((9875, 9906), 'numpy.arange', 'np.arange', (['inter_array.shape[0]'], {}), '(inter_array.shape[0])\n', (9884, 9906), True, 'import numpy as np, keras.backend as K\n'), ((13431, 13488), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['inter_array', 'self.M_list', 'self.m_list'], {}), '(inter_array, self.M_list, self.m_list)\n', (13449, 13488), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((13498, 13554), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (13516, 13554), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((13564, 13620), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (13582, 13620), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((13643, 13684), 'numpy.concatenate', 'np.concatenate', (['[data_array, inter_array]'], {}), '([data_array, inter_array])\n', (13657, 13684), True, 'import numpy as np, keras.backend as K\n'), ((13702, 13720), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (13710, 13720), True, 'import numpy as np, keras.backend as K\n'), ((13741, 13759), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (13749, 13759), True, 'import numpy as np, keras.backend as K\n'), ((13785, 13815), 'numpy.arange', 'np.arange', (['data_array.shape[0]'], {}), '(data_array.shape[0])\n', (13794, 13815), True, 'import numpy as np, keras.backend as K\n'), ((15224, 15280), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (15242, 15280), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((15566, 15592), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (15579, 15592), False, 'import shutil, os\n'), ((15602, 15623), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (15610, 15623), False, 'import shutil, os\n'), ((16350, 16515), 'src.VAE.get_gcn_vae_exp', 'get_gcn_vae_exp', (['T_k', 'support'], {'batch_size': 'self.batch_size', 'feature_dim': 'self.feature_dim', 'v': 'self.v', 'input_dim': 'self.input_dim', 'latent_dim': 'self.latent_dim_exp'}), '(T_k, support, batch_size=self.batch_size, feature_dim=self.\n feature_dim, v=self.v, input_dim=self.input_dim, latent_dim=self.\n latent_dim_exp)\n', (16365, 16515), False, 'from src.VAE import get_gcn, get_gcn_vae_id, get_gcn_vae_exp\n'), ((16533, 16563), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (16538, 16563), False, 'from keras.layers import Input\n'), ((16630, 16667), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (16640, 16667), True, 'import numpy as np, keras.backend as K\n'), ((17320, 17417), 'keras.backend.function', 'K.function', (['[real, self.mean_exp]', '[self.exp_loss, self.loss, self.kl_loss]', 'training_updates'], {}), '([real, self.mean_exp], [self.exp_loss, self.loss, self.kl_loss],\n training_updates)\n', (17330, 17417), True, 'import numpy as np, keras.backend as K\n'), ((17440, 17515), 'keras.backend.function', 'K.function', (['[real, self.mean_exp]', '[self.exp_loss, self.loss, self.kl_loss]'], {}), '([real, self.mean_exp], [self.exp_loss, self.loss, self.kl_loss])\n', (17450, 17515), True, 'import numpy as np, keras.backend as K\n'), ((18387, 18441), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['mean_exp', 'self.M_list', 'self.m_list'], {}), '(mean_exp, self.M_list, self.m_list)\n', (18405, 18441), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((18451, 18507), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (18469, 18507), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((18517, 18573), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (18535, 18573), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((18589, 18607), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (18597, 18607), True, 'import numpy as np, keras.backend as K\n'), ((18628, 18646), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (18636, 18646), True, 'import numpy as np, keras.backend as K\n'), ((18672, 18687), 'numpy.arange', 'np.arange', (['(6580)'], {}), '(6580)\n', (18681, 18687), True, 'import numpy as np, keras.backend as K\n'), ((19603, 19622), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (19610, 19622), True, 'import numpy as np, keras.backend as K\n'), ((19632, 19660), 'numpy.save', 'np.save', (['"""testlog"""', 'test_log'], {}), "('testlog', test_log)\n", (19639, 19660), True, 'import numpy as np, keras.backend as K\n'), ((19896, 19952), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (19914, 19952), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((20125, 20151), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (20138, 20151), False, 'import shutil, os\n'), ((20161, 20182), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (20169, 20182), False, 'import shutil, os\n'), ((20584, 20610), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (20597, 20610), False, 'import shutil, os\n'), ((20620, 20641), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (20628, 20641), False, 'import shutil, os\n'), ((20651, 20675), 'os.mkdir', 'os.mkdir', (['"""data/mesh/id"""'], {}), "('data/mesh/id')\n", (20659, 20675), False, 'import shutil, os\n'), ((20685, 20710), 'os.mkdir', 'os.mkdir', (['"""data/mesh/exp"""'], {}), "('data/mesh/exp')\n", (20693, 20710), False, 'import shutil, os\n'), ((20720, 20745), 'os.mkdir', 'os.mkdir', (['"""data/mesh/rec"""'], {}), "('data/mesh/rec')\n", (20728, 20745), False, 'import shutil, os\n'), ((20755, 20780), 'os.mkdir', 'os.mkdir', (['"""data/mesh/ori"""'], {}), "('data/mesh/ori')\n", (20763, 20780), False, 'import shutil, os\n'), ((22502, 22528), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (22515, 22528), False, 'import shutil, os\n'), ((22538, 22559), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (22546, 22559), False, 'import shutil, os\n'), ((22569, 22594), 'os.mkdir', 'os.mkdir', (['"""data/mesh/exp"""'], {}), "('data/mesh/exp')\n", (22577, 22594), False, 'import shutil, os\n'), ((22604, 22628), 'os.mkdir', 'os.mkdir', (['"""data/mesh/id"""'], {}), "('data/mesh/id')\n", (22612, 22628), False, 'import shutil, os\n'), ((22638, 22668), 'os.mkdir', 'os.mkdir', (['"""data/mesh/rec_plus"""'], {}), "('data/mesh/rec_plus')\n", (22646, 22668), False, 'import shutil, os\n'), ((22678, 22710), 'os.mkdir', 'os.mkdir', (['"""data/mesh/rec_fusion"""'], {}), "('data/mesh/rec_fusion')\n", (22686, 22710), False, 'import shutil, os\n'), ((25420, 25446), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (25433, 25446), False, 'import shutil, os\n'), ((25456, 25477), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (25464, 25477), False, 'import shutil, os\n'), ((25721, 25780), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array141', 'self.M_list', 'self.m_list'], {}), '(data_array141, self.M_list, self.m_list)\n', (25739, 25780), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((25790, 25849), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array142', 'self.M_list', 'self.m_list'], {}), '(data_array142, self.M_list, self.m_list)\n', (25808, 25849), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((27932, 27969), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (27942, 27969), True, 'import numpy as np, keras.backend as K\n'), ((27983, 28020), 'keras.backend.variable', 'K.variable', (['(self.m_list + self.M_list)'], {}), '(self.m_list + self.M_list)\n', (27993, 28020), True, 'import numpy as np, keras.backend as K\n'), ((28299, 28419), 'src.VAE.get_gcn', 'get_gcn', (['T_k', 'support'], {'batch_size': 'self.batch_size', 'feature_dim': 'self.feature_dim', 'v': 'self.v', 'input_dim': 'self.input_dim'}), '(T_k, support, batch_size=self.batch_size, feature_dim=self.\n feature_dim, v=self.v, input_dim=self.input_dim)\n', (28306, 28419), False, 'from src.VAE import get_gcn, get_gcn_vae_id, get_gcn_vae_exp\n'), ((28436, 28466), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (28441, 28466), False, 'from keras.layers import Input\n'), ((28496, 28526), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (28501, 28526), False, 'from keras.layers import Input\n'), ((28552, 28582), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (28557, 28582), False, 'from keras.layers import Input\n'), ((29075, 29173), 'keras.backend.function', 'K.function', (['[self.real, self.mean_exp, self.neutral_face]', '[self.loss]', 'self.training_updates'], {}), '([self.real, self.mean_exp, self.neutral_face], [self.loss], self\n .training_updates)\n', (29085, 29173), True, 'import numpy as np, keras.backend as K\n'), ((29195, 29265), 'keras.backend.function', 'K.function', (['[self.real, self.mean_exp, self.neutral_face]', '[self.loss]'], {}), '([self.real, self.mean_exp, self.neutral_face], [self.loss])\n', (29205, 29265), True, 'import numpy as np, keras.backend as K\n'), ((29871, 29927), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (29889, 29927), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((29937, 29991), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['mean_exp', 'self.M_list', 'self.m_list'], {}), '(mean_exp, self.M_list, self.m_list)\n', (29955, 29991), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((30007, 30025), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (30015, 30025), True, 'import numpy as np, keras.backend as K\n'), ((30046, 30064), 'numpy.zeros', 'np.zeros', (['(epoch,)'], {}), '((epoch,))\n', (30054, 30064), True, 'import numpy as np, keras.backend as K\n'), ((30160, 30192), 'numpy.arange', 'np.arange', (['(train_people_num * 47)'], {}), '(train_people_num * 47)\n', (30169, 30192), True, 'import numpy as np, keras.backend as K\n'), ((31873, 31902), 'numpy.save', 'np.save', (['"""test_log"""', 'test_log'], {}), "('test_log', test_log)\n", (31880, 31902), True, 'import numpy as np, keras.backend as K\n'), ((31912, 31931), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (31919, 31931), True, 'import numpy as np, keras.backend as K\n'), ((33011, 33068), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['inter_array', 'self.M_list', 'self.m_list'], {}), '(inter_array, self.M_list, self.m_list)\n', (33029, 33068), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((33078, 33134), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (33096, 33134), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((33144, 33200), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (33162, 33200), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((33210, 33264), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['mean_exp', 'self.M_list', 'self.m_list'], {}), '(mean_exp, self.M_list, self.m_list)\n', (33228, 33264), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((33297, 33348), 'numpy.concatenate', 'np.concatenate', (['[data_array, mean_exp, inter_array]'], {}), '([data_array, mean_exp, inter_array])\n', (33311, 33348), True, 'import numpy as np, keras.backend as K\n'), ((33432, 33469), 'numpy.zeros', 'np.zeros', (['(epoch * train_people_num,)'], {}), '((epoch * train_people_num,))\n', (33440, 33469), True, 'import numpy as np, keras.backend as K\n'), ((33490, 33527), 'numpy.zeros', 'np.zeros', (['(epoch * train_people_num,)'], {}), '((epoch * train_people_num,))\n', (33498, 33527), True, 'import numpy as np, keras.backend as K\n'), ((33601, 33628), 'numpy.arange', 'np.arange', (['train_people_num'], {}), '(train_people_num)\n', (33610, 33628), True, 'import numpy as np, keras.backend as K\n'), ((33841, 33878), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (33851, 33878), True, 'import numpy as np, keras.backend as K\n'), ((33892, 33929), 'keras.backend.variable', 'K.variable', (['(self.M_list + self.m_list)'], {}), '(self.M_list + self.m_list)\n', (33902, 33929), True, 'import numpy as np, keras.backend as K\n'), ((34658, 34743), 'keras.backend.function', 'K.function', (['[self.real]', '[loss_func, self.regularization_loss]', 'training_updates'], {}), '([self.real], [loss_func, self.regularization_loss], training_updates\n )\n', (34668, 34743), True, 'import numpy as np, keras.backend as K\n'), ((34764, 34826), 'keras.backend.function', 'K.function', (['[self.real]', '[loss_func, self.regularization_loss]'], {}), '([self.real], [loss_func, self.regularization_loss])\n', (34774, 34826), True, 'import numpy as np, keras.backend as K\n'), ((36089, 36117), 'numpy.save', 'np.save', (['"""testlog"""', 'test_log'], {}), "('testlog', test_log)\n", (36096, 36117), True, 'import numpy as np, keras.backend as K\n'), ((36127, 36146), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (36134, 36146), True, 'import numpy as np, keras.backend as K\n'), ((36350, 36387), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (36360, 36387), True, 'import numpy as np, keras.backend as K\n'), ((36401, 36438), 'keras.backend.variable', 'K.variable', (['(self.m_list + self.M_list)'], {}), '(self.m_list + self.M_list)\n', (36411, 36438), True, 'import numpy as np, keras.backend as K\n'), ((39959, 40090), 'keras.backend.function', 'K.function', (['[id_z, exp_z, z, x, y]', '[total_loss, loss_id, loss_exp, loss_disentangle, loss_rec, regular_loss]', 'training_updates'], {}), '([id_z, exp_z, z, x, y], [total_loss, loss_id, loss_exp,\n loss_disentangle, loss_rec, regular_loss], training_updates)\n', (39969, 40090), True, 'import numpy as np, keras.backend as K\n'), ((40107, 40206), 'keras.backend.function', 'K.function', (['[id_z, exp_z, z, x, y]', '[total_loss, loss_id, loss_exp, loss_disentangle, loss_rec]'], {}), '([id_z, exp_z, z, x, y], [total_loss, loss_id, loss_exp,\n loss_disentangle, loss_rec])\n', (40117, 40206), True, 'import numpy as np, keras.backend as K\n'), ((41109, 41166), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['inter_array', 'self.M_list', 'self.m_list'], {}), '(inter_array, self.M_list, self.m_list)\n', (41127, 41166), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((41176, 41232), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['test_array', 'self.M_list', 'self.m_list'], {}), '(test_array, self.M_list, self.m_list)\n', (41194, 41232), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((41242, 41298), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (41260, 41298), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((41308, 41362), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['mean_exp', 'self.M_list', 'self.m_list'], {}), '(mean_exp, self.M_list, self.m_list)\n', (41326, 41362), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((41395, 41446), 'numpy.concatenate', 'np.concatenate', (['[data_array, mean_exp, inter_array]'], {}), '([data_array, mean_exp, inter_array])\n', (41409, 41446), True, 'import numpy as np, keras.backend as K\n'), ((41530, 41567), 'numpy.zeros', 'np.zeros', (['(epoch * train_people_num,)'], {}), '((epoch * train_people_num,))\n', (41538, 41567), True, 'import numpy as np, keras.backend as K\n'), ((41588, 41625), 'numpy.zeros', 'np.zeros', (['(epoch * train_people_num,)'], {}), '((epoch * train_people_num,))\n', (41596, 41625), True, 'import numpy as np, keras.backend as K\n'), ((41688, 41715), 'numpy.arange', 'np.arange', (['train_people_num'], {}), '(train_people_num)\n', (41697, 41715), True, 'import numpy as np, keras.backend as K\n'), ((43531, 43560), 'numpy.save', 'np.save', (['"""test_log"""', 'test_log'], {}), "('test_log', test_log)\n", (43538, 43560), True, 'import numpy as np, keras.backend as K\n'), ((43570, 43589), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (43577, 43589), True, 'import numpy as np, keras.backend as K\n'), ((44714, 44770), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (44732, 44770), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((45387, 45443), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_exp', 'self.M_list', 'self.m_list'], {}), '(norm_exp, self.M_list, self.m_list)\n', (45407, 45443), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((45467, 45522), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_id', 'self.M_list', 'self.m_list'], {}), '(norm_id, self.M_list, self.m_list)\n', (45487, 45522), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((45621, 45647), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (45634, 45647), False, 'import shutil, os\n'), ((45657, 45678), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (45665, 45678), False, 'import shutil, os\n'), ((47291, 47317), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (47304, 47317), False, 'import shutil, os\n'), ((47327, 47348), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (47335, 47348), False, 'import shutil, os\n'), ((47358, 47386), 'os.mkdir', 'os.mkdir', (['"""data/mesh/people"""'], {}), "('data/mesh/people')\n", (47366, 47386), False, 'import shutil, os\n'), ((47396, 47426), 'os.mkdir', 'os.mkdir', (['"""data/mesh/transfer"""'], {}), "('data/mesh/transfer')\n", (47404, 47426), False, 'import shutil, os\n'), ((47686, 47745), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array141', 'self.M_list', 'self.m_list'], {}), '(data_array141, self.M_list, self.m_list)\n', (47704, 47745), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((47755, 47814), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array142', 'self.M_list', 'self.m_list'], {}), '(data_array142, self.M_list, self.m_list)\n', (47773, 47814), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((48291, 48326), 'numpy.repeat', 'np.repeat', (['norm_id[0:1]', '(47)'], {'axis': '(0)'}), '(norm_id[0:1], 47, axis=0)\n', (48300, 48326), True, 'import numpy as np, keras.backend as K\n'), ((48480, 48535), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['id_used', 'self.M_list', 'self.m_list'], {}), '(id_used, self.M_list, self.m_list)\n', (48500, 48535), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((48563, 48619), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_exp', 'self.M_list', 'self.m_list'], {}), '(norm_exp, self.M_list, self.m_list)\n', (48583, 48619), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((48648, 48709), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_transfer', 'self.M_list', 'self.m_list'], {}), '(norm_transfer, self.M_list, self.m_list)\n', (48668, 48709), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((52211, 52237), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (52224, 52237), False, 'import shutil, os\n'), ((52247, 52268), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (52255, 52268), False, 'import shutil, os\n'), ((52278, 52302), 'os.mkdir', 'os.mkdir', (['"""data/mesh/id"""'], {}), "('data/mesh/id')\n", (52286, 52302), False, 'import shutil, os\n'), ((52312, 52337), 'os.mkdir', 'os.mkdir', (['"""data/mesh/exp"""'], {}), "('data/mesh/exp')\n", (52320, 52337), False, 'import shutil, os\n'), ((52347, 52372), 'os.mkdir', 'os.mkdir', (['"""data/mesh/rec"""'], {}), "('data/mesh/rec')\n", (52355, 52372), False, 'import shutil, os\n'), ((52382, 52407), 'os.mkdir', 'os.mkdir', (['"""data/mesh/ori"""'], {}), "('data/mesh/ori')\n", (52390, 52407), False, 'import shutil, os\n'), ((52417, 52443), 'os.mkdir', 'os.mkdir', (['"""data/mesh/plus"""'], {}), "('data/mesh/plus')\n", (52425, 52443), False, 'import shutil, os\n'), ((52453, 52482), 'os.mkdir', 'os.mkdir', (['"""data/mesh/bp_plus"""'], {}), "('data/mesh/bp_plus')\n", (52461, 52482), False, 'import shutil, os\n'), ((52492, 52520), 'os.mkdir', 'os.mkdir', (['"""data/mesh/bp_rec"""'], {}), "('data/mesh/bp_rec')\n", (52500, 52520), False, 'import shutil, os\n'), ((56313, 56364), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['exp_1', 'self.M_list', 'self.m_list'], {}), '(exp_1, self.M_list, self.m_list)\n', (56331, 56364), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((56374, 56425), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['exp_2', 'self.M_list', 'self.m_list'], {}), '(exp_2, self.M_list, self.m_list)\n', (56392, 56425), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((56435, 56485), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['id_1', 'self.M_list', 'self.m_list'], {}), '(id_1, self.M_list, self.m_list)\n', (56453, 56485), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((56495, 56545), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['id_2', 'self.M_list', 'self.m_list'], {}), '(id_2, self.M_list, self.m_list)\n', (56513, 56545), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((57110, 57128), 'keras.layers.Input', 'Input', ([], {'shape': '(50,)'}), '(shape=(50,))\n', (57115, 57128), False, 'from keras.layers import Input\n'), ((57151, 57169), 'keras.layers.Input', 'Input', ([], {'shape': '(25,)'}), '(shape=(25,))\n', (57156, 57169), False, 'from keras.layers import Input\n'), ((57301, 57346), 'keras.models.Model', 'Model', (['[code_id, code_exp]', 'corespondent_mesh'], {}), '([code_id, code_exp], corespondent_mesh)\n', (57306, 57346), False, 'from keras.models import Model\n'), ((58947, 58973), 'shutil.rmtree', 'shutil.rmtree', (['"""data/mesh"""'], {}), "('data/mesh')\n", (58960, 58973), False, 'import shutil, os\n'), ((58983, 59004), 'os.mkdir', 'os.mkdir', (['"""data/mesh"""'], {}), "('data/mesh')\n", (58991, 59004), False, 'import shutil, os\n'), ((1644, 1702), 'scipy.sparse.linalg.eigen.arpack.eigsh', 'eigsh', (['laplacian', '(1)'], {'which': '"""LM"""', 'return_eigenvectors': '(False)'}), "(laplacian, 1, which='LM', return_eigenvectors=False)\n", (1649, 1702), False, 'from scipy.sparse.linalg.eigen.arpack import eigsh, ArpackNoConvergence\n'), ((6849, 6867), 'numpy.repeat', 'np.repeat', (['mask', '(9)'], {}), '(mask, 9)\n', (6858, 6867), True, 'import numpy as np, keras.backend as K\n'), ((7288, 7357), 'keras.backend.function', 'K.function', (['[target_feature_holder]', '[loss, target]', 'training_updates'], {}), '([target_feature_holder], [loss, target], training_updates)\n', (7298, 7357), True, 'import numpy as np, keras.backend as K\n'), ((9981, 10013), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (9998, 10013), True, 'import numpy as np, keras.backend as K\n'), ((10027, 10056), 'numpy.random.shuffle', 'np.random.shuffle', (['inter_list'], {}), '(inter_list)\n', (10044, 10056), True, 'import numpy as np, keras.backend as K\n'), ((12332, 12351), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (12339, 12351), True, 'import numpy as np, keras.backend as K\n'), ((12365, 12393), 'numpy.save', 'np.save', (['"""testlog"""', 'test_log'], {}), "('testlog', test_log)\n", (12372, 12393), True, 'import numpy as np, keras.backend as K\n'), ((13920, 13952), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (13937, 13952), True, 'import numpy as np, keras.backend as K\n'), ((14917, 14936), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (14924, 14936), True, 'import numpy as np, keras.backend as K\n'), ((14950, 14978), 'numpy.save', 'np.save', (['"""testlog"""', 'test_log'], {}), "('testlog', test_log)\n", (14957, 14978), True, 'import numpy as np, keras.backend as K\n'), ((18737, 18761), 'numpy.random.randint', 'np.random.randint', (['(1)', '(11)'], {}), '(1, 11)\n', (18754, 18761), True, 'import numpy as np, keras.backend as K\n'), ((18834, 18866), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (18851, 18866), True, 'import numpy as np, keras.backend as K\n'), ((21254, 21310), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (21272, 21310), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((23170, 23226), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (23188, 23226), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((23886, 23941), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_id', 'self.M_list', 'self.m_list'], {}), '(norm_id, self.M_list, self.m_list)\n', (23906, 23941), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((23969, 24025), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_exp', 'self.M_list', 'self.m_list'], {}), '(norm_exp, self.M_list, self.m_list)\n', (23989, 24025), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((24053, 24109), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_rec', 'self.M_list', 'self.m_list'], {}), '(norm_rec, self.M_list, self.m_list)\n', (24073, 24109), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((30242, 30266), 'numpy.random.randint', 'np.random.randint', (['(1)', '(11)'], {}), '(1, 11)\n', (30259, 30266), True, 'import numpy as np, keras.backend as K\n'), ((30387, 30419), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (30404, 30419), True, 'import numpy as np, keras.backend as K\n'), ((32662, 32700), 'keras.backend.reshape', 'K.reshape', (['x', '(self.batch_size, -1, 3)'], {}), '(x, (self.batch_size, -1, 3))\n', (32671, 32700), True, 'import numpy as np, keras.backend as K\n'), ((34921, 34953), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (34938, 34953), True, 'import numpy as np, keras.backend as K\n'), ((36731, 36769), 'keras.backend.reshape', 'K.reshape', (['x', '(self.batch_size, -1, 3)'], {}), '(x, (self.batch_size, -1, 3))\n', (36740, 36769), True, 'import numpy as np, keras.backend as K\n'), ((41765, 41789), 'numpy.random.randint', 'np.random.randint', (['(1)', '(11)'], {}), '(1, 11)\n', (41782, 41789), True, 'import numpy as np, keras.backend as K\n'), ((41863, 41895), 'numpy.random.shuffle', 'np.random.shuffle', (['constant_list'], {}), '(constant_list)\n', (41880, 41895), True, 'import numpy as np, keras.backend as K\n'), ((50591, 50614), 'keras.backend.variable', 'K.variable', (['id_start[0]'], {}), '(id_start[0])\n', (50601, 50614), True, 'import numpy as np, keras.backend as K\n'), ((50639, 50663), 'keras.backend.variable', 'K.variable', (['exp_start[0]'], {}), '(exp_start[0])\n', (50649, 50663), True, 'import numpy as np, keras.backend as K\n'), ((50701, 50731), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (50706, 50731), False, 'from keras.layers import Input\n'), ((50970, 51007), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (50980, 51007), True, 'import numpy as np, keras.backend as K\n'), ((51025, 51062), 'keras.backend.variable', 'K.variable', (['(self.M_list + self.m_list)'], {}), '(self.M_list + self.m_list)\n', (51035, 51062), True, 'import numpy as np, keras.backend as K\n'), ((51507, 51595), 'keras.backend.function', 'K.function', (['[target_feature_holder]', '[plus_loss, target_plus]', 'training_updates_plus'], {}), '([target_feature_holder], [plus_loss, target_plus],\n training_updates_plus)\n', (51517, 51595), True, 'import numpy as np, keras.backend as K\n'), ((51619, 51704), 'keras.backend.function', 'K.function', (['[target_feature_holder]', '[rec_loss, target_rec]', 'training_updates_rec'], {}), '([target_feature_holder], [rec_loss, target_rec],\n training_updates_rec)\n', (51629, 51704), True, 'import numpy as np, keras.backend as K\n'), ((53379, 53435), 'src.data_utils.normalize_fromfile', 'normalize_fromfile', (['data_array', 'self.M_list', 'self.m_list'], {}), '(data_array, self.M_list, self.m_list)\n', (53397, 53435), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((54096, 54152), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_exp', 'self.M_list', 'self.m_list'], {}), '(norm_exp, self.M_list, self.m_list)\n', (54116, 54152), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((54180, 54235), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_id', 'self.M_list', 'self.m_list'], {}), '(norm_id, self.M_list, self.m_list)\n', (54200, 54235), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((54259, 54285), 'numpy.zeros_like', 'np.zeros_like', (['feature_rec'], {}), '(feature_rec)\n', (54272, 54285), True, 'import numpy as np, keras.backend as K\n'), ((54307, 54333), 'numpy.zeros_like', 'np.zeros_like', (['feature_rec'], {}), '(feature_rec)\n', (54320, 54333), True, 'import numpy as np, keras.backend as K\n'), ((54654, 54708), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['f_plus', 'self.M_list', 'self.m_list'], {}), '(f_plus, self.M_list, self.m_list)\n', (54674, 54708), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((54732, 54785), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['f_rec', 'self.M_list', 'self.m_list'], {}), '(f_rec, self.M_list, self.m_list)\n', (54752, 54785), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((57869, 57892), 'keras.backend.variable', 'K.variable', (['id_start[0]'], {}), '(id_start[0])\n', (57879, 57892), True, 'import numpy as np, keras.backend as K\n'), ((57917, 57941), 'keras.backend.variable', 'K.variable', (['exp_start[0]'], {}), '(exp_start[0])\n', (57927, 57941), True, 'import numpy as np, keras.backend as K\n'), ((57979, 58009), 'keras.layers.Input', 'Input', ([], {'shape': '(self.input_dim,)'}), '(shape=(self.input_dim,))\n', (57984, 58009), False, 'from keras.layers import Input\n'), ((58200, 58237), 'keras.backend.variable', 'K.variable', (['(self.M_list - self.m_list)'], {}), '(self.M_list - self.m_list)\n', (58210, 58237), True, 'import numpy as np, keras.backend as K\n'), ((58255, 58292), 'keras.backend.variable', 'K.variable', (['(self.M_list + self.m_list)'], {}), '(self.M_list + self.m_list)\n', (58265, 58292), True, 'import numpy as np, keras.backend as K\n'), ((58514, 58618), 'keras.backend.function', 'K.function', (['[target_feature_holder]', '[rec_loss, target_rec, id_code, exp_code]', 'training_updates_rec'], {}), '([target_feature_holder], [rec_loss, target_rec, id_code,\n exp_code], training_updates_rec)\n', (58524, 58618), True, 'import numpy as np, keras.backend as K\n'), ((2215, 2233), 'scipy.sparse.eye', 'sp.eye', (['X.shape[0]'], {}), '(X.shape[0])\n', (2221, 2233), True, 'import scipy.sparse as sp\n'), ((6311, 6324), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (6320, 6324), True, 'import numpy as np, keras.backend as K\n'), ((6965, 7002), 'numpy.array', 'np.array', (['[1, 0, 0, 1, 0, 1, 0, 0, 0]'], {}), '([1, 0, 0, 1, 0, 1, 0, 0, 0])\n', (6973, 7002), True, 'import numpy as np, keras.backend as K\n'), ((7068, 7115), 'keras.backend.abs', 'K.abs', (['(ratio * (target - target_feature_holder))'], {}), '(ratio * (target - target_feature_holder))\n', (7073, 7115), True, 'import numpy as np, keras.backend as K\n'), ((8087, 8109), 'src.data_utils.data_recover', 'data_recover', (['start_id'], {}), '(start_id)\n', (8099, 8109), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((8171, 8194), 'src.data_utils.data_recover', 'data_recover', (['result_id'], {}), '(result_id)\n', (8183, 8194), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((8257, 8285), 'src.data_utils.data_recover', 'data_recover', (['target_feature'], {}), '(target_feature)\n', (8269, 8285), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((8961, 8994), 'numpy.mean', 'np.mean', (['interpolate_data'], {'axis': '(0)'}), '(interpolate_data, axis=0)\n', (8968, 8994), True, 'import numpy as np, keras.backend as K\n'), ((10268, 10309), 'numpy.random.randint', 'np.random.randint', (['(0)', '(47)', 'self.batch_size'], {}), '(0, 47, self.batch_size)\n', (10285, 10309), True, 'import numpy as np, keras.backend as K\n'), ((10340, 10399), 'numpy.random.randint', 'np.random.randint', (['(0)', 'inter_array.shape[0]', 'self.batch_size'], {}), '(0, inter_array.shape[0], self.batch_size)\n', (10357, 10399), True, 'import numpy as np, keras.backend as K\n'), ((10443, 10454), 'numpy.array', 'np.array', (['j'], {}), '(j)\n', (10451, 10454), True, 'import numpy as np, keras.backend as K\n'), ((10859, 10906), 'numpy.random.randint', 'np.random.randint', (['(0)', '(47)', 'inter_people.shape[0]'], {}), '(0, 47, inter_people.shape[0])\n', (10876, 10906), True, 'import numpy as np, keras.backend as K\n'), ((11053, 11076), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(1)'], {}), '(1)\n', (11073, 11076), True, 'import numpy as np, keras.backend as K\n'), ((11094, 11132), 'keras.backend.set_value', 'K.set_value', (['self.opt.lr', '(self.lr * 10)'], {}), '(self.opt.lr, self.lr * 10)\n', (11105, 11132), True, 'import numpy as np, keras.backend as K\n'), ((11272, 11311), 'keras.backend.set_value', 'K.set_value', (['self.opt.lr', '(self.lr * 0.1)'], {}), '(self.opt.lr, self.lr * 0.1)\n', (11283, 11311), True, 'import numpy as np, keras.backend as K\n'), ((11635, 11681), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10 * 47)', 'self.batch_size'], {}), '(0, 10 * 47, self.batch_size)\n', (11652, 11681), True, 'import numpy as np, keras.backend as K\n'), ((11795, 11818), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (11815, 11818), True, 'import numpy as np, keras.backend as K\n'), ((13034, 13067), 'numpy.mean', 'np.mean', (['interpolate_data'], {'axis': '(0)'}), '(interpolate_data, axis=0)\n', (13041, 13067), True, 'import numpy as np, keras.backend as K\n'), ((13254, 13268), 'numpy.arange', 'np.arange', (['(140)'], {}), '(140)\n', (13263, 13268), True, 'import numpy as np, keras.backend as K\n'), ((13350, 13363), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (13359, 13363), True, 'import numpy as np, keras.backend as K\n'), ((14066, 14107), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', 'self.batch_size'], {}), '(0, 10, self.batch_size)\n', (14083, 14107), True, 'import numpy as np, keras.backend as K\n'), ((14239, 14262), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(1)'], {}), '(1)\n', (14259, 14262), True, 'import numpy as np, keras.backend as K\n'), ((14398, 14421), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (14418, 14421), True, 'import numpy as np, keras.backend as K\n'), ((17239, 17255), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr'}), '(lr=self.lr)\n', (17243, 17255), False, 'from keras.optimizers import Adam\n'), ((18925, 18949), 'numpy.random.randint', 'np.random.randint', (['(0)', '(47)'], {}), '(0, 47)\n', (18942, 18949), True, 'import numpy as np, keras.backend as K\n'), ((28994, 29005), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (28998, 29005), False, 'from keras.optimizers import Adam\n'), ((31418, 31442), 'numpy.random.randint', 'np.random.randint', (['(1)', '(46)'], {}), '(1, 46)\n', (31435, 31442), True, 'import numpy as np, keras.backend as K\n'), ((32470, 32503), 'numpy.mean', 'np.mean', (['interpolate_data'], {'axis': '(0)'}), '(interpolate_data, axis=0)\n', (32477, 32503), True, 'import numpy as np, keras.backend as K\n'), ((34573, 34589), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr'}), '(lr=self.lr)\n', (34577, 34589), False, 'from keras.optimizers import Adam\n'), ((35412, 35450), 'numpy.random.randint', 'np.random.randint', (['test_array.shape[0]'], {}), '(test_array.shape[0])\n', (35429, 35450), True, 'import numpy as np, keras.backend as K\n'), ((39860, 39876), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'self.lr'}), '(lr=self.lr)\n', (39864, 39876), False, 'from keras.optimizers import Adam\n'), ((40648, 40681), 'numpy.mean', 'np.mean', (['interpolate_data'], {'axis': '(0)'}), '(interpolate_data, axis=0)\n', (40655, 40681), True, 'import numpy as np, keras.backend as K\n'), ((42716, 42740), 'numpy.random.randint', 'np.random.randint', (['(0)', '(46)'], {}), '(0, 46)\n', (42733, 42740), True, 'import numpy as np, keras.backend as K\n'), ((59758, 59814), 'src.data_utils.denormalize_fromfile', 'denormalize_fromfile', (['norm_rec', 'self.M_list', 'self.m_list'], {}), '(norm_rec, self.M_list, self.m_list)\n', (59778, 59814), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((7208, 7219), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (7212, 7219), False, 'from keras.optimizers import Adam\n'), ((14209, 14220), 'numpy.array', 'np.array', (['j'], {}), '(j)\n', (14217, 14220), True, 'import numpy as np, keras.backend as K\n'), ((15710, 15737), 'src.data_utils.data_recover', 'data_recover', (['feature_id[i]'], {}), '(feature_id[i])\n', (15722, 15737), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((15828, 15849), 'src.data_utils.data_recover', 'data_recover', (['data[i]'], {}), '(data[i])\n', (15840, 15849), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((20261, 20289), 'src.data_utils.data_recover', 'data_recover', (['feature_exp[i]'], {}), '(feature_exp[i])\n', (20273, 20289), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((20381, 20402), 'src.data_utils.data_recover', 'data_recover', (['data[i]'], {}), '(data[i])\n', (20393, 20402), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((26698, 26763), 'src.data_utils.data_recover', 'data_recover', (['(data141[0] - feature_id_141[0] + feature_exp_142[i])'], {}), '(data141[0] - feature_id_141[0] + feature_exp_142[i])\n', (26710, 26763), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((26850, 26915), 'src.data_utils.data_recover', 'data_recover', (['(data142[0] - feature_id_142[0] + feature_exp_141[i])'], {}), '(data142[0] - feature_id_142[0] + feature_exp_141[i])\n', (26862, 26915), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((34293, 34340), 'keras.backend.abs', 'K.abs', (['((self.real - rec_mesh) * ratio - 0.9 * s)'], {}), '((self.real - rec_mesh) * ratio - 0.9 * s)\n', (34298, 34340), True, 'import numpy as np, keras.backend as K\n'), ((36010, 36038), 'numpy.save', 'np.save', (['"""testlog"""', 'test_log'], {}), "('testlog', test_log)\n", (36017, 36038), True, 'import numpy as np, keras.backend as K\n'), ((36060, 36079), 'numpy.save', 'np.save', (['"""log"""', 'log'], {}), "('log', log)\n", (36067, 36079), True, 'import numpy as np, keras.backend as K\n'), ((45757, 45785), 'src.data_utils.data_recover', 'data_recover', (['feature_rec[i]'], {}), '(feature_rec[i])\n', (45769, 45785), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((45877, 45898), 'src.data_utils.data_recover', 'data_recover', (['data[i]'], {}), '(data[i])\n', (45889, 45898), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((45990, 46019), 'src.data_utils.data_recover', 'data_recover', (['feature_plus[i]'], {}), '(feature_plus[i])\n', (46002, 46019), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((46112, 46140), 'src.data_utils.data_recover', 'data_recover', (['feature_exp[i]'], {}), '(feature_exp[i])\n', (46124, 46140), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((46232, 46259), 'src.data_utils.data_recover', 'data_recover', (['feature_id[i]'], {}), '(feature_id[i])\n', (46244, 46259), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((51095, 51157), 'keras.backend.abs', 'K.abs', (['(ratio * (target_feature_holder - target_plus) - 0.9 * s)'], {}), '(ratio * (target_feature_holder - target_plus) - 0.9 * s)\n', (51100, 51157), True, 'import numpy as np, keras.backend as K\n'), ((51191, 51252), 'keras.backend.abs', 'K.abs', (['(ratio * (target_feature_holder - target_rec) - 0.9 * s)'], {}), '(ratio * (target_feature_holder - target_rec) - 0.9 * s)\n', (51196, 51252), True, 'import numpy as np, keras.backend as K\n'), ((51307, 51318), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (51311, 51318), False, 'from keras.optimizers import Adam\n'), ((51405, 51416), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (51409, 51416), False, 'from keras.optimizers import Adam\n'), ((55921, 55985), 'numpy.fromfile', 'np.fromfile', (['"""/home/jzh/CVPR2019/Exploring/extrapolated_144.dat"""'], {}), "('/home/jzh/CVPR2019/Exploring/extrapolated_144.dat')\n", (55932, 55985), True, 'import numpy as np, keras.backend as K\n'), ((56031, 56095), 'numpy.fromfile', 'np.fromfile', (['"""/home/jzh/CVPR2019/Exploring/extrapolated_167.dat"""'], {}), "('/home/jzh/CVPR2019/Exploring/extrapolated_167.dat')\n", (56042, 56095), True, 'import numpy as np, keras.backend as K\n'), ((58324, 58385), 'keras.backend.abs', 'K.abs', (['(ratio * (target_feature_holder - target_rec) - 0.9 * s)'], {}), '(ratio * (target_feature_holder - target_rec) - 0.9 * s)\n', (58329, 58385), True, 'import numpy as np, keras.backend as K\n'), ((58427, 58438), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (58431, 58438), False, 'from keras.optimizers import Adam\n'), ((4894, 4905), 'keras.backend.square', 'K.square', (['w'], {}), '(w)\n', (4902, 4905), True, 'import numpy as np, keras.backend as K\n'), ((4987, 4998), 'keras.backend.square', 'K.square', (['w'], {}), '(w)\n', (4995, 4998), True, 'import numpy as np, keras.backend as K\n'), ((21766, 21787), 'src.data_utils.data_recover', 'data_recover', (['data[i]'], {}), '(data[i])\n', (21778, 21787), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((21888, 21925), 'src.data_utils.data_recover', 'data_recover', (['(data[i] - feature_id[i])'], {}), '(data[i] - feature_id[i])\n', (21900, 21925), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((22023, 22051), 'src.data_utils.data_recover', 'data_recover', (['feature_exp[i]'], {}), '(feature_exp[i])\n', (22035, 22051), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((22152, 22206), 'src.data_utils.data_recover', 'data_recover', (['(feature_exp[i] + data[i] - feature_id[i])'], {}), '(feature_exp[i] + data[i] - feature_id[i])\n', (22164, 22206), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((24198, 24226), 'src.data_utils.data_recover', 'data_recover', (['feature_exp[i]'], {}), '(feature_exp[i])\n', (24210, 24226), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((24327, 24354), 'src.data_utils.data_recover', 'data_recover', (['feature_id[i]'], {}), '(feature_id[i])\n', (24339, 24354), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((24454, 24498), 'src.data_utils.data_recover', 'data_recover', (['(feature_id[i] + feature_exp[i])'], {}), '(feature_id[i] + feature_exp[i])\n', (24466, 24498), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((24604, 24632), 'src.data_utils.data_recover', 'data_recover', (['feature_rec[i]'], {}), '(feature_rec[i])\n', (24616, 24632), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((31555, 31607), 'numpy.repeat', 'np.repeat', (['test_emotion[:1]', 'self.batch_size'], {'axis': '(0)'}), '(test_emotion[:1], self.batch_size, axis=0)\n', (31564, 31607), True, 'import numpy as np, keras.backend as K\n'), ((34123, 34131), 'keras.backend.abs', 'K.abs', (['w'], {}), '(w)\n', (34128, 34131), True, 'import numpy as np, keras.backend as K\n'), ((34213, 34224), 'keras.backend.square', 'K.square', (['w'], {}), '(w)\n', (34221, 34224), True, 'import numpy as np, keras.backend as K\n'), ((38690, 38706), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (38698, 38706), True, 'import numpy as np, keras.backend as K\n'), ((38774, 38790), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (38782, 38790), True, 'import numpy as np, keras.backend as K\n'), ((38913, 38929), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (38921, 38929), True, 'import numpy as np, keras.backend as K\n'), ((38998, 39014), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (39006, 39014), True, 'import numpy as np, keras.backend as K\n'), ((39137, 39153), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (39145, 39153), True, 'import numpy as np, keras.backend as K\n'), ((39222, 39238), 'keras.backend.square', 'K.square', (['weight'], {}), '(weight)\n', (39230, 39238), True, 'import numpy as np, keras.backend as K\n'), ((49188, 49216), 'src.data_utils.data_recover', 'data_recover', (['people_feature'], {}), '(people_feature)\n', (49200, 49216), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((49319, 49349), 'src.data_utils.data_recover', 'data_recover', (['transfer_feature'], {}), '(transfer_feature)\n', (49331, 49349), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((54923, 54947), 'src.data_utils.data_recover', 'data_recover', (['bp_plus[i]'], {}), '(bp_plus[i])\n', (54935, 54947), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55052, 55075), 'src.data_utils.data_recover', 'data_recover', (['bp_rec[i]'], {}), '(bp_rec[i])\n', (55064, 55075), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55179, 55200), 'src.data_utils.data_recover', 'data_recover', (['data[i]'], {}), '(data[i])\n', (55191, 55200), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55301, 55329), 'src.data_utils.data_recover', 'data_recover', (['feature_rec[i]'], {}), '(feature_rec[i])\n', (55313, 55329), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55430, 55457), 'src.data_utils.data_recover', 'data_recover', (['feature_id[i]'], {}), '(feature_id[i])\n', (55442, 55457), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55557, 55585), 'src.data_utils.data_recover', 'data_recover', (['feature_exp[i]'], {}), '(feature_exp[i])\n', (55569, 55585), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((55686, 55730), 'src.data_utils.data_recover', 'data_recover', (['(feature_exp[i] + feature_id[i])'], {}), '(feature_exp[i] + feature_id[i])\n', (55698, 55730), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((59875, 59903), 'src.data_utils.data_recover', 'data_recover', (['feature_rec[0]'], {}), '(feature_rec[0])\n', (59887, 59903), False, 'from src.data_utils import normalize_fromfile, denormalize_fromfile, data_recover, batch_change\n'), ((4559, 4577), 'keras.backend.square', 'K.square', (['ori_mesh'], {}), '(ori_mesh)\n', (4567, 4577), True, 'import numpy as np, keras.backend as K\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 14:52:02 2021
@author: <NAME>
"""
# Importing Librries
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from utils import boilerplate_model
#for creating feature column
from tensorflow.keras import layers
from tensorflow import feature_column
from os import getcwd
#Importing Training and Validation Dataset
ds = pd.read_csv('train1.csv')
#Importing Test Data
ds_test = pd.read_csv('test.csv')
# Pre processing test data
X_test = ds_test.iloc[:,3].values
X_test.reshape(1,-1)
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_X=LabelEncoder()
X_test=labelencoder_X.fit_transform(X_test)
ds_test['alchemy_category'] = X_test
ds_test['alchemy_category_score'] = np.array(ds_test['alchemy_category_score'])
test_results = pd.read_csv('prediction.csv')
test_text_results = test_results.iloc[:,2].values
ds_test.pop('boilerplate')
ds_test.pop('url')
ds_test.pop('urlid')
ds_test.pop('news_front_page')
ds_test['boilerplate'] = np.array(test_text_results,dtype=float)
ds_test.info()
# Encoding categorical Variable
X = ds.iloc[:,3].values
X.reshape(1,-1)
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_X=LabelEncoder()
X=labelencoder_X.fit_transform(X)
ds['alchemy_category'] = X
#Getting Boilerplate results using boilerplate Model
text_results = boilerplate_model()
text_results = np.array(text_results)
ds.pop('boilerplate')
ds.pop('url')
ds.pop('urlid')
ds.pop('news_front_page')
ds['boilerplate'] = text_results
ds.info()
train, val = train_test_split(ds, test_size=0.2)
print(len(train), 'train examples')
print(len(val), 'validation examples')
#def df_to_dataset(dataframe, shuffle=True, batch_size=32):
# dataframe = dataframe.copy()
# labels = dataframe.pop('label')
# ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
# if shuffle:
# ds = ds.shuffle(buffer_size=len(dataframe))
# ds = ds.batch(batch_size)
# return ds
train.info()
train_X = train
train_Y = np.array(train.pop('label'))
val_X= val
val_Y = np.array(val.pop('label'))
#batch_size = 64 # A small batch sized is used for demonstration purposes
#train_ds = df_to_dataset(train, batch_size=batch_size)
#val_ds = df_to_dataset(val, shuffle=False,batch_size=batch_size)
## Creating Feature Layer
#feature_columns = []
#
## Numeric Cols.
## Create a list of numeric columns. Use the following list of columns
## that have a numeric datatype:
#numeric_columns = ['alchemy_category','alchemy_category_score','avglinksize', 'commonlinkratio_1','commonlinkratio_2','commonlinkratio_3','commonlinkratio_4', 'compression_ratio','embed_ratio', 'framebased','frameTagRatio', 'hasDomainLink','html_ratio','image_ratio','is_news','lengthyLinkDomain', 'linkwordscore','non_markup_alphanum_characters','numberOfLinks','numwords_in_url','parametrizedLinkRatio','spelling_errors_ratio','boilerplate']
#
#for header in numeric_columns:
# # Create a numeric feature column out of the header.
# numeric_feature_column = tf.feature_column.numeric_column(header)
#
# feature_columns.append(numeric_feature_column)
#
##feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
# MODEL
model = tf.keras.Sequential([
tf.keras.layers.Dense(64, input_dim=23, kernel_initializer='he_uniform', activation='tanh'),
tf.keras.layers.Dense(128, activation='selu'),
tf.keras.layers.Dense(256, activation='tanh'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation='selu'),
tf.keras.layers.Dense(64, activation='tanh'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='mae', optimizer=tf.keras.optimizers.RMSprop(
learning_rate=0.05, rho=0.9, momentum=0.2, epsilon=1e-07, centered=False,
name='RMSprop'
), metrics=['accuracy','AUC',tf.keras.metrics.Precision(),tf.keras.metrics.Recall()])
NUM_EPOCHS = 50
history = model.fit(x=train_X,y=train_Y, epochs=NUM_EPOCHS,validation_data=(val_X,val_Y))
results = model.predict(ds_test)
results = np.array(results)
results = np.round(results)
prediction = pd.DataFrame(results, columns=['predictions']).to_csv('prediction1.csv')
| [
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.metrics.Precision",
"tensorflow.keras.metrics.Recall",
"numpy.array",
"tensorflow.keras.layers.Dense",
"pandas.DataFrame",
"tensorflow.keras.opt... | [((486, 511), 'pandas.read_csv', 'pd.read_csv', (['"""train1.csv"""'], {}), "('train1.csv')\n", (497, 511), True, 'import pandas as pd\n'), ((547, 570), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {}), "('test.csv')\n", (558, 570), True, 'import pandas as pd\n'), ((740, 754), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (752, 754), False, 'from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n'), ((877, 920), 'numpy.array', 'np.array', (["ds_test['alchemy_category_score']"], {}), "(ds_test['alchemy_category_score'])\n", (885, 920), True, 'import numpy as np\n'), ((941, 970), 'pandas.read_csv', 'pd.read_csv', (['"""prediction.csv"""'], {}), "('prediction.csv')\n", (952, 970), True, 'import pandas as pd\n'), ((1150, 1190), 'numpy.array', 'np.array', (['test_text_results'], {'dtype': 'float'}), '(test_text_results, dtype=float)\n', (1158, 1190), True, 'import numpy as np\n'), ((1369, 1383), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (1381, 1383), False, 'from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n'), ((1521, 1540), 'utils.boilerplate_model', 'boilerplate_model', ([], {}), '()\n', (1538, 1540), False, 'from utils import boilerplate_model\n'), ((1557, 1579), 'numpy.array', 'np.array', (['text_results'], {}), '(text_results)\n', (1565, 1579), True, 'import numpy as np\n'), ((1725, 1760), 'sklearn.model_selection.train_test_split', 'train_test_split', (['ds'], {'test_size': '(0.2)'}), '(ds, test_size=0.2)\n', (1741, 1760), False, 'from sklearn.model_selection import train_test_split\n'), ((4288, 4305), 'numpy.array', 'np.array', (['results'], {}), '(results)\n', (4296, 4305), True, 'import numpy as np\n'), ((4317, 4334), 'numpy.round', 'np.round', (['results'], {}), '(results)\n', (4325, 4334), True, 'import numpy as np\n'), ((3452, 3547), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(64)'], {'input_dim': '(23)', 'kernel_initializer': '"""he_uniform"""', 'activation': '"""tanh"""'}), "(64, input_dim=23, kernel_initializer='he_uniform',\n activation='tanh')\n", (3473, 3547), True, 'import tensorflow as tf\n'), ((3554, 3599), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(128)'], {'activation': '"""selu"""'}), "(128, activation='selu')\n", (3575, 3599), True, 'import tensorflow as tf\n'), ((3610, 3655), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(256)'], {'activation': '"""tanh"""'}), "(256, activation='tanh')\n", (3631, 3655), True, 'import tensorflow as tf\n'), ((3666, 3694), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.5)'], {}), '(0.5)\n', (3689, 3694), True, 'import tensorflow as tf\n'), ((3705, 3750), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(128)'], {'activation': '"""selu"""'}), "(128, activation='selu')\n", (3726, 3750), True, 'import tensorflow as tf\n'), ((3761, 3805), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(64)'], {'activation': '"""tanh"""'}), "(64, activation='tanh')\n", (3782, 3805), True, 'import tensorflow as tf\n'), ((3816, 3862), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (3837, 3862), True, 'import tensorflow as tf\n'), ((3914, 4035), 'tensorflow.keras.optimizers.RMSprop', 'tf.keras.optimizers.RMSprop', ([], {'learning_rate': '(0.05)', 'rho': '(0.9)', 'momentum': '(0.2)', 'epsilon': '(1e-07)', 'centered': '(False)', 'name': '"""RMSprop"""'}), "(learning_rate=0.05, rho=0.9, momentum=0.2,\n epsilon=1e-07, centered=False, name='RMSprop')\n", (3941, 4035), True, 'import tensorflow as tf\n'), ((4349, 4395), 'pandas.DataFrame', 'pd.DataFrame', (['results'], {'columns': "['predictions']"}), "(results, columns=['predictions'])\n", (4361, 4395), True, 'import pandas as pd\n'), ((4072, 4100), 'tensorflow.keras.metrics.Precision', 'tf.keras.metrics.Precision', ([], {}), '()\n', (4098, 4100), True, 'import tensorflow as tf\n'), ((4101, 4126), 'tensorflow.keras.metrics.Recall', 'tf.keras.metrics.Recall', ([], {}), '()\n', (4124, 4126), True, 'import tensorflow as tf\n')] |
import numpy as np
""""
PARALLEL
"""
A = np.array([0,23,24,24])
A = np.ones((200))
dimension = 200
precision = 10
security = 100
ts = TemplateSecurity(A,precision,4)
wires_mult,wires_euc,et_list,et_euc,gc_euc,list_of_gc, keys_euc,keys_list_mult,square_sum_query,current,m = ts.parallel_euc_setup()
available_keys_euc = keys_euc[square_sum_query[1,0]:square_sum_query[1,0]+2*precision]
mult_keys_np = np.array(keys_list_mult)
available_keys_mult = mult_keys_np[:,precision:2*precision,:]
query = np.array([0,25,23,4])
query = np.zeros((200))
wires_euc,wires_mult = ts.parallel_prepare_query(query,square_sum_query,wires_euc,wires_mult,available_keys_euc,available_keys_mult)
t = time.time()
wi = group_degarbling_(np.array(et_list),wires_mult,list_of_gc[0].circuit,list_of_gc[0].security)
wires_euc[0:2*precision*dimension,:] = wi[:,m.matrix[1,:]].reshape((2*precision*dimension,security+1))
wires = degarbling_(et_euc,wires_euc,gc_euc.circuit,security)
print(time.time()-t)
"""
end of parallel
"""
wires,et,keys,A,square_sum_query,current,gc_euc = ts.euclidean_distance_setup()
keys1 = keys[0:dimension*precision]+keys[square_sum_query[1,0]:square_sum_query[1,0]+2*precision]
query = np.array([0,25,23])
wires,B = ts.prepare_query(query,square_sum_query,wires,keys1)
t= time.time()
wi= gc_euc.degarbling(et,wires)
print(time.time()-t)
| [
"numpy.array",
"numpy.zeros",
"numpy.ones"
] | [((43, 68), 'numpy.array', 'np.array', (['[0, 23, 24, 24]'], {}), '([0, 23, 24, 24])\n', (51, 68), True, 'import numpy as np\n'), ((70, 82), 'numpy.ones', 'np.ones', (['(200)'], {}), '(200)\n', (77, 82), True, 'import numpy as np\n'), ((402, 426), 'numpy.array', 'np.array', (['keys_list_mult'], {}), '(keys_list_mult)\n', (410, 426), True, 'import numpy as np\n'), ((497, 521), 'numpy.array', 'np.array', (['[0, 25, 23, 4]'], {}), '([0, 25, 23, 4])\n', (505, 521), True, 'import numpy as np\n'), ((527, 540), 'numpy.zeros', 'np.zeros', (['(200)'], {}), '(200)\n', (535, 540), True, 'import numpy as np\n'), ((1188, 1209), 'numpy.array', 'np.array', (['[0, 25, 23]'], {}), '([0, 25, 23])\n', (1196, 1209), True, 'import numpy as np\n'), ((715, 732), 'numpy.array', 'np.array', (['et_list'], {}), '(et_list)\n', (723, 732), True, 'import numpy as np\n')] |
"""
Unit test for selection operators.
"""
import random
from math import nan
import numpy as np
import pytest
from leap_ec import Individual
from leap_ec import ops, statistical_helpers
from leap_ec.binary_rep.problems import MaxOnes
from leap_ec.data import test_population
from leap_ec.real_rep.problems import SpheroidProblem
##############################
# Tests for sus_selection()
##############################
def test_sus_selection1():
''' Test of a deterministic case of stochastic universal sampling '''
# Make a population where sus_selection has an obvious
# reproducible choice
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
pop = Individual.evaluate_population(pop)
# This selection operator will always choose the [1, 1, 1] individual
# since [0, 0, 0] has zero fitness
selector = ops.sus_selection(pop)
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
# run one more time to test shuffle
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
@pytest.mark.stochastic
def test_sus_selection_shuffle():
''' Test of a stochastic case of SUS selection '''
# Make a population where sus_selection has an obvious
# reproducible choice
# Proportions here should be 1/4 and 3/4, respectively
pop = [Individual(np.array([0, 1, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# Assign a unique identifier to each individual
pop[0].id = 0
pop[1].id = 1
# We first need to evaluate all the individuals so that
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
selected = ops.sus_selection(pop)
N = 1000
p_thresh = 0.1
observed_dist = statistical_helpers.collect_distribution(
lambda: next(selected).id, samples=N)
expected_dist = {pop[0].id: 0.25*N, pop[1].id: 0.75*N}
print(f"Observed: {observed_dist}")
print(f"Expected: {expected_dist}")
assert(statistical_helpers.stochastic_equals(expected_dist,
observed_dist, p=p_thresh))
def test_sus_selection_offset():
''' Test of SUS selection with a non-default offset '''
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# evaluate population and negate fitness of second individual
pop = Individual.evaluate_population(pop)
pop[1].fitness = -pop[1].fitness
# now we try to evaluate normally (this should throw a ValueError)
# due to the negative fitness
with pytest.raises(ValueError):
selector = ops.sus_selection(pop)
selected = next(selector)
# it should work by setting the offset to +3
# this adds 3 to each fitness value, making the second
# individual's fitness 0.
selector = ops.sus_selection(pop, offset=3)
# we expect the first individual to always be selected
# since the new zero point is now -3.
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
def test_sus_selection_pop_min():
''' Test of SUS selection with pop-min offset '''
# Create a population of positive fitness individuals
# scaling the fitness by the population minimum makes it so the
# least fit member never gets selected.
pop = [Individual(np.array([0, 1, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
pop = Individual.evaluate_population(pop)
selector = ops.sus_selection(pop, offset='pop-min')
# we expect that the second individual is always selected
# since the new zero point will be at the minimum fitness
# of the population
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
def test_sus_selection_custom_key():
''' Test of SUS selection with custom evaluation '''
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
def custom_key(individual):
''' Returns fitness based on MaxZeros '''
return np.count_nonzero(individual.genome == 0)
pop = Individual.evaluate_population(pop)
selector = ops.sus_selection(pop, key=custom_key)
# we expect the first individual to always be selected
# since its genome is all 0s
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
def test_sus_selection_num_points():
''' Test of SUS selection with varying `n` random points '''
# the second individual should always be selected
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
pop = Individual.evaluate_population(pop)
# with negative points
with pytest.raises(ValueError):
selector = ops.sus_selection(pop, n=-1)
selected = next(selector)
# with n = None (default)
selector = ops.sus_selection(pop, n=None)
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
# with n less than len(population)
selector = ops.sus_selection(pop, n=1)
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
# with n greater than len(population)
selector = ops.sus_selection(pop, n=3)
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
##############################
# Tests for proportional_selection()
##############################
def test_proportional_selection1():
''' Test of a deterministic case of proportional selection '''
# Make a population where proportional_selection has an obvious
# reproducible choice
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
parents = Individual.evaluate_population(pop)
# This selection operator will always select the [1, 1, 1] individual since
# [0, 0, 0] has zero fitness
selector = ops.proportional_selection(parents)
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
@pytest.mark.stochastic
def test_proportional_selection2():
''' Test of a stochastic proportional selection '''
# Make a population where fitness proportional selection has an obvious
# reproducible choice
# Proportions here should be 1/4 and 3/4, respectively
pop = [Individual(np.array([0, 1, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# Assign a unique identifier to each individual
pop[0].id = 0
pop[1].id = 1
# We first need to evaluate all the individuals so that
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
selected = ops.proportional_selection(pop)
N = 1000
p_thresh = 0.1
observed_dist = statistical_helpers.collect_distribution(
lambda: next(selected).id, samples=N)
expected_dist = {pop[0].id: 0.25*N, pop[1].id: 0.75*N}
print(f"Observed: {observed_dist}")
print(f"Expected: {expected_dist}")
assert(statistical_helpers.stochastic_equals(expected_dist,
observed_dist, p=p_thresh))
def test_proportional_selection_offset():
''' Test of proportional selection with a non-default offset '''
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# evaluate population and negate fitness of second individual
pop = Individual.evaluate_population(pop)
pop[1].fitness = -pop[1].fitness
# now we try to evaluate normally (this should throw a ValueError)
# due to the negative fitness
with pytest.raises(ValueError):
selector = ops.proportional_selection(pop)
selected = next(selector)
# it should work by setting the offset to +3
# this adds 3 to each fitness value, making the second
# individual's fitness 0.
selector = ops.proportional_selection(pop, offset=3)
# we expect the first individual to always be selected
# since the new zero point is now -3.
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
def test_proportional_selection_pop_min():
''' Test of proportional selection with pop-min offset '''
# Create a population of positive fitness individuals
# scaling the fitness by the population minimum makes it so the
# least fit member never gets selected.
pop = [Individual(np.array([0, 1, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
pop = Individual.evaluate_population(pop)
selector = ops.proportional_selection(pop, offset='pop-min')
# we expect that the second individual is always selected
# since the new zero point will be at the minimum fitness
# of the population
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
selected = next(selector)
assert np.all(selected.genome == [1, 1, 1])
def test_proportional_selection_custom_key():
''' Test of proportional selection with custom evaluation '''
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
def custom_key(individual):
''' Returns fitness based on MaxZeros '''
return np.count_nonzero(individual.genome == 0)
pop = Individual.evaluate_population(pop)
selector = ops.proportional_selection(pop, key=custom_key)
# we expect the first individual to always be selected
# since its genome is all 0s
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
selected = next(selector)
assert np.all(selected.genome == [0, 0, 0])
##############################
# Tests for naive_cyclic_selection()
##############################
def test_naive_cyclic_selection():
""" Test of the naive deterministic cyclic selection """
pop = [Individual(np.array([0, 0]), problem=MaxOnes()),
Individual(np.array([0, 1]), problem=MaxOnes())]
# This selection operator will deterministically cycle through the
# given population
selector = ops.naive_cyclic_selection(pop)
selected = next(selector)
assert np.all(selected.genome == [0, 0])
selected = next(selector)
assert np.all(selected.genome == [0, 1])
# And now we cycle back to the first individual
selected = next(selector)
assert np.all(selected.genome == [0, 0])
##############################
# Tests for cyclic_selection()
##############################
def test_cyclic_selection():
""" Test of the deterministic cyclic selection """
# Set seed so that we get consistent test results. I.e., it is possible
# by happenstance for some tests to fail even though they're actually ok.
# E.g., the cyclic selection tests will test if the test_sequence
# shuffles between a complete cycle, but there's a chance that the same
# test_sequence may come up in the random shuffle, so the test will fail.
# However, if we set a random seed ahead of time, then we can control for
# those pathological scenarios.
random.seed(123)
# We're just going to use integers for the population as that's
# sufficient for testing this selection operator; we don't want to get in
# the weeds with comparing individuals for test_sequence equivalency
# testing.
pop = list(range(4))
# This selection operator will deterministically cycle through the
# given population
selector = ops.cyclic_selection(pop)
# first cycle should be the same order as we started
first_iteration = [next(selector) for _ in range(len(pop))]
assert pop == first_iteration
# the second iteration should be shuffled
second_iteration = [next(selector) for _ in range(len(pop))]
assert pop != second_iteration
##############################
# Tests for truncation_selection()
##############################
def test_truncation_selection():
""" Basic truncation selection test"""
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([0, 0, 1]), problem=MaxOnes()),
Individual(np.array([1, 1, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# We first need to evaluate all the individuals so that truncation
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
truncated = ops.truncation_selection(pop, 2)
assert len(truncated) == 2
# Just to make sure, check that the two best individuals from the
# original population are in the selected population
assert pop[2] in truncated
assert pop[3] in truncated
def test_truncation_parents_selection():
""" Test (mu + lambda), i.e., parents competing with offspring
Create parent and offspring populations such that each has an "best" individual that will be selected by
truncation selection.
"""
parents = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 0]), problem=MaxOnes())]
parents = Individual.evaluate_population(parents)
offspring = [Individual(np.array([0, 0, 1]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
offspring = Individual.evaluate_population(offspring)
truncated = ops.truncation_selection(offspring, 2, parents=parents)
assert len(truncated) == 2
assert parents[1] in truncated
assert offspring[1] in truncated
def test_truncation_selection_with_nan1():
"""If truncation selection encounters a NaN and non-NaN fitness
while maximizing, the non-NaN wins.
"""
# Make a population where binary tournament_selection has an obvious
# reproducible choice
problem = MaxOnes()
pop = [Individual(np.array([0, 0, 0]), problem=problem),
Individual(np.array([1, 1, 1]), problem=problem)]
# We first need to evaluate all the individuals so that truncation
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
# Now set the "best" to NaN
pop[1].fitness = nan
best = ops.truncation_selection(pop, size=1)
assert pop[0] == best[0]
def test_truncation_selection_with_nan2():
"""If truncation selection encounters a NaN and non-NaN fitness
while minimizing, the non-NaN wins.
"""
problem = SpheroidProblem(maximize=False)
pop = []
pop.append(Individual(np.array([0]), problem=problem))
pop.append(Individual(np.array([1]), problem=problem))
pop = Individual.evaluate_population(pop)
# First *normal* selection should yield the 0 as the "best"
best = ops.truncation_selection(pop, size=1)
assert pop[0] == best[0]
# But now let's set that best to a NaN, which *should* force the other
# individual to be selected.
pop[0].fitness = nan
best = ops.truncation_selection(pop, size=1)
assert pop[1] == best[0]
##############################
# Tests for tournament_selection()
##############################
@pytest.mark.stochastic
def test_tournament_selection1():
"""If there are just two individuals in the population, then binary tournament
selection will select the better one with 75% probability."""
# Make a population where binary tournament_selection has an obvious
# reproducible choice
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# Assign a unique identifier to each individual
pop[0].id = 0
pop[1].id = 1
# We first need to evaluate all the individuals so that
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
selected = ops.tournament_selection(pop)
N = 1000
p_thresh = 0.1
observed_dist = statistical_helpers.collect_distribution(lambda: next(selected).id, samples=N)
expected_dist = { pop[0].id: 0.25*N, pop[1].id: 0.75*N }
print(f"Observed: {observed_dist}")
print(f"Expected: {expected_dist}")
assert(statistical_helpers.stochastic_equals(expected_dist, observed_dist, p=p_thresh))
@pytest.mark.stochastic
def test_tournament_selection2():
"""If there are just two individuals in the population, and we set select_worst=True,
then binary tournament selection will select the worse one with 75% probability."""
# Make a population where binary tournament_selection has an obvious
# reproducible choice
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# Assign a unique identifier to each individual
pop[0].id = 0
pop[1].id = 1
# We first need to evaluate all the individuals so that
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
selected = ops.tournament_selection(pop, select_worst=True)
N = 1000
p_thresh = 0.1
observed_dist = statistical_helpers.collect_distribution(lambda: next(selected).id, samples=N)
expected_dist = { pop[0].id: 0.75*N, pop[1].id: 0.25*N }
print(f"Observed: {observed_dist}")
print(f"Expected: {expected_dist}")
assert(statistical_helpers.stochastic_equals(expected_dist, observed_dist, p=p_thresh))
def test_tournament_selection_indices():
"""If an empty list is provided to tournament selection, it should be populated with
the index of the selected individual.
If we select a second individual, the list should be cleared and populated with the
index of the second individual."""
pop = test_population
indices = []
op = ops.tournament_selection(indices=indices)
# Select an individual
s = next(op(pop))
# Ensure the returned index is correct
assert(len(indices) == 1)
idx = indices[0]
assert(idx >= 0)
assert(idx < len(pop))
assert(pop[idx] is s)
# Select another individual
s = next(op(pop))
# Ensure the returned index is correct
assert(len(indices) == 1)
idx = indices[0]
assert(idx >= 0)
assert(idx < len(pop))
assert(pop[idx] is s)
##############################
# Tests for random_selection()
##############################
@pytest.mark.stochastic
def test_random_selection1():
"""If there are just two individuals in the population, then random
selection will select the better one with 50% probability."""
pop = [Individual(np.array([0, 0, 0]), problem=MaxOnes()),
Individual(np.array([1, 1, 1]), problem=MaxOnes())]
# Assign a unique identifier to each individual
pop[0].id = 0
pop[1].id = 1
# We first need to evaluate all the individuals so that
# selection has fitnesses to compare
pop = Individual.evaluate_population(pop)
selected = ops.random_selection(pop)
N = 1000
p_thresh = 0.1
observed_dist = statistical_helpers.collect_distribution(lambda: next(selected).id, samples=N)
expected_dist = { pop[0].id: 0.5*N, pop[1].id: 0.5*N }
print(f"Observed: {observed_dist}")
print(f"Expected: {expected_dist}")
assert(statistical_helpers.stochastic_equals(expected_dist, observed_dist, p=p_thresh))
def test_random_selection_indices():
"""If an empty list is provided to random selection, it should be populated with
the index of the selected individual.
If we select a second individual, the list should be cleared and populated with the
index of the second individual."""
pop = test_population
indices = []
op = ops.random_selection(indices=indices)
# Select an individual
s = next(op(pop))
# Ensure the returned index is correct
assert(len(indices) == 1)
idx = indices[0]
assert(idx >= 0)
assert(idx < len(pop))
assert(pop[idx] is s)
# Select another individual
s = next(op(pop))
# Ensure the returned index is correct
assert(len(indices) == 1)
idx = indices[0]
assert(idx >= 0)
assert(idx < len(pop))
assert(pop[idx] is s)
| [
"leap_ec.ops.truncation_selection",
"leap_ec.ops.naive_cyclic_selection",
"leap_ec.binary_rep.problems.MaxOnes",
"leap_ec.ops.sus_selection",
"leap_ec.real_rep.problems.SpheroidProblem",
"leap_ec.ops.tournament_selection",
"leap_ec.ops.random_selection",
"leap_ec.statistical_helpers.stochastic_equals"... | [((751, 786), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (781, 786), False, 'from leap_ec import Individual\n'), ((915, 937), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {}), '(pop)\n', (932, 937), False, 'from leap_ec import ops, statistical_helpers\n'), ((980, 1016), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (986, 1016), True, 'import numpy as np\n'), ((1059, 1095), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (1065, 1095), True, 'import numpy as np\n'), ((1178, 1214), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (1184, 1214), True, 'import numpy as np\n'), ((1801, 1836), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (1831, 1836), False, 'from leap_ec import Individual\n'), ((1852, 1874), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {}), '(pop)\n', (1869, 1874), False, 'from leap_ec import ops, statistical_helpers\n'), ((2166, 2245), 'leap_ec.statistical_helpers.stochastic_equals', 'statistical_helpers.stochastic_equals', (['expected_dist', 'observed_dist'], {'p': 'p_thresh'}), '(expected_dist, observed_dist, p=p_thresh)\n', (2203, 2245), False, 'from leap_ec import ops, statistical_helpers\n'), ((2594, 2629), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (2624, 2629), False, 'from leap_ec import Individual\n'), ((3038, 3070), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'offset': '(3)'}), '(pop, offset=3)\n', (3055, 3070), False, 'from leap_ec import ops, statistical_helpers\n'), ((3214, 3250), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (3220, 3250), True, 'import numpy as np\n'), ((3293, 3329), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (3299, 3329), True, 'import numpy as np\n'), ((3727, 3762), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (3757, 3762), False, 'from leap_ec import Individual\n'), ((3779, 3819), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'offset': '"""pop-min"""'}), "(pop, offset='pop-min')\n", (3796, 3819), False, 'from leap_ec import ops, statistical_helpers\n'), ((4010, 4046), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (4016, 4046), True, 'import numpy as np\n'), ((4089, 4125), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (4095, 4125), True, 'import numpy as np\n'), ((4498, 4533), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (4528, 4533), False, 'from leap_ec import Individual\n'), ((4549, 4587), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'key': 'custom_key'}), '(pop, key=custom_key)\n', (4566, 4587), False, 'from leap_ec import ops, statistical_helpers\n'), ((4722, 4758), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (4728, 4758), True, 'import numpy as np\n'), ((4801, 4837), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (4807, 4837), True, 'import numpy as np\n'), ((5133, 5168), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (5163, 5168), False, 'from leap_ec import Individual\n'), ((5360, 5390), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'n': 'None'}), '(pop, n=None)\n', (5377, 5390), False, 'from leap_ec import ops, statistical_helpers\n'), ((5432, 5468), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5438, 5468), True, 'import numpy as np\n'), ((5524, 5551), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'n': '(1)'}), '(pop, n=1)\n', (5541, 5551), False, 'from leap_ec import ops, statistical_helpers\n'), ((5593, 5629), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5599, 5629), True, 'import numpy as np\n'), ((5671, 5707), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5677, 5707), True, 'import numpy as np\n'), ((5766, 5793), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'n': '(3)'}), '(pop, n=3)\n', (5783, 5793), False, 'from leap_ec import ops, statistical_helpers\n'), ((5835, 5871), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5841, 5871), True, 'import numpy as np\n'), ((5913, 5949), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5919, 5949), True, 'import numpy as np\n'), ((5991, 6027), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (5997, 6027), True, 'import numpy as np\n'), ((6069, 6105), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (6075, 6105), True, 'import numpy as np\n'), ((6147, 6183), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (6153, 6183), True, 'import numpy as np\n'), ((6623, 6658), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (6653, 6658), False, 'from leap_ec import Individual\n'), ((6787, 6822), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['parents'], {}), '(parents)\n', (6813, 6822), False, 'from leap_ec import ops, statistical_helpers\n'), ((6865, 6901), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (6871, 6901), True, 'import numpy as np\n'), ((6944, 6980), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (6950, 6980), True, 'import numpy as np\n'), ((7586, 7621), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (7616, 7621), False, 'from leap_ec import Individual\n'), ((7637, 7668), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['pop'], {}), '(pop)\n', (7663, 7668), False, 'from leap_ec import ops, statistical_helpers\n'), ((7960, 8039), 'leap_ec.statistical_helpers.stochastic_equals', 'statistical_helpers.stochastic_equals', (['expected_dist', 'observed_dist'], {'p': 'p_thresh'}), '(expected_dist, observed_dist, p=p_thresh)\n', (7997, 8039), False, 'from leap_ec import ops, statistical_helpers\n'), ((8406, 8441), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (8436, 8441), False, 'from leap_ec import Individual\n'), ((8859, 8900), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['pop'], {'offset': '(3)'}), '(pop, offset=3)\n', (8885, 8900), False, 'from leap_ec import ops, statistical_helpers\n'), ((9044, 9080), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (9050, 9080), True, 'import numpy as np\n'), ((9123, 9159), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (9129, 9159), True, 'import numpy as np\n'), ((9575, 9610), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (9605, 9610), False, 'from leap_ec import Individual\n'), ((9627, 9676), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['pop'], {'offset': '"""pop-min"""'}), "(pop, offset='pop-min')\n", (9653, 9676), False, 'from leap_ec import ops, statistical_helpers\n'), ((9867, 9903), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (9873, 9903), True, 'import numpy as np\n'), ((9946, 9982), 'numpy.all', 'np.all', (['(selected.genome == [1, 1, 1])'], {}), '(selected.genome == [1, 1, 1])\n', (9952, 9982), True, 'import numpy as np\n'), ((10373, 10408), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (10403, 10408), False, 'from leap_ec import Individual\n'), ((10424, 10471), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['pop'], {'key': 'custom_key'}), '(pop, key=custom_key)\n', (10450, 10471), False, 'from leap_ec import ops, statistical_helpers\n'), ((10606, 10642), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (10612, 10642), True, 'import numpy as np\n'), ((10685, 10721), 'numpy.all', 'np.all', (['(selected.genome == [0, 0, 0])'], {}), '(selected.genome == [0, 0, 0])\n', (10691, 10721), True, 'import numpy as np\n'), ((11149, 11180), 'leap_ec.ops.naive_cyclic_selection', 'ops.naive_cyclic_selection', (['pop'], {}), '(pop)\n', (11175, 11180), False, 'from leap_ec import ops, statistical_helpers\n'), ((11223, 11256), 'numpy.all', 'np.all', (['(selected.genome == [0, 0])'], {}), '(selected.genome == [0, 0])\n', (11229, 11256), True, 'import numpy as np\n'), ((11299, 11332), 'numpy.all', 'np.all', (['(selected.genome == [0, 1])'], {}), '(selected.genome == [0, 1])\n', (11305, 11332), True, 'import numpy as np\n'), ((11427, 11460), 'numpy.all', 'np.all', (['(selected.genome == [0, 0])'], {}), '(selected.genome == [0, 0])\n', (11433, 11460), True, 'import numpy as np\n'), ((12138, 12154), 'random.seed', 'random.seed', (['(123)'], {}), '(123)\n', (12149, 12154), False, 'import random\n'), ((12525, 12550), 'leap_ec.ops.cyclic_selection', 'ops.cyclic_selection', (['pop'], {}), '(pop)\n', (12545, 12550), False, 'from leap_ec import ops, statistical_helpers\n'), ((13406, 13441), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (13436, 13441), False, 'from leap_ec import Individual\n'), ((13459, 13491), 'leap_ec.ops.truncation_selection', 'ops.truncation_selection', (['pop', '(2)'], {}), '(pop, 2)\n', (13483, 13491), False, 'from leap_ec import ops, statistical_helpers\n'), ((14117, 14156), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['parents'], {}), '(parents)\n', (14147, 14156), False, 'from leap_ec import Individual\n'), ((14312, 14353), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['offspring'], {}), '(offspring)\n', (14342, 14353), False, 'from leap_ec import Individual\n'), ((14371, 14426), 'leap_ec.ops.truncation_selection', 'ops.truncation_selection', (['offspring', '(2)'], {'parents': 'parents'}), '(offspring, 2, parents=parents)\n', (14395, 14426), False, 'from leap_ec import ops, statistical_helpers\n'), ((14806, 14815), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (14813, 14815), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((15061, 15096), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (15091, 15096), False, 'from leap_ec import Individual\n'), ((15167, 15204), 'leap_ec.ops.truncation_selection', 'ops.truncation_selection', (['pop'], {'size': '(1)'}), '(pop, size=1)\n', (15191, 15204), False, 'from leap_ec import ops, statistical_helpers\n'), ((15410, 15441), 'leap_ec.real_rep.problems.SpheroidProblem', 'SpheroidProblem', ([], {'maximize': '(False)'}), '(maximize=False)\n', (15425, 15441), False, 'from leap_ec.real_rep.problems import SpheroidProblem\n'), ((15586, 15621), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (15616, 15621), False, 'from leap_ec import Individual\n'), ((15698, 15735), 'leap_ec.ops.truncation_selection', 'ops.truncation_selection', (['pop'], {'size': '(1)'}), '(pop, size=1)\n', (15722, 15735), False, 'from leap_ec import ops, statistical_helpers\n'), ((15911, 15948), 'leap_ec.ops.truncation_selection', 'ops.truncation_selection', (['pop'], {'size': '(1)'}), '(pop, size=1)\n', (15935, 15948), False, 'from leap_ec import ops, statistical_helpers\n'), ((16709, 16744), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (16739, 16744), False, 'from leap_ec import Individual\n'), ((16760, 16789), 'leap_ec.ops.tournament_selection', 'ops.tournament_selection', (['pop'], {}), '(pop)\n', (16784, 16789), False, 'from leap_ec import ops, statistical_helpers\n'), ((17075, 17154), 'leap_ec.statistical_helpers.stochastic_equals', 'statistical_helpers.stochastic_equals', (['expected_dist', 'observed_dist'], {'p': 'p_thresh'}), '(expected_dist, observed_dist, p=p_thresh)\n', (17112, 17154), False, 'from leap_ec import ops, statistical_helpers\n'), ((17819, 17854), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (17849, 17854), False, 'from leap_ec import Individual\n'), ((17870, 17918), 'leap_ec.ops.tournament_selection', 'ops.tournament_selection', (['pop'], {'select_worst': '(True)'}), '(pop, select_worst=True)\n', (17894, 17918), False, 'from leap_ec import ops, statistical_helpers\n'), ((18204, 18283), 'leap_ec.statistical_helpers.stochastic_equals', 'statistical_helpers.stochastic_equals', (['expected_dist', 'observed_dist'], {'p': 'p_thresh'}), '(expected_dist, observed_dist, p=p_thresh)\n', (18241, 18283), False, 'from leap_ec import ops, statistical_helpers\n'), ((18644, 18685), 'leap_ec.ops.tournament_selection', 'ops.tournament_selection', ([], {'indices': 'indices'}), '(indices=indices)\n', (18668, 18685), False, 'from leap_ec import ops, statistical_helpers\n'), ((19740, 19775), 'leap_ec.Individual.evaluate_population', 'Individual.evaluate_population', (['pop'], {}), '(pop)\n', (19770, 19775), False, 'from leap_ec import Individual\n'), ((19791, 19816), 'leap_ec.ops.random_selection', 'ops.random_selection', (['pop'], {}), '(pop)\n', (19811, 19816), False, 'from leap_ec import ops, statistical_helpers\n'), ((20100, 20179), 'leap_ec.statistical_helpers.stochastic_equals', 'statistical_helpers.stochastic_equals', (['expected_dist', 'observed_dist'], {'p': 'p_thresh'}), '(expected_dist, observed_dist, p=p_thresh)\n', (20137, 20179), False, 'from leap_ec import ops, statistical_helpers\n'), ((20533, 20570), 'leap_ec.ops.random_selection', 'ops.random_selection', ([], {'indices': 'indices'}), '(indices=indices)\n', (20553, 20570), False, 'from leap_ec import ops, statistical_helpers\n'), ((2782, 2807), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2795, 2807), False, 'import pytest\n'), ((2828, 2850), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {}), '(pop)\n', (2845, 2850), False, 'from leap_ec import ops, statistical_helpers\n'), ((4446, 4486), 'numpy.count_nonzero', 'np.count_nonzero', (['(individual.genome == 0)'], {}), '(individual.genome == 0)\n', (4462, 4486), True, 'import numpy as np\n'), ((5205, 5230), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (5218, 5230), False, 'import pytest\n'), ((5251, 5279), 'leap_ec.ops.sus_selection', 'ops.sus_selection', (['pop'], {'n': '(-1)'}), '(pop, n=-1)\n', (5268, 5279), False, 'from leap_ec import ops, statistical_helpers\n'), ((8594, 8619), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8607, 8619), False, 'import pytest\n'), ((8640, 8671), 'leap_ec.ops.proportional_selection', 'ops.proportional_selection', (['pop'], {}), '(pop)\n', (8666, 8671), False, 'from leap_ec import ops, statistical_helpers\n'), ((10321, 10361), 'numpy.count_nonzero', 'np.count_nonzero', (['(individual.genome == 0)'], {}), '(individual.genome == 0)\n', (10337, 10361), True, 'import numpy as np\n'), ((636, 655), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (644, 655), True, 'import numpy as np\n'), ((699, 718), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (707, 718), True, 'import numpy as np\n'), ((1496, 1515), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (1504, 1515), True, 'import numpy as np\n'), ((1559, 1578), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (1567, 1578), True, 'import numpy as np\n'), ((2413, 2432), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (2421, 2432), True, 'import numpy as np\n'), ((2476, 2495), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (2484, 2495), True, 'import numpy as np\n'), ((3612, 3631), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (3620, 3631), True, 'import numpy as np\n'), ((3675, 3694), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (3683, 3694), True, 'import numpy as np\n'), ((4244, 4263), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (4252, 4263), True, 'import numpy as np\n'), ((4307, 4326), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (4315, 4326), True, 'import numpy as np\n'), ((5018, 5037), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (5026, 5037), True, 'import numpy as np\n'), ((5081, 5100), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (5089, 5100), True, 'import numpy as np\n'), ((6504, 6523), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (6512, 6523), True, 'import numpy as np\n'), ((6567, 6586), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (6575, 6586), True, 'import numpy as np\n'), ((7282, 7301), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (7290, 7301), True, 'import numpy as np\n'), ((7345, 7364), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (7353, 7364), True, 'import numpy as np\n'), ((8225, 8244), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (8233, 8244), True, 'import numpy as np\n'), ((8288, 8307), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (8296, 8307), True, 'import numpy as np\n'), ((9460, 9479), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (9468, 9479), True, 'import numpy as np\n'), ((9523, 9542), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (9531, 9542), True, 'import numpy as np\n'), ((10119, 10138), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (10127, 10138), True, 'import numpy as np\n'), ((10182, 10201), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (10190, 10201), True, 'import numpy as np\n'), ((10941, 10957), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (10949, 10957), True, 'import numpy as np\n'), ((11001, 11017), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (11009, 11017), True, 'import numpy as np\n'), ((13053, 13072), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (13061, 13072), True, 'import numpy as np\n'), ((13116, 13135), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (13124, 13135), True, 'import numpy as np\n'), ((13179, 13198), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (13187, 13198), True, 'import numpy as np\n'), ((13242, 13261), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (13250, 13261), True, 'import numpy as np\n'), ((13994, 14013), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (14002, 14013), True, 'import numpy as np\n'), ((14061, 14080), 'numpy.array', 'np.array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (14069, 14080), True, 'import numpy as np\n'), ((14186, 14205), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (14194, 14205), True, 'import numpy as np\n'), ((14255, 14274), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (14263, 14274), True, 'import numpy as np\n'), ((14838, 14857), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (14846, 14857), True, 'import numpy as np\n'), ((14899, 14918), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (14907, 14918), True, 'import numpy as np\n'), ((15483, 15496), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (15491, 15496), True, 'import numpy as np\n'), ((15542, 15555), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (15550, 15555), True, 'import numpy as np\n'), ((16405, 16424), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (16413, 16424), True, 'import numpy as np\n'), ((16468, 16487), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (16476, 16487), True, 'import numpy as np\n'), ((17515, 17534), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (17523, 17534), True, 'import numpy as np\n'), ((17578, 17597), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (17586, 17597), True, 'import numpy as np\n'), ((19436, 19455), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (19444, 19455), True, 'import numpy as np\n'), ((19499, 19518), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (19507, 19518), True, 'import numpy as np\n'), ((665, 674), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (672, 674), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((728, 737), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (735, 737), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((1525, 1534), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (1532, 1534), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((1588, 1597), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (1595, 1597), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((2442, 2451), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (2449, 2451), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((2505, 2514), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (2512, 2514), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((3641, 3650), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (3648, 3650), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((3704, 3713), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (3711, 3713), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((4273, 4282), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (4280, 4282), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((4336, 4345), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (4343, 4345), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((5047, 5056), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (5054, 5056), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((5110, 5119), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (5117, 5119), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((6533, 6542), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (6540, 6542), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((6596, 6605), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (6603, 6605), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((7311, 7320), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (7318, 7320), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((7374, 7383), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (7381, 7383), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((8254, 8263), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (8261, 8263), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((8317, 8326), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (8324, 8326), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((9489, 9498), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (9496, 9498), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((9552, 9561), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (9559, 9561), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((10148, 10157), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (10155, 10157), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((10211, 10220), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (10218, 10220), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((10967, 10976), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (10974, 10976), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((11027, 11036), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (11034, 11036), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((13082, 13091), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (13089, 13091), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((13145, 13154), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (13152, 13154), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((13208, 13217), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (13215, 13217), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((13271, 13280), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (13278, 13280), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((14023, 14032), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (14030, 14032), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((14090, 14099), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (14097, 14099), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((14215, 14224), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (14222, 14224), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((14284, 14293), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (14291, 14293), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((16434, 16443), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (16441, 16443), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((16497, 16506), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (16504, 16506), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((17544, 17553), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (17551, 17553), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((17607, 17616), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (17614, 17616), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((19465, 19474), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (19472, 19474), False, 'from leap_ec.binary_rep.problems import MaxOnes\n'), ((19528, 19537), 'leap_ec.binary_rep.problems.MaxOnes', 'MaxOnes', ([], {}), '()\n', (19535, 19537), False, 'from leap_ec.binary_rep.problems import MaxOnes\n')] |
import nnfs
import numpy as np
nnfs.init()
layer_outputs = [[4.8, 1.21, 2.385],
[8.9, -1.81, 0.2],
[1.41, 1.051, 0.026]]
exp_values = np.exp(layer_outputs)
norm_values = exp_values / np.sum(exp_values, axis=1, keepdims=True)
print(norm_values)
# print(sum(norm_values))
| [
"numpy.exp",
"numpy.sum",
"nnfs.init"
] | [((32, 43), 'nnfs.init', 'nnfs.init', ([], {}), '()\n', (41, 43), False, 'import nnfs\n'), ((171, 192), 'numpy.exp', 'np.exp', (['layer_outputs'], {}), '(layer_outputs)\n', (177, 192), True, 'import numpy as np\n'), ((221, 262), 'numpy.sum', 'np.sum', (['exp_values'], {'axis': '(1)', 'keepdims': '(True)'}), '(exp_values, axis=1, keepdims=True)\n', (227, 262), True, 'import numpy as np\n')] |
import time
import numpy as np
import pickle
import argparse
from parse_args import parse_args
from evaluator import Evaluator
class ItemToItemRecommender:
def __init__(self, algorithm, dataset):
with open('datasets/'+dataset+'/item_to_item_similarity_'+algorithm, 'rb') as f1:
self.model = pickle.load(f1)
def compute_user_item_features(self, user, item, items_liked_by_user, users_liking_the_item):
# randomly choose one item
if len(items_liked_by_user) > 0:
seed_item = np.random.choice(items_liked_by_user, 1)[0]
try:
features = [self.model[seed_item][item]]
except KeyError:
features = [0.]
else:
features = [0.]
return features
def fit(self, x_train, y_train, qids_train):
return 0
def predict(self, x_test, qids_test):
preds = x_test
return preds
if __name__ == '__main__':
np.random.seed(1) # fixed seed for reproducibility
start_time = time.time()
args = parse_args()
print('Starting item to item recommender..')
if not args.train:
args.train = 'datasets/' + args.dataset + '/train.dat'
if not args.test:
args.test = 'datasets/' + args.dataset + '/test.dat'
if not args.validation:
args.validation = 'datasets/' + args.dataset + '/val.dat'
rec = "Entity2Rec"
# initialize evaluator
if args.dataset == 'LastFM':
implicit = True
else:
implicit = args.implicit
if args.dataset == 'LibraryThing':
threshold = 8
else:
threshold = args.threshold
evaluat = Evaluator(implicit=implicit, threshold=threshold, all_unrated_items=args.all_unrated_items)
itemrec = ItemToItemRecommender(rec, args.dataset)
# compute features
x_train, y_train, qids_train, items_train, x_test, y_test, qids_test, items_test, x_val, y_val, qids_val, items_val = evaluat.features(
itemrec, args.train, args.test,
validation=False,
n_jobs=args.workers, supervised=False, n_users=args.num_users)
print('Finished computing features after %s seconds' % (time.time() - start_time))
scores = evaluat.evaluate(itemrec, x_test, y_test, qids_test, items_test,
write_to_file="results/%s/item_to_item_similarity/%s" % (args.dataset, rec))
print(scores)
print("--- %s seconds ---" % (time.time() - start_time))
| [
"evaluator.Evaluator",
"numpy.random.choice",
"parse_args.parse_args",
"pickle.load",
"numpy.random.seed",
"time.time"
] | [((998, 1015), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1012, 1015), True, 'import numpy as np\n'), ((1068, 1079), 'time.time', 'time.time', ([], {}), '()\n', (1077, 1079), False, 'import time\n'), ((1092, 1104), 'parse_args.parse_args', 'parse_args', ([], {}), '()\n', (1102, 1104), False, 'from parse_args import parse_args\n'), ((1697, 1793), 'evaluator.Evaluator', 'Evaluator', ([], {'implicit': 'implicit', 'threshold': 'threshold', 'all_unrated_items': 'args.all_unrated_items'}), '(implicit=implicit, threshold=threshold, all_unrated_items=args.\n all_unrated_items)\n', (1706, 1793), False, 'from evaluator import Evaluator\n'), ((320, 335), 'pickle.load', 'pickle.load', (['f1'], {}), '(f1)\n', (331, 335), False, 'import pickle\n'), ((546, 586), 'numpy.random.choice', 'np.random.choice', (['items_liked_by_user', '(1)'], {}), '(items_liked_by_user, 1)\n', (562, 586), True, 'import numpy as np\n'), ((2207, 2218), 'time.time', 'time.time', ([], {}), '()\n', (2216, 2218), False, 'import time\n'), ((2474, 2485), 'time.time', 'time.time', ([], {}), '()\n', (2483, 2485), False, 'import time\n')] |
import numpy as np
import pytest
import math
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestRegressor
import doubleml as dml
from ._utils import draw_smpls
from ._utils_irm_manual import fit_irm, boot_irm, tune_nuisance_irm
@pytest.fixture(scope='module',
params=[RandomForestRegressor()])
def learner_g(request):
return request.param
@pytest.fixture(scope='module',
params=[LogisticRegression()])
def learner_m(request):
return request.param
@pytest.fixture(scope='module',
params=['ATE', 'ATTE'])
def score(request):
return request.param
@pytest.fixture(scope='module',
params=['dml2'])
def dml_procedure(request):
return request.param
@pytest.fixture(scope='module',
params=[True, False])
def tune_on_folds(request):
return request.param
def get_par_grid(learner):
if learner.__class__ in [RandomForestRegressor]:
par_grid = {'n_estimators': [5, 10, 20]}
else:
assert learner.__class__ in [LogisticRegression]
par_grid = {'C': np.logspace(-4, 2, 10)}
return par_grid
@pytest.fixture(scope='module')
def dml_irm_fixture(generate_data_irm, learner_g, learner_m, score, dml_procedure, tune_on_folds):
par_grid = {'ml_g': get_par_grid(learner_g),
'ml_m': get_par_grid(learner_m)}
n_folds_tune = 4
boot_methods = ['normal']
n_folds = 2
n_rep_boot = 499
# collect data
(x, y, d) = generate_data_irm
# Set machine learning methods for m & g
ml_g = clone(learner_g)
ml_m = clone(learner_m)
np.random.seed(3141)
obj_dml_data = dml.DoubleMLData.from_arrays(x, y, d)
dml_irm_obj = dml.DoubleMLIRM(obj_dml_data,
ml_g, ml_m,
n_folds,
score=score,
dml_procedure=dml_procedure)
# tune hyperparameters
_ = dml_irm_obj.tune(par_grid, tune_on_folds=tune_on_folds, n_folds_tune=n_folds_tune)
dml_irm_obj.fit()
np.random.seed(3141)
n_obs = len(y)
all_smpls = draw_smpls(n_obs, n_folds)
smpls = all_smpls[0]
if tune_on_folds:
g0_params, g1_params, m_params = tune_nuisance_irm(y, x, d,
clone(learner_g), clone(learner_m), smpls, score,
n_folds_tune,
par_grid['ml_g'], par_grid['ml_m'])
else:
xx = [(np.arange(len(y)), np.array([]))]
g0_params, g1_params, m_params = tune_nuisance_irm(y, x, d,
clone(learner_g), clone(learner_m), xx, score,
n_folds_tune,
par_grid['ml_g'], par_grid['ml_m'])
g0_params = g0_params * n_folds
m_params = m_params * n_folds
if score == 'ATE':
g1_params = g1_params * n_folds
else:
assert score == 'ATTE'
g1_params = None
res_manual = fit_irm(y, x, d, clone(learner_g), clone(learner_m),
all_smpls, dml_procedure, score,
g0_params=g0_params, g1_params=g1_params, m_params=m_params)
res_dict = {'coef': dml_irm_obj.coef,
'coef_manual': res_manual['theta'],
'se': dml_irm_obj.se,
'se_manual': res_manual['se'],
'boot_methods': boot_methods}
for bootstrap in boot_methods:
np.random.seed(3141)
boot_theta, boot_t_stat = boot_irm(y, d, res_manual['thetas'], res_manual['ses'],
res_manual['all_g_hat0'], res_manual['all_g_hat1'],
res_manual['all_m_hat'], res_manual['all_p_hat'],
all_smpls, score, bootstrap, n_rep_boot)
np.random.seed(3141)
dml_irm_obj.bootstrap(method=bootstrap, n_rep_boot=n_rep_boot)
res_dict['boot_coef' + bootstrap] = dml_irm_obj.boot_coef
res_dict['boot_t_stat' + bootstrap] = dml_irm_obj.boot_t_stat
res_dict['boot_coef' + bootstrap + '_manual'] = boot_theta
res_dict['boot_t_stat' + bootstrap + '_manual'] = boot_t_stat
return res_dict
@pytest.mark.ci
def test_dml_irm_coef(dml_irm_fixture):
assert math.isclose(dml_irm_fixture['coef'],
dml_irm_fixture['coef_manual'],
rel_tol=1e-9, abs_tol=1e-4)
@pytest.mark.ci
def test_dml_irm_se(dml_irm_fixture):
assert math.isclose(dml_irm_fixture['se'],
dml_irm_fixture['se_manual'],
rel_tol=1e-9, abs_tol=1e-4)
@pytest.mark.ci
def test_dml_irm_boot(dml_irm_fixture):
for bootstrap in dml_irm_fixture['boot_methods']:
assert np.allclose(dml_irm_fixture['boot_coef' + bootstrap],
dml_irm_fixture['boot_coef' + bootstrap + '_manual'],
rtol=1e-9, atol=1e-4)
assert np.allclose(dml_irm_fixture['boot_t_stat' + bootstrap],
dml_irm_fixture['boot_t_stat' + bootstrap + '_manual'],
rtol=1e-9, atol=1e-4)
| [
"doubleml.DoubleMLIRM",
"numpy.allclose",
"math.isclose",
"sklearn.ensemble.RandomForestRegressor",
"sklearn.base.clone",
"sklearn.linear_model.LogisticRegression",
"numpy.array",
"doubleml.DoubleMLData.from_arrays",
"numpy.random.seed",
"pytest.fixture",
"numpy.logspace"
] | [((571, 625), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': "['ATE', 'ATTE']"}), "(scope='module', params=['ATE', 'ATTE'])\n", (585, 625), False, 'import pytest\n'), ((690, 737), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': "['dml2']"}), "(scope='module', params=['dml2'])\n", (704, 737), False, 'import pytest\n'), ((810, 862), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': '[True, False]'}), "(scope='module', params=[True, False])\n", (824, 862), False, 'import pytest\n'), ((1202, 1232), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1216, 1232), False, 'import pytest\n'), ((1630, 1646), 'sklearn.base.clone', 'clone', (['learner_g'], {}), '(learner_g)\n', (1635, 1646), False, 'from sklearn.base import clone\n'), ((1658, 1674), 'sklearn.base.clone', 'clone', (['learner_m'], {}), '(learner_m)\n', (1663, 1674), False, 'from sklearn.base import clone\n'), ((1680, 1700), 'numpy.random.seed', 'np.random.seed', (['(3141)'], {}), '(3141)\n', (1694, 1700), True, 'import numpy as np\n'), ((1720, 1757), 'doubleml.DoubleMLData.from_arrays', 'dml.DoubleMLData.from_arrays', (['x', 'y', 'd'], {}), '(x, y, d)\n', (1748, 1757), True, 'import doubleml as dml\n'), ((1776, 1872), 'doubleml.DoubleMLIRM', 'dml.DoubleMLIRM', (['obj_dml_data', 'ml_g', 'ml_m', 'n_folds'], {'score': 'score', 'dml_procedure': 'dml_procedure'}), '(obj_dml_data, ml_g, ml_m, n_folds, score=score,\n dml_procedure=dml_procedure)\n', (1791, 1872), True, 'import doubleml as dml\n'), ((2152, 2172), 'numpy.random.seed', 'np.random.seed', (['(3141)'], {}), '(3141)\n', (2166, 2172), True, 'import numpy as np\n'), ((4588, 4692), 'math.isclose', 'math.isclose', (["dml_irm_fixture['coef']", "dml_irm_fixture['coef_manual']"], {'rel_tol': '(1e-09)', 'abs_tol': '(0.0001)'}), "(dml_irm_fixture['coef'], dml_irm_fixture['coef_manual'],\n rel_tol=1e-09, abs_tol=0.0001)\n", (4600, 4692), False, 'import math\n'), ((4801, 4902), 'math.isclose', 'math.isclose', (["dml_irm_fixture['se']", "dml_irm_fixture['se_manual']"], {'rel_tol': '(1e-09)', 'abs_tol': '(0.0001)'}), "(dml_irm_fixture['se'], dml_irm_fixture['se_manual'], rel_tol=\n 1e-09, abs_tol=0.0001)\n", (4813, 4902), False, 'import math\n'), ((3291, 3307), 'sklearn.base.clone', 'clone', (['learner_g'], {}), '(learner_g)\n', (3296, 3307), False, 'from sklearn.base import clone\n'), ((3309, 3325), 'sklearn.base.clone', 'clone', (['learner_m'], {}), '(learner_m)\n', (3314, 3325), False, 'from sklearn.base import clone\n'), ((3741, 3761), 'numpy.random.seed', 'np.random.seed', (['(3141)'], {}), '(3141)\n', (3755, 3761), True, 'import numpy as np\n'), ((4133, 4153), 'numpy.random.seed', 'np.random.seed', (['(3141)'], {}), '(3141)\n', (4147, 4153), True, 'import numpy as np\n'), ((5070, 5207), 'numpy.allclose', 'np.allclose', (["dml_irm_fixture['boot_coef' + bootstrap]", "dml_irm_fixture['boot_coef' + bootstrap + '_manual']"], {'rtol': '(1e-09)', 'atol': '(0.0001)'}), "(dml_irm_fixture['boot_coef' + bootstrap], dml_irm_fixture[\n 'boot_coef' + bootstrap + '_manual'], rtol=1e-09, atol=0.0001)\n", (5081, 5207), True, 'import numpy as np\n'), ((5269, 5410), 'numpy.allclose', 'np.allclose', (["dml_irm_fixture['boot_t_stat' + bootstrap]", "dml_irm_fixture['boot_t_stat' + bootstrap + '_manual']"], {'rtol': '(1e-09)', 'atol': '(0.0001)'}), "(dml_irm_fixture['boot_t_stat' + bootstrap], dml_irm_fixture[\n 'boot_t_stat' + bootstrap + '_manual'], rtol=1e-09, atol=0.0001)\n", (5280, 5410), True, 'import numpy as np\n'), ((363, 386), 'sklearn.ensemble.RandomForestRegressor', 'RandomForestRegressor', ([], {}), '()\n', (384, 386), False, 'from sklearn.ensemble import RandomForestRegressor\n'), ((496, 516), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (514, 516), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1155, 1177), 'numpy.logspace', 'np.logspace', (['(-4)', '(2)', '(10)'], {}), '(-4, 2, 10)\n', (1166, 1177), True, 'import numpy as np\n'), ((2410, 2426), 'sklearn.base.clone', 'clone', (['learner_g'], {}), '(learner_g)\n', (2415, 2426), False, 'from sklearn.base import clone\n'), ((2428, 2444), 'sklearn.base.clone', 'clone', (['learner_m'], {}), '(learner_m)\n', (2433, 2444), False, 'from sklearn.base import clone\n'), ((2814, 2830), 'sklearn.base.clone', 'clone', (['learner_g'], {}), '(learner_g)\n', (2819, 2830), False, 'from sklearn.base import clone\n'), ((2832, 2848), 'sklearn.base.clone', 'clone', (['learner_m'], {}), '(learner_m)\n', (2837, 2848), False, 'from sklearn.base import clone\n'), ((2672, 2684), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2680, 2684), True, 'import numpy as np\n')] |
import logging
import traceback
import decimal
import json
import numpy
import django
from django.db import models # we're going to geodjango this one - might not need it, but could make some things nicer
from django.db.models import Q
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
User = get_user_model() # define user by this method rather than direct import - safer for the future
from guardian.shortcuts import assign_perm
from django.db.models.signals import post_save
from django.dispatch import receiver
from Waterspout import settings
import pandas
from Dapper import scenarios, get_version as get_dapper_version, worst_case
log = logging.getLogger("waterspout.models")
class SimpleJSONField(models.TextField):
"""
converts dicts to JSON strings on save and converts JSON to dicts
on load
"""
def get_prep_value(self, value):
return json.dumps(value)
def from_db_value(self, value, expression, connection):
return json.loads(value)
class UserProfile(models.Model):
"""
Basically just for user settings
"""
user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
_serializer_fields = ["id", "user", "show_organization_model_runs", "show_organization_model_runs_tooltip",
"dense_tables", "dense_tables_tooltip"]
# basic settings
show_organization_model_runs = models.BooleanField(default=True)
show_organization_model_runs_tooltip = "By default, the application shows all model runs from within your organization" \
" and gives you the option to temporarily show only your model runs." \
" This setting changes that behavior so that, by default, you only see model runs" \
" that you created yourself and then you can temporarily change the listing to" \
" see all model runs in your organization."
dense_tables = models.BooleanField(default=False)
dense_tables_tooltip = "Use less spacing in tables to see more data on screen at the same time"
# set up the signal receivers that get triggered after a user is created so that everyone has a userprofile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
new_profile = UserProfile.objects.create(user=instance)
assign_perm("change_userprofile", instance, new_profile)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
class Organization(models.Model):
"""
Since this application is designed to support multiple models, possibly in the same instance, make most things
be ties to an "organization" of some kind - we'll include users in the organization and arrange permissions
around users within the organization.
We could have made this a subclass of the Group object, but then reverse relationships may not work correctly.
Instead we'll just
"""
name = models.CharField(max_length=255, null=False, blank=False)
# TODO: This shouldn't allow nulls or blanks in the future
group = models.OneToOneField(Group, on_delete=models.DO_NOTHING, null=True, blank=True)
def has_member(self, user):
return self.group in user.groups.all() # True if this group is in that set, otherwise, False
def add_member(self, user):
self.group.user_set.add(user)
self.group.save()
def __str__(self):
return f"Organization: {self.name}"
class ModelArea(models.Model):
"""
This would be something like "The Delta", or "Washington" - mostly, this will be one to one with organizations,
but just in case we want to be able to deploy multiple models for an organization in the future, we'll store it
this way.
"""
organization = models.ForeignKey(Organization, null=True, blank=True, on_delete=models.SET_NULL, related_name="model_areas")
name = models.CharField(max_length=255, unique=True)
data_folder = models.CharField(max_length=255, default="dap") # which folder did the data for this come from during loading? Can
# help us if we want to update some data later
description = models.TextField(null=True, blank=True)
# preferences reverse 1 to 1
map_center_latitude = models.DecimalField(max_digits=4, decimal_places=2)
map_center_longitude = models.DecimalField(max_digits=5, decimal_places=2)
map_default_zoom = models.SmallIntegerField()
# these values define the ranges available when creating a model run in this region
min_water = models.PositiveSmallIntegerField(default=50)
max_water = models.PositiveSmallIntegerField(default=120)
min_rainfall = models.PositiveSmallIntegerField(default=10)
max_rainfall = models.PositiveSmallIntegerField(default=200)
min_land = models.PositiveSmallIntegerField(default=50)
max_land = models.PositiveSmallIntegerField(default=100)
min_price = models.PositiveSmallIntegerField(default=80)
max_price = models.PositiveSmallIntegerField(default=120)
min_yield = models.PositiveSmallIntegerField(default=80)
max_yield = models.PositiveSmallIntegerField(default=120)
min_crop_area = models.PositiveSmallIntegerField(default=0)
max_crop_area = models.PositiveSmallIntegerField(default=200)
main_help_page_content = models.TextField(null=True, blank=True)
feature_package_name = models.CharField(max_length=100, default="DEFAULT")
def __str__(self):
return self.name
@property
def model_defaults(self):
# Just making it a dict so that it comes out of the serializer grouped
return {
"min_water": self.min_water,
"max_water": self.max_water,
"min_rainfall": self.min_rainfall,
"max_rainfall": self.max_rainfall,
"min_land": self.min_land,
"max_land": self.max_land,
"min_price": self.min_price,
"max_price": self.max_price,
"min_yield": self.min_yield,
"max_yield": self.max_yield,
"min_crop_area": self.min_crop_area,
"max_crop_area": self.max_crop_area,
}
# elasticities code commented out because we don't run calibration
# ourselves right now
#@property
#def elasticities_as_dict(self):
# return {item.crop.crop_code: float(item.value) for item in self.elasticities}
@property
def supports_rainfall(self):
return self.region_set.filter(supports_rainfall=True).exists()
@property
def supports_irrigation(self):
return self.region_set.filter(supports_irrigation=True).exists()
@property
def background_code(self):
# this is a bit of a hack, but we're using the folder
# names as a class to set the backgrounds temporarily
return self.data_folder
class ModelAreaPreferences(models.Model):
"""
This model is so that we can group preferences and features for model areas
and keep them organized
"""
# should all users of this model area be able to see the model runs of all other users?
shared_model_runs = models.BooleanField(default=True)
# prevent users from reducing price/yield below the value that would make profits negative
# basically forces stormchaser to create cards for crops when All Crops
# goes to negative profits for the crop
enforce_price_yield_constraints = models.BooleanField(default=True)
# if True, and the user makes an adjustment that would create
# negative profits, it forces the slider they weren't using upward as they move the other
# downward. If False, it's purely advisory
lock_price_yield_ratio = models.BooleanField(default=False)
# Should visualizations and downloads include net revenues for this model area? By default we
# don't want to - in most cases, it won't be something we want people to see - but we'll want
# it to be able to be accessed for debugging purposes
include_net_revenue = models.BooleanField(default=False)
# should region-linking of crops be enabled?
region_linked_crops = models.BooleanField(default=False)
# whether or not to show the ability to view model run creation code
allow_model_run_creation_code_view = models.BooleanField(default=False)
# flags to indicate an entire set of features in data visualization
# where they can choose additional model runs for comparison,
# can normalize to a base run, and can see worst case outcomes
allow_viz_multiple_comparisons = models.BooleanField(default=False)
allow_viz_normalization = models.BooleanField(default=False)
allow_viz_region_filter = models.BooleanField(default=False)
allow_viz_worst_case = models.BooleanField(default=False)
allow_static_regions = models.BooleanField(default=False)
allow_removed_regions = models.BooleanField(default=False)
allow_linear_scaled_regions = models.BooleanField(default=False)
use_default_region_behaviors = models.BooleanField(default=True)
model_area = models.OneToOneField(ModelArea,
on_delete=models.CASCADE,
related_name="preferences"
)
# set up the signal receivers that get triggered after a model area is created so that everyone has a userprofile
@receiver(post_save, sender=ModelArea)
def create_model_area_preferences(sender, instance, created, **kwargs):
if created:
ModelAreaPreferences.objects.create(model_area=instance)
@receiver(post_save, sender=ModelArea)
def save_model_area(sender, instance, **kwargs):
instance.preferences.save()
#class Elasticity(models.Model):
# elasticities code commented out because we don't run calibration
# ourselves right now
# """
# We store elasticities for Dapper as individual records here,
# but we'll access them on the ModelArea object to send to Dapper
# """
# model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE, related_name="elasticities")
# crop = models.ForeignKey("Crop", on_delete=models.CASCADE, related_name="elasticities")
# value = models.DecimalField(max_digits=6, decimal_places=4)
class RegionGroup(models.Model):
name = models.CharField(max_length=255, null=False, blank=False)
internal_id = models.CharField(max_length=100, null=False, blank=False) # typically we have some kind of known ID to feed to a model that means something to people
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE)
geometry = models.JSONField(null=True, blank=True) # this will just store GeoJSON and then we'll combine into collections manually
class Region(models.Model):
MODELED = 0
REMOVED = 1
FIXED = 2
LINEAR_SCALED = 3
REGION_DEFAULT_MODELING_CHOICES = (
(MODELED, "Modeled"),
(REMOVED, "Removed"),
(FIXED, "Fixed"),
(LINEAR_SCALED, "Linear Scaled"),
)
class Meta:
unique_together = ['name', 'model_area']
indexes = [
models.Index(fields=("internal_id",)),
models.Index(fields=("model_area_id", "supports_rainfall",)), # we'll use these to set an attribute whenever someone loads a model area
models.Index(fields=("model_area_id", "supports_irrigation",))
]
name = models.CharField(max_length=255, null=False, blank=False)
internal_id = models.CharField(max_length=100, null=False, blank=False) # typically we have some kind of known ID to feed to a model that means something to people
external_id = models.CharField(max_length=100, null=True, blank=True) # a common external identifier of some kind
description = models.TextField(null=True, blank=True)
# .extra_attributes reverse lookup
# .modifications reverse lookup
default_behavior = models.SmallIntegerField(default=MODELED, choices=REGION_DEFAULT_MODELING_CHOICES)
geometry = models.JSONField(null=True, blank=True) # this will just store GeoJSON and then we'll combine into collections manually
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE)
group = models.ForeignKey(RegionGroup, null=True, blank=True, on_delete=models.CASCADE) # there could be a reason to make it a many to many instead, but
# I can't think of a use case right now, and it'd require some PITA
# logic to tease apart specifications for regions in overlapping groups
supports_rainfall = models.BooleanField(default=False) # whether or not this region has any rainfall/dryland components
supports_irrigation = models.BooleanField(default=True) # whether or not this region has any irrigated components
serializer_fields = ("id", "name", "internal_id", "description", "geometry", "model_area", "group",
"supports_rainfall", "supports_irrigation", "multipliers", "default_behavior",
"MODELED", "FIXED", "REMOVED", "LINEAR_SCALED")
def __str__(self):
return "Area {}: Region {}".format(self.model_area.name, self.name)
class RegionMultipliers(models.Model):
region = models.OneToOneField(Region, on_delete=models.CASCADE, related_name="multipliers")
total_revenue = models.DecimalField(max_digits=10, decimal_places=8, null=True, blank=True)
direct_value_add = models.DecimalField(max_digits=10, decimal_places=8, null=True, blank=True)
total_value_add = models.DecimalField(max_digits=10, decimal_places=8, null=True, blank=True)
direct_jobs = models.DecimalField(max_digits=10, decimal_places=8, null=True, blank=True)
total_jobs = models.DecimalField(max_digits=10, decimal_places=8, null=True, blank=True)
class RegionExtra(models.Model):
"""
Extra custom attributes that can be set per region instance, available by filtering
`region.extra_attributes.filter(name == "{attribute_name}")`, for example.
"""
region = models.ForeignKey(Region, on_delete=models.CASCADE, related_name="extra_attributes")
name = models.CharField(max_length=255, null=False, blank=False)
value = models.TextField(null=True, blank=True)
data_type = models.CharField(max_length=5) # indicates the Python data type to cast it to if it's not a string
class Crop(models.Model):
"""
A single unit for individual crops - note that we need to pull crops by organization - the same crop could
exist for multiple organizations. We don't want to load them in for all organizations because then we have to
worry about if it means the same exact thing across organizations, and what do changes mean to each group, etc,
etc. Let's keep it a known, manageable level of complex and assign crops to organizations even if it means
duplicating crops between organizations.
"""
class Meta:
unique_together = ['crop_code', 'model_area']
indexes = [
models.Index(fields=("name",))
]
name = models.CharField(max_length=255, null=False, blank=False) # human readable crop name
crop_code = models.CharField(max_length=30, null=False, blank=False) # code used in the models (like ALFAL for Alfalfa)
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE) # clear any crops for an org when deleted
def __str__(self):
return self.name
class CropGroup(models.Model):
"""
A unit to group individual crops together - note that we need to crop groups are also by organization and
the same crop group exist for multiple organizations
"""
name = models.CharField(max_length=255, null=False, blank=False)
crops = models.ManyToManyField(Crop) # Each crop can be in many groups
class RecordSet(models.Model):
class Meta:
abstract = True
"""
For storing the results of calibration parameters that come out of phase 1 of the model - we'll load a few sets
of calibrated parameters initially, but then provide a black box version of the calibration parameters. We can
then have behavior that tries a lookup for a calibration set, and if it doesn't exist, runs the calibration.
"""
record_model_name = "ModelItem"
years = models.TextField() # yes, text. We'll concatenate text as a year lookup
# prices = model
def as_data_frame(self, exclude_regions=None):
"""
Returns the data frame that needs to be run through the model itself
:param exclude_regions: list of region internal ids - regions in this list will not have their data
included in the output data frame
:return:
"""
# .values() makes a queryset into an iterable of dicts. Coerce that to a list of dicts
# and pass it to the pandas constructor.
# Django has a handy method to transform a queryset into a list of dicts,
# but we can't really use it because we need to retrieve foreign keys, and it
# can only retrieve either bare attributes or the ones we specify, so we'd
# need to either hardcode everything or run it twice and merge it. Easier
# to write our own, unfortunately. It's quite a bit slower than the Django though
# so maybe we can speed it up somehow. Maybe doing it as a raw SQL query and then
# dropping any excess fields would be better. Going to leave that for another
# day right now.
foreign_keys = ["region", "crop", "rainfall_set"]
record_model = globals()[self.record_model_name]
fields = [f.name for f in record_model._meta.get_fields()] # get all the fields for calibrated parameters
basic_fields = list(set(fields) - set(foreign_keys)) # remove the foreign keys - we'll process those separately
# reverse_name will exist for subclasses
data = getattr(self, self.reverse_name).all() # get all the records for this set
output = []
for record in data:
# if we were told to skip this region, don't add it - could also do this in pandas after conversion
if exclude_regions and record.region.internal_id in exclude_regions:
continue
output_dict = {}
for field in basic_fields: # apply the basic fields directly into a dictionary and coerce to floats
field_value = getattr(record, field)
output_dict[field] = float(field_value) if type(field_value) is decimal.Decimal else field_value
output_dict["i"] = record.crop.crop_code # but then grab the specific attributes of the foreign keys we wawnt
output_dict["g"] = record.region.internal_id
output.append(output_dict) # put the dict into the list so we can make a DF of it
return pandas.DataFrame(output) # construct a data frame and send it back
def to_csv(self, *args, **kwargs):
"""
Saves the set to a CSV file - all args are passed through to Pandas.to_csv, so it's
possible to have it return a CSV as a string by just calling to_csv()
:param args: waterspout_sort_columns is not compatible with waterspout_limited
:param kwargs:
:return:
"""
df = self.as_data_frame().sort_values(axis=0, by=["year", "g", "i"])
df = df.rename(columns={"g": "region", "i": "crop"})
if kwargs.pop("waterspout_sort_columns", False) is True:
# match the column output to how Spencer has it so we can compare
column_order = ("region", "crop", "year", "omegaland", "omegasupply", "omegalabor",
"omegaestablish", "omegacash", "omeganoncash", "omegatotal",
"xwater", "p", "y", "xland", "omegawater", "sigma", "theta",
"pimarginal", "rho", "betaland", "betawater", "betasupply",
"betalabor", "tau", "gamma", "delta", "xlandsc", "xwatersc",
"xdiffland", "xdifftotalland", "xdiffwater", "resource_flag")
df = df.reindex(columns=column_order)
if kwargs.pop("waterspout_limited", False) is True:
columns = settings.LIMITED_RESULTS_FIELDS
df = df[columns]
if "index" not in kwargs: # if the caller doesn't specify an option for pandas' index, set it to False explicitly so it doesn't export the index
kwargs["index"] = False
return df.to_csv(*args, **kwargs)
class InputDataSet(RecordSet):
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE, related_name="input_data")
reverse_name = "input_data_set"
class CalibrationSet(RecordSet):
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE, related_name="calibration_data")
record_model_name = "CalibratedParameter"
reverse_name = "calibration_set"
class RainfallSet(RecordSet):
model_area = models.ForeignKey(ModelArea, on_delete=models.CASCADE, related_name="rainfall_data")
reverse_name = "rainfall_set"
record_model_name = "RainfallParameter"
class ResultSet(RecordSet):
reverse_name = "result_set"
record_model_name = "Result"
model_run = models.ForeignKey("ModelRun", null=True, blank=True,
on_delete=models.CASCADE, related_name="results")
date_run = models.DateTimeField(default=django.utils.timezone.now, null=True, blank=True)
# store the dapper version that the model ran with - that way we can detect if an updated version might provide different results
dapper_version = models.CharField(max_length=20)
# in_calibration indicates whether or not the results have any negative profits
# or have otherwise fallen outside of calibrated values.
in_calibration = models.BooleanField(default=True)
# not using in_calibration_text for now. We'll have the web app figure out
# which records are negative profits and show a table if in_calibration is false
#in_calibration_text = models.TextField(null=True, blank=True)
infeasibilities_text = models.TextField(null=True, blank=True)
# infeasibilities reverse relation
def __str__(self):
return f"Results for Model Run {self.model_run.name} from Dapper {self.dapper_version} at {self.date_run}"
class ModelItem(models.Model):
"""
Fields that are allowed to be null are ones that aren't part of calibration, but instead may be set for final
results
"""
class Meta:
abstract = True
indexes = [
models.Index(fields=("year",))
]
crop = models.ForeignKey(Crop, on_delete=models.CASCADE)
region = models.ForeignKey(Region, on_delete=models.CASCADE)
year = models.IntegerField(null=True, blank=True) # inputs will have this, but calibrated items and results may not
p = models.DecimalField(max_digits=18, decimal_places=10)
y = models.DecimalField(max_digits=13, decimal_places=5)
xland = models.DecimalField(max_digits=18, decimal_places=10)
class InputModelItem(ModelItem):
class Meta:
abstract = True
omegaland = models.DecimalField(max_digits=10, decimal_places=1)
omegasupply = models.DecimalField(max_digits=10, decimal_places=1)
omegalabor = models.DecimalField(max_digits=10, decimal_places=1)
omegaestablish = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
omegacash = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
omeganoncash = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
omegatotal = models.DecimalField(max_digits=10, decimal_places=1, null=True, blank=True)
xwater = models.DecimalField(max_digits=18, decimal_places=10)
class InputDataItem(InputModelItem):
class Meta:
unique_together = ['crop', 'region', 'year']
dataset = models.ForeignKey(InputDataSet, on_delete=models.CASCADE, related_name="input_data_set")
serializer_fields = ["crop", "region", "year", "omegaland",
"omegasupply", "omegalabor", "omegaestablish", "omegacash",
"omeganoncash", "omegatotal", "p", "y", "xland", "xwater"]
class CalibratedParameter(InputModelItem):
"""
Note that it's of class InputDataItem, which is of class ModelItem - ModelItems define the various input
parameters and results that we use for calibration inputs, calibrated
parameters, and model results
"""
class Meta:
unique_together = ['crop', 'region', 'year']
omegawater = models.DecimalField(max_digits=10, decimal_places=2)
pc = models.DecimalField(max_digits=10, decimal_places=3)
sigma = models.DecimalField(max_digits=5, decimal_places=4)
theta = models.DecimalField(max_digits=5, decimal_places=4)
pimarginal = models.DecimalField(max_digits=18, decimal_places=10)
#alphaland = models.DecimalField(max_digits=11, decimal_places=10, null=True, blank=True)
# alphawater = models.DecimalField(max_digits=11, decimal_places=10, null=True, blank=True)
# alphasupply = models.DecimalField(max_digits=11, decimal_places=10, null=True, blank=True)
# alphalabor = models.DecimalField(max_digits=11, decimal_places=10, null=True, blank=True)
rho = models.DecimalField(max_digits=15, decimal_places=10)
# lambdaland = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
#lambdacrop = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
betaland = models.DecimalField(max_digits=18, decimal_places=10)
betawater = models.DecimalField(max_digits=18, decimal_places=10)
betasupply = models.DecimalField(max_digits=18, decimal_places=10)
betalabor = models.DecimalField(max_digits=18, decimal_places=10)
tau = models.DecimalField(max_digits=18, decimal_places=10)
gamma = models.DecimalField(max_digits=18, decimal_places=10)
delta = models.DecimalField(max_digits=18, decimal_places=10)
#xlandcalib = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
#xwatercalib = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
#difflandpct = models.DecimalField(max_digits=12, decimal_places=10, null=True, blank=True)
#diffwaterpct = models.DecimalField(max_digits=12, decimal_places=10, null=True, blank=True)
# this item helps us check on the front end whether or not modifications will send profits negative.
# we'll store it here since it comes out of the calibration and will be per region/crop combination
price_yield_correction_factor = models.DecimalField(max_digits=6, decimal_places=3, default=1)
calibration_set = models.ForeignKey(CalibrationSet, on_delete=models.CASCADE, related_name="calibration_set")
serializer_fields = ["crop", "region", "price_yield_correction_factor"]
#["crop", "region", "year", "omegaland", "omegawater",
# "omegasupply", "omegalabor", "omegaestablish", "omegacash",
# "omeganoncash", "omegatotal", "p", "y", "price_yeild_correction_factor"]
class RainfallParameter(ModelItem):
class Meta:
unique_together = ['crop', 'region', 'year']
rainfall_set = models.ForeignKey(RainfallSet, on_delete=models.CASCADE, related_name="rainfall_set")
coef_intercept = models.DecimalField(max_digits=10, decimal_places=5)
twin = models.DecimalField(max_digits=10, decimal_places=5)
tspr = models.DecimalField(max_digits=10, decimal_places=5)
tsum = models.DecimalField(max_digits=10, decimal_places=5)
coef_tsum = models.DecimalField(max_digits=10, decimal_places=5)
coef_tspr = models.DecimalField(max_digits=10, decimal_places=5)
coef_twin = models.DecimalField(max_digits=10, decimal_places=5)
ptspr = models.DecimalField(max_digits=10, decimal_places=5)
ptwin = models.DecimalField(max_digits=10, decimal_places=5)
ptsum = models.DecimalField(max_digits=10, decimal_places=5)
coef_ptspr = models.DecimalField(max_digits=10, decimal_places=5)
coef_ptwin = models.DecimalField(max_digits=10, decimal_places=5)
coef_ptsum = models.DecimalField(max_digits=10, decimal_places=5)
coef_crop = models.DecimalField(max_digits=10, decimal_places=5)
class Result(ModelItem):
"""
Holds the results for a single region/crop
"""
omegawater = models.DecimalField(max_digits=10, decimal_places=2)
resource_flag = models.CharField(max_length=5, null=True, blank=True)
# we may be able to drop these fields later, but they help us while we're comparing to the original DAP and our validation
xlandsc = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
xwatersc = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
xdiffland = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
xdifftotalland = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
xdiffwater = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
result_set = models.ForeignKey(ResultSet, on_delete=models.CASCADE, related_name="result_set")
net_revenue = models.DecimalField(max_digits=18, decimal_places=3, null=True, blank=True)
gross_revenue = models.DecimalField(max_digits=18, decimal_places=3, null=True, blank=True)
water_per_acre = models.DecimalField(max_digits=18, decimal_places=5, null=True, blank=True)
class RainfallResult(models.Model):
serializer_fields = ["region", "crop", "calc_yield", "gross_revenue", "xlandsc", "xwatersc"]
result_set = models.ForeignKey(ResultSet, on_delete=models.CASCADE, related_name="rainfall_result_set")
region = models.ForeignKey(Region, on_delete=models.CASCADE, related_name="rainfall_results")
crop = models.ForeignKey(Crop, on_delete=models.CASCADE, related_name="rainfall_results")
# yield is the only real result from the rainfall statistical model, so that's what we're storing, but we'll also
# want to store some of the same main results as the Result items so we can merge them
calc_yield = models.DecimalField(max_digits=18, decimal_places=3, null=True, blank=True)
gross_revenue = models.DecimalField(max_digits=18, decimal_places=3, null=True, blank=True)
# these aren't yet really outputs, but we need to include them for the viz to work correctly
xlandsc = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
xwatersc = models.DecimalField(max_digits=18, decimal_places=10, null=True, blank=True)
class ModelRun(models.Model):
"""
The central object for configuring an individual run of the model - is related to modification objects from the
modification side.
"""
class Meta:
indexes = [
models.Index(fields=("ready", "running", "complete")),
models.Index(fields=("date_submitted",))
]
name = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
ready = models.BooleanField(default=False, null=False) # marked after the web interface adds all modifications
running = models.BooleanField(default=False, null=False) # marked while in processing
complete = models.BooleanField(default=False, null=False) # tracks if the model has actually been run for this result yet
status_message = models.CharField(max_length=2048, default="", null=True, blank=True) # for status info or error messages
result_values = models.TextField(default="", null=True, blank=True)
log_data = models.TextField(null=True, blank=True) # we'll store log outputs from the model run here.
date_submitted = models.DateTimeField(default=django.utils.timezone.now, null=True, blank=True)
date_completed = models.DateTimeField(null=True, blank=True)
# which model run is the base, unmodified version? Useful for data viz
base_model_run = models.ForeignKey("ModelRun", null=True, blank=True, on_delete=models.DO_NOTHING)
is_base = models.BooleanField(default=False) # is this a base model run (True), or a normal model run (False)
# model_area relation is through calibration_set
calibration_set = models.ForeignKey(CalibrationSet, on_delete=models.CASCADE, related_name="model_runs")
calibrated_parameters_text = models.TextField(null=True, blank=True) # we'll put a snapshot of the calibration parameters in here, probably
# as a CSV. This way, if people eidt the calibration data for future runs,
# we still know what inputs ran this version of the model.
rainfall_set = models.ForeignKey(RainfallSet, on_delete=models.CASCADE, related_name="model_runs", null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="model_runs")
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="model_runs")
# region_modifications - back-reference from related content
# crop_modifications - back-reference from related content
serializer_fields = ['id', 'name', 'description', 'ready', 'running', 'complete', 'status_message',
'date_submitted', 'date_completed', "calibration_set", "rainfall_set",
"user_id", "organization", "base_model_run_id", "is_base",
"land_modifications_average", "water_modifications_average",
"price_modifications_average", "yield_modifications_average"]
def __str__(self):
return f"Model Run: {self.name}"
def as_dict(self):
return {field: getattr(self, field) for field in self.serializer_fields}
def as_json(self):
# using the Django serializer class handles datetimes, etc properly
return json.dumps(self.as_dict(), cls=django.core.serializers.json.DjangoJSONEncoder)
def _get_modification_average(self, queryset_name, property_name):
mods = list(getattr(self, queryset_name).all())
num_items = len(mods)
if num_items == 0:
return 0
return float(sum([getattr(mod, property_name) for mod in mods]))/num_items
@property
def land_modifications_average(self):
return self._get_modification_average("region_modifications", "land_proportion")
@property
def water_modifications_average(self):
return self._get_modification_average("region_modifications", "water_proportion")
@property
def price_modifications_average(self):
return self._get_modification_average("crop_modifications", "price_proportion")
@property
def yield_modifications_average(self):
return self._get_modification_average("crop_modifications", "yield_proportion")
@property
def scenario_df(self):
df = self.get_df(self.calibration_set)
# save the calibration data with any modifications as a text string to the DB - will exclude scenario
# level constraints though!
# saving the text version hasn't helped us and slows things down. Stop doing that for now
#self.calibrated_parameters_text = df.to_csv() # if we don't provide a path to to_csv, it returns a string
#self.save()
return df
@property
def rainfall_df(self):
if self.rainfall_set:
return self.get_df(self.rainfall_set)
else:
return None
def get_df(self, base_model):
"""
Given the currently attached modifications, etc, returns a complete calibration DF
:return:
"""
# we'll not send static or removed regions through the model, so drop them here
# for removed regions, this is all we need to do - for static regions, we'll
# pull their base case results later when we process results
exclude_ids = self.get_regions_for_behaviors([Region.FIXED, Region.REMOVED])
# pull initial calibration dataset as it is
df = base_model.as_data_frame(exclude_regions=exclude_ids)
# do any overrides or changes from the modifications
return df
def get_regions_for_behaviors(self, behaviors):
"""
Given one or more behaviors in an interable, returns the region IDs that the behaviors apply to as a list.
This isn't straightforward, because we need to see if the region modification applies a behavior, then
also check all the regions that *didn't* have a modification in the current model run (which will have
the behavior specified there) for their default behaviors
:param behavior:
:return:
"""
# compose the query portions for each section here in one loop
region_filter_includes = Q()
default_behavior_includes = Q()
for behavior in behaviors:
region_filter_includes = region_filter_includes | Q(modeled_type=behavior)
default_behavior_includes = default_behavior_includes | Q(default_behavior=behavior)
# get the regions to explicitly include from modifications
modifications = self.region_modifications.filter(region_filter_includes)
if modifications:
ids = [mod.region.internal_id for mod in modifications]
else:
ids = []
if self.calibration_set.model_area.preferences.use_default_region_behaviors:
# figure out which regions didn't have modifications in the current model run - we'll pull the defaults for these
regions_to_use_defaults_from = self.calibration_set.model_area.region_set.filter(default_behavior_includes)\
.difference(Region.objects.filter(modifications__in=self.region_modifications.all()))
if regions_to_use_defaults_from:
ids.extend([region.internal_id for region in regions_to_use_defaults_from])
return ids
def attach_modifications(self, scenario):
land_modifications = {}
water_modifications = {}
rainfall_modifications = {}
region_modifications = self.region_modifications.filter(region__isnull=False)
for modification in region_modifications: # get all the nondefault modifications
land_modifications[modification.region.internal_id] = float(modification.land_proportion)
if modification.region.supports_irrigation:
water_modifications[modification.region.internal_id] = float(modification.water_proportion)
if modification.region.supports_rainfall:
rainfall_modifications[modification.region.internal_id] = float(modification.rainfall_proportion)
default_region_modification = self.region_modifications.get(region__isnull=True)
scenario.perform_adjustment("land", land_modifications, default=float(default_region_modification.land_proportion))
# attach modifications for irrigation and rainfall depending on what the model area supports
if self.calibration_set.model_area.supports_irrigation:
scenario.perform_adjustment("water", water_modifications, default=float(default_region_modification.water_proportion))
if self.calibration_set.model_area.supports_rainfall:
scenario.perform_adjustment("rainfall", rainfall_modifications, default=float(default_region_modification.rainfall_proportion))
region_linked_key = "region_linked"
# now attach the crop modifications - start by loading the data into a dict
price_modifications = {region_linked_key: []}
yield_modifications = {region_linked_key: []}
crop_modifications = self.crop_modifications.filter(crop__isnull=False)
for modification in crop_modifications: # get all the nondefault modifications
crop_code = modification.crop.crop_code
if modification.region is None: # if it's not region-linked
price_modifications[crop_code] = float(modification.price_proportion)
yield_modifications[crop_code] = float(modification.yield_proportion)
region_id = None
else: # if it is region-linked
region_id = modification.region.internal_id
# create dictionaries for both price and yield constraints that include
# the region ID, the crop code, and the value
price_modifications["region_linked"].append({
"region": region_id,
"crop": crop_code,
"value": float(modification.price_proportion),
})
yield_modifications["region_linked"].append({
"region": region_id,
"crop": crop_code,
"value": float(modification.yield_proportion),
})
max_crop_area_constraint = modification.max_land_area_proportion
if max_crop_area_constraint and modification.min_land_area_proportion and not max_crop_area_constraint > modification.min_land_area_proportion:
# if the max and the min are both defined and the max is less than the min, skip adding the max -
# this is because stormchaser uses a value of -1 as its max value to indicate no upper limit
max_crop_area_constraint = None
# we can always add it, and it's OK if they're both None - that'll get checked later
scenario.add_crop_area_constraint(crop_code=modification.crop.crop_code,
min_proportion=modification.min_land_area_proportion,
max_proportion=max_crop_area_constraint,
region=region_id)
default_crop_modification = self.crop_modifications.get(crop__isnull=True)
# then pass those dicts to the scenario code regardless if there are items (so defaults get set)
scenario.perform_adjustment("price", price_modifications, default=float(default_crop_modification.price_proportion))
scenario.perform_adjustment("yield", yield_modifications, default=float(default_crop_modification.yield_proportion))
def run(self, csv_output=None, worst_case_csv_output=None):
# initially, we won't support calibrating the data here - we'll
# just use an initial calibration set and then make our modifications
# before running the scenarios
#calib = calibration.ModelCalibration(run.calbration_df)
#calib.calibrate()
self.running = True
self.save() # mark it as running and save it so the API updates the status
try:
scenario_runner = scenarios.Scenario(calibration_df=self.scenario_df, rainfall_df=self.rainfall_df)
self.attach_modifications(scenario=scenario_runner)
results = scenario_runner.run()
if csv_output is not None:
results.to_csv(csv_output)
# add the worst case scenario values to the same data frame
results = self.add_worst_case_and_linear_scaled_values(results)
if worst_case_csv_output is not None:
results.to_csv(worst_case_csv_output)
# before loading results, make sure we weren't deleted in the app between starting the run and now
if not ModelRun.objects.filter(id=self.id).exists():
return
# now we need to load the resulting df back into the DB
result_set = self.load_records(results_df=results, rainfall_df=scenario_runner.rainfall_df)
self.load_infeasibilities(scenario_runner, result_set)
self.complete = True
log.info("Model run complete")
finally: # make sure to mark it as not running regardless of its status or if it crashes
self.running = False
self.save()
def add_worst_case_and_linear_scaled_values(self, results):
results = worst_case.default_worst_case_scaling_function(results)
linear_scaled_regions = self.get_regions_for_behaviors([Region.LINEAR_SCALED,])
# just straight up overwrite the values for revenue, land, and water for linear scaled regions using the worst case values (linear scaled)
for region in linear_scaled_regions:
results.loc[(results.g == region), "gross_revenue"] = results.loc[(results.g == region), "worst_case_gross_revenue"]
results.loc[(results.g == region), "xlandsc"] = results.loc[(results.g == region), "worst_case_land"]
results.loc[(results.g == region), "xwatersc"] = results.loc[(results.g == region), "worst_case_water"]
results.loc[(results.g == region), "net_revenue"] = 0 # null out the net revenue field since it's invalid now.
return results
def load_records(self, results_df, rainfall_df=None):
"""
Given a set of model results, loads the results to the database
:param results_df:
:param model_run:
:return:
"""
log.info(f"Loading results for model run {self.id}")
result_set = ResultSet(model_run=self, dapper_version=get_dapper_version())
result_set.save()
# load the PMP results first
self._load_df(results_df=results_df, result_set=result_set, record_model=Result)
# now load the rainfall data if it applies
if rainfall_df is not None:
self._load_df(results_df=rainfall_df, result_set=result_set, record_model=RainfallResult)
return result_set
def _load_df(self, results_df, result_set, record_model=Result):
try:
for record in results_df.itertuples():
# get the first tuple's fields, then exit the loop
# this should be faster than retrieving it every time in the next loop, but we need to do it once
fields = list(set(record._fields) - set(["id", "g", "i", "calibration_set"]))
break
for record in results_df.itertuples(): # returns named tuples
result = record_model(result_set=result_set)
result.crop = Crop.objects.get(crop_code=record.i, model_area=self.calibration_set.model_area)
result.region = Region.objects.get(internal_id=record.g, model_area=self.calibration_set.model_area)
for column in fields: # _fields isn't private - it's just preventing conflicts - see namedtuple docs
value = getattr(record, column)
if value is not None and type(value) is not str and numpy.isnan(value): # if we got NaN (such as with an infeasibility) - filter out None values because they make numpy.isnan fail
value = None # then we need to skip it or it'll bork the whole table (seriously)
setattr(result, column, value)
if not result.net_revenue or result.net_revenue < 0: # if any record has negative net revenues, we're out of bounds on calibration - mark it
result_set.in_calibration = False
result.save()
if result_set.in_calibration is False: # if we changed the in_calibration value, save the result set - we check this here so we only trigger the save once
result_set.save()
return result_set
except:
result_set.delete() # clean up if we fail while loading data
raise
def load_infeasibilities(self, scenario, result_set):
log.debug("Assessing infeasibilities")
for infeasibility in scenario.infeasibilities:
Infeasibility.objects.create(result_set=result_set,
region=Region.objects.get(internal_id=infeasibility.region, model_area=self.calibration_set.model_area),
year=infeasibility.timeframe,
description=infeasibility.description
)
total_infeasibilities = len(scenario.infeasibilities)
crops = {}
# now let's see if there are any crops that are common to the infeasibilities
#if total_infeasibilities > 2: # if we have more than a handful, we'll assess which crops are common
for infeasibility in scenario.infeasibilities:
infeasible_region_results = Result.objects.filter(result_set=result_set,
region__internal_id=infeasibility.region,
year=infeasibility.timeframe)
for result in infeasible_region_results:
crop = result.crop.crop_code
if crop in crops:
crops[crop] += 1
else:
crops[crop] = 1
# ideally we'd want to key this by name so that we can show the name here
if len(crops.keys()) > 0:
sorted_by_appearance = {k:v for k,v in sorted(crops.items(), key=lambda item: item[1], reverse=True)}
infeasibility_items = ["{} ({})".format(crop, value) for crop, value in sorted_by_appearance.items()]
self.infeasibilities_text = ", ".join(infeasibility_items)
class Infeasibility(models.Model):
result_set = models.ForeignKey(ResultSet, on_delete=models.CASCADE, related_name="infeasibilities")
year = models.SmallIntegerField()
region = models.ForeignKey(Region, null=True, on_delete=models.SET_NULL, related_name="infeasibilities")
description = models.TextField()
class RegionModification(models.Model):
"""
A modification on a region to use in a model run. We'll need to have the model run build a new pandas data frame
from these based on the code inputs and the model adjustments
"""
class Meta:
unique_together = ['model_run', 'region']
# we have two nullable foreign keys here. If both are new, then the rule applies to the whole model area as the default.
# if only one is active, then it applies to either the region, or the group (and then we need something that applies
# it to the individual regions). It's possible that the group->individual application will occur in the JS because
# we'll want to display it all in a map, but we might want to do it here so that API calls can use the groups too
region = models.ForeignKey(Region,
on_delete=models.CASCADE,
related_name="modifications",
null=True, blank=True)
region_group = models.ForeignKey(RegionGroup,
on_delete=models.CASCADE,
related_name="modifications",
null=True, blank=True)
water_proportion = models.FloatField(default=1.0, blank=True) # the amount, relative to base values, to provide
rainfall_proportion = models.FloatField(default=1.0, blank=True) # the amount, relative to base values, to provide
land_proportion = models.FloatField(default=1.0, blank=True)
# extra flags on regions
modeled_type = models.SmallIntegerField(default=Region.MODELED, choices=Region.REGION_DEFAULT_MODELING_CHOICES)
model_run = models.ForeignKey(ModelRun, blank=True, on_delete=models.CASCADE, related_name="region_modifications")
serializer_fields = ["id", "region", "region_group", "water_proportion", "land_proportion", "rainfall_proportion",
"modeled_type"]
class CropModification(models.Model):
"""
A modification on a crop to use in a model run. We'll need to have the model run build a new pandas data frame
from these based on the code inputs and the model adjustments
"""
class Meta:
unique_together = ['model_run', 'crop', 'region']
serializer_fields = ["id", "crop", "crop_group", "price_proportion", "yield_proportion",
"min_land_area_proportion", "max_land_area_proportion", "region"]
crop = models.ForeignKey(Crop, on_delete=models.CASCADE, related_name="modifications",
null=True, blank=True)
region = models.ForeignKey(Region, on_delete=models.CASCADE, related_name="crop_modifications",
null=True, blank=True) # we'll be allowing region-tied crop modifications in a future update - as of 2021/March/02, there is no logic for handling this value yet - it'll all be null and won't go into the solver anywhere
crop_group = models.ForeignKey(CropGroup, on_delete=models.CASCADE, related_name="modifications",
null=True, blank=True)
price_proportion = models.FloatField(default=1.0, blank=True) # the amount, relative to base values, to provide
yield_proportion = models.FloatField(default=1.0, blank=True) # the amount, relative to base values, to provide
min_land_area_proportion = models.FloatField(null=True, blank=True) # the amount, relative to base values, to provide
max_land_area_proportion = models.FloatField(null=True, blank=True) # the amount, relative to base values, to provide
model_run = models.ForeignKey(ModelRun, null=True, blank=True, on_delete=models.CASCADE, related_name="crop_modifications")
class HelpDocument(models.Model):
"""
We'll store help documents in the DB as well so that they can
be pulled into the app via the API - we can also publish them
elswhere if we'd like - this is ultimately just a simple article
system.
We'll plan to load these from specific articles in the Sphinx
documentation
"""
title = models.CharField(max_length=2048)
author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
slug = models.CharField(max_length=64)
summary = models.TextField()
body = models.TextField()
| [
"logging.getLogger",
"django.db.models.TextField",
"django.db.models.IntegerField",
"Dapper.worst_case.default_worst_case_scaling_function",
"django.db.models.PositiveSmallIntegerField",
"Dapper.get_version",
"django.db.models.Index",
"django.contrib.auth.get_user_model",
"django.db.models.FloatFiel... | [((338, 354), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (352, 354), False, 'from django.contrib.auth import get_user_model\n'), ((694, 732), 'logging.getLogger', 'logging.getLogger', (['"""waterspout.models"""'], {}), "('waterspout.models')\n", (711, 732), False, 'import logging\n'), ((2260, 2292), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (2268, 2292), False, 'from django.dispatch import receiver\n'), ((2488, 2520), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'User'}), '(post_save, sender=User)\n', (2496, 2520), False, 'from django.dispatch import receiver\n'), ((9014, 9051), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'ModelArea'}), '(post_save, sender=ModelArea)\n', (9022, 9051), False, 'from django.dispatch import receiver\n'), ((9198, 9235), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'ModelArea'}), '(post_save, sender=ModelArea)\n', (9206, 9235), False, 'from django.dispatch import receiver\n'), ((1100, 1176), 'django.db.models.OneToOneField', 'models.OneToOneField', (['User'], {'related_name': '"""profile"""', 'on_delete': 'models.CASCADE'}), "(User, related_name='profile', on_delete=models.CASCADE)\n", (1120, 1176), False, 'from django.db import models\n'), ((1400, 1433), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (1419, 1433), False, 'from django.db import models\n'), ((2017, 2051), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (2036, 2051), False, 'from django.db import models\n'), ((3049, 3106), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (3065, 3106), False, 'from django.db import models\n'), ((3177, 3256), 'django.db.models.OneToOneField', 'models.OneToOneField', (['Group'], {'on_delete': 'models.DO_NOTHING', 'null': '(True)', 'blank': '(True)'}), '(Group, on_delete=models.DO_NOTHING, null=True, blank=True)\n', (3197, 3256), False, 'from django.db import models\n'), ((3823, 3937), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Organization'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.SET_NULL', 'related_name': '"""model_areas"""'}), "(Organization, null=True, blank=True, on_delete=models.\n SET_NULL, related_name='model_areas')\n", (3840, 3937), False, 'from django.db import models\n'), ((3941, 3986), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'unique': '(True)'}), '(max_length=255, unique=True)\n', (3957, 3986), False, 'from django.db import models\n'), ((4003, 4050), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'default': '"""dap"""'}), "(max_length=255, default='dap')\n", (4019, 4050), False, 'from django.db import models\n'), ((4195, 4234), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (4211, 4234), False, 'from django.db import models\n'), ((4289, 4340), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(4)', 'decimal_places': '(2)'}), '(max_digits=4, decimal_places=2)\n', (4308, 4340), False, 'from django.db import models\n'), ((4365, 4416), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(5)', 'decimal_places': '(2)'}), '(max_digits=5, decimal_places=2)\n', (4384, 4416), False, 'from django.db import models\n'), ((4437, 4463), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {}), '()\n', (4461, 4463), False, 'from django.db import models\n'), ((4563, 4607), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(50)'}), '(default=50)\n', (4595, 4607), False, 'from django.db import models\n'), ((4621, 4666), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(120)'}), '(default=120)\n', (4653, 4666), False, 'from django.db import models\n'), ((4683, 4727), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(10)'}), '(default=10)\n', (4715, 4727), False, 'from django.db import models\n'), ((4744, 4789), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(200)'}), '(default=200)\n', (4776, 4789), False, 'from django.db import models\n'), ((4802, 4846), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(50)'}), '(default=50)\n', (4834, 4846), False, 'from django.db import models\n'), ((4859, 4904), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(100)'}), '(default=100)\n', (4891, 4904), False, 'from django.db import models\n'), ((4918, 4962), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(80)'}), '(default=80)\n', (4950, 4962), False, 'from django.db import models\n'), ((4976, 5021), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(120)'}), '(default=120)\n', (5008, 5021), False, 'from django.db import models\n'), ((5035, 5079), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(80)'}), '(default=80)\n', (5067, 5079), False, 'from django.db import models\n'), ((5093, 5138), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(120)'}), '(default=120)\n', (5125, 5138), False, 'from django.db import models\n'), ((5156, 5199), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(0)'}), '(default=0)\n', (5188, 5199), False, 'from django.db import models\n'), ((5217, 5262), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(200)'}), '(default=200)\n', (5249, 5262), False, 'from django.db import models\n'), ((5290, 5329), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (5306, 5329), False, 'from django.db import models\n'), ((5355, 5406), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'default': '"""DEFAULT"""'}), "(max_length=100, default='DEFAULT')\n", (5371, 5406), False, 'from django.db import models\n'), ((6865, 6898), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (6884, 6898), False, 'from django.db import models\n'), ((7141, 7174), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (7160, 7174), False, 'from django.db import models\n'), ((7400, 7434), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (7419, 7434), False, 'from django.db import models\n'), ((7704, 7738), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (7723, 7738), False, 'from django.db import models\n'), ((7809, 7843), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (7828, 7843), False, 'from django.db import models\n'), ((7953, 7987), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (7972, 7987), False, 'from django.db import models\n'), ((8219, 8253), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8238, 8253), False, 'from django.db import models\n'), ((8281, 8315), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8300, 8315), False, 'from django.db import models\n'), ((8343, 8377), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8362, 8377), False, 'from django.db import models\n'), ((8402, 8436), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8421, 8436), False, 'from django.db import models\n'), ((8462, 8496), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8481, 8496), False, 'from django.db import models\n'), ((8522, 8556), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8541, 8556), False, 'from django.db import models\n'), ((8588, 8622), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (8607, 8622), False, 'from django.db import models\n'), ((8656, 8689), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (8675, 8689), False, 'from django.db import models\n'), ((8705, 8795), 'django.db.models.OneToOneField', 'models.OneToOneField', (['ModelArea'], {'on_delete': 'models.CASCADE', 'related_name': '"""preferences"""'}), "(ModelArea, on_delete=models.CASCADE, related_name=\n 'preferences')\n", (8725, 8795), False, 'from django.db import models\n'), ((9875, 9932), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (9891, 9932), False, 'from django.db import models\n'), ((9948, 10005), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(False)', 'blank': '(False)'}), '(max_length=100, null=False, blank=False)\n', (9964, 10005), False, 'from django.db import models\n'), ((10113, 10167), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE'}), '(ModelArea, on_delete=models.CASCADE)\n', (10130, 10167), False, 'from django.db import models\n'), ((10181, 10220), 'django.db.models.JSONField', 'models.JSONField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (10197, 10220), False, 'from django.db import models\n'), ((10865, 10922), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (10881, 10922), False, 'from django.db import models\n'), ((10938, 10995), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(False)', 'blank': '(False)'}), '(max_length=100, null=False, blank=False)\n', (10954, 10995), False, 'from django.db import models\n'), ((11104, 11159), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)', 'blank': '(True)'}), '(max_length=100, null=True, blank=True)\n', (11120, 11159), False, 'from django.db import models\n'), ((11220, 11259), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (11236, 11259), False, 'from django.db import models\n'), ((11350, 11437), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': 'MODELED', 'choices': 'REGION_DEFAULT_MODELING_CHOICES'}), '(default=MODELED, choices=\n REGION_DEFAULT_MODELING_CHOICES)\n', (11374, 11437), False, 'from django.db import models\n'), ((11446, 11485), 'django.db.models.JSONField', 'models.JSONField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (11462, 11485), False, 'from django.db import models\n'), ((11582, 11636), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE'}), '(ModelArea, on_delete=models.CASCADE)\n', (11599, 11636), False, 'from django.db import models\n'), ((11646, 11725), 'django.db.models.ForeignKey', 'models.ForeignKey', (['RegionGroup'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.CASCADE'}), '(RegionGroup, null=True, blank=True, on_delete=models.CASCADE)\n', (11663, 11725), False, 'from django.db import models\n'), ((11988, 12022), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (12007, 12022), False, 'from django.db import models\n'), ((12112, 12145), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (12131, 12145), False, 'from django.db import models\n'), ((12620, 12707), 'django.db.models.OneToOneField', 'models.OneToOneField', (['Region'], {'on_delete': 'models.CASCADE', 'related_name': '"""multipliers"""'}), "(Region, on_delete=models.CASCADE, related_name=\n 'multipliers')\n", (12640, 12707), False, 'from django.db import models\n'), ((12721, 12796), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(8)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=8, null=True, blank=True)\n', (12740, 12796), False, 'from django.db import models\n'), ((12817, 12892), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(8)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=8, null=True, blank=True)\n', (12836, 12892), False, 'from django.db import models\n'), ((12912, 12987), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(8)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=8, null=True, blank=True)\n', (12931, 12987), False, 'from django.db import models\n'), ((13003, 13078), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(8)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=8, null=True, blank=True)\n', (13022, 13078), False, 'from django.db import models\n'), ((13093, 13168), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(8)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=8, null=True, blank=True)\n', (13112, 13168), False, 'from django.db import models\n'), ((13387, 13476), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'on_delete': 'models.CASCADE', 'related_name': '"""extra_attributes"""'}), "(Region, on_delete=models.CASCADE, related_name=\n 'extra_attributes')\n", (13404, 13476), False, 'from django.db import models\n'), ((13480, 13537), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (13496, 13537), False, 'from django.db import models\n'), ((13547, 13586), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (13563, 13586), False, 'from django.db import models\n'), ((13600, 13630), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(5)'}), '(max_length=5)\n', (13616, 13630), False, 'from django.db import models\n'), ((14347, 14404), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (14363, 14404), False, 'from django.db import models\n'), ((14446, 14502), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'null': '(False)', 'blank': '(False)'}), '(max_length=30, null=False, blank=False)\n', (14462, 14502), False, 'from django.db import models\n'), ((14569, 14623), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE'}), '(ModelArea, on_delete=models.CASCADE)\n', (14586, 14623), False, 'from django.db import models\n'), ((14921, 14978), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'null': '(False)', 'blank': '(False)'}), '(max_length=255, null=False, blank=False)\n', (14937, 14978), False, 'from django.db import models\n'), ((14988, 15016), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Crop'], {}), '(Crop)\n', (15010, 15016), False, 'from django.db import models\n'), ((15507, 15525), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (15523, 15525), False, 'from django.db import models\n'), ((19348, 19434), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE', 'related_name': '"""input_data"""'}), "(ModelArea, on_delete=models.CASCADE, related_name=\n 'input_data')\n", (19365, 19434), False, 'from django.db import models\n'), ((19512, 19604), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE', 'related_name': '"""calibration_data"""'}), "(ModelArea, on_delete=models.CASCADE, related_name=\n 'calibration_data')\n", (19529, 19604), False, 'from django.db import models\n'), ((19723, 19812), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelArea'], {'on_delete': 'models.CASCADE', 'related_name': '"""rainfall_data"""'}), "(ModelArea, on_delete=models.CASCADE, related_name=\n 'rainfall_data')\n", (19740, 19812), False, 'from django.db import models\n'), ((19983, 20090), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""ModelRun"""'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.CASCADE', 'related_name': '"""results"""'}), "('ModelRun', null=True, blank=True, on_delete=models.\n CASCADE, related_name='results')\n", (20000, 20090), False, 'from django.db import models\n'), ((20131, 20209), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'null': '(True)', 'blank': '(True)'}), '(default=django.utils.timezone.now, null=True, blank=True)\n', (20151, 20209), False, 'from django.db import models\n'), ((20360, 20391), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)'}), '(max_length=20)\n', (20376, 20391), False, 'from django.db import models\n'), ((20550, 20583), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (20569, 20583), False, 'from django.db import models\n'), ((20831, 20870), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (20847, 20870), False, 'from django.db import models\n'), ((21295, 21344), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Crop'], {'on_delete': 'models.CASCADE'}), '(Crop, on_delete=models.CASCADE)\n', (21312, 21344), False, 'from django.db import models\n'), ((21355, 21406), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'on_delete': 'models.CASCADE'}), '(Region, on_delete=models.CASCADE)\n', (21372, 21406), False, 'from django.db import models\n'), ((21415, 21457), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (21434, 21457), False, 'from django.db import models\n'), ((21530, 21583), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (21549, 21583), False, 'from django.db import models\n'), ((21589, 21641), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(13)', 'decimal_places': '(5)'}), '(max_digits=13, decimal_places=5)\n', (21608, 21641), False, 'from django.db import models\n'), ((21651, 21704), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (21670, 21704), False, 'from django.db import models\n'), ((21785, 21837), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)'}), '(max_digits=10, decimal_places=1)\n', (21804, 21837), False, 'from django.db import models\n'), ((21853, 21905), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)'}), '(max_digits=10, decimal_places=1)\n', (21872, 21905), False, 'from django.db import models\n'), ((21920, 21972), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)'}), '(max_digits=10, decimal_places=1)\n', (21939, 21972), False, 'from django.db import models\n'), ((21991, 22066), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=1, null=True, blank=True)\n', (22010, 22066), False, 'from django.db import models\n'), ((22080, 22155), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=1, null=True, blank=True)\n', (22099, 22155), False, 'from django.db import models\n'), ((22172, 22247), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=1, null=True, blank=True)\n', (22191, 22247), False, 'from django.db import models\n'), ((22262, 22337), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(1)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=10, decimal_places=1, null=True, blank=True)\n', (22281, 22337), False, 'from django.db import models\n'), ((22348, 22401), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (22367, 22401), False, 'from django.db import models\n'), ((22513, 22606), 'django.db.models.ForeignKey', 'models.ForeignKey', (['InputDataSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""input_data_set"""'}), "(InputDataSet, on_delete=models.CASCADE, related_name=\n 'input_data_set')\n", (22530, 22606), False, 'from django.db import models\n'), ((23169, 23221), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(2)'}), '(max_digits=10, decimal_places=2)\n', (23188, 23221), False, 'from django.db import models\n'), ((23228, 23280), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(3)'}), '(max_digits=10, decimal_places=3)\n', (23247, 23280), False, 'from django.db import models\n'), ((23290, 23341), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(5)', 'decimal_places': '(4)'}), '(max_digits=5, decimal_places=4)\n', (23309, 23341), False, 'from django.db import models\n'), ((23351, 23402), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(5)', 'decimal_places': '(4)'}), '(max_digits=5, decimal_places=4)\n', (23370, 23402), False, 'from django.db import models\n'), ((23417, 23470), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (23436, 23470), False, 'from django.db import models\n'), ((23849, 23902), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(15)', 'decimal_places': '(10)'}), '(max_digits=15, decimal_places=10)\n', (23868, 23902), False, 'from django.db import models\n'), ((24100, 24153), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24119, 24153), False, 'from django.db import models\n'), ((24167, 24220), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24186, 24220), False, 'from django.db import models\n'), ((24235, 24288), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24254, 24288), False, 'from django.db import models\n'), ((24302, 24355), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24321, 24355), False, 'from django.db import models\n'), ((24363, 24416), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24382, 24416), False, 'from django.db import models\n'), ((24426, 24479), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24445, 24479), False, 'from django.db import models\n'), ((24489, 24542), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)'}), '(max_digits=18, decimal_places=10)\n', (24508, 24542), False, 'from django.db import models\n'), ((25152, 25214), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(6)', 'decimal_places': '(3)', 'default': '(1)'}), '(max_digits=6, decimal_places=3, default=1)\n', (25171, 25214), False, 'from django.db import models\n'), ((25235, 25331), 'django.db.models.ForeignKey', 'models.ForeignKey', (['CalibrationSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""calibration_set"""'}), "(CalibrationSet, on_delete=models.CASCADE, related_name=\n 'calibration_set')\n", (25252, 25331), False, 'from django.db import models\n'), ((25756, 25846), 'django.db.models.ForeignKey', 'models.ForeignKey', (['RainfallSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""rainfall_set"""'}), "(RainfallSet, on_delete=models.CASCADE, related_name=\n 'rainfall_set')\n", (25773, 25846), False, 'from django.db import models\n'), ((25861, 25913), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (25880, 25913), False, 'from django.db import models\n'), ((25922, 25974), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (25941, 25974), False, 'from django.db import models\n'), ((25983, 26035), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26002, 26035), False, 'from django.db import models\n'), ((26044, 26096), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26063, 26096), False, 'from django.db import models\n'), ((26110, 26162), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26129, 26162), False, 'from django.db import models\n'), ((26176, 26228), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26195, 26228), False, 'from django.db import models\n'), ((26242, 26294), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26261, 26294), False, 'from django.db import models\n'), ((26304, 26356), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26323, 26356), False, 'from django.db import models\n'), ((26366, 26418), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26385, 26418), False, 'from django.db import models\n'), ((26428, 26480), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26447, 26480), False, 'from django.db import models\n'), ((26495, 26547), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26514, 26547), False, 'from django.db import models\n'), ((26562, 26614), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26581, 26614), False, 'from django.db import models\n'), ((26629, 26681), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26648, 26681), False, 'from django.db import models\n'), ((26695, 26747), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(5)'}), '(max_digits=10, decimal_places=5)\n', (26714, 26747), False, 'from django.db import models\n'), ((26845, 26897), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(2)'}), '(max_digits=10, decimal_places=2)\n', (26864, 26897), False, 'from django.db import models\n'), ((26915, 26968), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(5)', 'null': '(True)', 'blank': '(True)'}), '(max_length=5, null=True, blank=True)\n', (26931, 26968), False, 'from django.db import models\n'), ((27104, 27180), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (27123, 27180), False, 'from django.db import models\n'), ((27193, 27269), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (27212, 27269), False, 'from django.db import models\n'), ((27283, 27359), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (27302, 27359), False, 'from django.db import models\n'), ((27378, 27454), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (27397, 27454), False, 'from django.db import models\n'), ((27469, 27545), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (27488, 27545), False, 'from django.db import models\n'), ((27561, 27647), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ResultSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""result_set"""'}), "(ResultSet, on_delete=models.CASCADE, related_name=\n 'result_set')\n", (27578, 27647), False, 'from django.db import models\n'), ((27659, 27734), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(3)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=3, null=True, blank=True)\n', (27678, 27734), False, 'from django.db import models\n'), ((27752, 27827), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(3)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=3, null=True, blank=True)\n', (27771, 27827), False, 'from django.db import models\n'), ((27846, 27921), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(5)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=5, null=True, blank=True)\n', (27865, 27921), False, 'from django.db import models\n'), ((28069, 28164), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ResultSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""rainfall_result_set"""'}), "(ResultSet, on_delete=models.CASCADE, related_name=\n 'rainfall_result_set')\n", (28086, 28164), False, 'from django.db import models\n'), ((28171, 28260), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'on_delete': 'models.CASCADE', 'related_name': '"""rainfall_results"""'}), "(Region, on_delete=models.CASCADE, related_name=\n 'rainfall_results')\n", (28188, 28260), False, 'from django.db import models\n'), ((28264, 28351), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Crop'], {'on_delete': 'models.CASCADE', 'related_name': '"""rainfall_results"""'}), "(Crop, on_delete=models.CASCADE, related_name=\n 'rainfall_results')\n", (28281, 28351), False, 'from django.db import models\n'), ((28565, 28640), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(3)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=3, null=True, blank=True)\n', (28584, 28640), False, 'from django.db import models\n'), ((28658, 28733), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(3)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=3, null=True, blank=True)\n', (28677, 28733), False, 'from django.db import models\n'), ((28840, 28916), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (28859, 28916), False, 'from django.db import models\n'), ((28929, 29005), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(18)', 'decimal_places': '(10)', 'null': '(True)', 'blank': '(True)'}), '(max_digits=18, decimal_places=10, null=True, blank=True)\n', (28948, 29005), False, 'from django.db import models\n'), ((29324, 29356), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (29340, 29356), False, 'from django.db import models\n'), ((29372, 29411), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (29388, 29411), False, 'from django.db import models\n'), ((29422, 29468), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'null': '(False)'}), '(default=False, null=False)\n', (29441, 29468), False, 'from django.db import models\n'), ((29537, 29583), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'null': '(False)'}), '(default=False, null=False)\n', (29556, 29583), False, 'from django.db import models\n'), ((29626, 29672), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'null': '(False)'}), '(default=False, null=False)\n', (29645, 29672), False, 'from django.db import models\n'), ((29757, 29825), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2048)', 'default': '""""""', 'null': '(True)', 'blank': '(True)'}), "(max_length=2048, default='', null=True, blank=True)\n", (29773, 29825), False, 'from django.db import models\n'), ((29880, 29931), 'django.db.models.TextField', 'models.TextField', ([], {'default': '""""""', 'null': '(True)', 'blank': '(True)'}), "(default='', null=True, blank=True)\n", (29896, 29931), False, 'from django.db import models\n'), ((29944, 29983), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (29960, 29983), False, 'from django.db import models\n'), ((30054, 30132), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'null': '(True)', 'blank': '(True)'}), '(default=django.utils.timezone.now, null=True, blank=True)\n', (30074, 30132), False, 'from django.db import models\n'), ((30151, 30194), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (30171, 30194), False, 'from django.db import models\n'), ((30286, 30372), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""ModelRun"""'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.DO_NOTHING'}), "('ModelRun', null=True, blank=True, on_delete=models.\n DO_NOTHING)\n", (30303, 30372), False, 'from django.db import models\n'), ((30379, 30413), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (30398, 30413), False, 'from django.db import models\n'), ((30550, 30641), 'django.db.models.ForeignKey', 'models.ForeignKey', (['CalibrationSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""model_runs"""'}), "(CalibrationSet, on_delete=models.CASCADE, related_name=\n 'model_runs')\n", (30567, 30641), False, 'from django.db import models\n'), ((30667, 30706), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (30683, 30706), False, 'from django.db import models\n'), ((30954, 31065), 'django.db.models.ForeignKey', 'models.ForeignKey', (['RainfallSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""model_runs"""', 'null': '(True)', 'blank': '(True)'}), "(RainfallSet, on_delete=models.CASCADE, related_name=\n 'model_runs', null=True, blank=True)\n", (30971, 31065), False, 'from django.db import models\n'), ((31070, 31149), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {'on_delete': 'models.DO_NOTHING', 'related_name': '"""model_runs"""'}), "(User, on_delete=models.DO_NOTHING, related_name='model_runs')\n", (31087, 31149), False, 'from django.db import models\n'), ((31166, 31255), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Organization'], {'on_delete': 'models.CASCADE', 'related_name': '"""model_runs"""'}), "(Organization, on_delete=models.CASCADE, related_name=\n 'model_runs')\n", (31183, 31255), False, 'from django.db import models\n'), ((45676, 45767), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ResultSet'], {'on_delete': 'models.CASCADE', 'related_name': '"""infeasibilities"""'}), "(ResultSet, on_delete=models.CASCADE, related_name=\n 'infeasibilities')\n", (45693, 45767), False, 'from django.db import models\n'), ((45771, 45797), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {}), '()\n', (45795, 45797), False, 'from django.db import models\n'), ((45808, 45907), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'null': '(True)', 'on_delete': 'models.SET_NULL', 'related_name': '"""infeasibilities"""'}), "(Region, null=True, on_delete=models.SET_NULL,\n related_name='infeasibilities')\n", (45825, 45907), False, 'from django.db import models\n'), ((45919, 45937), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (45935, 45937), False, 'from django.db import models\n'), ((46708, 46817), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'on_delete': 'models.CASCADE', 'related_name': '"""modifications"""', 'null': '(True)', 'blank': '(True)'}), "(Region, on_delete=models.CASCADE, related_name=\n 'modifications', null=True, blank=True)\n", (46725, 46817), False, 'from django.db import models\n'), ((46913, 47027), 'django.db.models.ForeignKey', 'models.ForeignKey', (['RegionGroup'], {'on_delete': 'models.CASCADE', 'related_name': '"""modifications"""', 'null': '(True)', 'blank': '(True)'}), "(RegionGroup, on_delete=models.CASCADE, related_name=\n 'modifications', null=True, blank=True)\n", (46930, 47027), False, 'from django.db import models\n'), ((47146, 47188), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(1.0)', 'blank': '(True)'}), '(default=1.0, blank=True)\n', (47163, 47188), False, 'from django.db import models\n'), ((47263, 47305), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(1.0)', 'blank': '(True)'}), '(default=1.0, blank=True)\n', (47280, 47305), False, 'from django.db import models\n'), ((47376, 47418), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(1.0)', 'blank': '(True)'}), '(default=1.0, blank=True)\n', (47393, 47418), False, 'from django.db import models\n'), ((47462, 47563), 'django.db.models.SmallIntegerField', 'models.SmallIntegerField', ([], {'default': 'Region.MODELED', 'choices': 'Region.REGION_DEFAULT_MODELING_CHOICES'}), '(default=Region.MODELED, choices=Region.\n REGION_DEFAULT_MODELING_CHOICES)\n', (47486, 47563), False, 'from django.db import models\n'), ((47573, 47679), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelRun'], {'blank': '(True)', 'on_delete': 'models.CASCADE', 'related_name': '"""region_modifications"""'}), "(ModelRun, blank=True, on_delete=models.CASCADE,\n related_name='region_modifications')\n", (47590, 47679), False, 'from django.db import models\n'), ((48311, 48418), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Crop'], {'on_delete': 'models.CASCADE', 'related_name': '"""modifications"""', 'null': '(True)', 'blank': '(True)'}), "(Crop, on_delete=models.CASCADE, related_name=\n 'modifications', null=True, blank=True)\n", (48328, 48418), False, 'from django.db import models\n'), ((48453, 48567), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Region'], {'on_delete': 'models.CASCADE', 'related_name': '"""crop_modifications"""', 'null': '(True)', 'blank': '(True)'}), "(Region, on_delete=models.CASCADE, related_name=\n 'crop_modifications', null=True, blank=True)\n", (48470, 48567), False, 'from django.db import models\n'), ((48804, 48916), 'django.db.models.ForeignKey', 'models.ForeignKey', (['CropGroup'], {'on_delete': 'models.CASCADE', 'related_name': '"""modifications"""', 'null': '(True)', 'blank': '(True)'}), "(CropGroup, on_delete=models.CASCADE, related_name=\n 'modifications', null=True, blank=True)\n", (48821, 48916), False, 'from django.db import models\n'), ((48965, 49007), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(1.0)', 'blank': '(True)'}), '(default=1.0, blank=True)\n', (48982, 49007), False, 'from django.db import models\n'), ((49079, 49121), 'django.db.models.FloatField', 'models.FloatField', ([], {'default': '(1.0)', 'blank': '(True)'}), '(default=1.0, blank=True)\n', (49096, 49121), False, 'from django.db import models\n'), ((49201, 49241), 'django.db.models.FloatField', 'models.FloatField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (49218, 49241), False, 'from django.db import models\n'), ((49321, 49361), 'django.db.models.FloatField', 'models.FloatField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (49338, 49361), False, 'from django.db import models\n'), ((49427, 49542), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ModelRun'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.CASCADE', 'related_name': '"""crop_modifications"""'}), "(ModelRun, null=True, blank=True, on_delete=models.CASCADE,\n related_name='crop_modifications')\n", (49444, 49542), False, 'from django.db import models\n'), ((49880, 49913), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2048)'}), '(max_length=2048)\n', (49896, 49913), False, 'from django.db import models\n'), ((49924, 49976), 'django.db.models.ForeignKey', 'models.ForeignKey', (['User'], {'on_delete': 'models.DO_NOTHING'}), '(User, on_delete=models.DO_NOTHING)\n', (49941, 49976), False, 'from django.db import models\n'), ((49985, 50016), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(64)'}), '(max_length=64)\n', (50001, 50016), False, 'from django.db import models\n'), ((50029, 50047), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (50045, 50047), False, 'from django.db import models\n'), ((50056, 50074), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (50072, 50074), False, 'from django.db import models\n'), ((908, 925), 'json.dumps', 'json.dumps', (['value'], {}), '(value)\n', (918, 925), False, 'import json\n'), ((993, 1010), 'json.loads', 'json.loads', (['value'], {}), '(value)\n', (1003, 1010), False, 'import json\n'), ((2428, 2484), 'guardian.shortcuts.assign_perm', 'assign_perm', (['"""change_userprofile"""', 'instance', 'new_profile'], {}), "('change_userprofile', instance, new_profile)\n", (2439, 2484), False, 'from guardian.shortcuts import assign_perm\n'), ((17799, 17823), 'pandas.DataFrame', 'pandas.DataFrame', (['output'], {}), '(output)\n', (17815, 17823), False, 'import pandas\n'), ((34676, 34679), 'django.db.models.Q', 'Q', ([], {}), '()\n', (34677, 34679), False, 'from django.db.models import Q\n'), ((34710, 34713), 'django.db.models.Q', 'Q', ([], {}), '()\n', (34711, 34713), False, 'from django.db.models import Q\n'), ((40985, 41040), 'Dapper.worst_case.default_worst_case_scaling_function', 'worst_case.default_worst_case_scaling_function', (['results'], {}), '(results)\n', (41031, 41040), False, 'from Dapper import scenarios, get_version as get_dapper_version, worst_case\n'), ((10607, 10644), 'django.db.models.Index', 'models.Index', ([], {'fields': "('internal_id',)"}), "(fields=('internal_id',))\n", (10619, 10644), False, 'from django.db import models\n'), ((10649, 10708), 'django.db.models.Index', 'models.Index', ([], {'fields': "('model_area_id', 'supports_rainfall')"}), "(fields=('model_area_id', 'supports_rainfall'))\n", (10661, 10708), False, 'from django.db import models\n'), ((10789, 10850), 'django.db.models.Index', 'models.Index', ([], {'fields': "('model_area_id', 'supports_irrigation')"}), "(fields=('model_area_id', 'supports_irrigation'))\n", (10801, 10850), False, 'from django.db import models\n'), ((14303, 14333), 'django.db.models.Index', 'models.Index', ([], {'fields': "('name',)"}), "(fields=('name',))\n", (14315, 14333), False, 'from django.db import models\n'), ((21251, 21281), 'django.db.models.Index', 'models.Index', ([], {'fields': "('year',)"}), "(fields=('year',))\n", (21263, 21281), False, 'from django.db import models\n'), ((29213, 29266), 'django.db.models.Index', 'models.Index', ([], {'fields': "('ready', 'running', 'complete')"}), "(fields=('ready', 'running', 'complete'))\n", (29225, 29266), False, 'from django.db import models\n'), ((29271, 29311), 'django.db.models.Index', 'models.Index', ([], {'fields': "('date_submitted',)"}), "(fields=('date_submitted',))\n", (29283, 29311), False, 'from django.db import models\n'), ((39889, 39975), 'Dapper.scenarios.Scenario', 'scenarios.Scenario', ([], {'calibration_df': 'self.scenario_df', 'rainfall_df': 'self.rainfall_df'}), '(calibration_df=self.scenario_df, rainfall_df=self.\n rainfall_df)\n', (39907, 39975), False, 'from Dapper import scenarios, get_version as get_dapper_version, worst_case\n'), ((34796, 34820), 'django.db.models.Q', 'Q', ([], {'modeled_type': 'behavior'}), '(modeled_type=behavior)\n', (34797, 34820), False, 'from django.db.models import Q\n'), ((34880, 34908), 'django.db.models.Q', 'Q', ([], {'default_behavior': 'behavior'}), '(default_behavior=behavior)\n', (34881, 34908), False, 'from django.db.models import Q\n'), ((42067, 42087), 'Dapper.get_version', 'get_dapper_version', ([], {}), '()\n', (42085, 42087), True, 'from Dapper import scenarios, get_version as get_dapper_version, worst_case\n'), ((43299, 43317), 'numpy.isnan', 'numpy.isnan', (['value'], {}), '(value)\n', (43310, 43317), False, 'import numpy\n')] |
"""Test generate entities."""
import os
import shutil
import unittest
import emmental
import numpy as np
import torch
import ujson
import bootleg.extract_all_entities as extract_all_entities
import bootleg.run as run
from bootleg.utils import utils
from bootleg.utils.parser import parser_utils
class TestGenEntities(unittest.TestCase):
"""Test generate entites."""
def setUp(self) -> None:
"""Set up."""
self.args = parser_utils.parse_boot_and_emm_args(
"tests/run_args/test_end2end.json"
)
# This _MUST_ get passed the args so it gets a random seed set
emmental.init(log_dir="tests/temp_log", config=self.args)
if not os.path.exists(emmental.Meta.log_path):
os.makedirs(emmental.Meta.log_path)
def tearDown(self) -> None:
"""Tear down."""
dir = os.path.join(
self.args.data_config.data_dir, self.args.data_config.data_prep_dir
)
if utils.exists_dir(dir):
shutil.rmtree(dir, ignore_errors=True)
dir = os.path.join(
self.args.data_config.entity_dir, self.args.data_config.entity_prep_dir
)
if utils.exists_dir(dir):
shutil.rmtree(dir, ignore_errors=True)
dir = os.path.join("tests/temp_log")
if os.path.exists(dir):
shutil.rmtree(dir, ignore_errors=True)
def test_end2end(self):
"""Test end to end."""
# For the collate and dataloaders to play nicely, the spawn must be fork (this is set in run.py)
torch.multiprocessing.set_start_method("fork", force=True)
# Train and save model
run.run_model(mode="train", config=self.args)
self.args["model_config"][
"model_path"
] = f"{emmental.Meta.log_path}/last_model.pth"
emmental.Meta.config["model_config"][
"model_path"
] = f"{emmental.Meta.log_path}/last_model.pth"
out_emb_file = extract_all_entities.run_model(config=self.args)
assert os.path.exists(out_emb_file)
embs = np.load(out_emb_file)
assert list(embs.shape) == [6, 32]
final_result_file = run.run_model(
mode="dump_preds", config=self.args, entity_emb_file=out_emb_file
)
lines = [ujson.loads(ln) for ln in open(final_result_file)]
final_result_file = run.run_model(
mode="dump_preds", config=self.args, entity_emb_file=None
)
lines_no_emb_file = [ujson.loads(ln) for ln in open(final_result_file)]
assert len(lines) == len(lines_no_emb_file)
if __name__ == "__main__":
unittest.main()
| [
"os.path.exists",
"bootleg.run.run_model",
"os.makedirs",
"os.path.join",
"bootleg.extract_all_entities.run_model",
"bootleg.utils.utils.exists_dir",
"shutil.rmtree",
"unittest.main",
"bootleg.utils.parser.parser_utils.parse_boot_and_emm_args",
"torch.multiprocessing.set_start_method",
"emmental... | [((2624, 2639), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2637, 2639), False, 'import unittest\n'), ((446, 518), 'bootleg.utils.parser.parser_utils.parse_boot_and_emm_args', 'parser_utils.parse_boot_and_emm_args', (['"""tests/run_args/test_end2end.json"""'], {}), "('tests/run_args/test_end2end.json')\n", (482, 518), False, 'from bootleg.utils.parser import parser_utils\n'), ((620, 677), 'emmental.init', 'emmental.init', ([], {'log_dir': '"""tests/temp_log"""', 'config': 'self.args'}), "(log_dir='tests/temp_log', config=self.args)\n", (633, 677), False, 'import emmental\n'), ((853, 939), 'os.path.join', 'os.path.join', (['self.args.data_config.data_dir', 'self.args.data_config.data_prep_dir'], {}), '(self.args.data_config.data_dir, self.args.data_config.\n data_prep_dir)\n', (865, 939), False, 'import os\n'), ((968, 989), 'bootleg.utils.utils.exists_dir', 'utils.exists_dir', (['dir'], {}), '(dir)\n', (984, 989), False, 'from bootleg.utils import utils\n'), ((1056, 1146), 'os.path.join', 'os.path.join', (['self.args.data_config.entity_dir', 'self.args.data_config.entity_prep_dir'], {}), '(self.args.data_config.entity_dir, self.args.data_config.\n entity_prep_dir)\n', (1068, 1146), False, 'import os\n'), ((1175, 1196), 'bootleg.utils.utils.exists_dir', 'utils.exists_dir', (['dir'], {}), '(dir)\n', (1191, 1196), False, 'from bootleg.utils import utils\n'), ((1263, 1293), 'os.path.join', 'os.path.join', (['"""tests/temp_log"""'], {}), "('tests/temp_log')\n", (1275, 1293), False, 'import os\n'), ((1305, 1324), 'os.path.exists', 'os.path.exists', (['dir'], {}), '(dir)\n', (1319, 1324), False, 'import os\n'), ((1550, 1608), 'torch.multiprocessing.set_start_method', 'torch.multiprocessing.set_start_method', (['"""fork"""'], {'force': '(True)'}), "('fork', force=True)\n", (1588, 1608), False, 'import torch\n'), ((1649, 1694), 'bootleg.run.run_model', 'run.run_model', ([], {'mode': '"""train"""', 'config': 'self.args'}), "(mode='train', config=self.args)\n", (1662, 1694), True, 'import bootleg.run as run\n'), ((1961, 2009), 'bootleg.extract_all_entities.run_model', 'extract_all_entities.run_model', ([], {'config': 'self.args'}), '(config=self.args)\n', (1991, 2009), True, 'import bootleg.extract_all_entities as extract_all_entities\n'), ((2025, 2053), 'os.path.exists', 'os.path.exists', (['out_emb_file'], {}), '(out_emb_file)\n', (2039, 2053), False, 'import os\n'), ((2069, 2090), 'numpy.load', 'np.load', (['out_emb_file'], {}), '(out_emb_file)\n', (2076, 2090), True, 'import numpy as np\n'), ((2163, 2248), 'bootleg.run.run_model', 'run.run_model', ([], {'mode': '"""dump_preds"""', 'config': 'self.args', 'entity_emb_file': 'out_emb_file'}), "(mode='dump_preds', config=self.args, entity_emb_file=out_emb_file\n )\n", (2176, 2248), True, 'import bootleg.run as run\n'), ((2364, 2436), 'bootleg.run.run_model', 'run.run_model', ([], {'mode': '"""dump_preds"""', 'config': 'self.args', 'entity_emb_file': 'None'}), "(mode='dump_preds', config=self.args, entity_emb_file=None)\n", (2377, 2436), True, 'import bootleg.run as run\n'), ((693, 731), 'os.path.exists', 'os.path.exists', (['emmental.Meta.log_path'], {}), '(emmental.Meta.log_path)\n', (707, 731), False, 'import os\n'), ((745, 780), 'os.makedirs', 'os.makedirs', (['emmental.Meta.log_path'], {}), '(emmental.Meta.log_path)\n', (756, 780), False, 'import os\n'), ((1003, 1041), 'shutil.rmtree', 'shutil.rmtree', (['dir'], {'ignore_errors': '(True)'}), '(dir, ignore_errors=True)\n', (1016, 1041), False, 'import shutil\n'), ((1210, 1248), 'shutil.rmtree', 'shutil.rmtree', (['dir'], {'ignore_errors': '(True)'}), '(dir, ignore_errors=True)\n', (1223, 1248), False, 'import shutil\n'), ((1338, 1376), 'shutil.rmtree', 'shutil.rmtree', (['dir'], {'ignore_errors': '(True)'}), '(dir, ignore_errors=True)\n', (1351, 1376), False, 'import shutil\n'), ((2284, 2299), 'ujson.loads', 'ujson.loads', (['ln'], {}), '(ln)\n', (2295, 2299), False, 'import ujson\n'), ((2488, 2503), 'ujson.loads', 'ujson.loads', (['ln'], {}), '(ln)\n', (2499, 2503), False, 'import ujson\n')] |
from matplotlib import pyplot
import numpy
data = numpy.loadtxt(fname='../data/inflammation-01.csv', delimiter=',')
image = pyplot.imshow(data)
pyplot.show(image)
ave_inflammation = data.mean(axis=0)
ave_plot = pyplot.plot(ave_inflammation)
pyplot.show(ave_plot)
max_plot = pyplot.plot(data.max(axis=0))
pyplot.show(max_plot)
min_plot = pyplot.plot(data.min(axis=0))
pyplot.show(min_plot) | [
"matplotlib.pyplot.imshow",
"numpy.loadtxt",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
] | [((52, 117), 'numpy.loadtxt', 'numpy.loadtxt', ([], {'fname': '"""../data/inflammation-01.csv"""', 'delimiter': '""","""'}), "(fname='../data/inflammation-01.csv', delimiter=',')\n", (65, 117), False, 'import numpy\n'), ((128, 147), 'matplotlib.pyplot.imshow', 'pyplot.imshow', (['data'], {}), '(data)\n', (141, 147), False, 'from matplotlib import pyplot\n'), ((148, 166), 'matplotlib.pyplot.show', 'pyplot.show', (['image'], {}), '(image)\n', (159, 166), False, 'from matplotlib import pyplot\n'), ((216, 245), 'matplotlib.pyplot.plot', 'pyplot.plot', (['ave_inflammation'], {}), '(ave_inflammation)\n', (227, 245), False, 'from matplotlib import pyplot\n'), ((246, 267), 'matplotlib.pyplot.show', 'pyplot.show', (['ave_plot'], {}), '(ave_plot)\n', (257, 267), False, 'from matplotlib import pyplot\n'), ((310, 331), 'matplotlib.pyplot.show', 'pyplot.show', (['max_plot'], {}), '(max_plot)\n', (321, 331), False, 'from matplotlib import pyplot\n'), ((374, 395), 'matplotlib.pyplot.show', 'pyplot.show', (['min_plot'], {}), '(min_plot)\n', (385, 395), False, 'from matplotlib import pyplot\n')] |
import os
import sys
import pandas as pd
import numpy as np
import scipy.stats as stats
from scipy.special import logsumexp, softmax, gammaln, logit, expit
from scipy import linalg
import joblib
from time import time
import flipflop_model
import dynesty
from dynesty import NestedSampler
def runModel(S, lam, mu, gamma, age):
return flipflop_model.runModel(S, lam, mu, gamma, age)
def beta_lpdf(y, alpha, beta):
return flipflop_model.beta_lpdf(y, alpha, beta)
def rescale_beta(beta, delta, eta):
# Linear transform of beta values from between
# 0 and 1 to between delta and eta
return (eta - delta) * beta + delta
def beta_convert_params(mu, kappa):
"""
Convert mean/dispersion parameterization of a beta distribution to the ones scipy supports
"""
if np.any(kappa <= 0):
raise Exception("kappa must be greater than 0")
elif np.any(mu <= 0) or np.any(mu >= 1):
raise Exception("mu must be between 0 and 1")
alpha = kappa * mu
beta = kappa * (1- mu)
return alpha, beta
def beta_ppf(y, mean, kappa):
alpha, beta = beta_convert_params(mean, kappa)
return stats.beta.ppf(y, alpha, beta)
def beta_rvs(mean, kappa, **kwargs):
alpha, beta = beta_convert_params(mean, kappa)
return stats.beta.rvs(alpha, beta, **kwargs)
def truncnormal_convert_params(mean, std, lb=0.0, ub=1.0):
"""
Convert mean/dispersion parameterization of a beta distribution to the ones scipy supports
"""
if np.isfinite(lb):
a = (lb - mean) / std
else:
a = lb
if np.isfinite(ub):
b = (ub - mean) / std
else:
b = ub
return a, b
def truncnormal_ppf(y, mean, std, lb=0.0, ub=1.0):
a, b = truncnormal_convert_params(mean, std, lb, ub)
return stats.truncnorm.ppf(y, a, b, loc=mean, scale=std)
def prior_transform(flat_prior, scales):
# priors for parameters [lam_S, mu, gamma, delta, eta, kappamean, kappadisp, kappa[]]
prior = np.empty(np.shape(flat_prior))
prior[:3] = stats.halfnorm.ppf(flat_prior[:3], scale=scales)
# priors on delta and eta
prior[3] = stats.beta.ppf(flat_prior[3], 5, 95)
prior[4] = stats.beta.ppf(flat_prior[4], 95, 5)
# mean and dispersion hyperpriors of kappa
prior[5] = stats.halfnorm.ppf(flat_prior[5], scale = 500)
prior[6] = stats.halfnorm.ppf(flat_prior[6], scale = 50)
# hierarchical priors on kappa[]
prior[7:] = truncnormal_ppf(flat_prior[7:], prior[5], prior[6], lb=0.0, ub=np.inf)
return prior
def loglikelihood_perpoint(params, y, S, age):
# unpack parameters
lam, mu, gamma, delta, eta, kappamean, kappadisp = params[:7]
kappa = params[7:]
# calucalate p(z|lam, mu, gamma)
ProbDist = runModel(S, lam, mu, gamma, age)
lProbDist = np.log(ProbDist)
# repeat the above values to create a (2S+1, n) array
lpk = np.repeat(lProbDist[:, np.newaxis], np.shape(y)[0], axis=1)
# linear transform of "true" beta peaks
betatrue = rescale_beta(np.linspace(0, 1, 2*S+1), delta, eta)
# transform the mean and shape parameters to the ones scipy supports
alpha, beta = beta_convert_params(betatrue, kappa)
# calculate log(p(y|z))
lpk += beta_lpdf(y, alpha, beta)
# p(y|lam, mu, gamma) = sum(p(y|z)*p(z|lam, mu, gamma))
# on the log scale this requires logsumexp
LL = logsumexp(lpk, axis = 0)
return LL
def loglikelihood(params, beta, S, age):
return np.sum(loglikelihood_perpoint(params, beta, S, age))
def run_inference(
beta,
age,
S,
nlive=1500,
lamscale=1.0,
muscale=0.05,
gammascale=0.05,
verbose=False
):
# set the std of the halfnormal priors on lam, mu, gamma
scales = np.array([lamscale, muscale, gammascale])
ndims = 7 + 2*S +1
# create dummy functions which takes only the params as an argument to pass
# to dynesty
prior_function = lambda flat_prior: prior_transform(flat_prior, scales)
loglikelihood_function = lambda params: loglikelihood(params, beta, S, age)
t0 = time()
print('Performing Dynesty sampling')
sampler = NestedSampler(loglikelihood_function, prior_function, ndims,
bound='multi', sample='rwalk', nlive=nlive)
sampler.run_nested(print_progress=verbose)
res = sampler.results
t1 = time()
timesampler = int(t1-t0)
print("\nTime taken to run Dynesty is {} seconds".format(timesampler))
print(res.summary())
return res
| [
"flipflop_model.beta_lpdf",
"scipy.stats.beta.rvs",
"scipy.stats.truncnorm.ppf",
"dynesty.NestedSampler",
"numpy.log",
"numpy.any",
"numpy.array",
"numpy.linspace",
"flipflop_model.runModel",
"numpy.isfinite",
"time.time",
"numpy.shape",
"scipy.stats.halfnorm.ppf",
"scipy.special.logsumexp... | [((341, 388), 'flipflop_model.runModel', 'flipflop_model.runModel', (['S', 'lam', 'mu', 'gamma', 'age'], {}), '(S, lam, mu, gamma, age)\n', (364, 388), False, 'import flipflop_model\n'), ((432, 472), 'flipflop_model.beta_lpdf', 'flipflop_model.beta_lpdf', (['y', 'alpha', 'beta'], {}), '(y, alpha, beta)\n', (456, 472), False, 'import flipflop_model\n'), ((798, 816), 'numpy.any', 'np.any', (['(kappa <= 0)'], {}), '(kappa <= 0)\n', (804, 816), True, 'import numpy as np\n'), ((1149, 1179), 'scipy.stats.beta.ppf', 'stats.beta.ppf', (['y', 'alpha', 'beta'], {}), '(y, alpha, beta)\n', (1163, 1179), True, 'import scipy.stats as stats\n'), ((1282, 1319), 'scipy.stats.beta.rvs', 'stats.beta.rvs', (['alpha', 'beta'], {}), '(alpha, beta, **kwargs)\n', (1296, 1319), True, 'import scipy.stats as stats\n'), ((1501, 1516), 'numpy.isfinite', 'np.isfinite', (['lb'], {}), '(lb)\n', (1512, 1516), True, 'import numpy as np\n'), ((1585, 1600), 'numpy.isfinite', 'np.isfinite', (['ub'], {}), '(ub)\n', (1596, 1600), True, 'import numpy as np\n'), ((1798, 1847), 'scipy.stats.truncnorm.ppf', 'stats.truncnorm.ppf', (['y', 'a', 'b'], {'loc': 'mean', 'scale': 'std'}), '(y, a, b, loc=mean, scale=std)\n', (1817, 1847), True, 'import scipy.stats as stats\n'), ((2044, 2092), 'scipy.stats.halfnorm.ppf', 'stats.halfnorm.ppf', (['flat_prior[:3]'], {'scale': 'scales'}), '(flat_prior[:3], scale=scales)\n', (2062, 2092), True, 'import scipy.stats as stats\n'), ((2139, 2175), 'scipy.stats.beta.ppf', 'stats.beta.ppf', (['flat_prior[3]', '(5)', '(95)'], {}), '(flat_prior[3], 5, 95)\n', (2153, 2175), True, 'import scipy.stats as stats\n'), ((2191, 2227), 'scipy.stats.beta.ppf', 'stats.beta.ppf', (['flat_prior[4]', '(95)', '(5)'], {}), '(flat_prior[4], 95, 5)\n', (2205, 2227), True, 'import scipy.stats as stats\n'), ((2292, 2336), 'scipy.stats.halfnorm.ppf', 'stats.halfnorm.ppf', (['flat_prior[5]'], {'scale': '(500)'}), '(flat_prior[5], scale=500)\n', (2310, 2336), True, 'import scipy.stats as stats\n'), ((2354, 2397), 'scipy.stats.halfnorm.ppf', 'stats.halfnorm.ppf', (['flat_prior[6]'], {'scale': '(50)'}), '(flat_prior[6], scale=50)\n', (2372, 2397), True, 'import scipy.stats as stats\n'), ((2807, 2823), 'numpy.log', 'np.log', (['ProbDist'], {}), '(ProbDist)\n', (2813, 2823), True, 'import numpy as np\n'), ((3377, 3399), 'scipy.special.logsumexp', 'logsumexp', (['lpk'], {'axis': '(0)'}), '(lpk, axis=0)\n', (3386, 3399), False, 'from scipy.special import logsumexp, softmax, gammaln, logit, expit\n'), ((3747, 3788), 'numpy.array', 'np.array', (['[lamscale, muscale, gammascale]'], {}), '([lamscale, muscale, gammascale])\n', (3755, 3788), True, 'import numpy as np\n'), ((4080, 4086), 'time.time', 'time', ([], {}), '()\n', (4084, 4086), False, 'from time import time\n'), ((4143, 4251), 'dynesty.NestedSampler', 'NestedSampler', (['loglikelihood_function', 'prior_function', 'ndims'], {'bound': '"""multi"""', 'sample': '"""rwalk"""', 'nlive': 'nlive'}), "(loglikelihood_function, prior_function, ndims, bound='multi',\n sample='rwalk', nlive=nlive)\n", (4156, 4251), False, 'from dynesty import NestedSampler\n'), ((4359, 4365), 'time.time', 'time', ([], {}), '()\n', (4363, 4365), False, 'from time import time\n'), ((2006, 2026), 'numpy.shape', 'np.shape', (['flat_prior'], {}), '(flat_prior)\n', (2014, 2026), True, 'import numpy as np\n'), ((3026, 3054), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(2 * S + 1)'], {}), '(0, 1, 2 * S + 1)\n', (3037, 3054), True, 'import numpy as np\n'), ((883, 898), 'numpy.any', 'np.any', (['(mu <= 0)'], {}), '(mu <= 0)\n', (889, 898), True, 'import numpy as np\n'), ((902, 917), 'numpy.any', 'np.any', (['(mu >= 1)'], {}), '(mu >= 1)\n', (908, 917), True, 'import numpy as np\n'), ((2929, 2940), 'numpy.shape', 'np.shape', (['y'], {}), '(y)\n', (2937, 2940), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib
def normalize(v, p=2):
''' project vector on to unit L-p ball. '''
norm=np.linalg.norm(v, ord=p)
if norm==0:
norm=np.finfo(v.dtype).eps
return v/norm
def matplotlib_init():
''' Initialize matplotlib parameters for pretty figures. '''
matplotlib.rcParams['lines.linewidth'] = 2
matplotlib.rcParams['axes.grid'] = True
matplotlib.rcParams['grid.linestyle'] = '--'
matplotlib.rcParams['grid.color'] = '#aaaaaa'
matplotlib.rcParams['xtick.major.size'] = 0
matplotlib.rcParams['ytick.major.size'] = 0
matplotlib.rcParams['xtick.labelsize'] = 12
matplotlib.rcParams['ytick.labelsize'] = 12
matplotlib.rcParams['axes.labelsize'] = 12
matplotlib.rcParams['axes.titlesize'] = 12
matplotlib.rcParams['legend.fontsize'] = 14
# matplotlib.rcParams['legend.frameon'] = False
matplotlib.rcParams['figure.subplot.top'] = 0.85
matplotlib.rcParams['axes.facecolor'] = 'white'
matplotlib.rcParams['axes.linewidth'] = 0.8
matplotlib.rcParams['figure.dpi'] = 600 | [
"numpy.finfo",
"numpy.linalg.norm"
] | [((118, 142), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {'ord': 'p'}), '(v, ord=p)\n', (132, 142), True, 'import numpy as np\n'), ((172, 189), 'numpy.finfo', 'np.finfo', (['v.dtype'], {}), '(v.dtype)\n', (180, 189), True, 'import numpy as np\n')] |
"""
Script for extracting features stats for featurization for RL experiment.
Uncomment code fragment in autoascend/combat/rl_scoring.py to generate the observations.txt file.
"""
import base64
import json
import pickle
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
with open('/tmp/vis/observations.txt') as f:
observations = defaultdict(list)
for line in f.readlines():
observation = pickle.loads(base64.b64decode(line))
for k, v in observation.items():
observations[k].append(v)
def plot_column(df, column):
if df[column].dtype == object:
plt.xticks(rotation=45)
try:
sns.histplot(df[column])
except ValueError:
print(f'ValueError when plotting {column}')
except IndexError:
print(f'IndexError when plotting {column}')
def plot_df(df_name, df, max_plots_in_row=10):
nrows = (len(df.columns) + max_plots_in_row - 1) // max_plots_in_row
fig = plt.figure(figsize=(8, 2 * nrows), dpi=80)
fig.suptitle(df_name, fontsize=100)
gridspec = fig.add_gridspec(nrows=nrows, ncols=max_plots_in_row)
for i, c in enumerate(df.columns):
row = i // max_plots_in_row
col = i % max_plots_in_row
ax = fig.add_subplot(gridspec[i:i + 1])
ax.title.set_text(c)
plt.sca(ax)
plot_column(df, c)
plt.tight_layout()
plt.show()
stats = defaultdict(dict)
for k, v in observations.items():
v = np.array(v)
print('----------------------', k, v.shape)
if len(v.shape) > 2:
v = v.transpose((0, 2, 3, 1))
v = v.reshape(-1, v.shape[-1])
print(k, v.shape)
print([np.mean(np.isnan(v[:, i])) for i in range(v.shape[1])])
# plot_df(k, pd.DataFrame(v).sample(10000), 5)
mean, std = np.nanmean(v, axis=0), np.nanstd(v, axis=0)
v_normalized = (v - mean) / std
minv = np.nanmin(v_normalized, axis=0)
print(mean)
print(std)
print(minv)
stats[k]['mean'] = mean.tolist()
stats[k]['std'] = mean.tolist()
stats[k]['min'] = mean.tolist()
if k == 'heur_action_priorities':
for i in range(v_normalized.shape[1]):
v_normalized[:, i][np.isnan(v_normalized[:, i])] = minv[i]
else:
v_normalized[np.isnan(v_normalized)] = 0
# plot_df(k + ' normalized', pd.DataFrame(v_normalized).sample(10000), 5)
print()
with open('/workspace/muzero/rl_features_stats.json', 'w') as f:
json.dump(stats, f, indent=4)
| [
"numpy.nanstd",
"matplotlib.pyplot.xticks",
"seaborn.histplot",
"matplotlib.pyplot.sca",
"base64.b64decode",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.nanmean",
"collections.defaultdict",
"numpy.isnan",
"matplotlib.pyplot.tight_layout",
"numpy.nanmin",
"json.dump",
"matplotlib.pypl... | [((1441, 1458), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (1452, 1458), False, 'from collections import defaultdict\n'), ((397, 414), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (408, 414), False, 'from collections import defaultdict\n'), ((1006, 1048), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 2 * nrows)', 'dpi': '(80)'}), '(figsize=(8, 2 * nrows), dpi=80)\n', (1016, 1048), True, 'import matplotlib.pyplot as plt\n'), ((1397, 1415), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1413, 1415), True, 'import matplotlib.pyplot as plt\n'), ((1420, 1430), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1428, 1430), True, 'import matplotlib.pyplot as plt\n'), ((1503, 1514), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (1511, 1514), True, 'import numpy as np\n'), ((1912, 1943), 'numpy.nanmin', 'np.nanmin', (['v_normalized'], {'axis': '(0)'}), '(v_normalized, axis=0)\n', (1921, 1943), True, 'import numpy as np\n'), ((2479, 2508), 'json.dump', 'json.dump', (['stats', 'f'], {'indent': '(4)'}), '(stats, f, indent=4)\n', (2488, 2508), False, 'import json\n'), ((658, 681), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(45)'}), '(rotation=45)\n', (668, 681), True, 'import matplotlib.pyplot as plt\n'), ((699, 723), 'seaborn.histplot', 'sns.histplot', (['df[column]'], {}), '(df[column])\n', (711, 723), True, 'import seaborn as sns\n'), ((1353, 1364), 'matplotlib.pyplot.sca', 'plt.sca', (['ax'], {}), '(ax)\n', (1360, 1364), True, 'import matplotlib.pyplot as plt\n'), ((1821, 1842), 'numpy.nanmean', 'np.nanmean', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (1831, 1842), True, 'import numpy as np\n'), ((1844, 1864), 'numpy.nanstd', 'np.nanstd', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (1853, 1864), True, 'import numpy as np\n'), ((481, 503), 'base64.b64decode', 'base64.b64decode', (['line'], {}), '(line)\n', (497, 503), False, 'import base64\n'), ((2289, 2311), 'numpy.isnan', 'np.isnan', (['v_normalized'], {}), '(v_normalized)\n', (2297, 2311), True, 'import numpy as np\n'), ((1706, 1723), 'numpy.isnan', 'np.isnan', (['v[:, i]'], {}), '(v[:, i])\n', (1714, 1723), True, 'import numpy as np\n'), ((2218, 2246), 'numpy.isnan', 'np.isnan', (['v_normalized[:, i]'], {}), '(v_normalized[:, i])\n', (2226, 2246), True, 'import numpy as np\n')] |
from node import Node
from collections import deque
from queue import PriorityQueue
import heapq
import numpy as np
import math
######################################
# Workspace
######################################
def isValidWorkspace(pt,r = 1,radiusClearance=0): #To be modified
x,y = pt
#------------------------------------------------------------------------------
# Circle pts
#------------------------------------------------------------------------------
ptInCircle = (x - math.floor(225/r))**2 + (y -math.floor(50/r))**2 - math.floor((25+radiusClearance)/r)**2 <= 0
#--------------------------------------------------------------------------------
# ellipse pts
#--------------------------------------------------------------------------------
ptInEllipse =((x - math.floor(150/r))/math.floor((40+radiusClearance)/r))**2 + ((y-math.floor(100/r))/math.floor((20+radiusClearance)/r))**2 <= 1
#---------------------------------------------------------------------------------
# Non Convex Polygon pts -- Partition nonconvex polygon into two convex regions
#---------------------------------------------------------------------------------
X = np.array([50,75,100,75,25,20,50])/r
Y = 200/r - np.array([150,120,150,185,185,120,150])/r
nonConvexRegion1 = (y-Y[0]) <= ((Y[1]-Y[0])/(X[1]-X[0]))*(x-X[0]) + \
radiusClearance/r * (1+math.sqrt(((Y[1]-Y[0])/(X[1]-X[0]))**2)) and \
(y-Y[1]) <= ((Y[2]-Y[1])/(X[2]-X[1]))*(x-X[1]) + \
radiusClearance/r * (1+math.sqrt(((Y[2]-Y[1])/(X[2]-X[1]))**2)) and \
(y-Y[2]) >= ((Y[3]-Y[2])/(X[3]-X[2]))*(x-X[2]) - \
radiusClearance/r * (1+math.sqrt(((Y[3]-Y[2])/(X[3]-X[2]))**2)) and \
(y-Y[3]) >= ((Y[0]-Y[3])/(X[0]-X[3]))*(x-X[3])
nonConvexRegion2 = (y-Y[3]) >= ((Y[4]-Y[3])/(X[4]-X[3]))*(x-X[3]) - \
radiusClearance/r * (1+math.sqrt(((Y[4]-Y[3])/(X[4]-X[3]))**2)) and \
(y-Y[4]) >= ((Y[5]-Y[4])/(X[5]-X[4]))*(x-X[4]) - \
radiusClearance/r * (1+math.sqrt(((Y[5]-Y[4])/(X[5]-X[4]))**2)) and \
(y-Y[5]) <= ((Y[6]-Y[5])/(X[6]-X[5]))*(x-X[5]) + \
radiusClearance/r * (1+math.sqrt(((Y[6]-Y[5])/(X[6]-X[5]))**2)) and \
(y-Y[6]) <= ((Y[3]-Y[6])/(X[3]-X[6]))*(x-X[6]) #+ \
#radiusClearance/r * (1+math.sqrt(((Y[3]-Y[6])/(X[3]-X[6]))**2))
ptInNonConvex = nonConvexRegion1 or nonConvexRegion2
#--------------------------------------------------------------------------------
# Rhombus pts
#--------------------------------------------------------------------------------
X = np.array([225,200,225,250])/r
Y = 200/r - np.array([40,25,10,25])/r
ptInRhombus = (y-Y[0]) >= ((Y[1]-Y[0])/(X[1]-X[0]))*(x-X[0]) - \
radiusClearance/r * (1+math.sqrt(((Y[1]-Y[0])/(X[1]-X[0]))**2)) and \
(y-Y[1]) <= ((Y[2]-Y[1])/(X[2]-X[1]))*(x-X[1]) + \
radiusClearance/r * (1+math.sqrt(((Y[2]-Y[1])/(X[2]-X[1]))**2)) and \
(y-Y[2]) <= ((Y[3]-Y[2])/(X[3]-X[2]))*(x-X[2]) + \
radiusClearance/r * (1+math.sqrt(((Y[3]-Y[2])/(X[3]-X[2]))**2)) and \
(y-Y[3]) >= ((Y[0]-Y[3])/(X[0]-X[3]))*(x-X[3]) - \
radiusClearance/r * (1+math.sqrt(((Y[0]-Y[3])/(X[0]-X[3]))**2))
#--------------------------------------------------------------------------------
# Tilted Rectangle pts
#--------------------------------------------------------------------------------
X = np.array([95+10*math.cos(math.radians(60)), 95-75*math.cos(math.radians(30))+10*math.cos(math.radians(60)),
95-75*math.cos(math.radians(30)), 95])/r
Y = 200/r - np.array([30+10*math.sin(math.radians(60)), 30+75*math.sin(math.radians(30))+10*math.sin(math.radians(60)),
30+75*math.sin(math.radians(30)), 30])/r
ptInRectangle = (y-Y[0]) >= ((Y[1]-Y[0])/(X[1]-X[0]))*(x-X[0]) - \
radiusClearance/r * (1+math.sqrt(((Y[1]-Y[0])/(X[1]-X[0]))**2)) and \
(y-Y[1]) >= ((Y[2]-Y[1])/(X[2]-X[1]))*(x-X[1]) - \
radiusClearance/r * (1+math.sqrt(((Y[2]-Y[1])/(X[2]-X[1]))**2)) and \
(y-Y[2]) <= ((Y[3]-Y[2])/(X[3]-X[2]))*(x-X[2]) + \
radiusClearance/r * (1+math.sqrt(((Y[3]-Y[2])/(X[3]-X[2]))**2)) and \
(y-Y[3]) <= ((Y[0]-Y[3])/(X[0]-X[3]))*(x-X[3]) + \
radiusClearance/r * (1+math.sqrt(((Y[0]-Y[3])/(X[0]-X[3]))**2))
if(ptInCircle or ptInEllipse or ptInNonConvex or ptInRhombus or ptInRectangle):
return False
return True
# checks whether next action is near an obstacle or ill defined
def isSafe(newState,r=1,radiusClearance = 0):
col = math.floor(300/r)
row = math.floor(200/r)
if(newState[0]< 0 or newState[0]>col or newState[1]<0 or newState[1]>row):
return False
return isValidWorkspace(newState[0:2],r,radiusClearance)
#prints solution path
def printPath(node):
l = []
current = node
while(current):
l.append(current.state)
current = current.parent
return l
def normalize(startPosition,startOrientation,threshDistance=0.5, threshAngle=30):
x,y = startPosition
t = startOrientation
x = round(x/threshDistance)* threshDistance
y = round(y/threshDistance)* threshDistance
t = round(t/threshAngle) * threshAngle
return [x,y,t]
# Calculating the Euclidean distance
def distance(startPosition,goalPosition):
sx,sy = startPosition
gx,gy = goalPosition
return math.sqrt((gx-sx)**2 + (gy-sy)**2)
#generates optimal path for robot
def generatePath(q,startPosition,startOrientation,goalPosition,nodesExplored,threshDistance = 0.5,threshAngle = 30,radiusClearance=0):
#normalize goal and start positions
sx,sy,st = normalize(startPosition,startOrientation,threshDistance,threshAngle)
gx,gy,gt = normalize(goalPosition,0,threshDistance,threshAngle)
#Initializing root node
key = str(sx) + str(sy) #+ str(st)
root = Node(np.array([sx,sy,st]),0.0,0.0,None)
nodesExplored[key] = root
count = 1
heapq.heappush(q,(root.cost,count,root))
while(len(q)>0):
_,_,currentNode = heapq.heappop(q)
if(distance(currentNode.state[0:2],goalPosition)<= 3*1.5):
sol = printPath(currentNode)
return [True,sol]
for theta in range(12):
x,y,t = currentNode.state
newOrientation = math.radians((threshAngle*theta + t)%360)
newPosX = threshDistance*math.cos(newOrientation) + x
newPosY = threshDistance*math.sin(newOrientation) + y
newState = np.array(normalize([newPosX,newPosY],newOrientation,threshDistance,threshAngle))
s = str(newState[0])+str(newState[1]) #+ str(newState[2])
if(s not in nodesExplored):
if(isSafe(newState,1,radiusClearance)):
newCostToCome = currentNode.costToCome + distance([newState[0],newState[1]],[x,y])
newCost = newCostToCome + distance([newState[0],newState[1]],[gx,gy])
newNode = Node(newState,newCost,newCostToCome,currentNode)
nodesExplored[s] = newNode
heapq.heappush(q,(newNode.cost,count,newNode))
count += 1
else:
if(nodesExplored[s].cost > currentNode.costToCome + distance([newState[0],newState[1]],[x,y]) + distance([newState[0],newState[1]],[gx,gy])):
nodesExplored[s].costToCome = currentNode.costToCome + distance([newState[0],newState[1]],[x,y])
nodesExplored[s].cost = nodesExplored[s].costToCome + distance([newState[0],newState[1]],[gx,gy])
nodesExplored[s].parent = currentNode
return [False,None]
if __name__ == "__main__":
nodesExplored = {}
# q = deque()
# q = PriorityQueue()
q = []
startPosition = np.array([295,195])
startOrientation = 0
goalPosition = np.array([5,5])
print(generatePath(q,startPosition,startOrientation,goalPosition,nodesExplored,5,30))
| [
"math.floor",
"math.sqrt",
"math.radians",
"math.cos",
"numpy.array",
"heapq.heappop",
"node.Node",
"heapq.heappush",
"math.sin"
] | [((5882, 5901), 'math.floor', 'math.floor', (['(300 / r)'], {}), '(300 / r)\n', (5892, 5901), False, 'import math\n'), ((5910, 5929), 'math.floor', 'math.floor', (['(200 / r)'], {}), '(200 / r)\n', (5920, 5929), False, 'import math\n'), ((6696, 6738), 'math.sqrt', 'math.sqrt', (['((gx - sx) ** 2 + (gy - sy) ** 2)'], {}), '((gx - sx) ** 2 + (gy - sy) ** 2)\n', (6705, 6738), False, 'import math\n'), ((7263, 7306), 'heapq.heappush', 'heapq.heappush', (['q', '(root.cost, count, root)'], {}), '(q, (root.cost, count, root))\n', (7277, 7306), False, 'import heapq\n'), ((9147, 9167), 'numpy.array', 'np.array', (['[295, 195]'], {}), '([295, 195])\n', (9155, 9167), True, 'import numpy as np\n'), ((9211, 9227), 'numpy.array', 'np.array', (['[5, 5]'], {}), '([5, 5])\n', (9219, 9227), True, 'import numpy as np\n'), ((1289, 1328), 'numpy.array', 'np.array', (['[50, 75, 100, 75, 25, 20, 50]'], {}), '([50, 75, 100, 75, 25, 20, 50])\n', (1297, 1328), True, 'import numpy as np\n'), ((3285, 3315), 'numpy.array', 'np.array', (['[225, 200, 225, 250]'], {}), '([225, 200, 225, 250])\n', (3293, 3315), True, 'import numpy as np\n'), ((7179, 7201), 'numpy.array', 'np.array', (['[sx, sy, st]'], {}), '([sx, sy, st])\n', (7187, 7201), True, 'import numpy as np\n'), ((7357, 7373), 'heapq.heappop', 'heapq.heappop', (['q'], {}), '(q)\n', (7370, 7373), False, 'import heapq\n'), ((1341, 1386), 'numpy.array', 'np.array', (['[150, 120, 150, 185, 185, 120, 150]'], {}), '([150, 120, 150, 185, 185, 120, 150])\n', (1349, 1386), True, 'import numpy as np\n'), ((3331, 3357), 'numpy.array', 'np.array', (['[40, 25, 10, 25]'], {}), '([40, 25, 10, 25])\n', (3339, 3357), True, 'import numpy as np\n'), ((7625, 7670), 'math.radians', 'math.radians', (['((threshAngle * theta + t) % 360)'], {}), '((threshAngle * theta + t) % 360)\n', (7637, 7670), False, 'import math\n'), ((598, 636), 'math.floor', 'math.floor', (['((25 + radiusClearance) / r)'], {}), '((25 + radiusClearance) / r)\n', (608, 636), False, 'import math\n'), ((903, 941), 'math.floor', 'math.floor', (['((40 + radiusClearance) / r)'], {}), '((40 + radiusClearance) / r)\n', (913, 941), False, 'import math\n'), ((967, 1005), 'math.floor', 'math.floor', (['((20 + radiusClearance) / r)'], {}), '((20 + radiusClearance) / r)\n', (977, 1005), False, 'import math\n'), ((7704, 7728), 'math.cos', 'math.cos', (['newOrientation'], {}), '(newOrientation)\n', (7712, 7728), False, 'import math\n'), ((7771, 7795), 'math.sin', 'math.sin', (['newOrientation'], {}), '(newOrientation)\n', (7779, 7795), False, 'import math\n'), ((8307, 8358), 'node.Node', 'Node', (['newState', 'newCost', 'newCostToCome', 'currentNode'], {}), '(newState, newCost, newCostToCome, currentNode)\n', (8311, 8358), False, 'from node import Node\n'), ((8424, 8473), 'heapq.heappush', 'heapq.heappush', (['q', '(newNode.cost, count, newNode)'], {}), '(q, (newNode.cost, count, newNode))\n', (8438, 8473), False, 'import heapq\n'), ((547, 566), 'math.floor', 'math.floor', (['(225 / r)'], {}), '(225 / r)\n', (557, 566), False, 'import math\n'), ((575, 593), 'math.floor', 'math.floor', (['(50 / r)'], {}), '(50 / r)\n', (585, 593), False, 'import math\n'), ((884, 903), 'math.floor', 'math.floor', (['(150 / r)'], {}), '(150 / r)\n', (894, 903), False, 'import math\n'), ((948, 967), 'math.floor', 'math.floor', (['(100 / r)'], {}), '(100 / r)\n', (958, 967), False, 'import math\n'), ((1550, 1597), 'math.sqrt', 'math.sqrt', (['(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)'], {}), '(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)\n', (1559, 1597), False, 'import math\n'), ((1766, 1813), 'math.sqrt', 'math.sqrt', (['(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)'], {}), '(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)\n', (1775, 1813), False, 'import math\n'), ((1982, 2029), 'math.sqrt', 'math.sqrt', (['(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)'], {}), '(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)\n', (1991, 2029), False, 'import math\n'), ((2305, 2352), 'math.sqrt', 'math.sqrt', (['(((Y[4] - Y[3]) / (X[4] - X[3])) ** 2)'], {}), '(((Y[4] - Y[3]) / (X[4] - X[3])) ** 2)\n', (2314, 2352), False, 'import math\n'), ((2521, 2568), 'math.sqrt', 'math.sqrt', (['(((Y[5] - Y[4]) / (X[5] - X[4])) ** 2)'], {}), '(((Y[5] - Y[4]) / (X[5] - X[4])) ** 2)\n', (2530, 2568), False, 'import math\n'), ((2737, 2784), 'math.sqrt', 'math.sqrt', (['(((Y[6] - Y[5]) / (X[6] - X[5])) ** 2)'], {}), '(((Y[6] - Y[5]) / (X[6] - X[5])) ** 2)\n', (2746, 2784), False, 'import math\n'), ((3516, 3563), 'math.sqrt', 'math.sqrt', (['(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)'], {}), '(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)\n', (3525, 3563), False, 'import math\n'), ((3724, 3771), 'math.sqrt', 'math.sqrt', (['(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)'], {}), '(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)\n', (3733, 3771), False, 'import math\n'), ((3932, 3979), 'math.sqrt', 'math.sqrt', (['(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)'], {}), '(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)\n', (3941, 3979), False, 'import math\n'), ((4140, 4187), 'math.sqrt', 'math.sqrt', (['(((Y[0] - Y[3]) / (X[0] - X[3])) ** 2)'], {}), '(((Y[0] - Y[3]) / (X[0] - X[3])) ** 2)\n', (4149, 4187), False, 'import math\n'), ((4961, 5008), 'math.sqrt', 'math.sqrt', (['(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)'], {}), '(((Y[1] - Y[0]) / (X[1] - X[0])) ** 2)\n', (4970, 5008), False, 'import math\n'), ((5171, 5218), 'math.sqrt', 'math.sqrt', (['(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)'], {}), '(((Y[2] - Y[1]) / (X[2] - X[1])) ** 2)\n', (5180, 5218), False, 'import math\n'), ((5381, 5428), 'math.sqrt', 'math.sqrt', (['(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)'], {}), '(((Y[3] - Y[2]) / (X[3] - X[2])) ** 2)\n', (5390, 5428), False, 'import math\n'), ((5591, 5638), 'math.sqrt', 'math.sqrt', (['(((Y[0] - Y[3]) / (X[0] - X[3])) ** 2)'], {}), '(((Y[0] - Y[3]) / (X[0] - X[3])) ** 2)\n', (5600, 5638), False, 'import math\n'), ((4453, 4469), 'math.radians', 'math.radians', (['(60)'], {}), '(60)\n', (4465, 4469), False, 'import math\n'), ((4517, 4533), 'math.radians', 'math.radians', (['(60)'], {}), '(60)\n', (4529, 4533), False, 'import math\n'), ((4579, 4595), 'math.radians', 'math.radians', (['(30)'], {}), '(30)\n', (4591, 4595), False, 'import math\n'), ((4487, 4503), 'math.radians', 'math.radians', (['(30)'], {}), '(30)\n', (4499, 4503), False, 'import math\n'), ((4647, 4663), 'math.radians', 'math.radians', (['(60)'], {}), '(60)\n', (4659, 4663), False, 'import math\n'), ((4711, 4727), 'math.radians', 'math.radians', (['(60)'], {}), '(60)\n', (4723, 4727), False, 'import math\n'), ((4773, 4789), 'math.radians', 'math.radians', (['(30)'], {}), '(30)\n', (4785, 4789), False, 'import math\n'), ((4681, 4697), 'math.radians', 'math.radians', (['(30)'], {}), '(30)\n', (4693, 4697), False, 'import math\n')] |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
import pickle as pk
import plotly.graph_objects as go
import numpy as np
from sklearn.preprocessing import minmax_scale
from Saving import *
from tsmoothie.smoother import *
from block_dev import *
fc = pd.read_csv('full_corpus.csv', index_col='Unnamed: 0')
pypl = fc.loc[(fc.Comp == 'pypl') & (fc.message != 'n')].iloc[-5000:]
embs = openPk('full_embs.pkl')
embs = embs[5]
t_vecs = openPk('topNg_vecs.pkl')
t_vecs = t_vecs[5]
t_vecs_plot = openPk('top_vecs4plot.pkl')
comps = ['aapl', 'abb', 'amzn', 'aon', 'bmy', 'cern', 'csco', 'ebay', 'hsbc', 'jpm', 'mmm', 'nflx', 'pypl']
tg_words = pd.read_csv('topic_words_wGram.csv', index_col='Topic').iloc[1:]
tNg_words = pd.read_csv('topic_words_noGram.csv', index_col='Topic').iloc[1:]
fig = go.Figure(data=go.Scatter(x=pypl['createdAt'], y=pypl['deviation'], hovertext=pypl['message']))
Deviation = [
dbc.CardHeader(html.H5('Measuring average devtiation over time - PayPal')),
dbc.CardBody([
dbc.Row([
dcc.Graph(id='topic-deviation', figure = fig)
]),
dbc.Row([
dbc.Col([
html.Div(id='wind-num', children='hdbdhbs'),
dcc.Slider(id='wind-slider', min = 2, max = 100, step=1, value=4)
])
])
])
]
Top_vec_comp = [
dbc.CardHeader(html.H5('Comparing Topic Vectors')),
dbc.CardBody([
dbc.Row([
dbc.Col(
dcc.Dropdown(
id = 't_set1',
options = [
{'label': 'No-Grams 2D', 'value': 'ng2D'},
{'label': 'No-Grams 5D r-dims', 'value': 'ng5D'},
{'label': 'With-Grams 2D', 'value': 'g2D'},
{'label': 'With-Grams 5D r-dims', 'value': 'g5D'},
],
placeholder = 'Graph 1',
value = 'ng2D',
), width={'size': 3}
),
dbc.Col(
dcc.Dropdown(
id = 't_set2',
options = [
{'label': 'No-Grams 2D', 'value': 'ng2D'},
{'label': 'No-Grams 5D r-dims', 'value': 'ng5D'},
{'label': 'With-Grams 2D', 'value': 'g2D'},
{'label': 'With-Grams 5D r-dims', 'value': 'g5D'},
],
placeholder = 'Graph 1',
value = 'ng5D',
), width={'size': 3}
)
]),
dbc.Row([
dbc.Col(
dcc.Graph(id='t_graph1')
),
dbc.Col(
dcc.Graph(id='t_graph2')
)
])
])
]
dev_from_start = [
dbc.CardHeader(html.H5('Measuring deviation from start of chat')),
dbc.CardBody([
dbc.Row([
dcc.Graph(id='dev_s_g')
]),
dbc.Row([
dbc.Col([
html.Div(id='window-size', children='Enter starting window size:'),
dcc.Slider(id='dev-wind-slider', min = 1, max = 100, step=1, value=4)
]),
dbc.Col(
dcc.Dropdown(
id = 'ds_comp',
options = [{'label': i, 'value': i} for i in comps],
placeholder = 'Company',
value = 'aapl',
), width={'size': 3}
)
])
])
]
dev_from_main = [
dbc.CardHeader(html.H5('Measuring deviation from main topic')),
dbc.CardBody([
dbc.Row([
dcc.Graph(id='dev_m_g')
]),
dbc.Row([
dbc.Col(
dcc.Dropdown(
id = 'dm_comp',
options = [{'label': i, 'value': i} for i in comps],
placeholder = 'Company',
value = 'aapl'
), width={'size': 3}
),
dbc.Col(
dcc.Dropdown(
id = 'smoother',
options = [
{'label': 'No Smoothing', 'value': 'n'},
{'label': 'Exponential', 'value': 'exp'},
{'label': 'Convolutional', 'value': 'conv'},
{'label': 'Kalman', 'value': 'k'}
],
placeholder = 'Smoother',
value = 'n'
), width={'size': 3, 'offset': 3}
)
]),
dbc.Row(
dbc.Col(
dcc.Markdown(id='stats', style={'white-space': 'pre-wrap'})
)
)
])
]
block_devs = [
dbc.CardHeader(html.H5('Deviation Scores per Block')),
dbc.CardBody([
dbc.Row([
dcc.Graph(id='block_dev')
]),
dbc.Row([
dbc.Col([
html.Div(id='b_wind', children='Enter block window size:'),
dcc.Slider(id='b-wind-slider', min = 1, max = 200, step=2, value=50),
html.Div(id='b-disc', children='Discount factor:'),
dcc.Slider('b_disc_f', min=0, max = 1, step=0.02, value=0.3)
]),
dbc.Col([
dcc.Dropdown(
id = 'bd_comp',
options = [{'label': i, 'value': i} for i in comps],
placeholder = 'Company',
value = ['aapl'],
multi = True
),
dcc.Checklist(
id='auto',
options = [{'label': 'Auto-Block', 'value': 'ab'}],
value = ['ab']
)], width={'size': 3}
)
]),
dbc.Row([
dbc.Col(
dcc.Markdown(id='block_stats', style={'white-space': 'pre-wrap'})
),
dbc.Col(
dcc.Dropdown(
id = 'block_smoother',
options = [
{'label': 'No Smoothing', 'value': 'n'},
{'label': 'Convolutional', 'value': 'conv'},
{'label': 'Kalman', 'value': 'k'}
],
placeholder = 'Smoother',
value = 'n'
), width={'size': 3, 'offset': 3})
])
])
]
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(children=[
html.H1('Topic Modelling', style={'align': 'center'}),
dbc.Container([
dbc.Row([
dbc.Col(dbc.Card(Deviation))
], style={'marginTop': 10}),
dbc.Row([
dbc.Col(dbc.Card(Top_vec_comp))
], style={'marginTop': 10}),
dbc.Row([
dbc.Col(dbc.Card(dev_from_start))
], style={'marginTop': 10}),
dbc.Row([
dbc.Col(dbc.Card(dev_from_main))
], style={'marginTop': 10}),
dbc.Row([
dbc.Col(dbc.Card(block_devs))
], style={'marginTop': 10})
])
])
# Block-level Deviation
@app.callback(
Output('b-wind-slider', 'value'),
[Input('auto', 'value'), Input('bd_comp', 'value')]
)
def check(val, comps):
if val == ['ab']:
winds = []
for comp in comps:
our_df = fc.loc[(fc.Comp == comp) & (fc.t2v != 'n')]
_, wind = split_df_auto(our_df, 0.05)
winds.append(wind)
return max(winds)
return 50
@app.callback(
Output('b-disc', 'children'),
[Input('b_disc_f', 'value')]
)
def show_df(val):
return 'Enter discount size: ' + str(val)
@app.callback(
Output('b_wind', 'children'),
[Input('b-wind-slider', 'value')]
)
def show_bs(w):
return 'Block Size: {} hours'.format(w)
@app.callback(
[Output('block_dev', 'figure'), Output('block_stats', 'children')],
[Input('bd_comp', 'value'), Input('b-wind-slider', 'value'), Input('block_smoother', 'value'), Input('b_disc_f', 'value')]
)
def block_main(comps, wind, s, disc_f):
fig = go.Figure()
stats = ''
main_ts = []
for comp in comps:
main_top, stat = get_block_devs(fig, comp, wind, s, disc_f)
main_ts.append(main_top)
stats += stat
fig.update_layout(
title="Deviation per block for {}".format(', '.join(comps)),
xaxis_title="Block Number",
yaxis_title="Deviation",
legend_title="Legend"
)
return fig, stats
# Dev from main callbacks
@app.callback(
Output('dev_m_g', 'figure'),
Output('stats', 'children'),
[Input('dm_comp', 'value'), Input('smoother', 'value')]
)
def dev_from_main(comp, s):
our_df = fc.loc[(fc.Comp == comp) & (fc.t2v != 'n')]
main_top = our_df['top_Ng'].value_counts().index.values[0]
if main_top == -1:
main_top = our_df['top_Ng'].value_counts().index.values[1]
main_top_vec = t_vecs[main_top, :]
nTops = t_vecs.shape[0]
main_vec = t_vecs[main_top, :]
dist_dict = {}
dist_dict[-1] = 0
for i in range(nTops):
cur_top = t_vecs[i, :]
similarity = np.linalg.norm(cur_top - main_vec)
dist_dict[i] = similarity
dists = our_df['top_Ng'].apply(lambda x: dist_dict[x])
if s == 'exp':
smoother = ExponentialSmoother(window_len=20, alpha=0.1)
smoother.smooth(dists)
dists = smoother.smooth_data[0]
if s == 'conv':
smoother = ConvolutionSmoother(window_len=20, window_type='ones')
smoother.smooth(dists)
dists = smoother.smooth_data[0]
if s == 'k':
smoother = KalmanSmoother(component='level_trend',
component_noise={'level':0.1, 'trend':0.1})
smoother.smooth(dists)
dists = smoother.smooth_data[0]
fig = go.Figure(data=go.Scatter(x=our_df['createdAt'], y=dists, hovertext=our_df['message']))
max_dist, min_dist = dists.max(), dists.min()
dists_norm = (dists - min_dist) / (max_dist - min_dist)
score = 1 - np.mean(dists_norm)
topic_words = tNg_words['Words'].iloc[main_top]
topic_words = ', '.join(topic_words.split(';'))
desc = '**Main topic:** {} \n**Topic words:** {} \n**Score:** {}'.format(str(main_top), topic_words, str(score))
return fig, desc
# Dev from start callbacks
@app.callback(
Output('window-size', 'children'),
[Input('dev-wind-slider', 'value')]
)
def set_wind_text(val):
return "Starting window size: {}".format(str(val))
@app.callback(
Output('dev_s_g', 'figure'),
[Input('dev-wind-slider', 'value'), Input('ds_comp', 'value')]
)
def plot_dFs(wind, comp):
our_df = fc.loc[(fc.Comp == comp) & (fc.t2v != 'n')]
inds = our_df.index.values
nd = embs.shape[1]
# get first average of first n messages for starting point
firstInds = inds[:wind]
start_vec = np.zeros(nd)
for i in firstInds:
start_vec += embs[i, :]
start_vec /= wind
dists = []
dates = []
msg = []
for i in inds[wind:]:
dist_vec = embs[i,:] - start_vec
dists.append(np.linalg.norm(dist_vec))
dates.append(fc['createdAt'].iloc[i])
msg.append(fc['message'].iloc[i])
fig = go.Figure(data=go.Scatter(x=dates, y=dists, hovertext=msg))
return fig
# comparing t-vecs callbacks
@app.callback(
Output('t_graph1', 'figure'),
[Input('t_set1', 'value')]
)
def plot_g1(val):
switcher = {'ng2D': t_vecs_plot['ng'][2],
'ng5D': t_vecs_plot['ng'][5],
'g2D': t_vecs_plot['g'][2],
'g5D': t_vecs_plot['g'][5]}
t_switcher = {'ng2D': tNg_words,
'ng5D': tNg_words,
'g2D': tg_words,
'g5D': tg_words}
df = pd.DataFrame(data=switcher[val], columns=['x', 'y'])
fig = go.Figure(data=go.Scatter(x=df['x'], y=df['y'], hovertext=t_switcher[val].Words, mode='markers'))
return fig
@app.callback(
Output('t_graph2', 'figure'),
[Input('t_set2', 'value')]
)
def plot_g2(val):
switcher = {'ng2D': t_vecs_plot['ng'][2],
'ng5D': t_vecs_plot['ng'][5],
'g2D': t_vecs_plot['g'][2],
'g5D': t_vecs_plot['g'][5]}
t_switcher = {'ng2D': tNg_words,
'ng5D': tNg_words,
'g2D': tg_words,
'g5D': tg_words}
df = pd.DataFrame(data=switcher[val], columns=['x', 'y'])
fig = go.Figure(data=go.Scatter(x=df['x'], y=df['y'], hovertext=t_switcher[val].Words, mode='markers'))
return fig
# paypal plot callbacks
@app.callback(
Output('wind-num', 'children'),
[Input('wind-slider', 'value')]
)
def show_num(w):
return 'Window Size: {}'.format(str(w))
@app.callback(
Output('topic-deviation', 'figure'),
[Input('wind-slider', 'value')]
)
def plot_deviation(window):
devs = []
inds = pypl.index.values
last_embs = np.zeros((window, embs.shape[1]))
last_devs = np.zeros(window)
rng = range(len(inds))
devs = []
for i in rng:
avg_dev = np.mean(last_devs)
dev = np.linalg.norm(embs[i, :] - last_embs[(i-1)%window, :])
last_embs[i%window, :] = embs[i,:]
last_devs[i%window] = dev
devs.append((dev-avg_dev)/(avg_dev+1))
fig = go.Figure(data=go.Scatter(x=pypl['createdAt'], y=devs, hovertext=pypl['message']))
fig.update_layout(title_text='Topic Deviation with window size: {}'.format(str(window)),
title_x=0.5,
yaxis_title='Deviation')
return fig
if __name__ == '__main__':
app.run_server(debug=True)
| [
"pandas.read_csv",
"dash.dependencies.Input",
"numpy.linalg.norm",
"dash_html_components.Div",
"dash.Dash",
"numpy.mean",
"dash.dependencies.Output",
"dash_html_components.H5",
"plotly.graph_objects.Scatter",
"dash_bootstrap_components.Card",
"pandas.DataFrame",
"dash_core_components.Checklist... | [((427, 481), 'pandas.read_csv', 'pd.read_csv', (['"""full_corpus.csv"""'], {'index_col': '"""Unnamed: 0"""'}), "('full_corpus.csv', index_col='Unnamed: 0')\n", (438, 481), True, 'import pandas as pd\n'), ((6492, 6556), 'dash.Dash', 'dash.Dash', (['__name__'], {'external_stylesheets': '[dbc.themes.BOOTSTRAP]'}), '(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])\n', (6501, 6556), False, 'import dash\n'), ((7223, 7255), 'dash.dependencies.Output', 'Output', (['"""b-wind-slider"""', '"""value"""'], {}), "('b-wind-slider', 'value')\n", (7229, 7255), False, 'from dash.dependencies import Input, Output, State\n'), ((7611, 7639), 'dash.dependencies.Output', 'Output', (['"""b-disc"""', '"""children"""'], {}), "('b-disc', 'children')\n", (7617, 7639), False, 'from dash.dependencies import Input, Output, State\n'), ((7759, 7787), 'dash.dependencies.Output', 'Output', (['"""b_wind"""', '"""children"""'], {}), "('b_wind', 'children')\n", (7765, 7787), False, 'from dash.dependencies import Input, Output, State\n'), ((8156, 8167), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (8165, 8167), True, 'import plotly.graph_objects as go\n'), ((8612, 8639), 'dash.dependencies.Output', 'Output', (['"""dev_m_g"""', '"""figure"""'], {}), "('dev_m_g', 'figure')\n", (8618, 8639), False, 'from dash.dependencies import Input, Output, State\n'), ((8645, 8672), 'dash.dependencies.Output', 'Output', (['"""stats"""', '"""children"""'], {}), "('stats', 'children')\n", (8651, 8672), False, 'from dash.dependencies import Input, Output, State\n'), ((10407, 10440), 'dash.dependencies.Output', 'Output', (['"""window-size"""', '"""children"""'], {}), "('window-size', 'children')\n", (10413, 10440), False, 'from dash.dependencies import Input, Output, State\n'), ((10925, 10937), 'numpy.zeros', 'np.zeros', (['nd'], {}), '(nd)\n', (10933, 10937), True, 'import numpy as np\n'), ((10583, 10610), 'dash.dependencies.Output', 'Output', (['"""dev_s_g"""', '"""figure"""'], {}), "('dev_s_g', 'figure')\n", (10589, 10610), False, 'from dash.dependencies import Input, Output, State\n'), ((11818, 11870), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'switcher[val]', 'columns': "['x', 'y']"}), "(data=switcher[val], columns=['x', 'y'])\n", (11830, 11870), True, 'import pandas as pd\n'), ((11396, 11424), 'dash.dependencies.Output', 'Output', (['"""t_graph1"""', '"""figure"""'], {}), "('t_graph1', 'figure')\n", (11402, 11424), False, 'from dash.dependencies import Input, Output, State\n'), ((12437, 12489), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'switcher[val]', 'columns': "['x', 'y']"}), "(data=switcher[val], columns=['x', 'y'])\n", (12449, 12489), True, 'import pandas as pd\n'), ((12015, 12043), 'dash.dependencies.Output', 'Output', (['"""t_graph2"""', '"""figure"""'], {}), "('t_graph2', 'figure')\n", (12021, 12043), False, 'from dash.dependencies import Input, Output, State\n'), ((12659, 12689), 'dash.dependencies.Output', 'Output', (['"""wind-num"""', '"""children"""'], {}), "('wind-num', 'children')\n", (12665, 12689), False, 'from dash.dependencies import Input, Output, State\n'), ((12972, 13005), 'numpy.zeros', 'np.zeros', (['(window, embs.shape[1])'], {}), '((window, embs.shape[1]))\n', (12980, 13005), True, 'import numpy as np\n'), ((13022, 13038), 'numpy.zeros', 'np.zeros', (['window'], {}), '(window)\n', (13030, 13038), True, 'import numpy as np\n'), ((12810, 12845), 'dash.dependencies.Output', 'Output', (['"""topic-deviation"""', '"""figure"""'], {}), "('topic-deviation', 'figure')\n", (12816, 12845), False, 'from dash.dependencies import Input, Output, State\n'), ((813, 868), 'pandas.read_csv', 'pd.read_csv', (['"""topic_words_wGram.csv"""'], {'index_col': '"""Topic"""'}), "('topic_words_wGram.csv', index_col='Topic')\n", (824, 868), True, 'import pandas as pd\n'), ((890, 946), 'pandas.read_csv', 'pd.read_csv', (['"""topic_words_noGram.csv"""'], {'index_col': '"""Topic"""'}), "('topic_words_noGram.csv', index_col='Topic')\n", (901, 946), True, 'import pandas as pd\n'), ((978, 1057), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': "pypl['createdAt']", 'y': "pypl['deviation']", 'hovertext': "pypl['message']"}), "(x=pypl['createdAt'], y=pypl['deviation'], hovertext=pypl['message'])\n", (988, 1057), True, 'import plotly.graph_objects as go\n'), ((1093, 1151), 'dash_html_components.H5', 'html.H5', (['"""Measuring average devtiation over time - PayPal"""'], {}), "('Measuring average devtiation over time - PayPal')\n", (1100, 1151), True, 'import dash_html_components as html\n'), ((1516, 1550), 'dash_html_components.H5', 'html.H5', (['"""Comparing Topic Vectors"""'], {}), "('Comparing Topic Vectors')\n", (1523, 1550), True, 'import dash_html_components as html\n'), ((2947, 2996), 'dash_html_components.H5', 'html.H5', (['"""Measuring deviation from start of chat"""'], {}), "('Measuring deviation from start of chat')\n", (2954, 2996), True, 'import dash_html_components as html\n'), ((3660, 3706), 'dash_html_components.H5', 'html.H5', (['"""Measuring deviation from main topic"""'], {}), "('Measuring deviation from main topic')\n", (3667, 3706), True, 'import dash_html_components as html\n'), ((4841, 4878), 'dash_html_components.H5', 'html.H5', (['"""Deviation Scores per Block"""'], {}), "('Deviation Scores per Block')\n", (4848, 4878), True, 'import dash_html_components as html\n'), ((7262, 7284), 'dash.dependencies.Input', 'Input', (['"""auto"""', '"""value"""'], {}), "('auto', 'value')\n", (7267, 7284), False, 'from dash.dependencies import Input, Output, State\n'), ((7286, 7311), 'dash.dependencies.Input', 'Input', (['"""bd_comp"""', '"""value"""'], {}), "('bd_comp', 'value')\n", (7291, 7311), False, 'from dash.dependencies import Input, Output, State\n'), ((7646, 7672), 'dash.dependencies.Input', 'Input', (['"""b_disc_f"""', '"""value"""'], {}), "('b_disc_f', 'value')\n", (7651, 7672), False, 'from dash.dependencies import Input, Output, State\n'), ((7794, 7825), 'dash.dependencies.Input', 'Input', (['"""b-wind-slider"""', '"""value"""'], {}), "('b-wind-slider', 'value')\n", (7799, 7825), False, 'from dash.dependencies import Input, Output, State\n'), ((7910, 7939), 'dash.dependencies.Output', 'Output', (['"""block_dev"""', '"""figure"""'], {}), "('block_dev', 'figure')\n", (7916, 7939), False, 'from dash.dependencies import Input, Output, State\n'), ((7941, 7974), 'dash.dependencies.Output', 'Output', (['"""block_stats"""', '"""children"""'], {}), "('block_stats', 'children')\n", (7947, 7974), False, 'from dash.dependencies import Input, Output, State\n'), ((7982, 8007), 'dash.dependencies.Input', 'Input', (['"""bd_comp"""', '"""value"""'], {}), "('bd_comp', 'value')\n", (7987, 8007), False, 'from dash.dependencies import Input, Output, State\n'), ((8009, 8040), 'dash.dependencies.Input', 'Input', (['"""b-wind-slider"""', '"""value"""'], {}), "('b-wind-slider', 'value')\n", (8014, 8040), False, 'from dash.dependencies import Input, Output, State\n'), ((8042, 8074), 'dash.dependencies.Input', 'Input', (['"""block_smoother"""', '"""value"""'], {}), "('block_smoother', 'value')\n", (8047, 8074), False, 'from dash.dependencies import Input, Output, State\n'), ((8076, 8102), 'dash.dependencies.Input', 'Input', (['"""b_disc_f"""', '"""value"""'], {}), "('b_disc_f', 'value')\n", (8081, 8102), False, 'from dash.dependencies import Input, Output, State\n'), ((9199, 9233), 'numpy.linalg.norm', 'np.linalg.norm', (['(cur_top - main_vec)'], {}), '(cur_top - main_vec)\n', (9213, 9233), True, 'import numpy as np\n'), ((10097, 10116), 'numpy.mean', 'np.mean', (['dists_norm'], {}), '(dists_norm)\n', (10104, 10116), True, 'import numpy as np\n'), ((8679, 8704), 'dash.dependencies.Input', 'Input', (['"""dm_comp"""', '"""value"""'], {}), "('dm_comp', 'value')\n", (8684, 8704), False, 'from dash.dependencies import Input, Output, State\n'), ((8706, 8732), 'dash.dependencies.Input', 'Input', (['"""smoother"""', '"""value"""'], {}), "('smoother', 'value')\n", (8711, 8732), False, 'from dash.dependencies import Input, Output, State\n'), ((10447, 10480), 'dash.dependencies.Input', 'Input', (['"""dev-wind-slider"""', '"""value"""'], {}), "('dev-wind-slider', 'value')\n", (10452, 10480), False, 'from dash.dependencies import Input, Output, State\n'), ((10617, 10650), 'dash.dependencies.Input', 'Input', (['"""dev-wind-slider"""', '"""value"""'], {}), "('dev-wind-slider', 'value')\n", (10622, 10650), False, 'from dash.dependencies import Input, Output, State\n'), ((10652, 10677), 'dash.dependencies.Input', 'Input', (['"""ds_comp"""', '"""value"""'], {}), "('ds_comp', 'value')\n", (10657, 10677), False, 'from dash.dependencies import Input, Output, State\n'), ((11431, 11455), 'dash.dependencies.Input', 'Input', (['"""t_set1"""', '"""value"""'], {}), "('t_set1', 'value')\n", (11436, 11455), False, 'from dash.dependencies import Input, Output, State\n'), ((12050, 12074), 'dash.dependencies.Input', 'Input', (['"""t_set2"""', '"""value"""'], {}), "('t_set2', 'value')\n", (12055, 12074), False, 'from dash.dependencies import Input, Output, State\n'), ((12696, 12725), 'dash.dependencies.Input', 'Input', (['"""wind-slider"""', '"""value"""'], {}), "('wind-slider', 'value')\n", (12701, 12725), False, 'from dash.dependencies import Input, Output, State\n'), ((13116, 13134), 'numpy.mean', 'np.mean', (['last_devs'], {}), '(last_devs)\n', (13123, 13134), True, 'import numpy as np\n'), ((13149, 13208), 'numpy.linalg.norm', 'np.linalg.norm', (['(embs[i, :] - last_embs[(i - 1) % window, :])'], {}), '(embs[i, :] - last_embs[(i - 1) % window, :])\n', (13163, 13208), True, 'import numpy as np\n'), ((12852, 12881), 'dash.dependencies.Input', 'Input', (['"""wind-slider"""', '"""value"""'], {}), "('wind-slider', 'value')\n", (12857, 12881), False, 'from dash.dependencies import Input, Output, State\n'), ((6595, 6648), 'dash_html_components.H1', 'html.H1', (['"""Topic Modelling"""'], {'style': "{'align': 'center'}"}), "('Topic Modelling', style={'align': 'center'})\n", (6602, 6648), True, 'import dash_html_components as html\n'), ((9895, 9966), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': "our_df['createdAt']", 'y': 'dists', 'hovertext': "our_df['message']"}), "(x=our_df['createdAt'], y=dists, hovertext=our_df['message'])\n", (9905, 9966), True, 'import plotly.graph_objects as go\n'), ((11148, 11172), 'numpy.linalg.norm', 'np.linalg.norm', (['dist_vec'], {}), '(dist_vec)\n', (11162, 11172), True, 'import numpy as np\n'), ((11288, 11331), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': 'dates', 'y': 'dists', 'hovertext': 'msg'}), '(x=dates, y=dists, hovertext=msg)\n', (11298, 11331), True, 'import plotly.graph_objects as go\n'), ((11896, 11982), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': "df['x']", 'y': "df['y']", 'hovertext': 't_switcher[val].Words', 'mode': '"""markers"""'}), "(x=df['x'], y=df['y'], hovertext=t_switcher[val].Words, mode=\n 'markers')\n", (11906, 11982), True, 'import plotly.graph_objects as go\n'), ((12515, 12601), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': "df['x']", 'y': "df['y']", 'hovertext': 't_switcher[val].Words', 'mode': '"""markers"""'}), "(x=df['x'], y=df['y'], hovertext=t_switcher[val].Words, mode=\n 'markers')\n", (12525, 12601), True, 'import plotly.graph_objects as go\n'), ((13355, 13421), 'plotly.graph_objects.Scatter', 'go.Scatter', ([], {'x': "pypl['createdAt']", 'y': 'devs', 'hovertext': "pypl['message']"}), "(x=pypl['createdAt'], y=devs, hovertext=pypl['message'])\n", (13365, 13421), True, 'import plotly.graph_objects as go\n'), ((1203, 1246), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""topic-deviation"""', 'figure': 'fig'}), "(id='topic-deviation', figure=fig)\n", (1212, 1246), True, 'import dash_core_components as dcc\n'), ((3048, 3071), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""dev_s_g"""'}), "(id='dev_s_g')\n", (3057, 3071), True, 'import dash_core_components as dcc\n'), ((3758, 3781), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""dev_m_g"""'}), "(id='dev_m_g')\n", (3767, 3781), True, 'import dash_core_components as dcc\n'), ((4713, 4772), 'dash_core_components.Markdown', 'dcc.Markdown', ([], {'id': '"""stats"""', 'style': "{'white-space': 'pre-wrap'}"}), "(id='stats', style={'white-space': 'pre-wrap'})\n", (4725, 4772), True, 'import dash_core_components as dcc\n'), ((4930, 4955), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""block_dev"""'}), "(id='block_dev')\n", (4939, 4955), True, 'import dash_core_components as dcc\n'), ((1627, 1900), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""t_set1"""', 'options': "[{'label': 'No-Grams 2D', 'value': 'ng2D'}, {'label': 'No-Grams 5D r-dims',\n 'value': 'ng5D'}, {'label': 'With-Grams 2D', 'value': 'g2D'}, {'label':\n 'With-Grams 5D r-dims', 'value': 'g5D'}]", 'placeholder': '"""Graph 1"""', 'value': '"""ng2D"""'}), "(id='t_set1', options=[{'label': 'No-Grams 2D', 'value': 'ng2D'\n }, {'label': 'No-Grams 5D r-dims', 'value': 'ng5D'}, {'label':\n 'With-Grams 2D', 'value': 'g2D'}, {'label': 'With-Grams 5D r-dims',\n 'value': 'g5D'}], placeholder='Graph 1', value='ng2D')\n", (1639, 1900), True, 'import dash_core_components as dcc\n'), ((2185, 2458), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""t_set2"""', 'options': "[{'label': 'No-Grams 2D', 'value': 'ng2D'}, {'label': 'No-Grams 5D r-dims',\n 'value': 'ng5D'}, {'label': 'With-Grams 2D', 'value': 'g2D'}, {'label':\n 'With-Grams 5D r-dims', 'value': 'g5D'}]", 'placeholder': '"""Graph 1"""', 'value': '"""ng5D"""'}), "(id='t_set2', options=[{'label': 'No-Grams 2D', 'value': 'ng2D'\n }, {'label': 'No-Grams 5D r-dims', 'value': 'ng5D'}, {'label':\n 'With-Grams 2D', 'value': 'g2D'}, {'label': 'With-Grams 5D r-dims',\n 'value': 'g5D'}], placeholder='Graph 1', value='ng5D')\n", (2197, 2458), True, 'import dash_core_components as dcc\n'), ((2772, 2796), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""t_graph1"""'}), "(id='t_graph1')\n", (2781, 2796), True, 'import dash_core_components as dcc\n'), ((2849, 2873), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""t_graph2"""'}), "(id='t_graph2')\n", (2858, 2873), True, 'import dash_core_components as dcc\n'), ((3347, 3466), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""ds_comp"""', 'options': "[{'label': i, 'value': i} for i in comps]", 'placeholder': '"""Company"""', 'value': '"""aapl"""'}), "(id='ds_comp', options=[{'label': i, 'value': i} for i in comps\n ], placeholder='Company', value='aapl')\n", (3359, 3466), True, 'import dash_core_components as dcc\n'), ((3849, 3968), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""dm_comp"""', 'options': "[{'label': i, 'value': i} for i in comps]", 'placeholder': '"""Company"""', 'value': '"""aapl"""'}), "(id='dm_comp', options=[{'label': i, 'value': i} for i in comps\n ], placeholder='Company', value='aapl')\n", (3861, 3968), True, 'import dash_core_components as dcc\n'), ((4141, 4390), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""smoother"""', 'options': "[{'label': 'No Smoothing', 'value': 'n'}, {'label': 'Exponential', 'value':\n 'exp'}, {'label': 'Convolutional', 'value': 'conv'}, {'label': 'Kalman',\n 'value': 'k'}]", 'placeholder': '"""Smoother"""', 'value': '"""n"""'}), "(id='smoother', options=[{'label': 'No Smoothing', 'value': 'n'\n }, {'label': 'Exponential', 'value': 'exp'}, {'label': 'Convolutional',\n 'value': 'conv'}, {'label': 'Kalman', 'value': 'k'}], placeholder=\n 'Smoother', value='n')\n", (4153, 4390), True, 'import dash_core_components as dcc\n'), ((5911, 5976), 'dash_core_components.Markdown', 'dcc.Markdown', ([], {'id': '"""block_stats"""', 'style': "{'white-space': 'pre-wrap'}"}), "(id='block_stats', style={'white-space': 'pre-wrap'})\n", (5923, 5976), True, 'import dash_core_components as dcc\n'), ((6029, 6236), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""block_smoother"""', 'options': "[{'label': 'No Smoothing', 'value': 'n'}, {'label': 'Convolutional',\n 'value': 'conv'}, {'label': 'Kalman', 'value': 'k'}]", 'placeholder': '"""Smoother"""', 'value': '"""n"""'}), "(id='block_smoother', options=[{'label': 'No Smoothing',\n 'value': 'n'}, {'label': 'Convolutional', 'value': 'conv'}, {'label':\n 'Kalman', 'value': 'k'}], placeholder='Smoother', value='n')\n", (6041, 6236), True, 'import dash_core_components as dcc\n'), ((1317, 1360), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""wind-num"""', 'children': '"""hdbdhbs"""'}), "(id='wind-num', children='hdbdhbs')\n", (1325, 1360), True, 'import dash_html_components as html\n'), ((1378, 1439), 'dash_core_components.Slider', 'dcc.Slider', ([], {'id': '"""wind-slider"""', 'min': '(2)', 'max': '(100)', 'step': '(1)', 'value': '(4)'}), "(id='wind-slider', min=2, max=100, step=1, value=4)\n", (1388, 1439), True, 'import dash_core_components as dcc\n'), ((3140, 3206), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""window-size"""', 'children': '"""Enter starting window size:"""'}), "(id='window-size', children='Enter starting window size:')\n", (3148, 3206), True, 'import dash_html_components as html\n'), ((3224, 3289), 'dash_core_components.Slider', 'dcc.Slider', ([], {'id': '"""dev-wind-slider"""', 'min': '(1)', 'max': '(100)', 'step': '(1)', 'value': '(4)'}), "(id='dev-wind-slider', min=1, max=100, step=1, value=4)\n", (3234, 3289), True, 'import dash_core_components as dcc\n'), ((5024, 5082), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""b_wind"""', 'children': '"""Enter block window size:"""'}), "(id='b_wind', children='Enter block window size:')\n", (5032, 5082), True, 'import dash_html_components as html\n'), ((5100, 5164), 'dash_core_components.Slider', 'dcc.Slider', ([], {'id': '"""b-wind-slider"""', 'min': '(1)', 'max': '(200)', 'step': '(2)', 'value': '(50)'}), "(id='b-wind-slider', min=1, max=200, step=2, value=50)\n", (5110, 5164), True, 'import dash_core_components as dcc\n'), ((5186, 5236), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""b-disc"""', 'children': '"""Discount factor:"""'}), "(id='b-disc', children='Discount factor:')\n", (5194, 5236), True, 'import dash_html_components as html\n'), ((5254, 5312), 'dash_core_components.Slider', 'dcc.Slider', (['"""b_disc_f"""'], {'min': '(0)', 'max': '(1)', 'step': '(0.02)', 'value': '(0.3)'}), "('b_disc_f', min=0, max=1, step=0.02, value=0.3)\n", (5264, 5312), True, 'import dash_core_components as dcc\n'), ((5369, 5502), 'dash_core_components.Dropdown', 'dcc.Dropdown', ([], {'id': '"""bd_comp"""', 'options': "[{'label': i, 'value': i} for i in comps]", 'placeholder': '"""Company"""', 'value': "['aapl']", 'multi': '(True)'}), "(id='bd_comp', options=[{'label': i, 'value': i} for i in comps\n ], placeholder='Company', value=['aapl'], multi=True)\n", (5381, 5502), True, 'import dash_core_components as dcc\n'), ((5643, 5735), 'dash_core_components.Checklist', 'dcc.Checklist', ([], {'id': '"""auto"""', 'options': "[{'label': 'Auto-Block', 'value': 'ab'}]", 'value': "['ab']"}), "(id='auto', options=[{'label': 'Auto-Block', 'value': 'ab'}],\n value=['ab'])\n", (5656, 5735), True, 'import dash_core_components as dcc\n'), ((6708, 6727), 'dash_bootstrap_components.Card', 'dbc.Card', (['Deviation'], {}), '(Deviation)\n', (6716, 6727), True, 'import dash_bootstrap_components as dbc\n'), ((6808, 6830), 'dash_bootstrap_components.Card', 'dbc.Card', (['Top_vec_comp'], {}), '(Top_vec_comp)\n', (6816, 6830), True, 'import dash_bootstrap_components as dbc\n'), ((6911, 6935), 'dash_bootstrap_components.Card', 'dbc.Card', (['dev_from_start'], {}), '(dev_from_start)\n', (6919, 6935), True, 'import dash_bootstrap_components as dbc\n'), ((7012, 7035), 'dash_bootstrap_components.Card', 'dbc.Card', (['dev_from_main'], {}), '(dev_from_main)\n', (7020, 7035), True, 'import dash_bootstrap_components as dbc\n'), ((7112, 7132), 'dash_bootstrap_components.Card', 'dbc.Card', (['block_devs'], {}), '(block_devs)\n', (7120, 7132), True, 'import dash_bootstrap_components as dbc\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 20:47:24 2019
@author: elif.ayvali
"""
import pandas as pd
import numpy as np
import matplotlib.collections as mc
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
def create_uniform_grid(low, high, bins=(10, 10)):
"""Define a uniformly-spaced grid that can be used to discretize a space.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
bins : tuple
Number of bins along each corresponding dimension.
Returns
-------
grid : list of array_like
A list of arrays containing split points for each dimension.
"""
grid = [np.linspace(low[dim], high[dim], bins[dim] + 1)[1:-1] for dim in range(len(bins))]
print(grid)
return grid
def discretize(sample, grid):
"""Discretize a sample as per given grid.
Parameters
----------
sample : array_like
A single sample from the (original) continuous space.
grid : list of array_like
A list of arrays containing split points for each dimension.
Returns
-------
discretized_sample : array_like
A sequence of integers with the same number of dimensions as sample.
"""
return list(int(np.digitize(s, g)) for s, g in zip(sample, grid)) # apply along each dimension
def discretize_tile(sample, grid):
"""Discretize a sample as per given grid.
Parameters
----------
sample : array_like
A single sample from the (original) continuous space.
grid : list of array_like
A list of arrays containing split points for each dimension.
Returns
-------
discretized_sample : array_like
A sequence of integers with the same number of dimensions as sample.
"""
return tuple(int(np.digitize(s, g)) for s, g in zip(sample, grid))
def visualize_samples(samples, discretized_samples, grid, low=None, high=None):
"""Visualize original and discretized samples on a given 2-dimensional grid."""
fig, ax = plt.subplots(figsize=(10, 10))
# Show grid
ax.xaxis.set_major_locator(plt.FixedLocator(grid[0]))
ax.yaxis.set_major_locator(plt.FixedLocator(grid[1]))
ax.grid(True)
# If bounds (low, high) are specified, use them to set axis limits
if low is not None and high is not None:
ax.set_xlim(low[0], high[0])
ax.set_ylim(low[1], high[1])
else:
# Otherwise use first, last grid locations as low, high (for further mapping discretized samples)
low = [splits[0] for splits in grid]
high = [splits[-1] for splits in grid]
# Map each discretized sample (which is really an index) to the center of corresponding grid cell
grid_extended = np.hstack((np.array([low]).T, grid, np.array([high]).T)) # add low and high ends
grid_centers = (grid_extended[:, 1:] + grid_extended[:, :-1]) / 2 # compute center of each grid cell
locs = np.stack(grid_centers[i, discretized_samples[:, i]] for i in range(len(grid))).T # map discretized samples
ax.plot(samples[:, 0], samples[:, 1], 'o') # plot original samples
ax.plot(locs[:, 0], locs[:, 1], 's') # plot discretized samples in mapped locations
ax.add_collection(mc.LineCollection(list(zip(samples, locs)), colors='orange')) # add a line connecting each original-discretized sample
ax.legend(['original', 'discretized'])
def visualize_tilings(tilings):
"""Plot each tiling as a grid."""
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
linestyles = ['-', '--', ':']
legend_lines = []
fig, ax = plt.subplots(figsize=(10, 10))
for i, grid in enumerate(tilings):
for x in grid[0]:
l = ax.axvline(x=x, color=colors[i % len(colors)], linestyle=linestyles[i % len(linestyles)], label=i)
for y in grid[1]:
l = ax.axhline(y=y, color=colors[i % len(colors)], linestyle=linestyles[i % len(linestyles)])
legend_lines.append(l)
ax.grid('off')
ax.legend(legend_lines, ["Tiling #{}".format(t) for t in range(len(legend_lines))], facecolor='white', framealpha=0.9)
ax.set_title("Tilings")
return ax # return Axis object to draw on later, if needed
def create_tiling_grid(low, high, bins=(10, 10), offsets=(0.0, 0.0)):
"""Define a uniformly-spaced grid that can be used for tile-coding a space.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
bins : tuple
Number of bins or tiles along each corresponding dimension.
offsets : tuple
Split points for each dimension should be offset by these values.
Returns
-------
grid : list of array_like
A list of arrays containing split points for each dimension.
Example
-------
if low = [-1.0, -5.0], high = [1.0, 5.0], bins = (10, 10), and offsets = (-0.1, 0.5),
then return a list of 2 NumPy arrays (2 dimensions) each containing the following split points (9 split points per dimension):
[array([-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7]),
array([-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5])]
Notice how the split points for the first dimension are offset by -0.1, and for the second dimension are offset by +0.5.
"""
#grid = [np.linspace(low[dim]+offsets[dim], high[dim]+offsets[dim], bins[dim] + 1)[1:-1] for dim in range(len(bins))]
grid = [np.linspace(low[dim], high[dim], bins[dim] + 1)[1:-1] + offsets[dim] for dim in range(len(bins))]
print("Tiling: [<low>, <high>] / <bins> + (<offset>) => <splits>")
for l, h, b, o, splits in zip(low, high, bins, offsets, grid):
print(" [{}, {}] / {} + ({}) => {}".format(l, h, b, o, splits))
return grid
def create_tilings(low, high, tiling_specs):
"""Define multiple tilings using the provided specifications.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
tiling_specs : list of tuples
A sequence of (bins, offsets) to be passed to create_tiling_grid().
Returns
-------
tilings : list
A list of tilings (grids), each produced by create_tiling_grid().
"""
return [create_tiling_grid(low, high, bins, offsets) for bins, offsets in tiling_specs]
def tile_encode(sample, tilings, flatten=False):
"""Encode given sample using tile-coding.
Parameters
----------
sample : array_like
A single sample from the (original) continuous space.
tilings : list
A list of tilings (grids), each produced by create_tiling_grid().
flatten : bool
If true, flatten the resulting binary arrays into a single long vector.
Returns
-------
encoded_sample : list or array_like
A list of binary vectors, one for each tiling, or flattened into one.
"""
encoded_sample = [discretize_tile(sample, grid) for grid in tilings]
return np.concatenate(encoded_sample) if flatten else encoded_sample
def visualize_encoded_samples(samples, encoded_samples, tilings, low=None, high=None):
"""Visualize samples by activating the respective tiles."""
samples = np.array(samples) # for ease of indexing
# Show tiling grids
ax = visualize_tilings(tilings)
# If bounds (low, high) are specified, use them to set axis limits
if low is not None and high is not None:
ax.set_xlim(low[0], high[0])
ax.set_ylim(low[1], high[1])
else:
# Pre-render (invisible) samples to automatically set reasonable axis limits, and use them as (low, high)
ax.plot(samples[:, 0], samples[:, 1], 'o', alpha=0.0)
low = [ax.get_xlim()[0], ax.get_ylim()[0]]
high = [ax.get_xlim()[1], ax.get_ylim()[1]]
# Map each encoded sample (which is really a list of indices) to the corresponding tiles it belongs to
tilings_extended = [np.hstack((np.array([low]).T, grid, np.array([high]).T)) for grid in tilings] # add low and high ends
tile_centers = [(grid_extended[:, 1:] + grid_extended[:, :-1]) / 2 for grid_extended in tilings_extended] # compute center of each tile
tile_toplefts = [grid_extended[:, :-1] for grid_extended in tilings_extended] # compute topleft of each tile
tile_bottomrights = [grid_extended[:, 1:] for grid_extended in tilings_extended] # compute bottomright of each tile
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
for sample, encoded_sample in zip(samples, encoded_samples):
for i, tile in enumerate(encoded_sample):
# Shade the entire tile with a rectangle
topleft = tile_toplefts[i][0][tile[0]], tile_toplefts[i][1][tile[1]]
bottomright = tile_bottomrights[i][0][tile[0]], tile_bottomrights[i][1][tile[1]]
ax.add_patch(Rectangle(topleft, bottomright[0] - topleft[0], bottomright[1] - topleft[1],
color=colors[i], alpha=0.33))
# In case sample is outside tile bounds, it may not have been highlighted properly
if any(sample < topleft) or any(sample > bottomright):
# So plot a point in the center of the tile and draw a connecting line
cx, cy = tile_centers[i][0][tile[0]], tile_centers[i][1][tile[1]]
ax.add_line(Line2D([sample[0], cx], [sample[1], cy], color=colors[i]))
ax.plot(cx, cy, 's', color=colors[i])
# Finally, plot original samples
ax.plot(samples[:, 0], samples[:, 1], 'o', color='r')
ax.margins(x=0, y=0) # remove unnecessary margins
ax.set_title("Tile-encoded samples")
return ax
class QTable:
"""Simple Q-table."""
def __init__(self, state_size, action_size):
"""Initialize Q-table.
Parameters
----------
state_size : tuple
Number of discrete values along each dimension of state space.
action_size : int
Number of discrete actions in action space.
"""
self.state_size = state_size
self.action_size = action_size
self.q_table = np.zeros(shape=(self.state_size + (self.action_size,)))
print("QTable(): size =", self.q_table.shape)
class TiledQTable:
"""Composite Q-table with an internal tile coding scheme."""
def __init__(self, low, high, tiling_specs, action_size):
"""Create tilings and initialize internal Q-table(s).
Parameters
----------
low : array_like
Lower bounds for each dimension of state space.
high : array_like
Upper bounds for each dimension of state space.
tiling_specs : list of tuples
A sequence of (bins, offsets) to be passed to create_tilings() along with low, high.
action_size : int
Number of discrete actions in action space.
"""
self.tilings = create_tilings(low, high, tiling_specs)
self.state_sizes = [tuple(len(splits)+1 for splits in tiling_grid) for tiling_grid in self.tilings]
self.action_size = action_size
self.q_tables = [QTable(state_size, self.action_size) for state_size in self.state_sizes]
print("TiledQTable(): no. of internal tables = ", len(self.q_tables))
def get(self, state, action):
"""Get Q-value for given <state, action> pair.
Parameters
----------
state : array_like
Vector representing the state in the original continuous space.
action : int
Index of desired action.
Returns
-------
value : float
Q-value of given <state, action> pair, averaged from all internal Q-tables.
"""
# Encode state to get tile indices
encoded_state = tile_encode(state, self.tilings)
# Retrieve q-value for each tiling, and return their average
value = 0.0
for idx, q_table in zip(encoded_state, self.q_tables):
value += q_table.q_table[tuple(idx + (action,))]
value /= len(self.q_tables)
return value
def update(self, state, action, value, alpha=0.1):
"""Soft-update Q-value for given <state, action> pair to value.
Instead of overwriting Q(state, action) with value, perform soft-update:
Q(state, action) = alpha * value + (1.0 - alpha) * Q(state, action)
Parameters
----------
state : array_like
Vector representing the state in the original continuous space.
action : int
Index of desired action.
value : float
Desired Q-value for <state, action> pair.
alpha : float
Update factor to perform soft-update, in [0.0, 1.0] range.
"""
# Encode state to get tile indices
encoded_state = tile_encode(state, self.tilings)
# Update q-value for each tiling by update factor alpha
for idx, q_table in zip(encoded_state, self.q_tables):
value_ = q_table.q_table[tuple(idx + (action,))] # current value
q_table.q_table[tuple(idx + (action,))] = alpha * value + (1.0 - alpha) * value_ | [
"matplotlib.patches.Rectangle",
"numpy.digitize",
"numpy.array",
"numpy.zeros",
"numpy.linspace",
"numpy.concatenate",
"matplotlib.pyplot.FixedLocator",
"matplotlib.lines.Line2D",
"matplotlib.pyplot.subplots"
] | [((2210, 2240), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (2222, 2240), True, 'import matplotlib.pyplot as plt\n'), ((3809, 3839), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (3821, 3839), True, 'import matplotlib.pyplot as plt\n'), ((7599, 7616), 'numpy.array', 'np.array', (['samples'], {}), '(samples)\n', (7607, 7616), True, 'import numpy as np\n'), ((2293, 2318), 'matplotlib.pyplot.FixedLocator', 'plt.FixedLocator', (['grid[0]'], {}), '(grid[0])\n', (2309, 2318), True, 'import matplotlib.pyplot as plt\n'), ((2351, 2376), 'matplotlib.pyplot.FixedLocator', 'plt.FixedLocator', (['grid[1]'], {}), '(grid[1])\n', (2367, 2376), True, 'import matplotlib.pyplot as plt\n'), ((7370, 7400), 'numpy.concatenate', 'np.concatenate', (['encoded_sample'], {}), '(encoded_sample)\n', (7384, 7400), True, 'import numpy as np\n'), ((10547, 10600), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.state_size + (self.action_size,))'}), '(shape=self.state_size + (self.action_size,))\n', (10555, 10600), True, 'import numpy as np\n'), ((839, 886), 'numpy.linspace', 'np.linspace', (['low[dim]', 'high[dim]', '(bins[dim] + 1)'], {}), '(low[dim], high[dim], bins[dim] + 1)\n', (850, 886), True, 'import numpy as np\n'), ((1421, 1438), 'numpy.digitize', 'np.digitize', (['s', 'g'], {}), '(s, g)\n', (1432, 1438), True, 'import numpy as np\n'), ((1974, 1991), 'numpy.digitize', 'np.digitize', (['s', 'g'], {}), '(s, g)\n', (1985, 1991), True, 'import numpy as np\n'), ((2933, 2948), 'numpy.array', 'np.array', (['[low]'], {}), '([low])\n', (2941, 2948), True, 'import numpy as np\n'), ((2958, 2974), 'numpy.array', 'np.array', (['[high]'], {}), '([high])\n', (2966, 2974), True, 'import numpy as np\n'), ((5747, 5794), 'numpy.linspace', 'np.linspace', (['low[dim]', 'high[dim]', '(bins[dim] + 1)'], {}), '(low[dim], high[dim], bins[dim] + 1)\n', (5758, 5794), True, 'import numpy as np\n'), ((9256, 9365), 'matplotlib.patches.Rectangle', 'Rectangle', (['topleft', '(bottomright[0] - topleft[0])', '(bottomright[1] - topleft[1])'], {'color': 'colors[i]', 'alpha': '(0.33)'}), '(topleft, bottomright[0] - topleft[0], bottomright[1] - topleft[1],\n color=colors[i], alpha=0.33)\n', (9265, 9365), False, 'from matplotlib.patches import Rectangle\n'), ((8329, 8344), 'numpy.array', 'np.array', (['[low]'], {}), '([low])\n', (8337, 8344), True, 'import numpy as np\n'), ((8354, 8370), 'numpy.array', 'np.array', (['[high]'], {}), '([high])\n', (8362, 8370), True, 'import numpy as np\n'), ((9758, 9815), 'matplotlib.lines.Line2D', 'Line2D', (['[sample[0], cx]', '[sample[1], cy]'], {'color': 'colors[i]'}), '([sample[0], cx], [sample[1], cy], color=colors[i])\n', (9764, 9815), False, 'from matplotlib.lines import Line2D\n')] |
import os
import random
from glob import glob
import cv2
import numpy as np
from augraphy.augmentations.lib import sobel
from augraphy.base.augmentation import Augmentation
from augraphy.utilities import *
class BleedThrough(Augmentation):
"""Emulates bleed through effect from the combination of ink bleed and
gaussian blur operations.
:param intensity_range: Pair of floats determining the range from which
noise intensity is sampled.
:type intensity: tuple, optional
:param color_range: Pair of ints determining the range from which color
noise is sampled.
:type color_range: tuple, optional
:param ksize: Tuple of height/width pairs from which to sample the kernel
size. Higher value increases the spreadness of bleeding effect.
:type ksizes: tuple, optional
:param sigmaX: Standard deviation of the kernel along the x-axis.
:type sigmaX: float, optional
:param alpha: Intensity of bleeding effect, recommended value range from
0.1 to 0.5.
:type alpha: float, optional
:param offsets: Tuple of x and y offset pair to shift the bleed through
effect from original input.
:type offsets: tuple, optional
:param dpi: DPI of foreground image for bleedthrough effect.
Select either 100, 200 or 300.
:type dpi: int, optional
:param p: The probability this Augmentation will be applied.
:type p: float, optional
"""
def __init__(
self,
intensity_range=(0.1, 0.2),
color_range=(0, 224),
ksize=(17, 17),
sigmaX=0,
alpha=0.3,
offsets=(10, 20),
dpi=100,
p=1,
):
super().__init__(p=p)
self.intensity_range = intensity_range
self.color_range = color_range
self.ksize = ksize
self.sigmaX = sigmaX
self.alpha = alpha
self.offsets = offsets
self.dpi = dpi
# Constructs a string representation of this Augmentation.
def __repr__(self):
return f"BleedThrough(intensity_range={self.intensity_range}, color_range={self.color_range}, ksize={self.ksize}, sigmaX={self.sigmaX},alpha={self.alpha},offsets={self.offsets},dpi={self.dpi},p={self.p})"
# Blend images to produce bleedthrough effect
def blend(self, img, img_bleed, alpha):
# convert to single channel to avoud unnecessary noise in colour image
if len(img_bleed.shape) > 2:
img_bleed_input = cv2.cvtColor(img_bleed.astype("uint8"), cv2.COLOR_BGR2GRAY)
else:
img_bleed_input = img_bleed.astype("uint8")
ob = OverlayBuilder("normal", img_bleed_input, img, 1, (1, 1), "center", 0, self.alpha)
return ob.build_overlay()
# Offset image so that bleedthrough effect is visible and not stacked with input image
def generate_offset(self, img_bleed, offsets):
x_offset = offsets[0]
y_offset = offsets[1]
if (x_offset == 0) and (y_offset == 0):
return img_bleed
elif x_offset == 0:
img_bleed[y_offset:, :] = img_bleed[:-y_offset, :]
elif y_offset == 0:
img_bleed[:, x_offset:] = img_bleed[:, :-x_offset]
else:
img_bleed[y_offset:, x_offset:] = img_bleed[:-y_offset, :-x_offset]
return img_bleed
# Preprocess and create bleeding ink effect
def generate_bleeding_ink(self, img, intensity_range, color_range, ksize, sigmaX):
intensity = random.uniform(intensity_range[0], intensity_range[1])
add_noise_fn = (
lambda x, y: random.randint(color_range[0], color_range[1])
if (y == 255 and random.random() < intensity)
else x
)
add_noise = np.vectorize(add_noise_fn)
sobelized = sobel(img)
img_noise = np.double(add_noise(img, sobelized))
img_bleed = cv2.GaussianBlur(img_noise, ksize=ksize, sigmaX=sigmaX)
return img_bleed
# create foreground image for bleedthrough effect
def create_bleedthrough_foreground(self, image):
try:
# Id for figshare published grayscale image
if self.dpi == 300:
article_ID = "19227981"
elif self.dpi == 200:
article_ID = "19227879"
else:
article_ID = "19210698"
# path to foreground folder
foreground_folder = os.path.join(os.getcwd() + "/figshare_bleedthrough/")
# create figshare downloader
fsdl = FigshareDownloader(directory="figshare_BleedThrough/")
# download files
fsdl.download_random_file_from_article(article_ID)
# file path list
foreground_images_path = glob(foreground_folder + "*.png", recursive=True)
# get random image path
random_path = foreground_images_path[random.randint(0, len(foreground_images_path) - 1)]
# get random image
image_bleedthrough_foreground = cv2.imread(random_path)
# resize foreground
image_bleedthrough_foreground = cv2.resize(
image_bleedthrough_foreground,
(image.shape[1], image.shape[0]),
interpolation=cv2.INTER_AREA,
)
# failed to download, flip and mirror image to get bleedthrough foreground
except Exception:
image_flip = cv2.flip(image, 0)
image_bleedthrough_foreground = cv2.flip(image_flip, 1)
return image_bleedthrough_foreground
# Applies the Augmentation to input data.
def __call__(self, image, layer=None, force=False):
if force or self.should_run():
image = image.copy()
image_bleedthrough_foreground = self.create_bleedthrough_foreground(image)
image_bleed = self.generate_bleeding_ink(
image_bleedthrough_foreground,
self.intensity_range,
self.color_range,
self.ksize,
self.sigmaX,
)
image_bleed_offset = self.generate_offset(image_bleed, self.offsets)
image_bleedthrough = self.blend(image, image_bleed_offset, self.alpha)
return image_bleedthrough
| [
"random.uniform",
"cv2.flip",
"os.getcwd",
"random.random",
"augraphy.augmentations.lib.sobel",
"cv2.resize",
"cv2.GaussianBlur",
"numpy.vectorize",
"random.randint",
"glob.glob",
"cv2.imread"
] | [((3478, 3532), 'random.uniform', 'random.uniform', (['intensity_range[0]', 'intensity_range[1]'], {}), '(intensity_range[0], intensity_range[1])\n', (3492, 3532), False, 'import random\n'), ((3737, 3763), 'numpy.vectorize', 'np.vectorize', (['add_noise_fn'], {}), '(add_noise_fn)\n', (3749, 3763), True, 'import numpy as np\n'), ((3784, 3794), 'augraphy.augmentations.lib.sobel', 'sobel', (['img'], {}), '(img)\n', (3789, 3794), False, 'from augraphy.augmentations.lib import sobel\n'), ((3872, 3927), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img_noise'], {'ksize': 'ksize', 'sigmaX': 'sigmaX'}), '(img_noise, ksize=ksize, sigmaX=sigmaX)\n', (3888, 3927), False, 'import cv2\n'), ((4738, 4787), 'glob.glob', 'glob', (["(foreground_folder + '*.png')"], {'recursive': '(True)'}), "(foreground_folder + '*.png', recursive=True)\n", (4742, 4787), False, 'from glob import glob\n'), ((5002, 5025), 'cv2.imread', 'cv2.imread', (['random_path'], {}), '(random_path)\n', (5012, 5025), False, 'import cv2\n'), ((5103, 5212), 'cv2.resize', 'cv2.resize', (['image_bleedthrough_foreground', '(image.shape[1], image.shape[0])'], {'interpolation': 'cv2.INTER_AREA'}), '(image_bleedthrough_foreground, (image.shape[1], image.shape[0]),\n interpolation=cv2.INTER_AREA)\n', (5113, 5212), False, 'import cv2\n'), ((3583, 3629), 'random.randint', 'random.randint', (['color_range[0]', 'color_range[1]'], {}), '(color_range[0], color_range[1])\n', (3597, 3629), False, 'import random\n'), ((5408, 5426), 'cv2.flip', 'cv2.flip', (['image', '(0)'], {}), '(image, 0)\n', (5416, 5426), False, 'import cv2\n'), ((5471, 5494), 'cv2.flip', 'cv2.flip', (['image_flip', '(1)'], {}), '(image_flip, 1)\n', (5479, 5494), False, 'import cv2\n'), ((4421, 4432), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4430, 4432), False, 'import os\n'), ((3659, 3674), 'random.random', 'random.random', ([], {}), '()\n', (3672, 3674), False, 'import random\n')] |
import numpy as np
import torch
import glob
import os
import pickle
import argparse
from torch.utils.data import DataLoader
from torch.utils.data.dataset import (TensorDataset,
ConcatDataset)
from i2i.cyclegan import CycleGAN
from util import (convert_to_rgb,
H5Dataset,
DatasetFromFolder)
from torchvision import transforms
from skimage.io import imsave, imread
from skimage.transform import rescale, resize
from importlib import import_module
def get_face_swap_iterators(bs):
"""DepthNet + GT <-> frontal GT faces"""
filename_vgg = "data/vgg/vgg.h5"
filename_celeba = "data/celeba/celebA.h5"
filename_celeba_swap = "data/celeba_faceswap/celeba_faceswap.h5"
a_train = H5Dataset(filename_celeba_swap, 'imgs', train=True)
vgg_side_train = H5Dataset('%s' % filename_vgg, 'src_GT', train=True)
vgg_frontal_train = H5Dataset('%s' % filename_vgg, 'tg_GT', train=True)
celeba_side_train = H5Dataset('%s' % filename_celeba, 'src_GT', train=True)
celeba_frontal_train = H5Dataset('%s' % filename_celeba, 'tg_GT', train=True)
b_train = ConcatDataset((vgg_side_train,
vgg_frontal_train,
celeba_side_train,
celeba_frontal_train))
a_valid = H5Dataset(filename_celeba_swap, 'imgs', train=False)
vgg_side_valid = H5Dataset('%s' % filename_vgg, 'src_GT', train=False)
vgg_frontal_valid = H5Dataset('%s' % filename_vgg, 'tg_GT', train=False)
celeba_side_valid = H5Dataset('%s' % filename_celeba, 'src_GT', train=False)
celeba_frontal_valid = H5Dataset('%s' % filename_celeba, 'tg_GT', train=False)
b_valid = ConcatDataset((vgg_side_valid,
vgg_frontal_valid,
celeba_side_valid,
celeba_frontal_valid))
loader_train_a = DataLoader(a_train, batch_size=bs, shuffle=True)
loader_train_b = DataLoader(b_train, batch_size=bs, shuffle=True)
loader_valid_a = DataLoader(a_valid, batch_size=bs, shuffle=True)
loader_valid_b = DataLoader(b_valid, batch_size=bs, shuffle=True)
return loader_train_a, loader_train_b, loader_valid_a, loader_valid_b
def image_dump_handler(out_folder, scale_factor=1.):
def _fn(losses, inputs, outputs, kwargs):
if kwargs['iter'] != 1:
return
A_real = inputs[0].data.cpu().numpy()
B_real = inputs[1].data.cpu().numpy()
atob, atob_btoa, btoa, btoa_atob = \
[elem.data.cpu().numpy() for elem in outputs.values()]
outs_np = [A_real, atob, atob_btoa, B_real, btoa, btoa_atob]
# determine # of channels
n_channels = outs_np[0].shape[1]
w, h = outs_np[0].shape[-1], outs_np[0].shape[-2]
# possible that A_real.bs != B_real.bs
bs = np.min([outs_np[0].shape[0], outs_np[3].shape[0]])
grid = np.zeros((h*bs, w*6, 3))
for j in range(bs):
for i in range(6):
n_channels = outs_np[i][j].shape[0]
img_to_write = convert_to_rgb(outs_np[i][j], is_grayscale=False)
grid[j*h:(j+1)*h, i*w:(i+1)*w, :] = img_to_write
imsave(arr=rescale(grid, scale=scale_factor),
fname="%s/%i_%s.png" % (out_folder, kwargs['epoch'], kwargs['mode']))
return _fn
if __name__ == '__main__':
from torchvision.utils import save_image
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--name', type=str,
default="my_experiment")
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--network', type=str, default=None)
parser.add_argument('--mode', choices=['train', 'test', 'vis'],
default='train')
parser.add_argument('--epochs', type=int, default=1000)
parser.add_argument('--loss', type=str, choices=['mse', 'bce'],
default='mse')
parser.add_argument('--lamb', type=float, default=10.0)
parser.add_argument('--beta', type=float, default=0.0)
parser.add_argument('--lr', type=float, default=2e-4)
parser.add_argument('--beta1', type=float, default=0.5)
parser.add_argument('--beta2', type=float, default=0.999)
parser.add_argument('--resume', type=str, default=None)
parser.add_argument('--save_path', type=str,
default='./results')
parser.add_argument('--model_save_path', type=str,
default='./models')
parser.add_argument('--cpu', action='store_true')
args = parser.parse_args()
return args
args = parse_args()
# Dynamically load in the selected generator
# module.
mod = import_module(args.network.replace("/", ".").\
replace(".py", ""))
gen_atob_fn, disc_a_fn, gen_btoa_fn, disc_b_fn = mod.get_network()
print("Loading iterators...")
it_train_a, it_train_b, it_valid_a, it_valid_b = \
get_face_swap_iterators(args.batch_size)
print("Loading CycleGAN...")
name = args.name
net = CycleGAN(
gen_atob_fn=gen_atob_fn,
disc_a_fn=disc_a_fn,
gen_btoa_fn=gen_btoa_fn,
disc_b_fn=disc_b_fn,
loss=args.loss,
lamb=args.lamb,
beta=args.beta,
opt_d_args={'lr': args.lr, 'betas': (args.beta1, args.beta2)},
opt_g_args={'lr': args.lr, 'betas': (args.beta1, args.beta2)},
handlers=[image_dump_handler("%s/%s" % (args.save_path, name))],
use_cuda=False if args.cpu else True
)
if args.resume is not None:
if args.resume == 'auto':
# autoresume
model_dir = "%s/%s" % (args.model_save_path, name)
# List all the pkl files.
files = glob.glob("%s/*.pkl" % model_dir)
# Make them absolute paths.
files = [ os.path.abspath(key) for key in files ]
if len(files) > 0:
# Get creation time and use that.
latest_model = max(files, key=os.path.getctime)
print("Auto-resume mode found latest model: %s" %
latest_model)
net.load(latest_model)
else:
print("Loading model: %s" % args.resume)
net.load(args.resume)
if args.mode == "train":
print("Training...")
net.train(
itr_a_train=it_train_a,
itr_b_train=it_train_b,
itr_a_valid=it_valid_a,
itr_b_valid=it_valid_b,
epochs=args.epochs,
model_dir="%s/%s" % (args.model_save_path, name),
result_dir="%s/%s" % (args.save_path, name)
)
elif args.mode == "vis":
print("Converting A -> B...")
net.g_atob.eval()
aa = iter(it_train_a).next()[0:1]
bb = net.g_atob(aa)
save_image(aa*0.5 + 0.5, "tmp/aa.png")
save_image(bb*0.5 + 0.5, "tmp/bb.png")
elif args.mode == 'test':
print("Dropping into pdb...")
import pdb
pdb.set_trace()
| [
"argparse.ArgumentParser",
"numpy.min",
"util.convert_to_rgb",
"numpy.zeros",
"pdb.set_trace",
"torch.utils.data.DataLoader",
"os.path.abspath",
"util.H5Dataset",
"torchvision.utils.save_image",
"skimage.transform.rescale",
"glob.glob",
"torch.utils.data.dataset.ConcatDataset"
] | [((764, 815), 'util.H5Dataset', 'H5Dataset', (['filename_celeba_swap', '"""imgs"""'], {'train': '(True)'}), "(filename_celeba_swap, 'imgs', train=True)\n", (773, 815), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((837, 889), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_vgg)", '"""src_GT"""'], {'train': '(True)'}), "('%s' % filename_vgg, 'src_GT', train=True)\n", (846, 889), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((914, 965), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_vgg)", '"""tg_GT"""'], {'train': '(True)'}), "('%s' % filename_vgg, 'tg_GT', train=True)\n", (923, 965), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((990, 1045), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_celeba)", '"""src_GT"""'], {'train': '(True)'}), "('%s' % filename_celeba, 'src_GT', train=True)\n", (999, 1045), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1073, 1127), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_celeba)", '"""tg_GT"""'], {'train': '(True)'}), "('%s' % filename_celeba, 'tg_GT', train=True)\n", (1082, 1127), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1142, 1237), 'torch.utils.data.dataset.ConcatDataset', 'ConcatDataset', (['(vgg_side_train, vgg_frontal_train, celeba_side_train, celeba_frontal_train)'], {}), '((vgg_side_train, vgg_frontal_train, celeba_side_train,\n celeba_frontal_train))\n', (1155, 1237), False, 'from torch.utils.data.dataset import TensorDataset, ConcatDataset\n'), ((1335, 1387), 'util.H5Dataset', 'H5Dataset', (['filename_celeba_swap', '"""imgs"""'], {'train': '(False)'}), "(filename_celeba_swap, 'imgs', train=False)\n", (1344, 1387), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1409, 1462), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_vgg)", '"""src_GT"""'], {'train': '(False)'}), "('%s' % filename_vgg, 'src_GT', train=False)\n", (1418, 1462), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1487, 1539), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_vgg)", '"""tg_GT"""'], {'train': '(False)'}), "('%s' % filename_vgg, 'tg_GT', train=False)\n", (1496, 1539), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1564, 1620), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_celeba)", '"""src_GT"""'], {'train': '(False)'}), "('%s' % filename_celeba, 'src_GT', train=False)\n", (1573, 1620), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1648, 1703), 'util.H5Dataset', 'H5Dataset', (["('%s' % filename_celeba)", '"""tg_GT"""'], {'train': '(False)'}), "('%s' % filename_celeba, 'tg_GT', train=False)\n", (1657, 1703), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((1718, 1813), 'torch.utils.data.dataset.ConcatDataset', 'ConcatDataset', (['(vgg_side_valid, vgg_frontal_valid, celeba_side_valid, celeba_frontal_valid)'], {}), '((vgg_side_valid, vgg_frontal_valid, celeba_side_valid,\n celeba_frontal_valid))\n', (1731, 1813), False, 'from torch.utils.data.dataset import TensorDataset, ConcatDataset\n'), ((1918, 1966), 'torch.utils.data.DataLoader', 'DataLoader', (['a_train'], {'batch_size': 'bs', 'shuffle': '(True)'}), '(a_train, batch_size=bs, shuffle=True)\n', (1928, 1966), False, 'from torch.utils.data import DataLoader\n'), ((1988, 2036), 'torch.utils.data.DataLoader', 'DataLoader', (['b_train'], {'batch_size': 'bs', 'shuffle': '(True)'}), '(b_train, batch_size=bs, shuffle=True)\n', (1998, 2036), False, 'from torch.utils.data import DataLoader\n'), ((2058, 2106), 'torch.utils.data.DataLoader', 'DataLoader', (['a_valid'], {'batch_size': 'bs', 'shuffle': '(True)'}), '(a_valid, batch_size=bs, shuffle=True)\n', (2068, 2106), False, 'from torch.utils.data import DataLoader\n'), ((2128, 2176), 'torch.utils.data.DataLoader', 'DataLoader', (['b_valid'], {'batch_size': 'bs', 'shuffle': '(True)'}), '(b_valid, batch_size=bs, shuffle=True)\n', (2138, 2176), False, 'from torch.utils.data import DataLoader\n'), ((2868, 2918), 'numpy.min', 'np.min', (['[outs_np[0].shape[0], outs_np[3].shape[0]]'], {}), '([outs_np[0].shape[0], outs_np[3].shape[0]])\n', (2874, 2918), True, 'import numpy as np\n'), ((2934, 2962), 'numpy.zeros', 'np.zeros', (['(h * bs, w * 6, 3)'], {}), '((h * bs, w * 6, 3))\n', (2942, 2962), True, 'import numpy as np\n'), ((3484, 3523), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (3507, 3523), False, 'import argparse\n'), ((5906, 5939), 'glob.glob', 'glob.glob', (["('%s/*.pkl' % model_dir)"], {}), "('%s/*.pkl' % model_dir)\n", (5915, 5939), False, 'import glob\n'), ((6981, 7021), 'torchvision.utils.save_image', 'save_image', (['(aa * 0.5 + 0.5)', '"""tmp/aa.png"""'], {}), "(aa * 0.5 + 0.5, 'tmp/aa.png')\n", (6991, 7021), False, 'from torchvision.utils import save_image\n'), ((7028, 7068), 'torchvision.utils.save_image', 'save_image', (['(bb * 0.5 + 0.5)', '"""tmp/bb.png"""'], {}), "(bb * 0.5 + 0.5, 'tmp/bb.png')\n", (7038, 7068), False, 'from torchvision.utils import save_image\n'), ((3101, 3150), 'util.convert_to_rgb', 'convert_to_rgb', (['outs_np[i][j]'], {'is_grayscale': '(False)'}), '(outs_np[i][j], is_grayscale=False)\n', (3115, 3150), False, 'from util import convert_to_rgb, H5Dataset, DatasetFromFolder\n'), ((3235, 3268), 'skimage.transform.rescale', 'rescale', (['grid'], {'scale': 'scale_factor'}), '(grid, scale=scale_factor)\n', (3242, 3268), False, 'from skimage.transform import rescale, resize\n'), ((6002, 6022), 'os.path.abspath', 'os.path.abspath', (['key'], {}), '(key)\n', (6017, 6022), False, 'import os\n'), ((7162, 7177), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (7175, 7177), False, 'import pdb\n')] |
"""Allows you to do math in any base."""
from __future__ import annotations
import sys
import numpy
import contextlib
from io import StringIO
from typing import Union
from .exceptions import *
def _execWithOutput(code:str, stdout=None):
try:
old = sys.stdout
if not stdout:
stdout = StringIO()
sys.stdout = stdout
exec(f"r = {code}\nprint(r)")
v = stdout.getvalue()
sys.stdout = old
return v
except Exception as e:
sys.stdout = old
raise IncorrectExpression(f"Expression {code} is incorrect.") from e
# if you're here to find out why, thing is that I don't know either.
def _checkCanSymbolDoMath(a, b):
if a.base != b.base:
raise BaseDoesNotMatchError(f"Cannot do math on two numbers with differing bases. ({a.base} and {b.base})")
class Math:
def __init__(self, base):
self.base = base
def symbol(self, *val):
r = []
for x in val:
r.append(
Symbol(int(x, self.base), self.base)
)
if len(r) == 1:
return r[0]
return tuple(r)
def calculate(self, expression:str):
values = [str(x) for x in range(10)] + [chr(x+65) for x in range(26)]
for e in expression:
if e not in values:
continue
if int(e, 36) > self.base:
raise NumberOutOfBaseRange(f"Character {e} (number {int(e, 36)}) in expression is out of the base's range ({self.base}).")
numInExpression = []
num = ""
for e in expression:
if not (e in values):
if num != "":
numInExpression.append(num.__str__())
num = ""
continue
else:
num += e
if num != "":
numInExpression.append(num.__str__())
newExpression = str(int(numInExpression[0], self.base))
currentInd = 0
expression = ''.join(expression.split())
for e in expression:
if e.upper() in values:
continue
else:
currentInd += 1
newExpression += e
if currentInd == len(numInExpression):
break
newExpression += str(int(numInExpression[currentInd], self.base))
result = _execWithOutput(newExpression)
return Symbol(int(result), self.base)
class Symbol(object):
value = 0
base = 0
def __init__(self, value, base):
self.value = value
self.base = base
def __str__(self):
return numpy.base_repr(self.value, self.base)
def __repr__(self):
return f"'{self.__str__()}'"
def __int__(self):
return self.value
def __add__(self, x):
if type(x) == Symbol:
_checkCanSymbolDoMath(self, x)
new = Symbol(int(x) + self.value, self.base)
return new
def __radd__(self, x):
return self.__add__(x)
def __sub__(self, x):
if type(x) == Symbol:
_checkCanSymbolDoMath(self, x)
return Symbol(self.value - int(x), self.base)
def __rsub__(self, x):
return Symbol(int(x) - self.value, self.base)
def __mul__(self, x):
if type(x) == Symbol:
_checkCanSymbolDoMath(self, x)
return Symbol(int(x) * self.value, self.base)
def __rmul__(self, x):
return self.__mul__(x)
def __div__(self, x):
raise CannotDivideSymbols("Symbols cannot be divided.")
def __rdiv__(self, x):
return self.__div__(x)
def __pow__(self, x):
if type(x) == Symbol:
_checkCanSymbolDoMath(self, x)
return Symbol(self.value ** int(x), self.base)
def __lt__(self, x):
if type(x) == Symbol:
if x.base != self.base:
raise CannotCompareDifferingBases(f"Cannot compare two numbers with differing bases. ({self.base} and {x.base})")
return self.value < int(x)
def __gt__(self, x):
if type(x) == Symbol:
if x.base != self.base:
raise CannotCompareDifferingBases(f"Cannot compare two numbers with differing bases. ({self.base} and {x.base})")
return self.value > int(x)
def __le__(self, x):
if type(x) == Symbol:
if x.base != self.base:
raise CannotCompareDifferingBases(f"Cannot compare two numbers with differing bases. ({self.base} and {x.base})")
return self.value <= int(x)
def __ge__(self, x):
if type(x) == Symbol:
if x.base != self.base:
raise CannotCompareDifferingBases(f"Cannot compare two numbers with differing bases. ({self.base} and {x.base})")
return self.value >= int(x)
def __eq__(self, x):
if type(x) == Symbol:
if x.base != self.base:
raise CannotCompareDifferingBases(f"Cannot compare two numbers with differing bases. ({self.base} and {x.base})")
return self.value == int(x)
def __neg__(self):
return -self.value | [
"io.StringIO",
"numpy.base_repr"
] | [((2702, 2740), 'numpy.base_repr', 'numpy.base_repr', (['self.value', 'self.base'], {}), '(self.value, self.base)\n', (2717, 2740), False, 'import numpy\n'), ((318, 328), 'io.StringIO', 'StringIO', ([], {}), '()\n', (326, 328), False, 'from io import StringIO\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.