code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
This module defines some functions aiming at describing subcavities
and caracterize their shapes
"""
import os
import numpy as np
from scipy import ndimage
from skimage.feature import peak_local_max
from skimage.morphology import watershed
from caviar.cavity_identification.gridtools import get_index_of_coor_list
from caviar.misc_tools.misc import export_pdb_subcavities
from .cavity import Cavity
__all__ = ['wrapper_subcavities']
def wrapper_subcavities(final_cavities, cav_of_interest, grid_min, grid_shape, cavities, code, out, sourcedir, list_ligands,
seeds_mindist = 3, merge_subcavs = True, minsize_subcavs = 50, min_contacts = 0.667, v = False,
printv = False, print_pphores_subcavs = False, export_subcavs = False, gridspace = 1.0, frame = None):
"""
Wraps transform_cav2im3d, find_subcav_watershed, map_subcav_in_cav
merge_small_enclosed_subcavs, print_subcavs_pphores and export_pdb_subcavities
as one function
"""
# Convert to a 3D image for skimage
im3d = transform_cav2im3d(final_cavities[cav_of_interest], grid_min,
grid_shape) #filtered_pharma[order][cav_of_interest])
# Perform the watershed algorithm, including entropy of pharmacophores
labels = find_subcav_watershed(im3d, seeds_mindist)
# Map results of watershed to grid points of cavity
#subcavs = map_subcav_in_cav(cavities, cav_of_interest, labels, args.code, grid_min, grid_shape)
subcavs = map_subcav_in_cav(labels, grid_min)
if merge_subcavs == True:
subcavs = merge_small_enclosed_subcavs(subcavs, minsize_subcavs = minsize_subcavs,
min_contacts = min_contacts, v = v)
subcavs_table = print_subcavs_pphores(cavities, subcavs, cav_of_interest, code, grid_min, grid_shape, frame)
# Export
if export_subcavs:
try:
os.mkdir(out)
except:
pass
if frame:
export_pdb_subcavities(subcavs, code[:-4]+"_"+str(frame), grid_min, grid_shape,
cavid = cav_of_interest, gridspace = gridspace, outdir = out,
listlig = list_ligands, oridir = sourcedir)
else:
export_pdb_subcavities(subcavs, code[:-4], grid_min, grid_shape,
cavid = cav_of_interest, gridspace = gridspace, outdir = out,
listlig = list_ligands, oridir = sourcedir)
return subcavs_table
def transform_cav2im3d(cavity_coords, grid_min, grid_shape):
"""
Takes coordinates of grid points and outputs an im3d for skimage
could be done in many ways but this one does the job
"""
# Simpler version with indices and array reshaping
#im1d = np.zeros(grid_shape[0]*grid_shape[1]*grid_shape[2])
#im1d[get_index_of_coor_list(cavity_coords, grid_min, grid_shape)] = 1
#im3d = np.reshape(im1d, grid_shape)
# Somehow doesnt' work always
# Generate an im3d object of correct size for the cavity
im3d = np.zeros(grid_shape)
# Align the cavity to zero and convert the silly floats to ints
aligned_cav = cavity_coords - grid_min
# np.around because stupid python cant broadcast from floats to ints because floating point error
# I am losing so much time with this kind of stupid behavior, seriously, WTF is this?
newtypes_cav = np.around(np.array(aligned_cav, dtype=np.float)).astype(int)
# Set as 1 the indices corresponding to cavity grid points in the im3d
im3d[newtypes_cav[:,0], newtypes_cav[:,1], newtypes_cav[:,2]] = True
# np.flatnonzero(im3d) should give the same result as
# get_index_of_coor_list(cavity_coords, grid_min, grid_shape)
return im3d
def find_subcav_watershed(im3d, seeds_mindist = 3):
"""
Uses skimage to perform a watershed algorithm in order to
identify subcavities. Seeds of the watershed algorithm are
defined by maximum local distance to the end of the cavity
Explanation here: https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_watershed.html
"""
# Euclidian distance transform
distance = ndimage.distance_transform_edt(im3d, sampling=None, return_distances=True,
return_indices=False, distances=None, indices=None) # Default
# Find peaks in the image
# min_distance can be tuned to change the definition of seeds for the watershed algorithm
# Peaks are separated by at least min_distance
# increasing the value decreases the number of seeds and thus subpockets
#print(seeds_mindist)
local_maxi = peak_local_max(distance, min_distance = int(seeds_mindist), #
threshold_abs=None, threshold_rel=None, exclude_border=True, # default
indices=False, # Modified to return boolean mask
footprint=None, labels=None,# default
num_peaks_per_label= 1)#, num_peaks = inf,) # Not several seeds in same label zone
# label the seeds
markers = ndimage.label(local_maxi)[0]
#
labels = watershed(-distance, markers = markers, mask=im3d,
connectivity = 1, offset = None, compactness = 0, watershed_line = False)
# Labels is of dimension grid_shape and contains integer values corresponding
# to the subcavity a point is issued from
return labels
def transform_cav2im3d_entropy(cavity_coords, grid_min, grid_shape, pharmaco):
"""
Takes coordinates of grid points and outputs an im3d for skimage
Uses entropy at 3A of pharmacophores as values to set the "greyscale"
"""
# First we simply the pharmacophores
names = np.array([0, 1, 1, 3, 3, 3, 4, 5, 0, 0, 0]) # type None & other, hydrophobic, polar, negative, positive
pharmacophores = names[pharmaco]
from scipy.spatial import cKDTree
from scipy.stats import entropy
tree1 = cKDTree(cavity_coords)
neighbors = tree1.query_ball_point(cavity_coords, r=3)
list_entropy = []
for i in neighbors:
pharma = pharmacophores[:,0][i]
list_entropy.append(entropy(pharma))
# Generate an im3d object of correct size for the cavity
im3d = np.zeros(grid_shape)
# Align the cavity to zero and convert the silly floats to ints
aligned_cav = cavity_coords - grid_min
# np.around because stupid python cant broadcast from floats to ints because floating point error
# I am lsoing so much time with this kind of stupid behavior, seriously, WTF is this?
newtypes_cav = np.around(aligned_cav).astype(int)
# Set as 1 the indices corresponding to cavity grid points in the im3d
im3d[newtypes_cav[:,0], newtypes_cav[:,1], newtypes_cav[:,2]] = 1/np.array(list_entropy)
# np.flatnonzero(im3d) should give the same result as
# get_index_of_coor_list(cavity_coords, grid_min, grid_shape)
return im3d
def find_subcav_watershed_entropy(im3d, seeds_mindist = 3):
"""
Uses skimage to perform a watershed algorithm in order to
identify subcavities. Seeds of the watershed algorithm are
defined by maximum local distance to the end of the cavity
Explanation here: https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_watershed.html
"""
# Euclidian distance transform
distance = ndimage.distance_transform_edt(im3d, sampling=None, return_distances=True,
return_indices=False, distances=None, indices=None) + np.round(im3d, 1)
# Find peaks in the image
# min_distance can be tuned to change the definition of seeds for the watershed algorithm
# Peaks are separated by at least min_distance
# increasing the value decreases the number of seeds and thus subpockets
local_maxi = peak_local_max(distance, min_distance = seeds_mindist, #
threshold_abs=None, threshold_rel=None, exclude_border=True, # default
indices=False, # Modified to return boolean mask
footprint=None, labels=None,# default
num_peaks_per_label= 1)#, num_peaks = inf,) # Not several seeds in same label zone
# label the seeds
markers = ndimage.label(local_maxi)[0]
#
labels = watershed(-distance, markers = markers, mask=im3d,
connectivity = 1, offset = None, compactness = 0, watershed_line = False)
# Labels is of dimension grid_shape and contains integer values corresponding
# to the subcavity a point is issued from
return labels
def merge_small_enclosed_subcavs(subcavs, minsize_subcavs = 50, min_contacts = 0.667, v = False):
"""
The watershed algorithm tends to overspan a bit, even when optimizing seeds.
This function aims at identifying small pockets (< minsize_subcavs)
that are heavily in contact with other subcavs (> min_contacts)
These subcavites are probably at the interface between 2 main subcavities,
or on their surface.
"""
# Create a copy of the subcavs array to not change in place, in case
_subcavs = subcavs.copy()
# lengths of each subcavity
lengths = [len(x) for x in subcavs]
#Smaller ones than min_contacts
smallsubcavs = [[x, lengths[x]] for x in range(0, len(lengths)) if lengths[x] < minsize_subcavs]
if not smallsubcavs:
return subcavs
from scipy.spatial.distance import cdist
to_del = {}
for small in smallsubcavs:
contacts = []
contact = 0.
total_contact = 0.
i = 0
# Check the contact between the small subcavity and the others
for other_subcavs in subcavs:
if i == small[0]:
contacts.append(0)
i+=1
continue
contact = len(set(np.nonzero(cdist(subcavs[small[0]], other_subcavs) < 1.01)[0]))
contacts.append(contact)
total_contact += contact/small[1]
i+=1
# If a small subcavity has more than min_contacts with neighbors, be ready to add it to the
# subcavity with which it has the more contacts
if total_contact >= min_contacts:
if v == True: print(f"Subcavity {small[0]} is small and enclosed {total_contact*100:.2f}% in other subcavs.\nIt will be added to subcavity {np.argmax(contacts)} (original numbering of subcavs from 0)")
to_del[small[0]] = np.argmax(contacts)
# to_del is dict which contains key = index of subcav to delete; value = index of subcav to merge it with
# If there's any subcavities to merge
# It's a mess because it's not easy to merge different array elements together and/or delete some...
if to_del:
dels = []
for index in range(0, len(subcavs)):
if index in to_del.keys():
# original version: works generally, except in some cases in which we merge and replace 2 equally sized small arrays (memory issue?)
try:
# _tmp contains the merged subcavity
_tmp = np.concatenate((_subcavs[to_del[index]], _subcavs[index]), axis = 0)
# now we assign the merged subcavity to the index of the main subcav
_subcavs[to_del[index]] = _tmp
# dirty work around: change to lists, and play with lists, and come back to array...
except:
_tmp = np.array(_subcavs[to_del[index]]).tolist() + np.array(_subcavs[index]).tolist()
_subcavs[to_del[index]] = np.array(_tmp)
dels.append(index)
subcavlist = []
for x in _subcavs:
# there is also here a mix of lists and arrays. Why?
try:
subcavlist.append(x.tolist())
except:
subcavlist.append(x)
for _del in sorted(dels, reverse=True):
del subcavlist[_del]
merged_subcavs = [np.array(x) for x in subcavlist]
return merged_subcavs
else:
return subcavs
def map_subcav_in_cav(labels, grid_min):
"""
Extract information from subcavities: return the coordinates as subcavs,
/! function cut with print_subcavs_pphores in case we merged small subcavities
"""
subcavs = []
for i in range(1, np.amax(labels)+1):
subcav = np.argwhere(labels == i) + grid_min
subcavs.append(subcav)
return subcavs
def transform_im3d2cav(im3d, grid):
"""
Invert of original function. It's a simple command but nice to have it here with a good name
"""
cav_coor = grid[np.flatnonzero(im3d)]
return cav_coor
def print_subcavs_pphores(cavities, subcavs, cav_of_interest, pdbcode, grid_min, grid_shape, frame = None):
"""
print information about PP environment
and in particular, set in cavities object (class) the subcavity indices
"""
#names = ["none", "aliphatic", "aromatic", "donor", "acceptor", "doneptor", "negative",
# "positive", "cys", "his", "metal"]
# Dictionary of pharmacophore types to print
import networkx as nx
names = ["shouldnotbethere", "hydrophobic", "shouldnotbethere", "polar non charged", "shouldnotbethere", "shouldnotbethere",
"negative", "positive", "other", "shouldnotbethere", "shouldnotbethere"]
subcavs_table = ""
for i in range(0, len(subcavs)):
# Find the corresponding indices in cavities[cav_of_interest]
subcav = subcavs[i]
oricav_indices = np.intersect1d(get_index_of_coor_list(subcav, grid_min, grid_shape),
get_index_of_coor_list(np.array([x.coords for x in cavities[cav_of_interest].gp]), grid_min, grid_shape),
return_indices=True)[2]
# Update the cavity object
cavities[cav_of_interest].subcavities[i+1] = oricav_indices # to not start at 0
# Update the graph
my_dict = {value: {"subcavs": i+1} for value in oricav_indices} # to not start at 0
nx.set_node_attributes(cavities[cav_of_interest].graph, my_dict)
# Find the pharmacophore types of the gridpoints of the subcavity
listouille = [cavities[cav_of_interest].gp[x].pharma[0] for x in oricav_indices]
# Convert types aromatic into "hydrophobic" alongside aliphatic (original nb1)
listouille = np.where(np.array(listouille)==2, 1, listouille)
# Convert types acceptor and doneptor into "polar non charged" (originally donor)
listouille = np.where(np.array(listouille)==4, 3, listouille)
listouille = np.where(np.array(listouille)==5, 3, listouille)
# Convert None, cys, his, metal to the same "other"
listouille = np.where(np.array(listouille)==0, 8, listouille)
listouille = np.where(np.array(listouille)==9, 8, listouille)
listouille = np.where(np.array(listouille)==10, 8, listouille)
# Count occurences of each value
values, counts = np.unique(listouille, return_counts=True)
total = np.sum(counts)
# create a dummy dictionary to store values better for printing
# set it up with 0 in case some values are absent
dico = {1: 0, 3: 0, 6: 0, 7: 0, 8: 0}
# Replace the 0 by the actual values
for aa in range(len(values)):
dico[values[aa]] = np.divide(counts[aa], total)
# create the table with subcavs information, that we may print or not
# Will be: PDB_chain cav_id subcav_id size hydroph polar neg pos other
if frame:
name = str(pdbcode[0:-4] + "_" + cavities[cav_of_interest].chains + "_" + str(frame))
else:
name = str(pdbcode[0:-4] + "_" + cavities[cav_of_interest].chains)
subcavs_table += f"{name:<12}"
subcavs_table += f"{cav_of_interest+1:^7d}{i+1:^8d}{len(oricav_indices):^6d}"
subcavs_table += f"{str(int(np.around(dico[1]*100)))+'%':^10}{str(int(np.around(dico[3]*100)))+'%':^7}"
subcavs_table += f"{str(int(np.around(dico[6]*100)))+'%':^6}{str(int(np.around(dico[7]*100)))+'%':^6}{str(int(np.around(dico[8]*100)))+'%':^6}"
subcavs_table += f"\n"
return subcavs_table | [
"os.mkdir",
"numpy.sum",
"skimage.feature.peak_local_max",
"numpy.argmax",
"numpy.around",
"scipy.spatial.cKDTree",
"numpy.round",
"caviar.cavity_identification.gridtools.get_index_of_coor_list",
"numpy.unique",
"scipy.ndimage.distance_transform_edt",
"scipy.spatial.distance.cdist",
"numpy.div... | [((2728, 2748), 'numpy.zeros', 'np.zeros', (['grid_shape'], {}), '(grid_shape)\n', (2736, 2748), True, 'import numpy as np\n'), ((3780, 3910), 'scipy.ndimage.distance_transform_edt', 'ndimage.distance_transform_edt', (['im3d'], {'sampling': 'None', 'return_distances': '(True)', 'return_indices': '(False)', 'distances': 'None', 'indices': 'None'}), '(im3d, sampling=None, return_distances=True,\n return_indices=False, distances=None, indices=None)\n', (3810, 3910), False, 'from scipy import ndimage\n'), ((4581, 4700), 'skimage.morphology.watershed', 'watershed', (['(-distance)'], {'markers': 'markers', 'mask': 'im3d', 'connectivity': '(1)', 'offset': 'None', 'compactness': '(0)', 'watershed_line': '(False)'}), '(-distance, markers=markers, mask=im3d, connectivity=1, offset=\n None, compactness=0, watershed_line=False)\n', (4590, 4700), False, 'from skimage.morphology import watershed\n'), ((5124, 5167), 'numpy.array', 'np.array', (['[0, 1, 1, 3, 3, 3, 4, 5, 0, 0, 0]'], {}), '([0, 1, 1, 3, 3, 3, 4, 5, 0, 0, 0])\n', (5132, 5167), True, 'import numpy as np\n'), ((5342, 5364), 'scipy.spatial.cKDTree', 'cKDTree', (['cavity_coords'], {}), '(cavity_coords)\n', (5349, 5364), False, 'from scipy.spatial import cKDTree\n'), ((5601, 5621), 'numpy.zeros', 'np.zeros', (['grid_shape'], {}), '(grid_shape)\n', (5609, 5621), True, 'import numpy as np\n'), ((7058, 7246), 'skimage.feature.peak_local_max', 'peak_local_max', (['distance'], {'min_distance': 'seeds_mindist', 'threshold_abs': 'None', 'threshold_rel': 'None', 'exclude_border': '(True)', 'indices': '(False)', 'footprint': 'None', 'labels': 'None', 'num_peaks_per_label': '(1)'}), '(distance, min_distance=seeds_mindist, threshold_abs=None,\n threshold_rel=None, exclude_border=True, indices=False, footprint=None,\n labels=None, num_peaks_per_label=1)\n', (7072, 7246), False, 'from skimage.feature import peak_local_max\n'), ((7438, 7557), 'skimage.morphology.watershed', 'watershed', (['(-distance)'], {'markers': 'markers', 'mask': 'im3d', 'connectivity': '(1)', 'offset': 'None', 'compactness': '(0)', 'watershed_line': '(False)'}), '(-distance, markers=markers, mask=im3d, connectivity=1, offset=\n None, compactness=0, watershed_line=False)\n', (7447, 7557), False, 'from skimage.morphology import watershed\n'), ((4538, 4563), 'scipy.ndimage.label', 'ndimage.label', (['local_maxi'], {}), '(local_maxi)\n', (4551, 4563), False, 'from scipy import ndimage\n'), ((6103, 6125), 'numpy.array', 'np.array', (['list_entropy'], {}), '(list_entropy)\n', (6111, 6125), True, 'import numpy as np\n'), ((6655, 6785), 'scipy.ndimage.distance_transform_edt', 'ndimage.distance_transform_edt', (['im3d'], {'sampling': 'None', 'return_distances': '(True)', 'return_indices': '(False)', 'distances': 'None', 'indices': 'None'}), '(im3d, sampling=None, return_distances=True,\n return_indices=False, distances=None, indices=None)\n', (6685, 6785), False, 'from scipy import ndimage\n'), ((6786, 6803), 'numpy.round', 'np.round', (['im3d', '(1)'], {}), '(im3d, 1)\n', (6794, 6803), True, 'import numpy as np\n'), ((7395, 7420), 'scipy.ndimage.label', 'ndimage.label', (['local_maxi'], {}), '(local_maxi)\n', (7408, 7420), False, 'from scipy import ndimage\n'), ((11194, 11214), 'numpy.flatnonzero', 'np.flatnonzero', (['im3d'], {}), '(im3d)\n', (11208, 11214), True, 'import numpy as np\n'), ((12450, 12514), 'networkx.set_node_attributes', 'nx.set_node_attributes', (['cavities[cav_of_interest].graph', 'my_dict'], {}), '(cavities[cav_of_interest].graph, my_dict)\n', (12472, 12514), True, 'import networkx as nx\n'), ((13328, 13369), 'numpy.unique', 'np.unique', (['listouille'], {'return_counts': '(True)'}), '(listouille, return_counts=True)\n', (13337, 13369), True, 'import numpy as np\n'), ((13380, 13394), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (13386, 13394), True, 'import numpy as np\n'), ((1757, 1770), 'os.mkdir', 'os.mkdir', (['out'], {}), '(out)\n', (1765, 1770), False, 'import os\n'), ((2009, 2178), 'caviar.misc_tools.misc.export_pdb_subcavities', 'export_pdb_subcavities', (['subcavs', 'code[:-4]', 'grid_min', 'grid_shape'], {'cavid': 'cav_of_interest', 'gridspace': 'gridspace', 'outdir': 'out', 'listlig': 'list_ligands', 'oridir': 'sourcedir'}), '(subcavs, code[:-4], grid_min, grid_shape, cavid=\n cav_of_interest, gridspace=gridspace, outdir=out, listlig=list_ligands,\n oridir=sourcedir)\n', (2031, 2178), False, 'from caviar.misc_tools.misc import export_pdb_subcavities\n'), ((5517, 5532), 'scipy.stats.entropy', 'entropy', (['pharma'], {}), '(pharma)\n', (5524, 5532), False, 'from scipy.stats import entropy\n'), ((5929, 5951), 'numpy.around', 'np.around', (['aligned_cav'], {}), '(aligned_cav)\n', (5938, 5951), True, 'import numpy as np\n'), ((9337, 9356), 'numpy.argmax', 'np.argmax', (['contacts'], {}), '(contacts)\n', (9346, 9356), True, 'import numpy as np\n'), ((10599, 10610), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (10607, 10610), True, 'import numpy as np\n'), ((10923, 10938), 'numpy.amax', 'np.amax', (['labels'], {}), '(labels)\n', (10930, 10938), True, 'import numpy as np\n'), ((10957, 10981), 'numpy.argwhere', 'np.argwhere', (['(labels == i)'], {}), '(labels == i)\n', (10968, 10981), True, 'import numpy as np\n'), ((13646, 13674), 'numpy.divide', 'np.divide', (['counts[aa]', 'total'], {}), '(counts[aa], total)\n', (13655, 13674), True, 'import numpy as np\n'), ((3066, 3103), 'numpy.array', 'np.array', (['aligned_cav'], {'dtype': 'np.float'}), '(aligned_cav, dtype=np.float)\n', (3074, 3103), True, 'import numpy as np\n'), ((12040, 12092), 'caviar.cavity_identification.gridtools.get_index_of_coor_list', 'get_index_of_coor_list', (['subcav', 'grid_min', 'grid_shape'], {}), '(subcav, grid_min, grid_shape)\n', (12062, 12092), False, 'from caviar.cavity_identification.gridtools import get_index_of_coor_list\n'), ((12773, 12793), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (12781, 12793), True, 'import numpy as np\n'), ((12921, 12941), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (12929, 12941), True, 'import numpy as np\n'), ((12985, 13005), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (12993, 13005), True, 'import numpy as np\n'), ((13103, 13123), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (13111, 13123), True, 'import numpy as np\n'), ((13167, 13187), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (13175, 13187), True, 'import numpy as np\n'), ((13231, 13251), 'numpy.array', 'np.array', (['listouille'], {}), '(listouille)\n', (13239, 13251), True, 'import numpy as np\n'), ((9899, 9965), 'numpy.concatenate', 'np.concatenate', (['(_subcavs[to_del[index]], _subcavs[index])'], {'axis': '(0)'}), '((_subcavs[to_del[index]], _subcavs[index]), axis=0)\n', (9913, 9965), True, 'import numpy as np\n'), ((12120, 12178), 'numpy.array', 'np.array', (['[x.coords for x in cavities[cav_of_interest].gp]'], {}), '([x.coords for x in cavities[cav_of_interest].gp])\n', (12128, 12178), True, 'import numpy as np\n'), ((10302, 10316), 'numpy.array', 'np.array', (['_tmp'], {}), '(_tmp)\n', (10310, 10316), True, 'import numpy as np\n'), ((9253, 9272), 'numpy.argmax', 'np.argmax', (['contacts'], {}), '(contacts)\n', (9262, 9272), True, 'import numpy as np\n'), ((14143, 14167), 'numpy.around', 'np.around', (['(dico[1] * 100)'], {}), '(dico[1] * 100)\n', (14152, 14167), True, 'import numpy as np\n'), ((14185, 14209), 'numpy.around', 'np.around', (['(dico[3] * 100)'], {}), '(dico[3] * 100)\n', (14194, 14209), True, 'import numpy as np\n'), ((14249, 14273), 'numpy.around', 'np.around', (['(dico[6] * 100)'], {}), '(dico[6] * 100)\n', (14258, 14273), True, 'import numpy as np\n'), ((14290, 14314), 'numpy.around', 'np.around', (['(dico[7] * 100)'], {}), '(dico[7] * 100)\n', (14299, 14314), True, 'import numpy as np\n'), ((14331, 14355), 'numpy.around', 'np.around', (['(dico[8] * 100)'], {}), '(dico[8] * 100)\n', (14340, 14355), True, 'import numpy as np\n'), ((8803, 8842), 'scipy.spatial.distance.cdist', 'cdist', (['subcavs[small[0]]', 'other_subcavs'], {}), '(subcavs[small[0]], other_subcavs)\n', (8808, 8842), False, 'from scipy.spatial.distance import cdist\n'), ((10191, 10224), 'numpy.array', 'np.array', (['_subcavs[to_del[index]]'], {}), '(_subcavs[to_del[index]])\n', (10199, 10224), True, 'import numpy as np\n'), ((10236, 10261), 'numpy.array', 'np.array', (['_subcavs[index]'], {}), '(_subcavs[index])\n', (10244, 10261), True, 'import numpy as np\n')] |
import ltfatpy
import numpy as np
__author__ = 'Andres'
class LTFATStft(object):
def __init__(self, windowLength, hopSize):
super().__init__()
self.windowLength = windowLength
self.hopSize = hopSize
self.g_analysis = {'name': 'gauss', 'M': windowLength}
self.g_synthesis = {'name': ('dual', self.g_analysis['name']), 'M': self.g_analysis['M']}
def oneSidedStft(self, signal):
return ltfatpy.dgtreal(signal, self.g_analysis, self.hopSize, self.windowLength)[0]
def inverseOneSidedStft(self, signal):
return ltfatpy.idgtreal(signal, self.g_synthesis, self.hopSize, self.windowLength)[0]
def magAndPhaseOneSidedStft(self, signal):
stft = self.oneSidedStft(signal)
return np.abs(stft), np.angle(stft)
def log10MagAndPhaseOneSidedStft(self, signal, clipBelow=1e-14):
realDGT = self.oneSidedStft(signal)
return self.log10MagFromRealDGT(realDGT, clipBelow), np.angle(realDGT)
def log10MagFromRealDGT(self, realDGT, clipBelow=1e-14):
return np.log10(np.clip(np.abs(realDGT), a_min=clipBelow, a_max=None))
def reconstructSignalFromLogged10Spectogram(self, logSpectrogram, phase):
reComplexStft = (10 ** logSpectrogram) * np.exp(1.0j * phase)
return self.inverseOneSidedStft(reComplexStft)
def logMagAndPhaseOneSidedStft(self, signal, clipBelow=np.e**-30, normalize=False):
realDGT = self.oneSidedStft(signal)
spectrogram = self.logMagFromRealDGT(realDGT, clipBelow, normalize)
return spectrogram, np.angle(realDGT)
def logMagFromRealDGT(self, realDGT, clipBelow=np.e**-30, normalize=False):
spectrogram = np.abs(realDGT)
if normalize:
spectrogram = spectrogram/np.max(spectrogram)
return np.log(np.clip(spectrogram, a_min=clipBelow, a_max=None))
def reconstructSignalFromLoggedSpectogram(self, logSpectrogram, phase):
reComplexStft = (np.e ** logSpectrogram) * np.exp(1.0j * phase)
return self.inverseOneSidedStft(reComplexStft)
| [
"numpy.abs",
"numpy.angle",
"ltfatpy.dgtreal",
"numpy.clip",
"ltfatpy.idgtreal",
"numpy.max",
"numpy.exp"
] | [((1688, 1703), 'numpy.abs', 'np.abs', (['realDGT'], {}), '(realDGT)\n', (1694, 1703), True, 'import numpy as np\n'), ((443, 516), 'ltfatpy.dgtreal', 'ltfatpy.dgtreal', (['signal', 'self.g_analysis', 'self.hopSize', 'self.windowLength'], {}), '(signal, self.g_analysis, self.hopSize, self.windowLength)\n', (458, 516), False, 'import ltfatpy\n'), ((580, 655), 'ltfatpy.idgtreal', 'ltfatpy.idgtreal', (['signal', 'self.g_synthesis', 'self.hopSize', 'self.windowLength'], {}), '(signal, self.g_synthesis, self.hopSize, self.windowLength)\n', (596, 655), False, 'import ltfatpy\n'), ((763, 775), 'numpy.abs', 'np.abs', (['stft'], {}), '(stft)\n', (769, 775), True, 'import numpy as np\n'), ((777, 791), 'numpy.angle', 'np.angle', (['stft'], {}), '(stft)\n', (785, 791), True, 'import numpy as np\n'), ((967, 984), 'numpy.angle', 'np.angle', (['realDGT'], {}), '(realDGT)\n', (975, 984), True, 'import numpy as np\n'), ((1254, 1274), 'numpy.exp', 'np.exp', (['(1.0j * phase)'], {}), '(1.0j * phase)\n', (1260, 1274), True, 'import numpy as np\n'), ((1567, 1584), 'numpy.angle', 'np.angle', (['realDGT'], {}), '(realDGT)\n', (1575, 1584), True, 'import numpy as np\n'), ((1806, 1855), 'numpy.clip', 'np.clip', (['spectrogram'], {'a_min': 'clipBelow', 'a_max': 'None'}), '(spectrogram, a_min=clipBelow, a_max=None)\n', (1813, 1855), True, 'import numpy as np\n'), ((1985, 2005), 'numpy.exp', 'np.exp', (['(1.0j * phase)'], {}), '(1.0j * phase)\n', (1991, 2005), True, 'import numpy as np\n'), ((1079, 1094), 'numpy.abs', 'np.abs', (['realDGT'], {}), '(realDGT)\n', (1085, 1094), True, 'import numpy as np\n'), ((1764, 1783), 'numpy.max', 'np.max', (['spectrogram'], {}), '(spectrogram)\n', (1770, 1783), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
========================
Polynomial interpolation
========================
This example demonstrates how to approximate a function with a polynomial of
degree n_degree by using ridge regression. Concretely, from n_samples 1d
points, it suffices to build the Vandermonde matrix, which is n_samples x
n_degree+1 and has the following form:
[[1, x_1, x_1 ** 2, x_1 ** 3, ...],
[1, x_2, x_2 ** 2, x_2 ** 3, ...],
...]
Intuitively, this matrix can be interpreted as a matrix of pseudo features (the
points raised to some power). The matrix is akin to (but different from) the
matrix induced by a polynomial kernel.
This example shows that you can do non-linear regression with a linear model,
using a pipeline to add non-linear features. Kernel methods extend this idea
and can induce very high (even infinite) dimensional feature spaces.
"""
print(__doc__)
# Author: <NAME>
# <NAME>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
def f(x):
""" function to approximate by polynomial interpolation"""
return x * np.sin(x)
# generate points used to plot
x_plot = np.linspace(0, 10, 100)
# generate points and keep a subset of them
x = np.linspace(0, 10, 100)
rng = np.random.RandomState(0)
rng.shuffle(x)
x = np.sort(x[:20])
y = f(x)
# create matrix versions of these arrays
X = x[:, np.newaxis]
X_plot = x_plot[:, np.newaxis]
#plt.plot(x_plot, f(x_plot), label="ground truth")
plt.scatter(x, y, label="training points")
for degree in [3, 4, 5]:
model = make_pipeline(PolynomialFeatures(degree), Ridge())
model.fit(X, y)
y_plot = model.predict(X_plot)
plt.plot(x_plot, y_plot, label="degree %d" % degree)
plt.legend(loc='lower left')
plt.show()
| [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"numpy.random.RandomState",
"numpy.sort",
"sklearn.preprocessing.PolynomialFeatures",
"numpy.sin",
"numpy.linspace",
"sklearn.linear_model.Ridge"
] | [((1274, 1297), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(100)'], {}), '(0, 10, 100)\n', (1285, 1297), True, 'import numpy as np\n'), ((1347, 1370), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(100)'], {}), '(0, 10, 100)\n', (1358, 1370), True, 'import numpy as np\n'), ((1377, 1401), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (1398, 1401), True, 'import numpy as np\n'), ((1421, 1436), 'numpy.sort', 'np.sort', (['x[:20]'], {}), '(x[:20])\n', (1428, 1436), True, 'import numpy as np\n'), ((1592, 1634), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'label': '"""training points"""'}), "(x, y, label='training points')\n", (1603, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1837, 1865), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""'}), "(loc='lower left')\n", (1847, 1865), True, 'import matplotlib.pyplot as plt\n'), ((1867, 1877), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1875, 1877), True, 'import matplotlib.pyplot as plt\n'), ((1783, 1835), 'matplotlib.pyplot.plot', 'plt.plot', (['x_plot', 'y_plot'], {'label': "('degree %d' % degree)"}), "(x_plot, y_plot, label='degree %d' % degree)\n", (1791, 1835), True, 'import matplotlib.pyplot as plt\n'), ((1222, 1231), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (1228, 1231), True, 'import numpy as np\n'), ((1687, 1713), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['degree'], {}), '(degree)\n', (1705, 1713), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((1715, 1722), 'sklearn.linear_model.Ridge', 'Ridge', ([], {}), '()\n', (1720, 1722), False, 'from sklearn.linear_model import Ridge\n')] |
#! /usr/bin/python3
# coding: utf-8
"""Matplotlib QtDesigner Widget."""
import numpy as np
import matplotlib.image as image
from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSignal
from matplotlib.figure import Figure
from matplotlib.collections import LineCollection
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
def make_segments(x, y):
"""Make segments."""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments
class MplCanvas(FigureCanvasQTAgg):
"""MplCanvas."""
depassement = pyqtSignal()
def __init__(self):
"""Init."""
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
FigureCanvasQTAgg.__init__(self, self.fig)
FigureCanvasQTAgg.setSizePolicy(
self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
FigureCanvasQTAgg.updateGeometry(self)
def graph(self, model, t=0):
"""Plot deformée."""
# Initialise l'espace du graphique
self.fig.clf()
self.ax = self.fig.add_subplot(111)
self.ax.set_title(model.legend['title'])
# Afiche la courbe de deformee coloree en fonction du resulat selectionné
if t == 0:
lc = self.colorline(model.deformee[0], model.deformee[1], np.round(np.absolute(model.deplacements[:-1:]), 10))
cbar = self.fig.colorbar(lc)
cbar.ax.set_title(r"Déplacement en $mm$")
elif t == 1:
contraintes = model.contraintes
lc = self.colorline(model.deformee[0], model.deformee[1], np.round(np.absolute(contraintes), 10))
cbar = self.fig.colorbar(lc)
cbar.ax.set_title(r"Contraintes en $MPa$")
if max(contraintes) >= model.material.Re:
self.depassement.emit()
# Affiche l'effort et les liasons
for effort in model.efforts:
self.ax.arrow(effort[0], effort[1], effort[2], effort[3], head_width=effort[4], head_length=effort[5], fc='m', ec='m')
encastrement_horiz = image.imread('ui/liaisons/encastrement_horiz.jpg')
encastrement_vert = image.imread('ui/liaisons/encastrement_vert.jpg')
glissiere = image.imread('ui/liaisons/glissiere.jpg')
rotule = image.imread('ui/liaisons/rotule.jpg')
ponctuelle = image.imread('ui/liaisons/ponctuelle.jpg')
if model.__class__.__name__ == "PoutreEnTraction":
self.ax.set_xlim([-0.1, 0.1])
self.ax.set_ylim([-50, model._lenght + 50])
self.ax.get_xaxis().set_visible(False)
self.ax.imshow(encastrement_horiz, aspect='auto', extent=(-0.01, 0.01, -30, 5))
elif model.__class__.__name__ == "PoutreEnFlexion":
if model.selected == 0:
self.ax.imshow(encastrement_vert, aspect='auto', extent=(-20, 10, -0.5, 0.5))
if model.selected == 1:
self.ax.imshow(encastrement_vert, aspect='auto', extent=(-20, 10, -0.005, 0.005))
self.ax.imshow(glissiere, aspect='auto', extent=(model._lenght-20, model._lenght + 20, -0.01, 0))
if model.selected == 2:
self.ax.imshow(rotule, aspect='auto', extent=(-20, 20, -0.03, 0))
self.ax.imshow(ponctuelle, aspect='auto', extent=(model._lenght-20, model._lenght + 20, -0.03, 0))
elif model.__class__.__name__ == "TreilliSimple":
pass
# Affiche la poutre initiale
self.ax.plot(model.initial[0], model.initial[1], linewidth=2, color='k', linestyle="-.")
self.ax.set_xlabel(model.legend['xtitle'])
self.ax.set_ylabel(model.legend['ytitle'])
self.draw()
def colorline(self, x, y, z):
"""Plot a colored line with coordinates x and y."""
z = np.asarray(z)
segments = make_segments(x, y)
lc = LineCollection(segments, array=z, cmap='jet', linewidth=6, alpha=1)
self.ax.add_collection(lc)
return lc
class MplWidget(QtWidgets.QWidget):
"""QtDesigner QtWidget Promotion Class."""
def __init__(self, parent=None):
"""Init."""
QtWidgets.QWidget.__init__(self, parent)
self.canvas = MplCanvas()
self.vbl = QtWidgets.QVBoxLayout()
self.vbl.addWidget(self.canvas)
self.setLayout(self.vbl)
| [
"PyQt5.QtCore.pyqtSignal",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setSizePolicy",
"matplotlib.image.imread",
"matplotlib.collections.LineCollection",
"numpy.absolute",
"numpy.asarray",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry",
"PyQt5.QtWidgets.QVBoxLayout",
... | [((461, 510), 'numpy.concatenate', 'np.concatenate', (['[points[:-1], points[1:]]'], {'axis': '(1)'}), '([points[:-1], points[1:]], axis=1)\n', (475, 510), True, 'import numpy as np\n'), ((609, 621), 'PyQt5.QtCore.pyqtSignal', 'pyqtSignal', ([], {}), '()\n', (619, 621), False, 'from PyQt5.QtCore import pyqtSignal\n'), ((686, 694), 'matplotlib.figure.Figure', 'Figure', ([], {}), '()\n', (692, 694), False, 'from matplotlib.figure import Figure\n'), ((747, 789), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__', 'FigureCanvasQTAgg.__init__', (['self', 'self.fig'], {}), '(self, self.fig)\n', (773, 789), False, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\n'), ((798, 905), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setSizePolicy', 'FigureCanvasQTAgg.setSizePolicy', (['self', 'QtWidgets.QSizePolicy.Expanding', 'QtWidgets.QSizePolicy.Expanding'], {}), '(self, QtWidgets.QSizePolicy.Expanding,\n QtWidgets.QSizePolicy.Expanding)\n', (829, 905), False, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\n'), ((923, 961), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry', 'FigureCanvasQTAgg.updateGeometry', (['self'], {}), '(self)\n', (955, 961), False, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\n'), ((2110, 2160), 'matplotlib.image.imread', 'image.imread', (['"""ui/liaisons/encastrement_horiz.jpg"""'], {}), "('ui/liaisons/encastrement_horiz.jpg')\n", (2122, 2160), True, 'import matplotlib.image as image\n'), ((2189, 2238), 'matplotlib.image.imread', 'image.imread', (['"""ui/liaisons/encastrement_vert.jpg"""'], {}), "('ui/liaisons/encastrement_vert.jpg')\n", (2201, 2238), True, 'import matplotlib.image as image\n'), ((2259, 2300), 'matplotlib.image.imread', 'image.imread', (['"""ui/liaisons/glissiere.jpg"""'], {}), "('ui/liaisons/glissiere.jpg')\n", (2271, 2300), True, 'import matplotlib.image as image\n'), ((2318, 2356), 'matplotlib.image.imread', 'image.imread', (['"""ui/liaisons/rotule.jpg"""'], {}), "('ui/liaisons/rotule.jpg')\n", (2330, 2356), True, 'import matplotlib.image as image\n'), ((2378, 2420), 'matplotlib.image.imread', 'image.imread', (['"""ui/liaisons/ponctuelle.jpg"""'], {}), "('ui/liaisons/ponctuelle.jpg')\n", (2390, 2420), True, 'import matplotlib.image as image\n'), ((3832, 3845), 'numpy.asarray', 'np.asarray', (['z'], {}), '(z)\n', (3842, 3845), True, 'import numpy as np\n'), ((3898, 3965), 'matplotlib.collections.LineCollection', 'LineCollection', (['segments'], {'array': 'z', 'cmap': '"""jet"""', 'linewidth': '(6)', 'alpha': '(1)'}), "(segments, array=z, cmap='jet', linewidth=6, alpha=1)\n", (3912, 3965), False, 'from matplotlib.collections import LineCollection\n'), ((4170, 4210), 'PyQt5.QtWidgets.QWidget.__init__', 'QtWidgets.QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (4196, 4210), False, 'from PyQt5 import QtWidgets\n'), ((4264, 4287), 'PyQt5.QtWidgets.QVBoxLayout', 'QtWidgets.QVBoxLayout', ([], {}), '()\n', (4285, 4287), False, 'from PyQt5 import QtWidgets\n'), ((409, 425), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (417, 425), True, 'import numpy as np\n'), ((1365, 1401), 'numpy.absolute', 'np.absolute', (['model.deplacements[:-1]'], {}), '(model.deplacements[:-1])\n', (1376, 1401), True, 'import numpy as np\n'), ((1648, 1672), 'numpy.absolute', 'np.absolute', (['contraintes'], {}), '(contraintes)\n', (1659, 1672), True, 'import numpy as np\n')] |
# RBM class
'''
Adapted from code by <NAME> and <NAME>
Available at: http://science.sciencemag.org/content/suppl/2006/08/04/313.5786.504.DC1
A class defining a restricted Boltzmann machine.
'''
import numpy as np
import random
import matplotlib.pyplot as plt
from numba import jit, prange
learning_rate = 0.1
def sigmoid(x):
return 1/(1+np.exp(-x))
class RBM:
def __init__(self,v_dim,h_dim):
'''
v_dim = dimension of the visible layer
h_dim = dimension of the hidden layer
'''
self.v_dim = v_dim
self.h_dim = h_dim
self.W = np.zeros((self.v_dim,self.h_dim))
self.a = np.zeros((self.v_dim,1))
self.b = np.zeros((self.h_dim,1))
return
@classmethod
def from_Values(cls,weights):
'''
Initialize with trained weights.
'''
W,a,b = weights['W'],weights['a'],weights['b']
assert (W.shape[0] == a.shape[0]) and (W.shape[1] == b.shape[0])
rbm = cls(W.shape[0],W.shape[1])
rbm.W = W
rbm.a = a
rbm.b = b
return rbm
@classmethod
def from_File(cls,filename):
'''
Initialize with weights loaded from a file.
'''
return cls.from_Values(RBM.load_weights(filename))
def v_probs(self,h):
'''
Input:
- h has shape (h_dim,m)
- a has shape (v_dim,1)
- W has shape (v_dim,h_dim)
'''
assert(h.shape[0] == self.h_dim)
v_probs = sigmoid(self.a + np.dot(self.W,h))
assert(not np.sum(np.isnan(v_probs)))
return v_probs
def h_probs(self,v):
'''
Input:
- v has shape (v_dim,m)
- b has shape (h_dim,1)
- W has shape (v_dim,h_dim)
'''
assert(v.shape[0] == self.v_dim)
h_probs = sigmoid(self.b + np.dot(self.W.T,v))
assert(not np.sum(np.isnan(h_probs)))
return h_probs
def train(self, x, epochs = 10, batch_size = 100, verbose = 1, learning_rate = learning_rate, initialize_weights = True):
'''
Trains the RBM with the 1-step Contrastive Divergence algorithm (Hinton, 2002).
Input:
- x has shape (v_dim, number_of_examples)
- plot = True plots debugging related plots after every epoch
- initialize_weights = False to continue training a model
(e.g. loaded from earlier trained weights)
'''
assert(x.shape[0]==self.v_dim)
@jit(cache=True,parallel=True)
def nb_binomial(n,p):
d0 = np.shape(p)[0]
d1 = np.shape(p)[1]
tmp = np.empty_like(p)
for c in prange(d0*d1):
i = c // d1
j = c % d1
tmp[i,j] = np.random.binomial(n,p[i,j])
return tmp
@jit(cache=True,parallel=True)
def nb_mean2(x):
d0 = np.shape(x)[0]
d1 = np.shape(x)[1]
tmp = np.empty((d0,d1))
for c in prange(d0*d1):
i = c // d1
j = c % d1
tmp[i,j] = np.mean(x[i,j,:])
return tmp
@jit(cache=True,parallel=True)
def nb_mean1(x):
#keeping the np array dimension
d0 = np.shape(x)[0]
tmp = np.empty((d0,1))
for i in prange(d0):
tmp[i,0] = np.mean(x[i,:])
return tmp
@jit()
def contrastive_grad(x,v_dim,h_dim,epochs,x_shape,batch_size,initialize_weights,verbose):
np.random.seed(0)
# track mse
error = 0.
error_sum = 0.
# hyperparameters used by Hinton for MNIST
initialmomentum = 0.5
finalmomentum = 0.9
weightcost = 0.0002
num_minibatches = int(x_shape/batch_size)
DW = np.zeros((v_dim,h_dim))
Da = np.zeros((v_dim,1))
Db = np.zeros((h_dim,1))
# initialize weights and parameters
if initialize_weights == True:
W = np.ascontiguousarray(np.random.normal(0.,0.1,size = (v_dim,h_dim)))
# visible bias a_i is initialized to ln(p_i/(1-p_i)), p_i = (proportion of examples where x_i = 1)
#self.a = (np.log(np.mean(x,axis = 1,keepdims=True)+1e-10) - np.log(1-np.mean(x,axis = 1,keepdims=True)+1e-10))
a = np.zeros((v_dim,1))
b = np.zeros((h_dim,1))
error_log = 0.
for i in range(epochs):
if verbose>0:
print("Epoch ",(i+1))
np.random.shuffle(x.T)
if i>5:
momentum = finalmomentum
else:
momentum = initialmomentum
for j in range(num_minibatches):
# get the next batch
v_pos_states = np.ascontiguousarray(x[:,j*batch_size:(j+1)*batch_size])
# get hidden probs, positive product, and sample hidden states
h_pos_probs = 1/(1+np.exp(-(b + np.dot(W.T,v_pos_states))))
pos_prods = np.expand_dims(v_pos_states,1)*np.expand_dims(h_pos_probs,0)
h_pos_states = nb_binomial(1,h_pos_probs)
# get negative probs and product
v_neg_probs = a + np.dot(W,h_pos_states)
h_neg_probs = 1/(1+np.exp(-(b + np.dot(W.T,v_neg_probs))))
neg_prods = np.expand_dims(v_neg_probs,1)*np.expand_dims(h_neg_probs,0)
# compute the gradients, averaged over minibatch, with momentum and regularization
cd = nb_mean2(pos_prods - neg_prods)
DW = momentum*DW + learning_rate*(cd - weightcost*W)
Da = momentum*Da + learning_rate*nb_mean1(v_pos_states - v_neg_probs)
Db = momentum*Db + learning_rate*nb_mean1(h_pos_probs - h_neg_probs)
# update weights and biases
W = W + DW
a = a + Da
b = b + Db
# log the mse of the reconstructed images
error = np.mean((v_pos_states - v_neg_probs)**2)
error_sum = error_sum + error
error_sum = error_sum/num_minibatches
if verbose>0:
print("Reconstruction MSE = ",error_sum)
if (abs(error_sum - error_log)/error_sum < 0.01) or (abs(error_sum - error_log) < 0.005):
break
error_log = error_sum
error_sum = 0.
return W, a, b
self.W, self.a, self.b = contrastive_grad(x,self.v_dim,self.h_dim,epochs,x.shape[1],batch_size,initialize_weights,verbose)
return
def gibbs_sampling(self, n=1, m=1,v=None):
'''
n - number of iterations of blocked Gibbs sampling
m - number of samples generated
'''
if v is None:
v_probs = np.full((self.v_dim,m),0.5)
v = np.random.binomial(1,v_probs)
h_probs = self.h_probs(v)
h_states = np.random.binomial(1,h_probs)
for i in range(n):
v_probs = self.v_probs(h_states)
v_states = np.random.binomial(1,v_probs)
h_probs = self.h_probs(v_states)
h_states = np.random.binomial(1,h_probs)
return v_states,h_states
def plot_weights(self):
'''
For debugging
'''
return
def plot_weight_histogram(self):
'''
For debugging
'''
plt.figure(1)
plt.subplot(311)
plt.title('Weights')
plt.hist(self.W.flatten(),bins='auto')
plt.subplot(312)
plt.title('Visible biases')
plt.hist(self.a.flatten(),bins='auto')
plt.subplot(313)
plt.title('Hidden biases')
plt.hist(self.b.flatten(),bins='auto')
plt.tight_layout()
plt.show()
return
def save(self, filename):
'''
Save trained weights of self to file
'''
weights = {"W":self.W,"a":self.a,"b":self.b}
RBM.save_weights(weights,filename)
return
@staticmethod
def save_weights(weights,filename):
'''
Save RBM weights to file
'''
np.savetxt(filename + '_a.csv',weights['a'],delimiter=",")
np.savetxt(filename + '_b.csv',weights['b'],delimiter=",")
np.savetxt(filename + '_W.csv',weights['W'],delimiter=",")
return
@staticmethod
def load_weights(filename):
'''
Save RBM weights to file
'''
W = np.loadtxt(filename + '_W.csv',delimiter=",")
a = np.loadtxt(filename + '_a.csv',delimiter=",").reshape((W.shape[0],1))
b = np.loadtxt(filename + '_b.csv',delimiter=",").reshape((W.shape[1],1))
return {"W":W,"a":a,"b":b}
| [
"matplotlib.pyplot.title",
"numpy.random.seed",
"numpy.empty",
"numpy.isnan",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.exp",
"numpy.random.normal",
"numba.prange",
"matplotlib.pyplot.tight_layout",
"numpy.full",
"numpy.savetxt",
"numpy.empty_like",
"numpy.loadtxt",... | [((621, 655), 'numpy.zeros', 'np.zeros', (['(self.v_dim, self.h_dim)'], {}), '((self.v_dim, self.h_dim))\n', (629, 655), True, 'import numpy as np\n'), ((672, 697), 'numpy.zeros', 'np.zeros', (['(self.v_dim, 1)'], {}), '((self.v_dim, 1))\n', (680, 697), True, 'import numpy as np\n'), ((714, 739), 'numpy.zeros', 'np.zeros', (['(self.h_dim, 1)'], {}), '((self.h_dim, 1))\n', (722, 739), True, 'import numpy as np\n'), ((2578, 2608), 'numba.jit', 'jit', ([], {'cache': '(True)', 'parallel': '(True)'}), '(cache=True, parallel=True)\n', (2581, 2608), False, 'from numba import jit, prange\n'), ((2917, 2947), 'numba.jit', 'jit', ([], {'cache': '(True)', 'parallel': '(True)'}), '(cache=True, parallel=True)\n', (2920, 2947), False, 'from numba import jit, prange\n'), ((3241, 3271), 'numba.jit', 'jit', ([], {'cache': '(True)', 'parallel': '(True)'}), '(cache=True, parallel=True)\n', (3244, 3271), False, 'from numba import jit, prange\n'), ((3524, 3529), 'numba.jit', 'jit', ([], {}), '()\n', (3527, 3529), False, 'from numba import jit, prange\n'), ((7427, 7457), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'h_probs'], {}), '(1, h_probs)\n', (7445, 7457), True, 'import numpy as np\n'), ((7916, 7929), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (7926, 7929), True, 'import matplotlib.pyplot as plt\n'), ((7939, 7955), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (7950, 7955), True, 'import matplotlib.pyplot as plt\n'), ((7964, 7984), 'matplotlib.pyplot.title', 'plt.title', (['"""Weights"""'], {}), "('Weights')\n", (7973, 7984), True, 'import matplotlib.pyplot as plt\n'), ((8049, 8065), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (8060, 8065), True, 'import matplotlib.pyplot as plt\n'), ((8074, 8101), 'matplotlib.pyplot.title', 'plt.title', (['"""Visible biases"""'], {}), "('Visible biases')\n", (8083, 8101), True, 'import matplotlib.pyplot as plt\n'), ((8166, 8182), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {}), '(313)\n', (8177, 8182), True, 'import matplotlib.pyplot as plt\n'), ((8191, 8217), 'matplotlib.pyplot.title', 'plt.title', (['"""Hidden biases"""'], {}), "('Hidden biases')\n", (8200, 8217), True, 'import matplotlib.pyplot as plt\n'), ((8274, 8292), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8290, 8292), True, 'import matplotlib.pyplot as plt\n'), ((8302, 8312), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8310, 8312), True, 'import matplotlib.pyplot as plt\n'), ((8671, 8731), 'numpy.savetxt', 'np.savetxt', (["(filename + '_a.csv')", "weights['a']"], {'delimiter': '""","""'}), "(filename + '_a.csv', weights['a'], delimiter=',')\n", (8681, 8731), True, 'import numpy as np\n'), ((8738, 8798), 'numpy.savetxt', 'np.savetxt', (["(filename + '_b.csv')", "weights['b']"], {'delimiter': '""","""'}), "(filename + '_b.csv', weights['b'], delimiter=',')\n", (8748, 8798), True, 'import numpy as np\n'), ((8805, 8865), 'numpy.savetxt', 'np.savetxt', (["(filename + '_W.csv')", "weights['W']"], {'delimiter': '""","""'}), "(filename + '_W.csv', weights['W'], delimiter=',')\n", (8815, 8865), True, 'import numpy as np\n'), ((9003, 9049), 'numpy.loadtxt', 'np.loadtxt', (["(filename + '_W.csv')"], {'delimiter': '""","""'}), "(filename + '_W.csv', delimiter=',')\n", (9013, 9049), True, 'import numpy as np\n'), ((364, 374), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (370, 374), True, 'import numpy as np\n'), ((2720, 2736), 'numpy.empty_like', 'np.empty_like', (['p'], {}), '(p)\n', (2733, 2736), True, 'import numpy as np\n'), ((2758, 2773), 'numba.prange', 'prange', (['(d0 * d1)'], {}), '(d0 * d1)\n', (2764, 2773), False, 'from numba import jit, prange\n'), ((3054, 3072), 'numpy.empty', 'np.empty', (['(d0, d1)'], {}), '((d0, d1))\n', (3062, 3072), True, 'import numpy as np\n'), ((3093, 3108), 'numba.prange', 'prange', (['(d0 * d1)'], {}), '(d0 * d1)\n', (3099, 3108), False, 'from numba import jit, prange\n'), ((3390, 3407), 'numpy.empty', 'np.empty', (['(d0, 1)'], {}), '((d0, 1))\n', (3398, 3407), True, 'import numpy as np\n'), ((3428, 3438), 'numba.prange', 'prange', (['d0'], {}), '(d0)\n', (3434, 3438), False, 'from numba import jit, prange\n'), ((3640, 3657), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (3654, 3657), True, 'import numpy as np\n'), ((3979, 4003), 'numpy.zeros', 'np.zeros', (['(v_dim, h_dim)'], {}), '((v_dim, h_dim))\n', (3987, 4003), True, 'import numpy as np\n'), ((4020, 4040), 'numpy.zeros', 'np.zeros', (['(v_dim, 1)'], {}), '((v_dim, 1))\n', (4028, 4040), True, 'import numpy as np\n'), ((4057, 4077), 'numpy.zeros', 'np.zeros', (['(h_dim, 1)'], {}), '((h_dim, 1))\n', (4065, 4077), True, 'import numpy as np\n'), ((7298, 7327), 'numpy.full', 'np.full', (['(self.v_dim, m)', '(0.5)'], {}), '((self.v_dim, m), 0.5)\n', (7305, 7327), True, 'import numpy as np\n'), ((7342, 7372), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'v_probs'], {}), '(1, v_probs)\n', (7360, 7372), True, 'import numpy as np\n'), ((7553, 7583), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'v_probs'], {}), '(1, v_probs)\n', (7571, 7583), True, 'import numpy as np\n'), ((7652, 7682), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'h_probs'], {}), '(1, h_probs)\n', (7670, 7682), True, 'import numpy as np\n'), ((1564, 1581), 'numpy.dot', 'np.dot', (['self.W', 'h'], {}), '(self.W, h)\n', (1570, 1581), True, 'import numpy as np\n'), ((1608, 1625), 'numpy.isnan', 'np.isnan', (['v_probs'], {}), '(v_probs)\n', (1616, 1625), True, 'import numpy as np\n'), ((1908, 1927), 'numpy.dot', 'np.dot', (['self.W.T', 'v'], {}), '(self.W.T, v)\n', (1914, 1927), True, 'import numpy as np\n'), ((1954, 1971), 'numpy.isnan', 'np.isnan', (['h_probs'], {}), '(h_probs)\n', (1962, 1971), True, 'import numpy as np\n'), ((2655, 2666), 'numpy.shape', 'np.shape', (['p'], {}), '(p)\n', (2663, 2666), True, 'import numpy as np\n'), ((2687, 2698), 'numpy.shape', 'np.shape', (['p'], {}), '(p)\n', (2695, 2698), True, 'import numpy as np\n'), ((2855, 2885), 'numpy.random.binomial', 'np.random.binomial', (['n', 'p[i, j]'], {}), '(n, p[i, j])\n', (2873, 2885), True, 'import numpy as np\n'), ((2989, 3000), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (2997, 3000), True, 'import numpy as np\n'), ((3021, 3032), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (3029, 3032), True, 'import numpy as np\n'), ((3190, 3209), 'numpy.mean', 'np.mean', (['x[i, j, :]'], {}), '(x[i, j, :])\n', (3197, 3209), True, 'import numpy as np\n'), ((3357, 3368), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (3365, 3368), True, 'import numpy as np\n'), ((3467, 3483), 'numpy.mean', 'np.mean', (['x[i, :]'], {}), '(x[i, :])\n', (3474, 3483), True, 'import numpy as np\n'), ((4514, 4534), 'numpy.zeros', 'np.zeros', (['(v_dim, 1)'], {}), '((v_dim, 1))\n', (4522, 4534), True, 'import numpy as np\n'), ((4554, 4574), 'numpy.zeros', 'np.zeros', (['(h_dim, 1)'], {}), '((h_dim, 1))\n', (4562, 4574), True, 'import numpy as np\n'), ((4726, 4748), 'numpy.random.shuffle', 'np.random.shuffle', (['x.T'], {}), '(x.T)\n', (4743, 4748), True, 'import numpy as np\n'), ((9061, 9107), 'numpy.loadtxt', 'np.loadtxt', (["(filename + '_a.csv')"], {'delimiter': '""","""'}), "(filename + '_a.csv', delimiter=',')\n", (9071, 9107), True, 'import numpy as np\n'), ((9143, 9189), 'numpy.loadtxt', 'np.loadtxt', (["(filename + '_b.csv')"], {'delimiter': '""","""'}), "(filename + '_b.csv', delimiter=',')\n", (9153, 9189), True, 'import numpy as np\n'), ((4212, 4259), 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(0.1)'], {'size': '(v_dim, h_dim)'}), '(0.0, 0.1, size=(v_dim, h_dim))\n', (4228, 4259), True, 'import numpy as np\n'), ((5045, 5108), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['x[:, j * batch_size:(j + 1) * batch_size]'], {}), '(x[:, j * batch_size:(j + 1) * batch_size])\n', (5065, 5108), True, 'import numpy as np\n'), ((6462, 6504), 'numpy.mean', 'np.mean', (['((v_pos_states - v_neg_probs) ** 2)'], {}), '((v_pos_states - v_neg_probs) ** 2)\n', (6469, 6504), True, 'import numpy as np\n'), ((5302, 5333), 'numpy.expand_dims', 'np.expand_dims', (['v_pos_states', '(1)'], {}), '(v_pos_states, 1)\n', (5316, 5333), True, 'import numpy as np\n'), ((5333, 5363), 'numpy.expand_dims', 'np.expand_dims', (['h_pos_probs', '(0)'], {}), '(h_pos_probs, 0)\n', (5347, 5363), True, 'import numpy as np\n'), ((5550, 5573), 'numpy.dot', 'np.dot', (['W', 'h_pos_states'], {}), '(W, h_pos_states)\n', (5556, 5573), True, 'import numpy as np\n'), ((5688, 5718), 'numpy.expand_dims', 'np.expand_dims', (['v_neg_probs', '(1)'], {}), '(v_neg_probs, 1)\n', (5702, 5718), True, 'import numpy as np\n'), ((5718, 5748), 'numpy.expand_dims', 'np.expand_dims', (['h_neg_probs', '(0)'], {}), '(h_neg_probs, 0)\n', (5732, 5748), True, 'import numpy as np\n'), ((5239, 5264), 'numpy.dot', 'np.dot', (['W.T', 'v_pos_states'], {}), '(W.T, v_pos_states)\n', (5245, 5264), True, 'import numpy as np\n'), ((5626, 5650), 'numpy.dot', 'np.dot', (['W.T', 'v_neg_probs'], {}), '(W.T, v_neg_probs)\n', (5632, 5650), True, 'import numpy as np\n')] |
import numpy as np
import logging
from mtrack.solve import solve
logger = logging.getLogger(__name__)
class CoreSolver(object):
def check_forced(self, g1):
"""
Check that the number of forced egdes
incident to any vertex is <= 2 for
a given g1 graph.
"""
for v in g1.get_vertex_iterator():
incident = g1.get_incident_edges(v)
forced = [g1.get_edge_property("selected", u=e.source(), v=e.target()) for e in incident]
assert(sum(forced)<=2)
def solve_subgraph(self,
subgraph,
index_map,
cc_min_vertices,
start_edge_prior,
selection_cost,
orientation_factor,
comb_angle_factor,
core_id,
voxel_size,
time_limit,
backend="Gurobi"):
logger.info("Solve connected subgraphs...")
ccs = subgraph.get_components(min_vertices=cc_min_vertices,
output_folder=None,
return_graphs=True)
j = 0
solutions = []
for cc in ccs:
cc.reindex_edges_save()
self.check_forced(cc)
cc_solution = solve(cc,
start_edge_prior,
orientation_factor,
comb_angle_factor,
selection_cost,
time_limit,
output_dir=None,
voxel_size=None,
chunk_shift=np.array([0.,0.,0.]),
backend=backend)
solutions.append(cc_solution)
j += 1
return solutions
| [
"numpy.array",
"logging.getLogger"
] | [((76, 103), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (93, 103), False, 'import logging\n'), ((1782, 1807), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1790, 1807), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import os
import librosa
from multiprocessing import Pool
SEED = int(1e9+7e7+17)
np.random.seed(SEED)
default_labels = ['blues']*100 + ['classical']*100 + ['country']*100 + ['disco']*100 + ['hiphop']*100 + ['jazz']*99 + ['metal']*100 + ['pop']*100 + ['reggae']*100 + ['rock']*100
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
features = ['chroma_stft_mean', 'chroma_stft_var', 'rms_mean',
'rms_var', 'spectral_centroid_mean', 'spectral_centroid_var',
'spectral_bandwidth_mean', 'spectral_bandwidth_var', 'rolloff_mean',
'rolloff_var', 'zero_crossing_rate_mean', 'zero_crossing_rate_var',
'harmony_mean', 'harmony_var', 'perceptr_mean', 'perceptr_var', 'tempo',
'mfcc1_mean', 'mfcc1_var', 'mfcc2_mean', 'mfcc2_var', 'mfcc3_mean',
'mfcc3_var', 'mfcc4_mean', 'mfcc4_var', 'mfcc5_mean', 'mfcc5_var',
'mfcc6_mean', 'mfcc6_var', 'mfcc7_mean', 'mfcc7_var', 'mfcc8_mean',
'mfcc8_var', 'mfcc9_mean', 'mfcc9_var', 'mfcc10_mean', 'mfcc10_var',
'mfcc11_mean', 'mfcc11_var', 'mfcc12_mean', 'mfcc12_var', 'mfcc13_mean',
'mfcc13_var', 'mfcc14_mean', 'mfcc14_var', 'mfcc15_mean', 'mfcc15_var',
'mfcc16_mean', 'mfcc16_var', 'mfcc17_mean', 'mfcc17_var', 'mfcc18_mean',
'mfcc18_var', 'mfcc19_mean', 'mfcc19_var', 'mfcc20_mean', 'mfcc20_var']
musicnet_path = 'musicnet'
def rel_path_to_abs(file, rel_path):
return os.path.join(os.path.abspath(os.path.dirname(os.path.abspath(file))), rel_path)
# def normalize(track):
# m,s = track.mean(), track.std()
# return (track-m)/s
def normalize(track):
mx,mn = max(track), min(track)
m = (mx+mn)/2
return (track-m)/(mx-m)
class Loader:
def __init__(self, n_jobs=-1):
self.n_jobs = n_jobs if n_jobs>0 else os.cpu_count()
self.names = None
def load_tracks(self, path, n_jobs=-1, verbose=0, get_names=False, normalize=True):
n_jobs = self.n_jobs if n_jobs==-1 else n_jobs
dataset, names = self.__scan_folder__(path, n_jobs, verbose, True, normalize=normalize)
dataset = np.array(dataset)
self.names = names
return (dataset,names) if get_names else dataset
def __scan_folder__(self, path, n_jobs, verbose, get_names, normalize, blacklist=['jazz.00054.wav']):
tracks_paths = []
tmp_paths = []
tracks = []
tracks_names = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
tmp_paths.append(os.path.join(dirpath, filename))
tmp_paths.sort()
for music_path in tmp_paths:
filename = os.path.split(music_path)[1]
if filename in blacklist:
continue
tracks_names.append(filename)
tracks_paths.append(music_path)
if verbose==1:
print(filename)
with Pool(n_jobs) as p:
tracks = p.starmap(self.__load_track__, [(track, verbose, normalize) for track in tracks_paths])
return (tracks, tracks_names) if get_names else tracks
def __load_track__(self, path, verbose, _normalize):
X,sr = librosa.load(path)
if _normalize:
X = normalize(X)
if verbose==2:
print(os.path.split(path)[1])
return X
class Cutter:
def __init__(self, n_jobs=-1):
self.n_jobs = n_jobs if n_jobs>0 else os.cpu_count()
def cut_dataset(self, dataset, durations, sr=22050, n_jobs=-1, default_labels=None, normalize=True):
n_jobs = self.n_jobs if n_jobs==-1 else n_jobs
new_dataset = []
labels = []
self.normalize = normalize
for duration in durations:
if not default_labels:
new_dataset.extend(self.cut_album_in_pieces(dataset, duration, sr, n_jobs))
else:
new_data = self.cut_album_in_pieces(dataset, duration, sr, n_jobs, default_labels)
new_dataset.extend(new_data[0])
labels.extend(new_data[1])
new_dataset = np.array(new_dataset)
return new_dataset if not default_labels else (new_dataset, labels)
def cut_album_in_pieces(self, dataset, duration, sr=22050, n_jobs=-1, default_labels=None):
n_jobs = self.n_jobs if n_jobs==-1 else n_jobs
subtracks = []
labels = []
album = dataset.copy()
if len(album[0].shape)==0:
album = album.reshape((1,-1))
with Pool(n_jobs) as p:
if not default_labels:
new_data = p.starmap(self.cut_track_in_pieces, [(track, duration, sr) for track in album])
else:
new_data = p.starmap(self.cut_track_in_pieces, [(album[i], duration, sr, default_labels[i]) for i in range(len(album))])
for new_data_sample in new_data:
subtracks.extend(new_data_sample[0])
if not default_labels is None:
labels.extend([new_data_sample[1]]*len(new_data_sample[0]))
return subtracks if not default_labels else (subtracks, labels)
def cut_track_in_pieces(self, track, duration, sr=22050, label=None):
subtracks = []
if duration == 0:
raise Exception("Duration must be non-zero")
if duration < 0:
n_pieces = int((-1)/duration)
duration = track.shape[0]/sr/n_pieces
else:
n_pieces = int((track.shape[0]/sr)//duration)
for i in range(n_pieces):
_start, _stop = int(i*duration*sr), int((i+1)*duration*sr)
if self.normalize:
subtracks.append(normalize(track[_start:_stop]))
else:
subtracks.append(track[_start:_stop])
return (subtracks, label)
class MusicFeaturesExtractor:
def __init__(self, n_jobs=-1):
self.n_jobs = n_jobs if n_jobs>0 else os.cpu_count()
self.columns = features
def extract(self, dataset, n_jobs=-1):
###################### mono sound ##########################
n_jobs = self.n_jobs if n_jobs==-1 else n_jobs
if dataset.shape[0]==1:
return pd.DataFrame([self.__extract__(dataset[0])], columns=self.columns)
elif len(dataset[0].shape)==0:
return pd.DataFrame([self.__extract__(dataset)], columns=self.columns)
else:
with Pool(n_jobs) as p:
self.data_features = p.map(self.__extract__, dataset)#, chunksize=4)
data_features = pd.DataFrame(self.data_features, columns=self.columns)
return data_features
def extract_batch(self, data, batch_size=None):
X = None
if batch_size is None:
batch_size=max(1, data.shape[0]//100)
for start_index in range(0, data.shape[0], batch_size):
_start, _stop = start_index, start_index+batch_size
tmpX = self.extract(data[_start:_stop])
if X is None:
X = tmpX
else:
X = pd.concat((X,tmpX), axis=0, ignore_index=True)
return X
def __extract__(self, audio):
features = []
tmp = np.abs(librosa.feature.chroma_stft(audio))
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.feature.rms(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.feature.spectral_centroid(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.feature.spectral_bandwidth(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.feature.spectral_rolloff(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.feature.zero_crossing_rate(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.effects.harmonic(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.effects.percussive(audio)
features.append(tmp.mean())
features.append(tmp.var())
tmp = librosa.beat.tempo(audio)[0]
features.append(tmp)
tmp = librosa.feature.mfcc(audio)
for i in range(20):
features.append(tmp[i].mean())
features.append(tmp[i].var())
return features
| [
"numpy.random.seed",
"os.walk",
"librosa.feature.chroma_stft",
"librosa.feature.mfcc",
"os.path.join",
"pandas.DataFrame",
"os.path.abspath",
"librosa.feature.spectral_bandwidth",
"librosa.feature.zero_crossing_rate",
"pandas.concat",
"librosa.feature.rms",
"librosa.feature.spectral_rolloff",
... | [((128, 148), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (142, 148), True, 'import numpy as np\n'), ((2197, 2214), 'numpy.array', 'np.array', (['dataset'], {}), '(dataset)\n', (2205, 2214), True, 'import numpy as np\n'), ((2554, 2567), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (2561, 2567), False, 'import os\n'), ((3290, 3308), 'librosa.load', 'librosa.load', (['path'], {}), '(path)\n', (3302, 3308), False, 'import librosa\n'), ((4220, 4241), 'numpy.array', 'np.array', (['new_dataset'], {}), '(new_dataset)\n', (4228, 4241), True, 'import numpy as np\n'), ((7521, 7547), 'librosa.feature.rms', 'librosa.feature.rms', (['audio'], {}), '(audio)\n', (7540, 7547), False, 'import librosa\n'), ((7636, 7676), 'librosa.feature.spectral_centroid', 'librosa.feature.spectral_centroid', (['audio'], {}), '(audio)\n', (7669, 7676), False, 'import librosa\n'), ((7765, 7806), 'librosa.feature.spectral_bandwidth', 'librosa.feature.spectral_bandwidth', (['audio'], {}), '(audio)\n', (7799, 7806), False, 'import librosa\n'), ((7895, 7934), 'librosa.feature.spectral_rolloff', 'librosa.feature.spectral_rolloff', (['audio'], {}), '(audio)\n', (7927, 7934), False, 'import librosa\n'), ((8023, 8064), 'librosa.feature.zero_crossing_rate', 'librosa.feature.zero_crossing_rate', (['audio'], {}), '(audio)\n', (8057, 8064), False, 'import librosa\n'), ((8153, 8184), 'librosa.effects.harmonic', 'librosa.effects.harmonic', (['audio'], {}), '(audio)\n', (8177, 8184), False, 'import librosa\n'), ((8273, 8306), 'librosa.effects.percussive', 'librosa.effects.percussive', (['audio'], {}), '(audio)\n', (8299, 8306), False, 'import librosa\n'), ((8469, 8496), 'librosa.feature.mfcc', 'librosa.feature.mfcc', (['audio'], {}), '(audio)\n', (8489, 8496), False, 'import librosa\n'), ((1888, 1902), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (1900, 1902), False, 'import os\n'), ((3021, 3033), 'multiprocessing.Pool', 'Pool', (['n_jobs'], {}), '(n_jobs)\n', (3025, 3033), False, 'from multiprocessing import Pool\n'), ((3552, 3566), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (3564, 3566), False, 'import os\n'), ((4644, 4656), 'multiprocessing.Pool', 'Pool', (['n_jobs'], {}), '(n_jobs)\n', (4648, 4656), False, 'from multiprocessing import Pool\n'), ((6068, 6082), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (6080, 6082), False, 'import os\n'), ((7397, 7431), 'librosa.feature.chroma_stft', 'librosa.feature.chroma_stft', (['audio'], {}), '(audio)\n', (7424, 7431), False, 'import librosa\n'), ((8395, 8420), 'librosa.beat.tempo', 'librosa.beat.tempo', (['audio'], {}), '(audio)\n', (8413, 8420), False, 'import librosa\n'), ((1552, 1573), 'os.path.abspath', 'os.path.abspath', (['file'], {}), '(file)\n', (1567, 1573), False, 'import os\n'), ((2764, 2789), 'os.path.split', 'os.path.split', (['music_path'], {}), '(music_path)\n', (2777, 2789), False, 'import os\n'), ((6703, 6757), 'pandas.DataFrame', 'pd.DataFrame', (['self.data_features'], {'columns': 'self.columns'}), '(self.data_features, columns=self.columns)\n', (6715, 6757), True, 'import pandas as pd\n'), ((7232, 7279), 'pandas.concat', 'pd.concat', (['(X, tmpX)'], {'axis': '(0)', 'ignore_index': '(True)'}), '((X, tmpX), axis=0, ignore_index=True)\n', (7241, 7279), True, 'import pandas as pd\n'), ((2643, 2674), 'os.path.join', 'os.path.join', (['dirpath', 'filename'], {}), '(dirpath, filename)\n', (2655, 2674), False, 'import os\n'), ((3406, 3425), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (3419, 3425), False, 'import os\n'), ((6569, 6581), 'multiprocessing.Pool', 'Pool', (['n_jobs'], {}), '(n_jobs)\n', (6573, 6581), False, 'from multiprocessing import Pool\n')] |
"""
Visualization of a Histogram2D as a heaatmap
"""
import re
import logging
import base64
import io
import numpy as np
import scipy as sp
from PIL import Image
from progressivis.core.utils import indices_len
from progressivis.core.slot import SlotDescriptor
from progressivis.table import Table
from progressivis.table.module import TableModule
logger = logging.getLogger(__name__)
class Heatmap(TableModule):
"Heatmap module"
parameters = [('cmax', np.dtype(float), np.nan),
('cmin', np.dtype(float), np.nan),
('high', np.dtype(int), 65536),
('low', np.dtype(int), 0),
('filename', np.dtype(object), None),
('history', np.dtype(int), 3)]
inputs = [SlotDescriptor('array', type=Table)]
# schema = [('image', np.dtype(object), None),
# ('filename', np.dtype(object), None),
# UPDATE_COLUMN_DESC]
schema = "{filename: string, time: int64}"
def __init__(self, colormap=None, **kwds):
super(Heatmap, self).__init__(**kwds)
self.colormap = colormap
self.default_step_size = 1
name = self.generate_table_name('Heatmap')
# params = self.params
# if params.filename is None:
# params.filename = name+'%d.png'
self.result = Table(name, dshape=Heatmap.schema, create=True)
def predict_step_size(self, duration):
_ = duration
# Module sample is constant time (supposedly)
return 1
def run_step(self, run_number, step_size, howlong):
dfslot = self.get_input_slot('array')
input_df = dfslot.data()
# dfslot.update(run_number)
dfslot.deleted.next()
indices = dfslot.created.next()
steps = indices_len(indices)
if steps == 0:
indices = dfslot.updated.next()
steps = indices_len(indices)
if steps == 0:
return self._return_run_step(self.state_blocked, steps_run=1)
histo = input_df.last()['array']
if histo is None:
return self._return_run_step(self.state_blocked, steps_run=1)
params = self.params
cmax = params.cmax
if np.isnan(cmax):
cmax = None
cmin = params.cmin
if np.isnan(cmin):
cmin = None
high = params.high
low = params.low
try:
#import pdb;pdb.set_trace()
if cmin is None:
cmin = histo.min()
if cmax is None:
cmax = histo.max()
cscale = cmax - cmin
scale_hl = float(high - low)
scale = float(high - low) / cscale
#data = (sp.special.cbrt(histo) * 1.0 - cmin) * scale + 0.4999
data = (sp.special.cbrt(histo) * 1.0 - cmin) * scale_hl + 0.4999
data[data > high] = high
data[data < 0] = 0
data = np.cast[np.uint32](data)
if low != 0:
data += low
image = Image.fromarray(data, mode='I')
image = image.transpose(Image.FLIP_TOP_BOTTOM)
filename = params.filename
except:
image = None
filename = None
if filename is not None:
try:
if re.search(r'%(0[\d])?d', filename):
filename = filename % (run_number)
filename = self.storage.fullname(self, filename)
# TODO should do it atomically since it will be
# called 4 times with the same fn
image.save(filename, format='PNG') # bits=16)
logger.debug('Saved image %s', filename)
image = None
except:
logger.error('Cannot save image %s', filename)
raise
else:
buffered = io.BytesIO()
image.save(buffered, format='PNG', bits=16)
res = str(base64.b64encode(buffered.getvalue()), "ascii")
filename = "data:image/png;base64,"+res
if len(self.result) == 0 or self.result.last()['time'] != run_number:
values = {'filename': filename, 'time': run_number}
self.result.add(values)
return self._return_run_step(self.state_blocked, steps_run=1)
def is_visualization(self):
return True
def get_visualization(self):
return "heatmap"
def to_json(self, short=False):
json = super(Heatmap, self).to_json(short)
if short:
return json
return self.heatmap_to_json(json, short)
def heatmap_to_json(self, json, short):
dfslot = self.get_input_slot('array')
histo = dfslot.output_module
json['columns'] = [histo.x_column, histo.y_column]
histo_df = dfslot.data()
if histo_df is not None and len(histo_df) != 0:
row = histo_df.last()
if not (np.isnan(row['xmin']) or np.isnan(row['xmax'])
or np.isnan(row['ymin']) or np.isnan(row['ymax'])):
json['bounds'] = {
'xmin': row['xmin'],
'ymin': row['ymin'],
'xmax': row['xmax'],
'ymax': row['ymax']
}
df = self.result
if df is not None and self._last_update != 0:
row = df.last()
json['image'] = row['filename']
return json
def get_image(self, run_number=None):
if self.result is None or len(self.result) == 0:
return None
last = self.result.last()
if run_number is None or run_number >= last['time']:
run_number = last['time']
filename = last['filename']
else:
time = self.result['time']
idx = np.where(time == run_number)[0]
if len(idx) == 0:
filename = last['filename']
else:
filename = self.result['filename'][idx[0]]
return filename
def get_image_bin(self, run_number=None):
file_url = self.get_image(run_number)
payload = file_url.split(',',1)[1]
return base64.b64decode(payload)
| [
"io.BytesIO",
"progressivis.core.slot.SlotDescriptor",
"numpy.dtype",
"numpy.isnan",
"base64.b64decode",
"PIL.Image.fromarray",
"numpy.where",
"progressivis.table.Table",
"scipy.special.cbrt",
"progressivis.core.utils.indices_len",
"re.search",
"logging.getLogger"
] | [((358, 385), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (375, 385), False, 'import logging\n'), ((757, 792), 'progressivis.core.slot.SlotDescriptor', 'SlotDescriptor', (['"""array"""'], {'type': 'Table'}), "('array', type=Table)\n", (771, 792), False, 'from progressivis.core.slot import SlotDescriptor\n'), ((1334, 1381), 'progressivis.table.Table', 'Table', (['name'], {'dshape': 'Heatmap.schema', 'create': '(True)'}), '(name, dshape=Heatmap.schema, create=True)\n', (1339, 1381), False, 'from progressivis.table import Table\n'), ((1776, 1796), 'progressivis.core.utils.indices_len', 'indices_len', (['indices'], {}), '(indices)\n', (1787, 1796), False, 'from progressivis.core.utils import indices_len\n'), ((2218, 2232), 'numpy.isnan', 'np.isnan', (['cmax'], {}), '(cmax)\n', (2226, 2232), True, 'import numpy as np\n'), ((2296, 2310), 'numpy.isnan', 'np.isnan', (['cmin'], {}), '(cmin)\n', (2304, 2310), True, 'import numpy as np\n'), ((6150, 6175), 'base64.b64decode', 'base64.b64decode', (['payload'], {}), '(payload)\n', (6166, 6175), False, 'import base64\n'), ((464, 479), 'numpy.dtype', 'np.dtype', (['float'], {}), '(float)\n', (472, 479), True, 'import numpy as np\n'), ((517, 532), 'numpy.dtype', 'np.dtype', (['float'], {}), '(float)\n', (525, 532), True, 'import numpy as np\n'), ((570, 583), 'numpy.dtype', 'np.dtype', (['int'], {}), '(int)\n', (578, 583), True, 'import numpy as np\n'), ((619, 632), 'numpy.dtype', 'np.dtype', (['int'], {}), '(int)\n', (627, 632), True, 'import numpy as np\n'), ((669, 685), 'numpy.dtype', 'np.dtype', (['object'], {}), '(object)\n', (677, 685), True, 'import numpy as np\n'), ((724, 737), 'numpy.dtype', 'np.dtype', (['int'], {}), '(int)\n', (732, 737), True, 'import numpy as np\n'), ((1884, 1904), 'progressivis.core.utils.indices_len', 'indices_len', (['indices'], {}), '(indices)\n', (1895, 1904), False, 'from progressivis.core.utils import indices_len\n'), ((3028, 3059), 'PIL.Image.fromarray', 'Image.fromarray', (['data'], {'mode': '"""I"""'}), "(data, mode='I')\n", (3043, 3059), False, 'from PIL import Image\n'), ((3857, 3869), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (3867, 3869), False, 'import io\n'), ((3296, 3330), 're.search', 're.search', (['"""%(0[\\\\d])?d"""', 'filename'], {}), "('%(0[\\\\d])?d', filename)\n", (3305, 3330), False, 'import re\n'), ((5792, 5820), 'numpy.where', 'np.where', (['(time == run_number)'], {}), '(time == run_number)\n', (5800, 5820), True, 'import numpy as np\n'), ((4918, 4939), 'numpy.isnan', 'np.isnan', (["row['xmin']"], {}), "(row['xmin'])\n", (4926, 4939), True, 'import numpy as np\n'), ((4943, 4964), 'numpy.isnan', 'np.isnan', (["row['xmax']"], {}), "(row['xmax'])\n", (4951, 4964), True, 'import numpy as np\n'), ((4988, 5009), 'numpy.isnan', 'np.isnan', (["row['ymin']"], {}), "(row['ymin'])\n", (4996, 5009), True, 'import numpy as np\n'), ((5013, 5034), 'numpy.isnan', 'np.isnan', (["row['ymax']"], {}), "(row['ymax'])\n", (5021, 5034), True, 'import numpy as np\n'), ((2785, 2807), 'scipy.special.cbrt', 'sp.special.cbrt', (['histo'], {}), '(histo)\n', (2800, 2807), True, 'import scipy as sp\n')] |
import numpy as np
import pandas as pd
import sklearn.svm
from sklearn.model_selection import train_test_split
def fitness(sol, total_features, label, split = 0.2):
feature = reduce_features(sol, total_features)
xtrain, xtest, ytrain, ytest = train_test_split(feature, label, test_size = split, random_state = 4 )
SVM_classifier = sklearn.svm.SVC(kernel='rbf',gamma='scale',C=5)
SVM_classifier.fit(xtrain, ytrain)
predictions = SVM_classifier.predict(xtest)
clf_value = classification_accuracy(ytest, predictions)
val = 1-clf_value
#in case of multi objective []
set_cnt=sum(sol)
set_cnt=set_cnt/np.shape(sol)[0]
val=omega*val+(1-omega)*set_cnt
return val
binarised_vector = np.random.randint(low=0, high=2, size=pop_shape)
def reduce_features(solution, features):
selected_elements_indices = np.where(solution == 1)[0]
reduced_features = features[:, selected_elements_indices]
return reduced_features
def SOPF(sol_vector, features):
binarised_vector = sol_vector
for i in range(len(binarised_vector)):
temp_vector = binarised_vector
if (binarised_vector[i] == 1):
binarised_vector[i] = 0
else:
binarised_vector[i] = 1
if (fitness(temp_vector, features, label)<fitness(binarised_vector, features, label)):
resultant_vector = temp_vector
else:
resultant_vector = binarised_vector
return resultant_vector
def AWCM(population):
weighted_solution = []
for i in range(len(population)):
temp_weighted_solution = []
for j in range(len(population[i])):
candidate_solution = population[i][j]
Acc_d = fitness(candidate_solution, data_inputs, data_outputs, 0.5)
temp_goodness = []
for k in range(len(population[i][j])):
temp_goodness.append(population[i][j][k]*Acc_d)
temp_weighted_solution.append(temp_goodness)
weighted_solution.append(temp_weighted_solution)
summed_solution = []
for i in range(len(population)):
for j in range(len(weighted_solution[i])):
if (j==0):
sum_list = weighted_solution[i][j]
else:
sum_list = [(a + b) for a, b in zip(sum_list, weighted_solution[i][j])]
summed_solution.append(sum_list)
mean = []
for i in range(len(summed_solution)):
sum = 0
for j in range(len(summed_solution[i])):
sum += summed_solution[i][j]/len(summed_solution[i])
mean.append(sum)
final_population = []
for i in range(len(mean)):
final_solution = []
for j in range(len(summed_solution[i])):
if (summed_solution[i][j] >= mean[i]):
final_solution.append(1)
else:
final_solution.append(0)
final_population.append(final_solution)
return final_population
| [
"numpy.shape",
"sklearn.model_selection.train_test_split",
"numpy.random.randint",
"numpy.where"
] | [((709, 757), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(2)', 'size': 'pop_shape'}), '(low=0, high=2, size=pop_shape)\n', (726, 757), True, 'import numpy as np\n'), ((251, 316), 'sklearn.model_selection.train_test_split', 'train_test_split', (['feature', 'label'], {'test_size': 'split', 'random_state': '(4)'}), '(feature, label, test_size=split, random_state=4)\n', (267, 316), False, 'from sklearn.model_selection import train_test_split\n'), ((832, 855), 'numpy.where', 'np.where', (['(solution == 1)'], {}), '(solution == 1)\n', (840, 855), True, 'import numpy as np\n'), ((624, 637), 'numpy.shape', 'np.shape', (['sol'], {}), '(sol)\n', (632, 637), True, 'import numpy as np\n')] |
from .base import Source
from ..config import default_units
from ..util import make_properties
import astropy.units as u
import astropy.constants as const
import numpy as np
__all__ = ['Star']
_L0 = 3.0128E28 * u.W # https://www.iau.org/static/resolutions/IAU2015_English.pdf eq.1
_f0 = 2.518021002E-8 * u.W/u.m**2 # https://www.iau.org/static/resolutions/IAU2015_English.pdf eq.3
# --- Auxiliary functions ---
def surface_gravity(mass, radius):
return const.G*mass/radius**2
def stefan_boltzmann_luminosity(temperature, radius):
return const.sigma_sb * temperature**4 * radius**2 * np.pi
def absolute_bolometric_magnitude(luminosity):
return -2.5 * np.log10((luminosity/_L0).value)
def irradiance1(luminosity, distance):
return luminosity / (4*np.pi*distance**2)
def irradiance2(apparent_bolometric_magnitude):
return _f0 * 10**(-0.4 * apparent_bolometric_magnitude)
def apparent_bolometric_magnitude(irradiance):
return -2.5 * np.log10((irradiance/_f0).value)
def luminosity1(absolute_bolometric_magnitude):
return _L0 * 10**(-0.4 * absolute_bolometric_magnitude)
def luminosity2(irradiance, distance):
return 4*np.pi*distance**2 * irradiance
class Star(Source):
'''
Class for simulating a Star as input Source.
Parameters
----------
wavelengths: UnitField
Wavelengths at which the simulation is done and the spectral model
should be evaluated.
location: astropy.SkyCoord or astropy.units.Quantity
Location of the star in sky coordinates or w.r.t. the telescope
pointing (e.g. (0, 0) puts it in the center of the field of view).
PropertyList Parameters
-----------------------
radius: float or astropy.units.Quantity
Radius of the star in solar radii or with specified units
temperature: float or astropy.units.Quantity
Temperature of the star in K or with specified units
mass: float or astropy.units.Quanity
Mass of the star in solar mass or with specified units
distance: float or astropy.units.Quantity
Distance of the star in parsec or with specified units
radial_velocity: float or astropy.unit.Quantity
Radial velocity of the star w.r.t. the observer in km/s or with
specified units
surface gravity: float or astropy.unit.Quantity
Surface gravity of the star in cm/s^2 or with specified units
luminosity: float or astropy.unit.Quantity
Luminosity of the star in solar luminosity or with specified units
absolute_bolometric_magnitude: float
Absolute bolometric magnitude of the star
apparent_bolometric_magnitude: float
Apparent bolometric magnitude of the star
irradiance: float or astropy.unit.Quantity
Irradiance of the star in W/m^2 or with specified units
'''
property_list = {
'radius': {
'unit': u.R_sun,
'default': 1*u.R_sun
},
'temperature': {
'unit': default_units.temperature,
'default': 6000 * u.K
},
'mass': {
'unit': u.M_sun,
'default': 1*u.M_sun
},
'distance': {
'unit': u.pc,
'default': 10*u.pc
},
'radial_velocity': {
'unit': u.km/u.s,
'default': 0
},
'surface_gravity': {
'unit': u.cm/u.s**2,
'functions': [(surface_gravity, ('mass', 'radius'))]
},
'luminosity': {
'unit': u.L_sun,
'functions': [(luminosity1, ('absolute_bolometric_magnitude',)),
(luminosity2, ('irradiance', 'distance')),
(stefan_boltzmann_luminosity, ('temperature',
'radius'))],
'default': 1.0 * const.L_sun
},
'absolute_bolometric_magnitude': {
'functions': [(absolute_bolometric_magnitude, ('luminosity',))],
},
'irradiance': {
'unit': default_units.power / default_units.area,
'functions': [(irradiance1, ('luminosity', 'distance')),
(irradiance2, ('apparent_bolometric_magnitude',))],
},
'apparent_bolometric_magnitude': {
'functions': [(apparent_bolometric_magnitude, ('irradiance',))]
}
}
def __init__(self, wavelengths=None, location=[0, 0], **kwargs):
make_properties(self, self.property_list, kwargs)
super().__init__(wavelengths, location)
| [
"numpy.log10"
] | [((670, 704), 'numpy.log10', 'np.log10', (['(luminosity / _L0).value'], {}), '((luminosity / _L0).value)\n', (678, 704), True, 'import numpy as np\n'), ((964, 998), 'numpy.log10', 'np.log10', (['(irradiance / _f0).value'], {}), '((irradiance / _f0).value)\n', (972, 998), True, 'import numpy as np\n')] |
import numpy as np
from lmfit import Model
import matplotlib.pyplot as plt
path = r'D:\data\20191206\141911_power_sweep_evaporated_drum_device'
power, fr, _, _, a ,_ = np.loadtxt(path, unpack=True)
pw = np.linspace(power[0],power[-1],31)
freq = np.split(fr, 31)[0]
data = np.split(a,31)
# def S21(f, f0, k, norm):
# return np.abs(norm/(-1j*(f-f0)*(2/k)+1 ))
m = Fitter (S11r)
k_list = []
for i in np.arange(31):
fguess = freq[np.argmax(data[i])]
kguess = 6.5e6
norm_guess = np.max(data[i])
print(i)
data2fit = data[i][75:-60]
f2fit = freq[75:-60]
result = m.fit(data2fit, f= f2fit, f0 = fguess, k = kguess, norm = norm_guess)
plt.plot(f2fit, data2fit,'-ro', f2fit, result.best_fit, '-g')
plt.title(str(pw[i]-30)+' '+'dBm')
plt.savefig(r'D:\data\20190826\180629_power_sweep_at_max_sloope_c.038 Cavity_1\figs\%f.png'%i, transparent = True)
plt.clf()
print(result.best_values['k'])
k_list = np.append(k_list, result.best_values['k'])
plt.clf()
plt.plot(pw-30, k_list, '-ro')
plt.grid()
plt.show()
# plt.show()
| [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"numpy.argmax",
"numpy.split",
"numpy.append",
"numpy.max",
"numpy.arange",
"numpy.loadtxt",
"numpy.linspace",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig"
] | [((174, 203), 'numpy.loadtxt', 'np.loadtxt', (['path'], {'unpack': '(True)'}), '(path, unpack=True)\n', (184, 203), True, 'import numpy as np\n'), ((212, 248), 'numpy.linspace', 'np.linspace', (['power[0]', 'power[-1]', '(31)'], {}), '(power[0], power[-1], 31)\n', (223, 248), True, 'import numpy as np\n'), ((285, 300), 'numpy.split', 'np.split', (['a', '(31)'], {}), '(a, 31)\n', (293, 300), True, 'import numpy as np\n'), ((426, 439), 'numpy.arange', 'np.arange', (['(31)'], {}), '(31)\n', (435, 439), True, 'import numpy as np\n'), ((991, 1000), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (998, 1000), True, 'import matplotlib.pyplot as plt\n'), ((1002, 1034), 'matplotlib.pyplot.plot', 'plt.plot', (['(pw - 30)', 'k_list', '"""-ro"""'], {}), "(pw - 30, k_list, '-ro')\n", (1010, 1034), True, 'import matplotlib.pyplot as plt\n'), ((1034, 1044), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1042, 1044), True, 'import matplotlib.pyplot as plt\n'), ((1046, 1056), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1054, 1056), True, 'import matplotlib.pyplot as plt\n'), ((255, 271), 'numpy.split', 'np.split', (['fr', '(31)'], {}), '(fr, 31)\n', (263, 271), True, 'import numpy as np\n'), ((509, 524), 'numpy.max', 'np.max', (['data[i]'], {}), '(data[i])\n', (515, 524), True, 'import numpy as np\n'), ((671, 733), 'matplotlib.pyplot.plot', 'plt.plot', (['f2fit', 'data2fit', '"""-ro"""', 'f2fit', 'result.best_fit', '"""-g"""'], {}), "(f2fit, data2fit, '-ro', f2fit, result.best_fit, '-g')\n", (679, 733), True, 'import matplotlib.pyplot as plt\n'), ((772, 900), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('D:\\\\data\\\\20190826\\\\180629_power_sweep_at_max_sloope_c.038 Cavity_1\\\\figs\\\\%f.png'\n % i)"], {'transparent': '(True)'}), "(\n 'D:\\\\data\\\\20190826\\\\180629_power_sweep_at_max_sloope_c.038 Cavity_1\\\\figs\\\\%f.png'\n % i, transparent=True)\n", (783, 900), True, 'import matplotlib.pyplot as plt\n'), ((889, 898), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (896, 898), True, 'import matplotlib.pyplot as plt\n'), ((943, 985), 'numpy.append', 'np.append', (['k_list', "result.best_values['k']"], {}), "(k_list, result.best_values['k'])\n", (952, 985), True, 'import numpy as np\n'), ((457, 475), 'numpy.argmax', 'np.argmax', (['data[i]'], {}), '(data[i])\n', (466, 475), True, 'import numpy as np\n')] |
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
import torchvision
import timm
from .gazenet import get_backbone
from models.backbone import *
class ITracker(nn.Module):
def __init__(self, pretrained=True):
super(ITracker, self).__init__()
self.face_backbone = resnet50(pretrained=pretrained)
self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
self.fc_eye = nn.Sequential(
nn.Linear(2048 * 2, 128),
nn.ReLU(True)
)
self.fc_face = nn.Sequential(
nn.Linear(2048, 128),
nn.ReLU(True),
nn.Linear(128, 128),
nn.ReLU(True)
)
self.fc_out = nn.Sequential(
nn.Linear(128 * 2, 128),
nn.ReLU(True),
nn.Linear(128, 2)
)
def encode_input(self, data):
face_data = data['face']
leye_box = data['left_eye_box']
reye_box = data['right_eye_box']
B = face_data.shape[0]
batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)
leye_box_ = torch.cat([batch_order, leye_box], dim=1)
reye_box_ = torch.cat([batch_order, reye_box], dim=1)
leye_data = torchvision.ops.roi_align(face_data, leye_box_, 128, aligned=True)
reye_data = torchvision.ops.roi_align(face_data, reye_box_, 128, aligned=True)
encoded_data = {
'face': face_data,
'left_eye': leye_data.clone(),
'right_eye': reye_data.clone()
}
return encoded_data
def forward(self, data):
data = self.encode_input(data)
face = data['face']
left_eye = data['left_eye']
right_eye = data['right_eye']
B = face.shape[0]
x_leye = self.leye_backbone(left_eye).view(B, -1)
x_reye = self.reye_backbone(right_eye).view(B, -1)
x_eye = torch.cat([x_leye, x_reye], dim=1)
x_eye = self.fc_eye(x_eye)
x_face = self.face_backbone(face).view(B, -1)
x_face = self.fc_face(x_face)
x = torch.cat([x_eye, x_face], dim=1)
x = self.fc_out(x)
return x
class AttBlock(nn.Module):
def __init__(self, q_dim, kv_dim, d_k, qkv_bias=True):
super(AttBlock, self).__init__()
self.scale = d_k
self.Wq = nn.Linear(q_dim, d_k, bias=qkv_bias)
self.Wk = nn.Linear(kv_dim, d_k, bias=qkv_bias)
self.Wv = nn.Linear(kv_dim, d_k, bias=qkv_bias)
self.proj = nn.Linear(d_k, kv_dim)
def forward(self, x_q, x_kv):
q = self.Wq(x_q)
k = self.Wk(x_kv)
v = self.Wv(x_kv)
# attn: b, s, s
scores = torch.matmul(q.view(-1, self.scale, 1), k.view(-1, 1, self.scale))
attn = F.softmax(scores / self.scale, dim=-1)
x = torch.matmul(attn, v.view(-1, self.scale, 1)).view(-1, self.scale)
x = self.proj(x)
return x
class MultiHeadAttBlock(nn.Module):
def __init__(self, features_dim, num_head, d_k, qkv_bias=True):
super(MultiHeadAttBlock, self).__init__()
self.dim = features_dim
self.num_head = num_head
self.d_k = d_k
# assert head_dim * self.num_head == self.dim, "head num setting wrong"
self.Wq = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)
self.Wk = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)
self.Wv = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)
self.proj = nn.Linear(self.num_head * self.d_k, self.dim)
def forward(self, x):
# x: b, s, c
B, S, C = x.shape
# qkv: b, nhead, s, d_k
q = self.Wq(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)
k = self.Wk(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)
v = self.Wv(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)
# scores: b, nhead, s, s
scores = torch.matmul(q, k.transpose(-1, -2)) / np.sqrt(self.d_k)
attn = F.softmax(scores, dim=-1)
# x_attn: b, nhead, s, d_k
x_attn = torch.matmul(attn, v).transpose(1, 2).contiguous().view(B, -1, self.num_head * self.d_k)
output = self.proj(x_attn)
return output
class ITrackerAttention(nn.Module):
def __init__(self, pretrained=True):
super(ITrackerAttention, self).__init__()
self.face_backbone = resnet50(pretrained=pretrained)
self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
self.attn_l = AttBlock(q_dim=2048, kv_dim=2048, d_k=1024)
self.attn_r = AttBlock(q_dim=2048, kv_dim=2048, d_k=1024)
self.mlp = nn.Sequential(
nn.Linear(2048 * 2, 128),
nn.ReLU(True),
nn.Linear(128, 128),
nn.ReLU(True)
)
self.fc_out = nn.Linear(128, 2)
def encode_input(self, data):
face_data = data['face']
leye_box = data['left_eye_box']
reye_box = data['right_eye_box']
B = face_data.shape[0]
batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)
leye_box_ = torch.cat([batch_order, leye_box], dim=1)
reye_box_ = torch.cat([batch_order, reye_box], dim=1)
leye_data = torchvision.ops.roi_align(face_data, leye_box_, 64, aligned=True)
reye_data = torchvision.ops.roi_align(face_data, reye_box_, 64, aligned=True)
encoded_data = {
'face': face_data,
'left_eye': leye_data.clone(),
'right_eye': reye_data.clone()
}
return encoded_data
def forward(self, data):
data = self.encode_input(data)
face = data['face']
left_eye = data['left_eye']
right_eye = data['right_eye']
B = face.shape[0]
x_leye = self.leye_backbone(left_eye).view(B, -1)
x_reye = self.reye_backbone(right_eye).view(B, -1)
x_face = self.face_backbone(face).view(B, -1)
x_leye = self.attn_l(x_q=x_face, x_kv=x_leye)
x_reye = self.attn_r(x_q=x_face, x_kv=x_reye)
x = torch.cat([x_leye, x_reye], dim=1)
x = self.mlp(x)
x = self.fc_out(x)
return x
# class TBasicLayer(nn.Module):
# def __init__(self, features_dim, out_dim, num_head, d_k, qkv_bias=True):
# super(TBasicLayer, self).__init__()
#
# self.mh = MultiHeadAttBlock(features_dim=features_dim, num_head=num_head, d_k=d_k, qkv_bias=qkv_bias)
# self.norm = nn.LayerNorm(3)
# self.fnn = nn.Sequential(
# nn.Linear(features_dim, features_dim),
# nn.ReLU(True),
# nn.Linear(features_dim, out_dim)
# )
class ITrackerMultiHeadAttention(nn.Module):
def __init__(self, pretrained=True):
super(ITrackerMultiHeadAttention, self).__init__()
# feature extract
self.face_backbone = resnet50(pretrained=pretrained)
self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])
# multi-head attention
self.mha = MultiHeadAttBlock(
features_dim=2048,
num_head=4,
d_k=256
)
self.norm1 = nn.LayerNorm(2048)
self.ffn = nn.Sequential(
nn.Linear(2048, 2048),
nn.ReLU(True),
nn.Linear(2048, 2048)
)
self.norm2 = nn.LayerNorm(2048)
# fc output
self.fc_eye = nn.Sequential(
nn.Linear(2048 * 2, 128),
nn.ReLU(True)
)
self.fc_face = nn.Sequential(
nn.Linear(2048, 128),
nn.ReLU(True),
nn.Linear(128, 128),
nn.ReLU(True)
)
self.fc_out = nn.Sequential(
nn.Linear(128 * 2, 128),
nn.ReLU(True),
nn.Linear(128, 2)
)
def encode_input(self, data):
face_data = data['face']
leye_box = data['left_eye_box']
reye_box = data['right_eye_box']
B = face_data.shape[0]
batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)
leye_box_ = torch.cat([batch_order, leye_box], dim=1)
reye_box_ = torch.cat([batch_order, reye_box], dim=1)
leye_data = torchvision.ops.roi_align(face_data, leye_box_, 128, aligned=True)
reye_data = torchvision.ops.roi_align(face_data, reye_box_, 128, aligned=True)
encoded_data = {
'face': face_data,
'left_eye': leye_data.clone(),
'right_eye': reye_data.clone()
}
return encoded_data
def forward(self, data):
data = self.encode_input(data)
face = data['face']
left_eye = data['left_eye']
right_eye = data['right_eye']
B = face.shape[0]
x_leye = self.leye_backbone(left_eye).view(B, 1, -1)
x_reye = self.reye_backbone(right_eye).view(B, 1, -1)
x_face = self.face_backbone(face).view(B, 1, -1)
x_seq = torch.cat([x_leye, x_reye, x_face], dim=1)
x_seq = x_seq + self.norm1(self.mha(x_seq))
x_ffn = x_seq + self.norm2(self.ffn(x_seq))
x_leye, x_reye, x_face = torch.unbind(x_ffn, dim=1)
x_eye = torch.cat([x_leye, x_reye], dim=1)
x_eye = self.fc_eye(x_eye)
x_face = self.fc_face(x_face)
x = torch.cat([x_eye, x_face], dim=1)
x = self.fc_out(x)
return x
| [
"torchvision.ops.roi_align",
"torch.nn.ReLU",
"torch.cat",
"torch.nn.functional.softmax",
"torch.nn.LayerNorm",
"torch.arange",
"torch.nn.Linear",
"torch.unbind",
"torch.matmul",
"numpy.sqrt"
] | [((1298, 1339), 'torch.cat', 'torch.cat', (['[batch_order, leye_box]'], {'dim': '(1)'}), '([batch_order, leye_box], dim=1)\n', (1307, 1339), False, 'import torch\n'), ((1360, 1401), 'torch.cat', 'torch.cat', (['[batch_order, reye_box]'], {'dim': '(1)'}), '([batch_order, reye_box], dim=1)\n', (1369, 1401), False, 'import torch\n'), ((1423, 1489), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'leye_box_', '(128)'], {'aligned': '(True)'}), '(face_data, leye_box_, 128, aligned=True)\n', (1448, 1489), False, 'import torchvision\n'), ((1510, 1576), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'reye_box_', '(128)'], {'aligned': '(True)'}), '(face_data, reye_box_, 128, aligned=True)\n', (1535, 1576), False, 'import torchvision\n'), ((2091, 2125), 'torch.cat', 'torch.cat', (['[x_leye, x_reye]'], {'dim': '(1)'}), '([x_leye, x_reye], dim=1)\n', (2100, 2125), False, 'import torch\n'), ((2267, 2300), 'torch.cat', 'torch.cat', (['[x_eye, x_face]'], {'dim': '(1)'}), '([x_eye, x_face], dim=1)\n', (2276, 2300), False, 'import torch\n'), ((2517, 2553), 'torch.nn.Linear', 'nn.Linear', (['q_dim', 'd_k'], {'bias': 'qkv_bias'}), '(q_dim, d_k, bias=qkv_bias)\n', (2526, 2553), True, 'import torch.nn as nn\n'), ((2572, 2609), 'torch.nn.Linear', 'nn.Linear', (['kv_dim', 'd_k'], {'bias': 'qkv_bias'}), '(kv_dim, d_k, bias=qkv_bias)\n', (2581, 2609), True, 'import torch.nn as nn\n'), ((2628, 2665), 'torch.nn.Linear', 'nn.Linear', (['kv_dim', 'd_k'], {'bias': 'qkv_bias'}), '(kv_dim, d_k, bias=qkv_bias)\n', (2637, 2665), True, 'import torch.nn as nn\n'), ((2686, 2708), 'torch.nn.Linear', 'nn.Linear', (['d_k', 'kv_dim'], {}), '(d_k, kv_dim)\n', (2695, 2708), True, 'import torch.nn as nn\n'), ((2945, 2983), 'torch.nn.functional.softmax', 'F.softmax', (['(scores / self.scale)'], {'dim': '(-1)'}), '(scores / self.scale, dim=-1)\n', (2954, 2983), True, 'from torch.nn import functional as F\n'), ((3449, 3509), 'torch.nn.Linear', 'nn.Linear', (['self.dim', '(self.num_head * self.d_k)'], {'bias': 'qkv_bias'}), '(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n', (3458, 3509), True, 'import torch.nn as nn\n'), ((3528, 3588), 'torch.nn.Linear', 'nn.Linear', (['self.dim', '(self.num_head * self.d_k)'], {'bias': 'qkv_bias'}), '(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n', (3537, 3588), True, 'import torch.nn as nn\n'), ((3607, 3667), 'torch.nn.Linear', 'nn.Linear', (['self.dim', '(self.num_head * self.d_k)'], {'bias': 'qkv_bias'}), '(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n', (3616, 3667), True, 'import torch.nn as nn\n'), ((3689, 3734), 'torch.nn.Linear', 'nn.Linear', (['(self.num_head * self.d_k)', 'self.dim'], {}), '(self.num_head * self.d_k, self.dim)\n', (3698, 3734), True, 'import torch.nn as nn\n'), ((4190, 4215), 'torch.nn.functional.softmax', 'F.softmax', (['scores'], {'dim': '(-1)'}), '(scores, dim=-1)\n', (4199, 4215), True, 'from torch.nn import functional as F\n'), ((5150, 5167), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(2)'], {}), '(128, 2)\n', (5159, 5167), True, 'import torch.nn as nn\n'), ((5465, 5506), 'torch.cat', 'torch.cat', (['[batch_order, leye_box]'], {'dim': '(1)'}), '([batch_order, leye_box], dim=1)\n', (5474, 5506), False, 'import torch\n'), ((5527, 5568), 'torch.cat', 'torch.cat', (['[batch_order, reye_box]'], {'dim': '(1)'}), '([batch_order, reye_box], dim=1)\n', (5536, 5568), False, 'import torch\n'), ((5590, 5655), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'leye_box_', '(64)'], {'aligned': '(True)'}), '(face_data, leye_box_, 64, aligned=True)\n', (5615, 5655), False, 'import torchvision\n'), ((5676, 5741), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'reye_box_', '(64)'], {'aligned': '(True)'}), '(face_data, reye_box_, 64, aligned=True)\n', (5701, 5741), False, 'import torchvision\n'), ((6415, 6449), 'torch.cat', 'torch.cat', (['[x_leye, x_reye]'], {'dim': '(1)'}), '([x_leye, x_reye], dim=1)\n', (6424, 6449), False, 'import torch\n'), ((7638, 7656), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['(2048)'], {}), '(2048)\n', (7650, 7656), True, 'import torch.nn as nn\n'), ((7818, 7836), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['(2048)'], {}), '(2048)\n', (7830, 7836), True, 'import torch.nn as nn\n'), ((8575, 8616), 'torch.cat', 'torch.cat', (['[batch_order, leye_box]'], {'dim': '(1)'}), '([batch_order, leye_box], dim=1)\n', (8584, 8616), False, 'import torch\n'), ((8637, 8678), 'torch.cat', 'torch.cat', (['[batch_order, reye_box]'], {'dim': '(1)'}), '([batch_order, reye_box], dim=1)\n', (8646, 8678), False, 'import torch\n'), ((8700, 8766), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'leye_box_', '(128)'], {'aligned': '(True)'}), '(face_data, leye_box_, 128, aligned=True)\n', (8725, 8766), False, 'import torchvision\n'), ((8787, 8853), 'torchvision.ops.roi_align', 'torchvision.ops.roi_align', (['face_data', 'reye_box_', '(128)'], {'aligned': '(True)'}), '(face_data, reye_box_, 128, aligned=True)\n', (8812, 8853), False, 'import torchvision\n'), ((9432, 9474), 'torch.cat', 'torch.cat', (['[x_leye, x_reye, x_face]'], {'dim': '(1)'}), '([x_leye, x_reye, x_face], dim=1)\n', (9441, 9474), False, 'import torch\n'), ((9612, 9638), 'torch.unbind', 'torch.unbind', (['x_ffn'], {'dim': '(1)'}), '(x_ffn, dim=1)\n', (9624, 9638), False, 'import torch\n'), ((9656, 9690), 'torch.cat', 'torch.cat', (['[x_leye, x_reye]'], {'dim': '(1)'}), '([x_leye, x_reye], dim=1)\n', (9665, 9690), False, 'import torch\n'), ((9778, 9811), 'torch.cat', 'torch.cat', (['[x_eye, x_face]'], {'dim': '(1)'}), '([x_eye, x_face], dim=1)\n', (9787, 9811), False, 'import torch\n'), ((630, 654), 'torch.nn.Linear', 'nn.Linear', (['(2048 * 2)', '(128)'], {}), '(2048 * 2, 128)\n', (639, 654), True, 'import torch.nn as nn\n'), ((668, 681), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (675, 681), True, 'import torch.nn as nn\n'), ((742, 762), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(128)'], {}), '(2048, 128)\n', (751, 762), True, 'import torch.nn as nn\n'), ((776, 789), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (783, 789), True, 'import torch.nn as nn\n'), ((803, 822), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(128)'], {}), '(128, 128)\n', (812, 822), True, 'import torch.nn as nn\n'), ((836, 849), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (843, 849), True, 'import torch.nn as nn\n'), ((909, 932), 'torch.nn.Linear', 'nn.Linear', (['(128 * 2)', '(128)'], {}), '(128 * 2, 128)\n', (918, 932), True, 'import torch.nn as nn\n'), ((946, 959), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (953, 959), True, 'import torch.nn as nn\n'), ((973, 990), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(2)'], {}), '(128, 2)\n', (982, 990), True, 'import torch.nn as nn\n'), ((4157, 4174), 'numpy.sqrt', 'np.sqrt', (['self.d_k'], {}), '(self.d_k)\n', (4164, 4174), True, 'import numpy as np\n'), ((5005, 5029), 'torch.nn.Linear', 'nn.Linear', (['(2048 * 2)', '(128)'], {}), '(2048 * 2, 128)\n', (5014, 5029), True, 'import torch.nn as nn\n'), ((5043, 5056), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (5050, 5056), True, 'import torch.nn as nn\n'), ((5070, 5089), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(128)'], {}), '(128, 128)\n', (5079, 5089), True, 'import torch.nn as nn\n'), ((5103, 5116), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (5110, 5116), True, 'import torch.nn as nn\n'), ((7703, 7724), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(2048)'], {}), '(2048, 2048)\n', (7712, 7724), True, 'import torch.nn as nn\n'), ((7738, 7751), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (7745, 7751), True, 'import torch.nn as nn\n'), ((7765, 7786), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(2048)'], {}), '(2048, 2048)\n', (7774, 7786), True, 'import torch.nn as nn\n'), ((7907, 7931), 'torch.nn.Linear', 'nn.Linear', (['(2048 * 2)', '(128)'], {}), '(2048 * 2, 128)\n', (7916, 7931), True, 'import torch.nn as nn\n'), ((7945, 7958), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (7952, 7958), True, 'import torch.nn as nn\n'), ((8019, 8039), 'torch.nn.Linear', 'nn.Linear', (['(2048)', '(128)'], {}), '(2048, 128)\n', (8028, 8039), True, 'import torch.nn as nn\n'), ((8053, 8066), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (8060, 8066), True, 'import torch.nn as nn\n'), ((8080, 8099), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(128)'], {}), '(128, 128)\n', (8089, 8099), True, 'import torch.nn as nn\n'), ((8113, 8126), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (8120, 8126), True, 'import torch.nn as nn\n'), ((8186, 8209), 'torch.nn.Linear', 'nn.Linear', (['(128 * 2)', '(128)'], {}), '(128 * 2, 128)\n', (8195, 8209), True, 'import torch.nn as nn\n'), ((8223, 8236), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (8230, 8236), True, 'import torch.nn as nn\n'), ((8250, 8267), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(2)'], {}), '(128, 2)\n', (8259, 8267), True, 'import torch.nn as nn\n'), ((1204, 1265), 'torch.arange', 'torch.arange', (['B'], {'dtype': 'leye_box.dtype', 'device': 'leye_box.device'}), '(B, dtype=leye_box.dtype, device=leye_box.device)\n', (1216, 1265), False, 'import torch\n'), ((5371, 5432), 'torch.arange', 'torch.arange', (['B'], {'dtype': 'leye_box.dtype', 'device': 'leye_box.device'}), '(B, dtype=leye_box.dtype, device=leye_box.device)\n', (5383, 5432), False, 'import torch\n'), ((8481, 8542), 'torch.arange', 'torch.arange', (['B'], {'dtype': 'leye_box.dtype', 'device': 'leye_box.device'}), '(B, dtype=leye_box.dtype, device=leye_box.device)\n', (8493, 8542), False, 'import torch\n'), ((4269, 4290), 'torch.matmul', 'torch.matmul', (['attn', 'v'], {}), '(attn, v)\n', (4281, 4290), False, 'import torch\n')] |
import sys
import numpy as np
n, a, *x = map(int, sys.stdin.read().split())
def main():
m = 2500
dp = np.zeros((n + 1, m + 1), dtype=np.int64)
dp[0, 0] = 1
for i in range(n):
dp[1:, x[i] :] += dp[:-1, : -x[i]].copy()
i = np.arange(1, n + 1)
print(dp[i, i * a].sum())
if __name__ == "__main__":
main()
| [
"sys.stdin.read",
"numpy.zeros",
"numpy.arange"
] | [((123, 163), 'numpy.zeros', 'np.zeros', (['(n + 1, m + 1)'], {'dtype': 'np.int64'}), '((n + 1, m + 1), dtype=np.int64)\n', (131, 163), True, 'import numpy as np\n'), ((266, 285), 'numpy.arange', 'np.arange', (['(1)', '(n + 1)'], {}), '(1, n + 1)\n', (275, 285), True, 'import numpy as np\n'), ((56, 72), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (70, 72), False, 'import sys\n')] |
import numpy as np
sbox = [
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
]
hamm = [bin(i).count('1') for i in range(256)]
def hypothesis(inputs, outputs, traces, byte_num, byte_check):
best_corr = 0
x = np.zeros(len(traces))
for i in range(len(traces)):
x[i] = hamm[sbox[inputs[i][byte_num] ^ byte_check]]
traces1 = traces.T
for trace_pos in range(len(traces[0])):
y = traces1[trace_pos]
r = abs(np.corrcoef(x, y)[0][1])
if r > best_corr:
best_corr = r
return best_corr
def find_byte(inputs, outputs, traces, byte_num):
all = []
for i in range(256):
#print str(i) + "/256",
r = hypothesis(inputs, outputs, traces, byte_num, i)
r = int(r * 10000) / 100.0
#print r
all.append((r, i))
all = sorted(all)[::-1]
return all
| [
"numpy.corrcoef"
] | [((1998, 2015), 'numpy.corrcoef', 'np.corrcoef', (['x', 'y'], {}), '(x, y)\n', (2009, 2015), True, 'import numpy as np\n')] |
import numpy as np
import pygame as pg
class gen_player_cloud:
def __init__ (self, num_players, player_class):
self.init_players(num_players, player_class)
self.set_random_colors()
self.tick = 0
def init_players(self, num_players, player_class):
self.active_players_num = num_players
self.players = []
self.ticks = []
self.last_dist = []
for index in range(num_players):
self.players.append(player_class())
self.ticks.append(0)
self.last_dist.append(0)
def modify_colors(self, sorted_scores):
for ind, player_ind in enumerate(sorted_scores):
new_color = self.validate_color(255*ind/len(self.players))
self.players[player_ind].color = (0,0,new_color)
if(ind<20):
winner_color = self.validate_color((255 * (20-ind))/20)
self.players[player_ind].color = (0,winner_color,0)
def get_best_players(self):
scores = np.array([self.players[i].score for i in range(len(self.players))])# np.array(self.ticks)
arg_sorted_scores = np.argsort(scores)
arg_sorted_scores = arg_sorted_scores[::-1]
self.modify_colors(arg_sorted_scores)
return arg_sorted_scores
def reset_players(self):
self.tick = 0
self.active_players_num = len(self.players)
for ind, player in enumerate(self.players):
player.reset_player()
self.ticks[ind] = 0
def validate_color(self, ind):
val_ind = int(max(min(255,ind),0))
return val_ind
def set_random_colors(self):
for player in self.players:
player.color = list(np.random.choice(range(256), size=3))
def get_next_active_player(self, current_index, reverse = False):
start_index = current_index
delta = 1
if reverse:
delta = -1
while(True):
current_index += delta
if current_index < 0 or current_index >= len(self.players):
return start_index
else:
if self.players[current_index].active:
return current_index
def update_players(self, screen, board, nn_outputs, nn_inputs):
self.tick+=1
active_players = True
for ind, player in enumerate(self.players):
if player.active:
deactivate_flag, nn_inputs[ind] = player.update(board, screen, nn_outputs[ind])
if deactivate_flag:
self.active_players_num -= 1
if self.active_players_num == 0:
active_players = False
return active_players, nn_inputs
def draw_players(self,screen):
for player in self.players:
if player.active:
player.draw(screen)
class gen_player:
def __init__(self):
self.active = True
self.pos = self.start_pos.copy()
self.speed = self.start_speed.copy()
self.acc = self.start_acc
self.ticks = 0
def update_nn_inputs(self, board):
#Specific
print("No specific nn inputs update")
def apply_nn_outputs(self, nn_outputs):
#Specific
print("No specific nn outputs application")
def apply_specific_movement(self):
#Specific
print("No specific movement implemented")
pass
def move_player(self, nn_outputs):
#Generic
self.apply_nn_outputs(nn_outputs)
self.pos += self.speed
self.speed += self.acc
self.apply_specific_movement()
def reset_player(self):
self.active = True
self.pos = self.start_pos.copy()
self.speed = self.start_speed.copy()
self.acc = self.start_acc.copy()
self.ticks = 0
def calculate_score(self, board):
#Specific
print("Implement Score Calculation")
pass
def elimination_condition(self, board):
#Specific
print("Implement Elimination Condition")
pass
def update(self, board, screen, nn_outputs):
#Generic
deactivated = False
new_nn_inputs = None
if self.active == True:
self.ticks+=1
self.move_player(nn_outputs)
new_nn_inputs = self.update_nn_inputs(board)
deactivated = self.elimination_condition(board)
if deactivated == True:
self.calculate_score(board)
return deactivated, new_nn_inputs
def draw(self, screen):
#Specific
print("No draw function implemented") | [
"numpy.argsort"
] | [((1170, 1188), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (1180, 1188), True, 'import numpy as np\n')] |
import csv
import sys
import numpy as np
from fooof import FOOOF
# Take input arguments from matlab
inputname = sys.argv[1]
path2 = sys.argv[2]
withKnee = sys.argv[3]
# Read .csv file
with open(path2 + '\\' + inputname + '.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
fs = []
psd = []
for idx,row in enumerate(spamreader):
temp = row[0].split(',')
fs.append(float(temp[0]))
psd.append(list(map(float,temp[1:])))
# Turn into numpy arrays
psd = np.array(psd)
fs = np.array(fs)
# Run fooof on each time average from this patient
if(withKnee == "1"):
fm = FOOOF(peak_width_limits=[2.0, 15.0], max_n_peaks=3, aperiodic_mode='knee')
else:
fm = FOOOF(peak_width_limits=[2.0, 15.0], max_n_peaks=3, aperiodic_mode='fixed')
peakFreq = []
peakHeight = []
OOF = []
peakWidth = []
rsquare = []
for i in range(0,psd.shape[1]):
fm.fit(fs,psd[:,i])
peakFreq.append(fm.get_results().peak_params[:,0])
peakWidth.append(fm.get_results().peak_params[:,1])
peakHeight.append(fm.get_results().peak_params[:,2])
OOF.append(fm.aperiodic_params_)
rsquare.append(fm.r_squared_)
# Save peak position and height into .csv files
with open(path2 + '\\' + inputname + '_peakFreq.csv','w',newline='') as csvfile:
wrt = csv.writer(csvfile, delimiter=',')
for peaks in peakFreq:
if(len(peaks)==0):
wrt.writerow('0')
else:
wrt.writerow(peaks)
with open(path2 + '\\' + inputname + '_peakHeight.csv','w',newline='') as csvfile:
wrt = csv.writer(csvfile, delimiter=',')
for peaks in peakHeight:
if(len(peaks)==0):
wrt.writerow('0')
else:
wrt.writerow(peaks)
with open(path2 + '\\' + inputname + '_OOF.csv','w',newline='') as csvfile:
wrt = csv.writer(csvfile, delimiter=',')
for ps in OOF:
if(len(ps)==0):
wrt.writerow('0')
else:
wrt.writerow(ps)
with open(path2 + '\\' + inputname + '_peakWidth.csv','w',newline='') as csvfile:
wrt = csv.writer(csvfile, delimiter=',')
for ps in peakWidth:
if(len(ps)==0):
wrt.writerow('0')
else:
wrt.writerow(ps)
with open(path2 + '\\' + inputname + '_rsquared.csv','w',newline='') as csvfile:
wrt = csv.writer(csvfile, delimiter=',')
wrt.writerow(rsquare)
| [
"fooof.FOOOF",
"csv.reader",
"numpy.array",
"csv.writer"
] | [((534, 547), 'numpy.array', 'np.array', (['psd'], {}), '(psd)\n', (542, 547), True, 'import numpy as np\n'), ((553, 565), 'numpy.array', 'np.array', (['fs'], {}), '(fs)\n', (561, 565), True, 'import numpy as np\n'), ((272, 321), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""" """', 'quotechar': '"""|"""'}), "(csvfile, delimiter=' ', quotechar='|')\n", (282, 321), False, 'import csv\n'), ((648, 722), 'fooof.FOOOF', 'FOOOF', ([], {'peak_width_limits': '[2.0, 15.0]', 'max_n_peaks': '(3)', 'aperiodic_mode': '"""knee"""'}), "(peak_width_limits=[2.0, 15.0], max_n_peaks=3, aperiodic_mode='knee')\n", (653, 722), False, 'from fooof import FOOOF\n'), ((738, 813), 'fooof.FOOOF', 'FOOOF', ([], {'peak_width_limits': '[2.0, 15.0]', 'max_n_peaks': '(3)', 'aperiodic_mode': '"""fixed"""'}), "(peak_width_limits=[2.0, 15.0], max_n_peaks=3, aperiodic_mode='fixed')\n", (743, 813), False, 'from fooof import FOOOF\n'), ((1316, 1350), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1326, 1350), False, 'import csv\n'), ((1575, 1609), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1585, 1609), False, 'import csv\n'), ((1829, 1863), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1839, 1863), False, 'import csv\n'), ((2073, 2107), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (2083, 2107), False, 'import csv\n'), ((2323, 2357), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (2333, 2357), False, 'import csv\n')] |
'''This module contains the following:
Controller
A class for Keras (Tensorflow backend) based OpenAI gym controllers.
Models
A class implementing and supplying Keras models to the Controller
class.
ActionTransformations
A container class for methods that transform the controller (Keras model)
output (action) to a representation suitable for the OpenAI gym
environment.
action_transformations
A dictionary that links the action transformation to the specific
environment name. The Controller.fitness method accesses this
dictionary.
EarlyStop
A class containing a method and dictionary that enable
the controller.fitness evaluation to be prematurely terminated if a
candidate controllers performance is poor. This reduces computational cost.
'''
import numpy as np
import gym
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, Flatten
from keras.utils import plot_model
class Controller(object):
'''Class for Keras (Tensorflow backend) based OpenAI gym controllers.'''
def __init__(self, model_constructor, env,
episode_length, device='/cpu:0', render=False,
force_action_space=None):
'''Initialize a controller.
Args:
model_constructor (function):
Function that returns a keras model.
The function takes the input and output
dimensions of the keras model as an argument.
env (str):
A OpenAI gym envrionment name.
episode_length (int):
Number of frames to process.
device (str, optional):
String that specifies the tensorflow device to use.
render (bool, optional):
Boolean to indicate whether the environment is rendered.
force_action_space (int, optional):
Whenever the gym environment is not correctly implemented
( `type(env.action_space_low)!=np.ndarray` ) use this input to
manually specify action_space dimension.
'''
# get obs/act space dims. was not always correctly implemented in gym
# hence the uglyness
self.env = gym.make(env)
self.observation_space_low = self.env.observation_space.low
self.action_space_low = self.env.action_space.sample()
# get the model
if type(self.action_space_low) == np.ndarray:
self.model = model_constructor(
self.observation_space_low.shape[0], len(self.action_space_low))
# whenever gym would not work properly, set using additional parameter
else:
self.model = model_constructor(
self.observation_space_low.shape[0], force_action_space)
self.stacked_weights = self.model.get_weights()
# save some useful things
self.env_name = env
self.episode_length = episode_length
self.device = device
self.frame_count = 0
self.render = render
# save weight sizes for output as column vector
self.weight_sizes = [(x.shape, x.size) for x in self.stacked_weights]
# save the dimension by simply adding all sizes
self.n = sum([x.size for x in self.stacked_weights])
def fitness(self, flat_weights):
'''Sample the cumulative return of one episode acting according to
current weights.
Args:
flat_wights (numpy.ndarray): Vector of length self.n specifying the
weights of the controller to sample.
Returns:
float: Cumulative reward after an episode
of length self.episode_length.
'''
# convert weight vector to keras structure and set
self.set_weights(flat_weights)
# reset environment
observation = self.env.reset()
fitness = 0
# loop over steps
for step in range(self.episode_length):
# check rendering
if self.render:
self.env.render()
# be sure to use preferred device
with tf.device(self.device):
# get controller output
action = self.model.predict(np.array([observation]))
# convert action to gym format
action = action_transformations[self.env_name](action)
# act
observation, reward, done, info = self.env.step(action)
fitness += reward
self.frame_count += 1
# check for early stopping
if done or EarlyStop.check(step, fitness, self.env_name):
# inverse fitness for minimizing algorithms
return -fitness
# inverse fitness for minimizing algorithms
return -fitness
def set_weights(self, flat_weights):
'''Convert the weight vector from optimizer friendly format
to a layerwise representation. Use this to set model weights to.
Args:
flat_weights (numpy.ndarray): A vector of shape (self.n,) holding
the weights the controller should be set to.
'''
i = 0
j = 0
# get layer representation
for weight_size in self.weight_sizes:
self.stacked_weights[j] = np.reshape(
flat_weights[i:i+weight_size[1]], weight_size[0])
j += 1
i += weight_size[1]
# set keras model weights
self.model.set_weights(self.stacked_weights)
def get_weights(self):
'''Just a wrapper for the standard methods that returns the
stacked (layerwise) weights of the Keras model.
Returns:
Stacked model weights.
'''
return self.model.get_weights()
class Models(object):
'''Container for methods that return a Keras model.
The method must take the dimensionality of the state space as well
as the dimensionality of the action space as arguments.
'''
@staticmethod
def smallModel(input_dim, output_dim):
model = Sequential()
model.add(Dense(10, input_dim=input_dim))
model.add(Activation('elu'))
model.add(Dense(output_dim))
model.add(Activation('sigmoid'))
return model
@staticmethod
def bipedalModel(input_dim, output_dim):
model = Sequential()
model.add(Dense(30, input_dim=input_dim))
model.add(Activation('elu'))
model.add(Dense(30))
model.add(Activation('elu'))
model.add(Dense(15))
model.add(Activation('elu'))
model.add(Dense(10))
model.add(Activation('elu'))
model.add(Dense(output_dim))
model.add(Activation('sigmoid'))
return model
@staticmethod
def robopongModel(input_dim, output_dim):
model = Sequential()
model.add(Dense(30, input_dim=input_dim))
model.add(Activation('elu'))
model.add(Dense(30))
model.add(Activation('elu'))
model.add(Dense(15))
model.add(Activation('elu'))
model.add(Dense(10))
model.add(Activation('elu'))
model.add(Dense(output_dim))
model.add(Activation('sigmoid'))
return model
@staticmethod
def acrobotModel(input_dim, output_dim):
input_dim=input_dim[0]
model=Sequential()
model.add(Dense(30, input_dim=input_dim))
model.add(Activation('elu'))
model.add(Dense(30))
model.add(Activation('elu'))
model.add(Dense(10))
model.add(Activation('elu'))
model.add(Dense(output_dim))
model.add(Activation('sigmoid'))
return model
class ActionTransformations(object):
'''Container for methods that transform the controller (Keras model)
output (action) to a representation suitable for the OpenAI gym
environment.
Typically the method is implemented to suit a specific
controller-environment configuration.
'''
@staticmethod
def cartPoleV0(action):
return int(action[0, 0])
@staticmethod
def carRacingV0(action):
return action[0]
@staticmethod
def bipedalWalkerV2(action):
return (action[0]-[0.5, 0.5, 0.5, 0.5])*2
@staticmethod
def breakoutRamV0(action):
return np.argmax(action[0])
@staticmethod
def roboschoolPongV1(action):
return (action[0]-[0.5, 0.5])*2
@staticmethod
def acrobotV1(action):
#print(action,np.argmax(action[0]))
return np.argmax(action[0])
action_transformations={'CartPole-v0': ActionTransformations.cartPoleV0,
'CarRacing-v0': ActionTransformations.carRacingV0,
'BipedalWalker-v2': ActionTransformations.bipedalWalkerV2,
'Breakout-ram-v0': ActionTransformations.breakoutRamV0,
'RoboschoolPong-v1': ActionTransformations.roboschoolPongV1,
'Acrobot-v1': ActionTransformations.acrobotV1}
'''dict: Links the action transformation to the specific environment name.
The fitness method accesses this dictionary.'''
class EarlyStop(object):
'''Contains a method and dictionary that enable
the controller.fitness evaluation to be prematurely terminated if a
candidate controllers performance is poor. This reduces computational cost.
If a given controller falls short of reaching a the specified cumulative
reward within the corresponding number of timesteps, the evaluation
in controller.fitness is prematurely terminated in order to reduce
the runtime. The interface to the controller.fitness is given by the
EarlyStop.check method.
'''
step_fitness_dict = {'CartPole-v0': [],
'CarRacing-v0': [],
'Breakout-ram-v0': [],
'BipedalWalker-v2': [(190, 15), (300, 30), (400, 40), (600, 50),
(700, 65), (800, 80)],
'RoboschoolPong-v1': [],
'Acrobot-v1': []}
'''dict: A dictionary specifying corresponding fitness and
time-step thresholds for the envrionments.'''
@classmethod
def check(cls, step, fitness, env_name):
'''The interface to the controller.fitness.
Here the check is performed.
Args:
step (int): The current time-step.
fitness (float): The current cumulative reward.
env_name (str): The environments name.
Returns:
bool: Indicating whether evaluation should be prematurely
terminated.
'''
for i in range( len(cls.step_fitness_dict[env_name]) ):
if ( step > cls.step_fitness_dict[env_name][i][0] ) and\
( fitness < cls.step_fitness_dict[env_name][i][1] ):
return True
return False
| [
"gym.make",
"numpy.argmax",
"keras.layers.Activation",
"tensorflow.device",
"keras.layers.Dense",
"numpy.array",
"numpy.reshape",
"keras.models.Sequential"
] | [((2305, 2318), 'gym.make', 'gym.make', (['env'], {}), '(env)\n', (2313, 2318), False, 'import gym\n'), ((6243, 6255), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (6253, 6255), False, 'from keras.models import Sequential\n'), ((6534, 6546), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (6544, 6546), False, 'from keras.models import Sequential\n'), ((7029, 7041), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (7039, 7041), False, 'from keras.models import Sequential\n'), ((7553, 7565), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (7563, 7565), False, 'from keras.models import Sequential\n'), ((8546, 8566), 'numpy.argmax', 'np.argmax', (['action[0]'], {}), '(action[0])\n', (8555, 8566), True, 'import numpy as np\n'), ((8774, 8794), 'numpy.argmax', 'np.argmax', (['action[0]'], {}), '(action[0])\n', (8783, 8794), True, 'import numpy as np\n'), ((5448, 5510), 'numpy.reshape', 'np.reshape', (['flat_weights[i:i + weight_size[1]]', 'weight_size[0]'], {}), '(flat_weights[i:i + weight_size[1]], weight_size[0])\n', (5458, 5510), True, 'import numpy as np\n'), ((6275, 6305), 'keras.layers.Dense', 'Dense', (['(10)'], {'input_dim': 'input_dim'}), '(10, input_dim=input_dim)\n', (6280, 6305), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6326, 6343), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (6336, 6343), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6364, 6381), 'keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (6369, 6381), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6402, 6423), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (6412, 6423), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6566, 6596), 'keras.layers.Dense', 'Dense', (['(30)'], {'input_dim': 'input_dim'}), '(30, input_dim=input_dim)\n', (6571, 6596), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6617, 6634), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (6627, 6634), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6655, 6664), 'keras.layers.Dense', 'Dense', (['(30)'], {}), '(30)\n', (6660, 6664), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6685, 6702), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (6695, 6702), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6723, 6732), 'keras.layers.Dense', 'Dense', (['(15)'], {}), '(15)\n', (6728, 6732), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6753, 6770), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (6763, 6770), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6791, 6800), 'keras.layers.Dense', 'Dense', (['(10)'], {}), '(10)\n', (6796, 6800), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6821, 6838), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (6831, 6838), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6859, 6876), 'keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (6864, 6876), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((6897, 6918), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (6907, 6918), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7061, 7091), 'keras.layers.Dense', 'Dense', (['(30)'], {'input_dim': 'input_dim'}), '(30, input_dim=input_dim)\n', (7066, 7091), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7112, 7129), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7122, 7129), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7150, 7159), 'keras.layers.Dense', 'Dense', (['(30)'], {}), '(30)\n', (7155, 7159), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7180, 7197), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7190, 7197), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7218, 7227), 'keras.layers.Dense', 'Dense', (['(15)'], {}), '(15)\n', (7223, 7227), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7248, 7265), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7258, 7265), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7286, 7295), 'keras.layers.Dense', 'Dense', (['(10)'], {}), '(10)\n', (7291, 7295), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7316, 7333), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7326, 7333), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7354, 7371), 'keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (7359, 7371), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7392, 7413), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (7402, 7413), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7585, 7615), 'keras.layers.Dense', 'Dense', (['(30)'], {'input_dim': 'input_dim'}), '(30, input_dim=input_dim)\n', (7590, 7615), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7636, 7653), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7646, 7653), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7674, 7683), 'keras.layers.Dense', 'Dense', (['(30)'], {}), '(30)\n', (7679, 7683), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7704, 7721), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7714, 7721), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7742, 7751), 'keras.layers.Dense', 'Dense', (['(10)'], {}), '(10)\n', (7747, 7751), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7772, 7789), 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), "('elu')\n", (7782, 7789), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7810, 7827), 'keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (7815, 7827), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((7848, 7869), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (7858, 7869), False, 'from keras.layers import Dense, Activation, Convolution2D, Flatten\n'), ((4250, 4272), 'tensorflow.device', 'tf.device', (['self.device'], {}), '(self.device)\n', (4259, 4272), True, 'import tensorflow as tf\n'), ((4360, 4383), 'numpy.array', 'np.array', (['[observation]'], {}), '([observation])\n', (4368, 4383), True, 'import numpy as np\n')] |
import random
import numpy as np
from Utils.constants import Prior
class Cell:
"""
Represents a single cell in the Map() objects grid
"""
def __init__(self, center, cell_length:float=1) -> None:
self._center = center
self._cell_length = cell_length
self._probability = 0
self._std = 0
@property
def corners(self):
offset = self._cell_length / 2
corner_vectors = np.array(
[[0, offset], [offset, 0], [0, -offset], [-offset, 0]])
return self._center + corner_vectors
@property
def center(self):
return self._center
def center_hash(self):
tmp = self._center[1] + (self._center[0] + 1) / 2
return self._center + tmp * tmp
@property
def probability(self):
return self._probability
@probability.setter
def probability(self, prob:float):
self._probability = prob
@property
def std(self):
return self._std
@std.setter
def std(self, std):
self._std = std
def isNeighbor(self, cell):
return np.linalg.norm(cell.center - self._center) <= np.sqrt(2 * self._cell_length)
def __str__(self) -> str:
return f"Cell: Center:{self._center} Prob: {self._probability} Cov: {self._std}"
class Map():
def __init__(self, bottom_corner, shape, cell_size:float=1) -> None:
"""
The map encapsulates the grid of cells which are used in the gaussian process model.
Arguments:
bottom_corner: n-dimensional array of the starting point ie [0,0] only supports 2/3 atm
shape: n-dimensional array representing the total map space ie (30,30)
cell_size: the size of each cell
"""
if len(bottom_corner) != len(shape):
raise ValueError(
f"Dimension mismatch: len(bottom_corner) ({len(bottom_corner)}) != len(shape) ({len(shape)})")
self._cells = []
self._bottom_corner = np.array(bottom_corner)
self._shape = np.array(shape)
self._previous_cell = None
self._cell_size = cell_size
self.cell_centers = np.empty((0, len(self._shape)))
starting_point = self._bottom_corner + cell_size/2
ending_point = self._bottom_corner + cell_size*self._shape
for i in np.arange(starting_point[0], ending_point[0], step=self._cell_size):
for j in np.arange(ending_point[1], starting_point[1], step=-self._cell_size):
if len(self._shape) == 3:
for k in np.arange(ending_point[2], starting_point[2], step=-self._cell_size):
center = np.array([i, j])
self._cells.append(Cell(center, self._cell_size))
self.cell_centers = np.append(
self.cell_centers, np.array([center]), axis=0)
else:
center = np.array([i, j])
self._cells.append(Cell(center, self._cell_size))
self.cell_centers = np.append(
self.cell_centers, np.array([center]), axis=0)
def add_new_cells(self, new_cells:list):
for cell in new_cells:
self._cells.append(cell)
@property
def get_shape(self):
return self._shape
@property
def get_cells(self):
return self._cells
@property
def get_cell_size(self):
return self._cell_size
@property
def previous_cell(self):
return self._previous_cell
@previous_cell.setter
def previous_cell(self, cell:Cell):
self._previous_cell = cell
def reset_map(self):
"Removes any prior, is used when a new target device is to be calculated"
self._previous_cell = None
def calculate_cell_probabilities(self, measurements:dict, beacons:dict, prior:Prior=Prior.UNIFORM):
"""Calculates the new probabilities for all the cells """
standard_deviation = 2
distance_sum = np.zeros(len(self.cell_centers))
std_sum = np.zeros(len(self.cell_centers))
beacons_used = {address: beacon for address,
beacon in beacons.items() if address in measurements.keys()}
for address, beacon in beacons_used.items():
rssi_predictions, std_predictions = beacon.predict_rssi(
self.cell_centers)
distance_sum += np.square(measurements[address] - rssi_predictions)
std_sum += std_predictions
distances = np.sqrt(distance_sum / len(beacons_used))
nlog_p = np.exp2(distances) / (2 * np.exp2(standard_deviation)) #negative log p is calculated to avoid reverse sorting later
#updates cell information if it passes the prior condition
for i, cell in enumerate(self._cells):
prior_condition = (prior is Prior.LOCAL and self.previous_cell is not None and self.previous_cell.isNeighbor(
cell)) or random.randint(0,9) < 2 or prior is Prior.UNIFORM or self.previous_cell is None
cell.probability = nlog_p[i] if prior_condition else 1*10**9
cell.std = std_sum[i]
return self._cells
| [
"numpy.exp2",
"random.randint",
"numpy.square",
"numpy.linalg.norm",
"numpy.array",
"numpy.arange",
"numpy.sqrt"
] | [((438, 502), 'numpy.array', 'np.array', (['[[0, offset], [offset, 0], [0, -offset], [-offset, 0]]'], {}), '([[0, offset], [offset, 0], [0, -offset], [-offset, 0]])\n', (446, 502), True, 'import numpy as np\n'), ((1980, 2003), 'numpy.array', 'np.array', (['bottom_corner'], {}), '(bottom_corner)\n', (1988, 2003), True, 'import numpy as np\n'), ((2026, 2041), 'numpy.array', 'np.array', (['shape'], {}), '(shape)\n', (2034, 2041), True, 'import numpy as np\n'), ((2319, 2386), 'numpy.arange', 'np.arange', (['starting_point[0]', 'ending_point[0]'], {'step': 'self._cell_size'}), '(starting_point[0], ending_point[0], step=self._cell_size)\n', (2328, 2386), True, 'import numpy as np\n'), ((1096, 1138), 'numpy.linalg.norm', 'np.linalg.norm', (['(cell.center - self._center)'], {}), '(cell.center - self._center)\n', (1110, 1138), True, 'import numpy as np\n'), ((1142, 1172), 'numpy.sqrt', 'np.sqrt', (['(2 * self._cell_length)'], {}), '(2 * self._cell_length)\n', (1149, 1172), True, 'import numpy as np\n'), ((2409, 2477), 'numpy.arange', 'np.arange', (['ending_point[1]', 'starting_point[1]'], {'step': '(-self._cell_size)'}), '(ending_point[1], starting_point[1], step=-self._cell_size)\n', (2418, 2477), True, 'import numpy as np\n'), ((4416, 4467), 'numpy.square', 'np.square', (['(measurements[address] - rssi_predictions)'], {}), '(measurements[address] - rssi_predictions)\n', (4425, 4467), True, 'import numpy as np\n'), ((4587, 4605), 'numpy.exp2', 'np.exp2', (['distances'], {}), '(distances)\n', (4594, 4605), True, 'import numpy as np\n'), ((4613, 4640), 'numpy.exp2', 'np.exp2', (['standard_deviation'], {}), '(standard_deviation)\n', (4620, 4640), True, 'import numpy as np\n'), ((2550, 2618), 'numpy.arange', 'np.arange', (['ending_point[2]', 'starting_point[2]'], {'step': '(-self._cell_size)'}), '(ending_point[2], starting_point[2], step=-self._cell_size)\n', (2559, 2618), True, 'import numpy as np\n'), ((2925, 2941), 'numpy.array', 'np.array', (['[i, j]'], {}), '([i, j])\n', (2933, 2941), True, 'import numpy as np\n'), ((4968, 4988), 'random.randint', 'random.randint', (['(0)', '(9)'], {}), '(0, 9)\n', (4982, 4988), False, 'import random\n'), ((2653, 2669), 'numpy.array', 'np.array', (['[i, j]'], {}), '([i, j])\n', (2661, 2669), True, 'import numpy as np\n'), ((3106, 3124), 'numpy.array', 'np.array', (['[center]'], {}), '([center])\n', (3114, 3124), True, 'import numpy as np\n'), ((2846, 2864), 'numpy.array', 'np.array', (['[center]'], {}), '([center])\n', (2854, 2864), True, 'import numpy as np\n')] |
import numpy as np
from keras.models import Model
from src.modules import config
class NeuronCoverage:
def __init__(self, model, threshold=None, excluded_layer=None):
if excluded_layer is None:
excluded_layer = ['pool', 'fc', 'flatten', 'input']
if threshold is None:
self.threshold = float(config.get("evaluation.neuron_cover_threshold"))
if model is None:
raise RuntimeError('Model needs to be a keras model')
self.model: Model = model
# the layers that are considered in neuron coverage computation
self.included_layers = []
for layer in self.model.layers:
if all(ex not in layer.name for ex in excluded_layer):
self.included_layers.append(layer.name)
# init coverage table
self.coverage_tracker = {}
try:
for layer_name in self.included_layers:
for index in range(self.model.get_layer(layer_name).output_shape[-1]):
self.coverage_tracker[(layer_name, index)] = False
except Exception as ex:
raise Exception(f"Error while checking model layer to initialize neuron coverage tracker: {ex}")
@staticmethod
def normalize(layer_outputs):
# Normalize layout output to 0-1 range
r = (layer_outputs.max() - layer_outputs.min())
if r == 0:
return np.zeros(shape=layer_outputs.shape)
return (layer_outputs - layer_outputs.min()) / r
def fill_coverage_tracker(self, input_data):
"""
Given the input, update the neuron covered in the model by this input.
This includes mark the neurons covered by this input as "covered"
:param accumulative: find accumulative coverage or not
:param input_data: the input image
:return: the neurons that can be covered by the input
"""
for layer_name in self.included_layers:
layer_model = Model(self.model.inputs,
self.model.get_layer(layer_name).output)
layer_outputs = layer_model.predict(input_data)
for layer_output in layer_outputs:
normalized_val = self.normalize(layer_output)
for neuron_idx in range(normalized_val.shape[-1]):
if np.mean(normalized_val[..., neuron_idx]) > self.threshold:
self.coverage_tracker[(layer_name, neuron_idx)] = True
del layer_outputs
del layer_model
def reset_coverage_tracker(self):
"""
Reset the coverage table
:return:
"""
for layer_name in self.included_layers:
for index in range(self.model.get_layer(layer_name).output_shape[-1]):
self.coverage_tracker[(layer_name, index)] = False
def calculate_coverage(self):
covered_neurons = len([v for v in self.coverage_tracker.values() if v])
total_neurons = len(self.coverage_tracker)
return covered_neurons, total_neurons, covered_neurons / float(total_neurons)
| [
"src.modules.config.get",
"numpy.mean",
"numpy.zeros"
] | [((1407, 1442), 'numpy.zeros', 'np.zeros', ([], {'shape': 'layer_outputs.shape'}), '(shape=layer_outputs.shape)\n', (1415, 1442), True, 'import numpy as np\n'), ((340, 387), 'src.modules.config.get', 'config.get', (['"""evaluation.neuron_cover_threshold"""'], {}), "('evaluation.neuron_cover_threshold')\n", (350, 387), False, 'from src.modules import config\n'), ((2331, 2371), 'numpy.mean', 'np.mean', (['normalized_val[..., neuron_idx]'], {}), '(normalized_val[..., neuron_idx])\n', (2338, 2371), True, 'import numpy as np\n')] |
import cvxpy as cp
import numpy as np
import logging
from tprmp.models.coriolis import compute_coriolis_force
from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric
logger = logging.getLogger(__name__)
def optimize_dynamics(tp_gmm, demos, **kwargs):
alpha = kwargs.get('alpha', 1e-5)
beta = kwargs.get('beta', 1e-5)
stiff_scale = kwargs.get('stiff_scale', 1.)
mass_scale = kwargs.get('mass_scale', 1.)
tau = kwargs.get('tau', 1.)
delta = kwargs.get('delta', 1.)
potential_method = kwargs.get('potential_method', 'quadratic')
train_method = kwargs.get('train_method', 'match_accel')
d_min = kwargs.get('d_min', 0.)
energy = kwargs.get('energy', 0.)
verbose = kwargs.get('verbose', False)
phi0 = optimize_potentials(tp_gmm, demos, alpha=alpha, stiff_scale=stiff_scale, mass_scale=mass_scale, tau=tau, delta=delta, potential_method=potential_method, energy=energy, verbose=verbose)
d0 = optimize_dissipation(tp_gmm, demos, phi0, beta=beta, stiff_scale=stiff_scale, mass_scale=mass_scale,
tau=tau, delta=delta, potential_method=potential_method, train_method=train_method, d_min=d_min, verbose=verbose)
return phi0, d0
def optimize_potentials(tp_gmm, demos, **kwargs):
alpha = kwargs.get('alpha', 1e-5)
stiff_scale = kwargs.get('stiff_scale', 1.)
mass_scale = kwargs.get('mass_scale', 1.)
tau = kwargs.get('tau', 1.)
delta = kwargs.get('delta', 1.)
potential_method = kwargs.get('potential_method', 'quadratic')
energy = kwargs.get('energy', 0.)
eps = kwargs.get('eps', 1e-4)
verbose = kwargs.get('verbose', False)
gap = energy / tp_gmm.num_comp
phi0 = cp.Variable(tp_gmm.num_comp)
loss = 0.
for demo in demos:
x, dx = demo.traj, demo.d_traj
mvns = tp_gmm.generate_global_gmm(demo.get_task_parameters())
for t in range(x.shape[1]):
weights = compute_obsrv_prob(x[:, t], mvns)
f = compute_potential_term(weights, phi0, x[:, t], mvns, stiff_scale=stiff_scale, tau=tau, delta=delta, potential_method=potential_method)
M = compute_riemannian_metric(x[:, t], mvns, mass_scale=mass_scale)
M_inv = np.linalg.inv(M)
v = dx[:, t]
norm_v = np.linalg.norm(v)
if norm_v > eps:
v = v / norm_v
loss += (cp.norm(v - M_inv @ f) / x.shape[1])
loss /= len(demos)
if alpha > 0.:
loss += alpha * cp.pnorm(phi0, p=2)**2 # L2 regularization
objective = cp.Minimize(loss)
problem = cp.Problem(objective, potential_constraints(phi0, gap))
problem.solve(verbose=verbose)
logger.info('Optimizing potential...')
logger.info(f'Status: {problem.status}')
logger.info(f'Final loss: {loss.value}')
logger.info(f'Optimal phi0: {phi0.value}')
return phi0.value
def optimize_dissipation(tp_gmm, demos, phi0, **kwargs):
beta = kwargs.get('beta', 1e-5)
stiff_scale = kwargs.get('stiff_scale', 1.)
mass_scale = kwargs.get('mass_scale', 1.)
tau = kwargs.get('tau', 1.)
delta = kwargs.get('delta', 1.)
potential_method = kwargs.get('potential_method', 'quadratic')
train_method = kwargs.get('train_method', 'match_accel')
d_min = kwargs.get('d_min', 0.)
d_default = kwargs.get('d_default', 50.)
max_iters = kwargs.get('max_iters', 500)
verbose = kwargs.get('verbose', False)
d0 = cp.Variable(tp_gmm.num_comp)
loss = 0.
for demo in demos:
x, dx, ddx = demo.traj, demo.d_traj, demo.dd_traj
mvns = tp_gmm.generate_global_gmm(demo.get_task_parameters())
if train_method == 'match_accel':
for t in range(x.shape[1]):
M = compute_riemannian_metric(x[:, t], mvns, mass_scale=mass_scale)
M_inv = np.linalg.inv(M)
f = compute_policy(phi0, d0, x[:, t], dx[:, t], mvns, stiff_scale=stiff_scale, tau=tau, delta=delta, potential_method=potential_method)
f -= compute_coriolis_force(x[:, t], dx[:, t], mvns, mass_scale=mass_scale)
loss += cp.norm(ddx[:, t] - M_inv @ f)
elif train_method == 'match_energy':
energy = compute_hamiltonian(phi0, x[:, 0], dx[:, 0], mvns, stiff_scale=stiff_scale, mass_scale=mass_scale, tau=tau, delta=delta, potential_method=potential_method)
d_energy = 0. # d_energy is negative
for t in range(x.shape[1] - 1):
weights = compute_obsrv_prob(x[:, t], mvns)
d_energy += compute_dissipation_term(weights, d0, dx[:, t]) @ (dx[:, t] * demo.dt)
loss += cp.norm(energy + d_energy)
else:
raise ValueError(f'Dissipation training method {train_method} is unrecognized!')
loss /= len(demos)
if beta > 0.:
loss += beta * cp.pnorm(d0, p=2)**2 # L2 regularization
objective = cp.Minimize(loss)
problem = cp.Problem(objective, dissipation_constraints(d0, d_min))
try:
problem.solve(max_iters=max_iters, verbose=verbose)
logger.info('Optimizing dissipation...')
logger.info(f'Status: {problem.status}')
logger.info(f'Final loss: {loss.value}')
logger.info(f'Optimal d0: {d0.value}')
res = d0.value
except cp.error.SolverError:
logger.warn(f'Optimizing dissipation failed! Using d_default {d_default}')
res = d_default * np.ones(tp_gmm.num_comp)
return res
def potential_constraints(phi0, gap=0.):
constraints = []
for k in range(phi0.size - 1):
constraints.append(phi0[k] >= (phi0[k + 1] + gap))
constraints.append(phi0[phi0.size - 1] >= 0)
return constraints
def dissipation_constraints(d0, d_min=0.):
constraints = []
for k in range(d0.size - 1):
constraints.append(d0[k] <= d0[k + 1])
constraints.append(d0[0] >= d_min)
return constraints
if __name__ == '__main__':
from tprmp.demonstrations.probability import ManifoldGaussian
from tprmp.demonstrations.manifold import Manifold
from tprmp.demonstrations.base import Demonstration
from tprmp.models.tp_gmm import TPGMM
# from tprmp.visualization.dynamics import visualize_rmp
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
def simple_demo(T, dt):
ddx = np.ones((2, T))
ddx[:, int(T / 2):] = -1
dx = np.cumsum(ddx, axis=1) * dt
x = np.cumsum(dx, axis=1) * dt
return x, dx, ddx
manifold = Manifold.get_euclidean_manifold(2)
num_comp = 10
max_range = 4
means = np.linspace(1, max_range, num_comp)
var = (max_range - 1) / (2 * num_comp)
scale_var = 1.
mvns = [{'obj': ManifoldGaussian(manifold, means[k] * np.ones(2), scale_var * var * np.eye(2))} for k in range(num_comp)]
T = 400
dt = 0.01
x, dx, ddx = simple_demo(T, dt)
demo = Demonstration(x, dt=dt)
demo.add_frame_from_pose(np.zeros(2), 'obj')
model = TPGMM(num_comp=num_comp)
model._mvns = mvns
model._frame_names = ['obj']
# test training
phi0, d0 = optimize_dynamics(model, [demo], alpha=1e-5, beta=1e-5)
| [
"tprmp.demonstrations.manifold.Manifold.get_euclidean_manifold",
"numpy.ones",
"numpy.linalg.norm",
"tprmp.models.tp_gmm.TPGMM",
"tprmp.models.rmp.compute_potential_term",
"numpy.cumsum",
"numpy.linspace",
"cvxpy.pnorm",
"tprmp.models.coriolis.compute_coriolis_force",
"tprmp.models.rmp.compute_ham... | [((283, 310), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (300, 310), False, 'import logging\n'), ((1792, 1820), 'cvxpy.Variable', 'cp.Variable', (['tp_gmm.num_comp'], {}), '(tp_gmm.num_comp)\n', (1803, 1820), True, 'import cvxpy as cp\n'), ((2635, 2652), 'cvxpy.Minimize', 'cp.Minimize', (['loss'], {}), '(loss)\n', (2646, 2652), True, 'import cvxpy as cp\n'), ((3523, 3551), 'cvxpy.Variable', 'cp.Variable', (['tp_gmm.num_comp'], {}), '(tp_gmm.num_comp)\n', (3534, 3551), True, 'import cvxpy as cp\n'), ((4974, 4991), 'cvxpy.Minimize', 'cp.Minimize', (['loss'], {}), '(loss)\n', (4985, 4991), True, 'import cvxpy as cp\n'), ((6283, 6304), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (6302, 6304), False, 'import logging\n'), ((6566, 6600), 'tprmp.demonstrations.manifold.Manifold.get_euclidean_manifold', 'Manifold.get_euclidean_manifold', (['(2)'], {}), '(2)\n', (6597, 6600), False, 'from tprmp.demonstrations.manifold import Manifold\n'), ((6649, 6684), 'numpy.linspace', 'np.linspace', (['(1)', 'max_range', 'num_comp'], {}), '(1, max_range, num_comp)\n', (6660, 6684), True, 'import numpy as np\n'), ((6946, 6969), 'tprmp.demonstrations.base.Demonstration', 'Demonstration', (['x'], {'dt': 'dt'}), '(x, dt=dt)\n', (6959, 6969), False, 'from tprmp.demonstrations.base import Demonstration\n'), ((7031, 7055), 'tprmp.models.tp_gmm.TPGMM', 'TPGMM', ([], {'num_comp': 'num_comp'}), '(num_comp=num_comp)\n', (7036, 7055), False, 'from tprmp.models.tp_gmm import TPGMM\n'), ((6395, 6410), 'numpy.ones', 'np.ones', (['(2, T)'], {}), '((2, T))\n', (6402, 6410), True, 'import numpy as np\n'), ((6999, 7010), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (7007, 7010), True, 'import numpy as np\n'), ((2025, 2058), 'tprmp.models.rmp.compute_obsrv_prob', 'compute_obsrv_prob', (['x[:, t]', 'mvns'], {}), '(x[:, t], mvns)\n', (2043, 2058), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((2075, 2214), 'tprmp.models.rmp.compute_potential_term', 'compute_potential_term', (['weights', 'phi0', 'x[:, t]', 'mvns'], {'stiff_scale': 'stiff_scale', 'tau': 'tau', 'delta': 'delta', 'potential_method': 'potential_method'}), '(weights, phi0, x[:, t], mvns, stiff_scale=\n stiff_scale, tau=tau, delta=delta, potential_method=potential_method)\n', (2097, 2214), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((2226, 2289), 'tprmp.models.rmp.compute_riemannian_metric', 'compute_riemannian_metric', (['x[:, t]', 'mvns'], {'mass_scale': 'mass_scale'}), '(x[:, t], mvns, mass_scale=mass_scale)\n', (2251, 2289), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((2310, 2326), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (2323, 2326), True, 'import numpy as np\n'), ((2373, 2390), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (2387, 2390), True, 'import numpy as np\n'), ((6309, 6328), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (6326, 6328), False, 'import logging\n'), ((6457, 6479), 'numpy.cumsum', 'np.cumsum', (['ddx'], {'axis': '(1)'}), '(ddx, axis=1)\n', (6466, 6479), True, 'import numpy as np\n'), ((6497, 6518), 'numpy.cumsum', 'np.cumsum', (['dx'], {'axis': '(1)'}), '(dx, axis=1)\n', (6506, 6518), True, 'import numpy as np\n'), ((2472, 2494), 'cvxpy.norm', 'cp.norm', (['(v - M_inv @ f)'], {}), '(v - M_inv @ f)\n', (2479, 2494), True, 'import cvxpy as cp\n'), ((2575, 2594), 'cvxpy.pnorm', 'cp.pnorm', (['phi0'], {'p': '(2)'}), '(phi0, p=2)\n', (2583, 2594), True, 'import cvxpy as cp\n'), ((3819, 3882), 'tprmp.models.rmp.compute_riemannian_metric', 'compute_riemannian_metric', (['x[:, t]', 'mvns'], {'mass_scale': 'mass_scale'}), '(x[:, t], mvns, mass_scale=mass_scale)\n', (3844, 3882), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((3907, 3923), 'numpy.linalg.inv', 'np.linalg.inv', (['M'], {}), '(M)\n', (3920, 3923), True, 'import numpy as np\n'), ((3944, 4079), 'tprmp.models.rmp.compute_policy', 'compute_policy', (['phi0', 'd0', 'x[:, t]', 'dx[:, t]', 'mvns'], {'stiff_scale': 'stiff_scale', 'tau': 'tau', 'delta': 'delta', 'potential_method': 'potential_method'}), '(phi0, d0, x[:, t], dx[:, t], mvns, stiff_scale=stiff_scale,\n tau=tau, delta=delta, potential_method=potential_method)\n', (3958, 4079), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((4097, 4167), 'tprmp.models.coriolis.compute_coriolis_force', 'compute_coriolis_force', (['x[:, t]', 'dx[:, t]', 'mvns'], {'mass_scale': 'mass_scale'}), '(x[:, t], dx[:, t], mvns, mass_scale=mass_scale)\n', (4119, 4167), False, 'from tprmp.models.coriolis import compute_coriolis_force\n'), ((4192, 4222), 'cvxpy.norm', 'cp.norm', (['(ddx[:, t] - M_inv @ f)'], {}), '(ddx[:, t] - M_inv @ f)\n', (4199, 4222), True, 'import cvxpy as cp\n'), ((4289, 4453), 'tprmp.models.rmp.compute_hamiltonian', 'compute_hamiltonian', (['phi0', 'x[:, 0]', 'dx[:, 0]', 'mvns'], {'stiff_scale': 'stiff_scale', 'mass_scale': 'mass_scale', 'tau': 'tau', 'delta': 'delta', 'potential_method': 'potential_method'}), '(phi0, x[:, 0], dx[:, 0], mvns, stiff_scale=stiff_scale,\n mass_scale=mass_scale, tau=tau, delta=delta, potential_method=\n potential_method)\n', (4308, 4453), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((4718, 4744), 'cvxpy.norm', 'cp.norm', (['(energy + d_energy)'], {}), '(energy + d_energy)\n', (4725, 4744), True, 'import cvxpy as cp\n'), ((4916, 4933), 'cvxpy.pnorm', 'cp.pnorm', (['d0'], {'p': '(2)'}), '(d0, p=2)\n', (4924, 4933), True, 'import cvxpy as cp\n'), ((5492, 5516), 'numpy.ones', 'np.ones', (['tp_gmm.num_comp'], {}), '(tp_gmm.num_comp)\n', (5499, 5516), True, 'import numpy as np\n'), ((4565, 4598), 'tprmp.models.rmp.compute_obsrv_prob', 'compute_obsrv_prob', (['x[:, t]', 'mvns'], {}), '(x[:, t], mvns)\n', (4583, 4598), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n'), ((6805, 6815), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (6812, 6815), True, 'import numpy as np\n'), ((6835, 6844), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (6841, 6844), True, 'import numpy as np\n'), ((4627, 4674), 'tprmp.models.rmp.compute_dissipation_term', 'compute_dissipation_term', (['weights', 'd0', 'dx[:, t]'], {}), '(weights, d0, dx[:, t])\n', (4651, 4674), False, 'from tprmp.models.rmp import compute_dissipation_term, compute_hamiltonian, compute_obsrv_prob, compute_policy, compute_potential_term, compute_riemannian_metric\n')] |
from models import MLP, TwinHeadModel
from jax.random import PRNGKey
from buffer import Batch
from algo import (extract_latent_factors, get_transition, mse_loss,
select_action, update_ppo)
from segar.envs.env import SEGAREnv
import glob
import importlib
import os
import subprocess
from collections import deque
from typing import Any
import numpy as np
import optax
import wandb
from absl import app, flags
from flax.training import checkpoints
from flax.training.train_state import TrainState
import jax
import jax.numpy as jnp
def setup_packages():
subprocess.call(
"pip install -e {0}".format(
os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.pardir, os.pardir)),
shell=True,
)
import site
importlib.reload(site)
spec = importlib.util.find_spec("segar")
globals()["segar"] = importlib.util.module_from_spec(spec)
setup_packages()
try:
from azureml.core.run import Run
except Exception as e:
print("Failed to import AzureML")
print(e)
def safe_mean(x: Any):
return np.nan if len(x) == 0 else np.mean(x)
FLAGS = flags.FLAGS
# Task
flags.DEFINE_string("env_name", "empty-easy-rgb", "Env name")
flags.DEFINE_integer("seed", 1, "Random seed.")
flags.DEFINE_integer("num_envs", 64, "Num of parallel envs.")
flags.DEFINE_integer("num_train_levels", 10, "Num of training levels envs.")
flags.DEFINE_integer("num_test_levels", 500, "Num of test levels envs.")
flags.DEFINE_integer("train_steps", 1_000_000, "Number of train frames.")
flags.DEFINE_integer("framestack", 1, "Number of frames to stack")
flags.DEFINE_integer("resolution", 64, "Resolution of pixel observations")
# PPO
flags.DEFINE_float("max_grad_norm", 10, "Max grad norm")
flags.DEFINE_float("gamma", 0.999, "Gamma")
flags.DEFINE_integer("n_steps", 30, "GAE n-steps")
flags.DEFINE_integer("n_minibatch", 4, "Number of PPO minibatches")
flags.DEFINE_float("lr", 1e-4, "PPO learning rate")
flags.DEFINE_integer("epoch_ppo", 1, "Number of PPO epochs on a single batch")
flags.DEFINE_float("clip_eps", 0.2, "Clipping range")
flags.DEFINE_float("gae_lambda", 0.95, "GAE lambda")
flags.DEFINE_float("entropy_coeff", 3e-4, "Entropy loss coefficient")
flags.DEFINE_float("critic_coeff", 0.1, "Value loss coefficient")
# Ablations
flags.DEFINE_boolean(
"probe_latent_factors",
True,
"Probe latent factors from the PPO state representation?",
)
flags.DEFINE_boolean("add_latent_factors", False,
"Add latent factors to PPO state representation?")
flags.DEFINE_boolean("log_episodes", False, "Log episode samples on W&B?")
# Logging
flags.DEFINE_integer("checkpoint_interval", 10, "Checkpoint frequency")
flags.DEFINE_string("output_dir", ".", "Output dir")
flags.DEFINE_string("run_id", "jax_ppo",
"Run ID. Change that to change W&B name")
flags.DEFINE_string("wandb_mode", "disabled",
"W&B logging (disabled, online, offline)")
flags.DEFINE_string("wandb_key", None, "W&B key")
flags.DEFINE_string("wandb_entity", "dummy_username",
"W&B entity (username or team name)")
flags.DEFINE_string("wandb_project", "dummy_project", "W&B project name")
def main(argv):
# Setting all rnadom seeds
if FLAGS.seed == -1:
seed = np.random.randint(100000000)
else:
seed = FLAGS.seed
np.random.seed(seed)
key = PRNGKey(seed)
# If W&B is to be used - set job and group names
if FLAGS.wandb_key is not None:
os.environ["WANDB_API_KEY"] = FLAGS.wandb_key
group_name = "%s_%s_%d" % (FLAGS.run_id, FLAGS.env_name,
FLAGS.num_train_levels)
run_name = "%s_%s_%d_%d" % (
FLAGS.run_id,
FLAGS.env_name,
FLAGS.num_train_levels,
np.random.randint(100000000),
)
run = wandb.init(
project=FLAGS.wandb_project,
entity=FLAGS.wandb_entity,
config=FLAGS,
group=group_name,
name=run_name,
sync_tensorboard=False,
mode=FLAGS.wandb_mode,
dir=FLAGS.output_dir,
)
# Initialize train and test environemnts
# Test environments always have the same number of test levels for
# fair comparison across runs
MAX_STEPS = 100
env = SEGAREnv(
FLAGS.env_name,
num_envs=FLAGS.num_envs,
num_levels=FLAGS.num_train_levels,
framestack=FLAGS.framestack,
resolution=FLAGS.resolution,
max_steps=MAX_STEPS,
_async=False,
seed=FLAGS.seed,
save_path=os.path.join(FLAGS.output_dir, run_name)
)
env_test = SEGAREnv(
FLAGS.env_name,
num_envs=1,
num_levels=FLAGS.num_test_levels,
framestack=FLAGS.framestack,
resolution=FLAGS.resolution,
max_steps=MAX_STEPS,
_async=False,
seed=FLAGS.seed + 1,
save_path=os.path.join(FLAGS.output_dir, run_name)
)
n_action = env.action_space[0].shape[-1]
# Create PPO model, optimizer and buffer
model = TwinHeadModel(
action_dim=n_action,
prefix_critic="vfunction",
prefix_actor="policy",
action_scale=1.0,
add_latent_factors=FLAGS.add_latent_factors,
)
state = env.reset()
state_test = env_test.reset()
if FLAGS.add_latent_factors:
next_state, reward, done, info = env.step(
env.env.action_space.sample())
latent_factors = extract_latent_factors(info)
params_model = model.init(key, state, latent_factors)
else:
params_model = model.init(key, state, None)
latent_factors = None
tx = optax.chain(optax.clip_by_global_norm(FLAGS.max_grad_norm),
optax.adam(FLAGS.lr, eps=1e-5))
train_state = TrainState.create(apply_fn=model.apply,
params=params_model,
tx=tx)
# Optionally, create an MLP to probe latent factors
if FLAGS.probe_latent_factors:
predictor = MLP(dims=[256, 20 * 5], batch_norm=True)
tx_predictor = optax.chain(
optax.clip_by_global_norm(FLAGS.max_grad_norm),
optax.adam(FLAGS.lr, eps=1e-5),
)
z_obs = train_state.apply_fn(train_state.params,
state,
method=model.encode)
params_predictor = predictor.init(key, z_obs)
train_state_predictor = TrainState.create(apply_fn=predictor.apply,
params=params_predictor,
tx=tx_predictor)
batch = Batch(
discount=FLAGS.gamma,
gae_lambda=FLAGS.gae_lambda,
n_steps=FLAGS.n_steps + 1,
num_envs=FLAGS.num_envs,
n_actions=n_action,
state_shape=env.observation_space.shape,
latent_factors=FLAGS.add_latent_factors,
)
returns_train_buf = deque(maxlen=10)
success_train_buf = deque(maxlen=10)
factor_train_buf = deque(maxlen=10)
returns_test_buf = deque(maxlen=10)
success_test_buf = deque(maxlen=10)
sample_episode_acc = [state[0]]
for step in range(1, int(FLAGS.train_steps // FLAGS.num_envs + 1)):
# Pick action according to PPO policy and update state
action_test, _, _, _, key = select_action(
train_state,
state_test.astype(jnp.float32) / 255.0,
latent_factors,
key,
sample=True,
)
state_test, _, _, test_infos = env_test.step(action_test)
(train_state, state, latent_factors, batch, key, reward, done,
train_infos) = get_transition(train_state, env, state, latent_factors,
batch, key)
# Save episode returns and success rate
for info in train_infos:
maybe_success = info.get("success")
if maybe_success:
success_train_buf.append(maybe_success)
maybe_epinfo = info.get("returns")
if maybe_epinfo:
returns_train_buf.append(maybe_epinfo)
for info in test_infos:
maybe_success = info.get("success")
if maybe_success:
success_test_buf.append(maybe_success)
maybe_epinfo = info.get("returns")
if maybe_epinfo:
returns_test_buf.append(maybe_epinfo)
sample_episode_acc.append(state[0].copy())
if done[0]:
sample_episode_acc = []
# Train once the batch is full
if (step * FLAGS.num_envs) % (FLAGS.n_steps + 1) == 0:
data = batch.get()
metric_dict, train_state, key = update_ppo(
train_state,
data,
FLAGS.num_envs,
FLAGS.n_steps,
FLAGS.n_minibatch,
FLAGS.epoch_ppo,
FLAGS.clip_eps,
FLAGS.entropy_coeff,
FLAGS.critic_coeff,
key,
)
# Optionally, predict latent factors from observation
if FLAGS.probe_latent_factors:
X = train_state.apply_fn(
train_state.params,
jnp.stack(data[0]).reshape(-1, *data[0][0].shape[1:]),
method=model.encode,
)
y = jnp.stack(data[-1]).reshape(-1, *data[-1][0].shape[1:])
grad_fn = jax.value_and_grad(mse_loss, has_aux=True)
(total_loss, square_res), grads = grad_fn(
train_state_predictor.params,
train_state_predictor.apply_fn,
X=X,
y=y,
)
train_state_predictor = train_state_predictor.apply_gradients(
grads=grads)
per_factor_error = square_res.reshape(-1, 20,
5).mean(2).mean(0)
per_factor_error = per_factor_error.mean()
factor_train_buf.append(per_factor_error)
batch.reset()
renamed_dict = {}
for k, v in metric_dict.items():
renamed_dict["metrics/%s" % k] = v
wandb.log(renamed_dict, step=FLAGS.num_envs * step)
wandb.log(
{
"returns/eprew_train":
safe_mean([x for x in returns_train_buf]),
"returns/success_train":
safe_mean([x for x in success_train_buf]),
"returns/eprew_test":
safe_mean([x for x in returns_test_buf]),
"returns/success_test":
safe_mean([x for x in success_test_buf]),
"returns/per_factor_error":
safe_mean([x for x in factor_train_buf]),
},
step=FLAGS.num_envs * step,
)
print("[%d] Returns (train): %f Returns (test): %f" % (
FLAGS.num_envs * step,
safe_mean([x for x in returns_train_buf]),
safe_mean([x for x in returns_test_buf]),
))
# Optionally, log a GIF of the agent's trajectory during training
# if FLAGS.log_episodes:
# sample_episode_acc = np.array(
# sample_episode_acc).transpose(0, 3, 1, 2)
# # import matplotlib.pyplot as plt
# # plt.imshow(sample_episode_acc[0].transpose(1,2,0))
# # plt.show()
# wandb.log(
# {
# "video":
# wandb.Video(
# sample_episode_acc, fps=4, format="gif")
# },
# step=FLAGS.num_envs * step)
# At the end of training, save model locally and on W&B
model_dir = os.path.join(FLAGS.output_dir, run_name, "model_weights")
if not os.path.isdir(model_dir):
os.makedirs(model_dir)
print("Saving model weights")
checkpoints.save_checkpoint(
ckpt_dir=model_dir,
target=train_state,
step=step * FLAGS.num_envs,
overwrite=True,
keep=1,
)
if FLAGS.wandb_mode != "disabled":
artifact = wandb.Artifact(run_name, type="model_checkpoint")
ckpt = glob.glob(model_dir + "/checkpoint_*")[0]
artifact.add_file(ckpt)
run.log_artifact(artifact)
# Return performance metric for HP tuning
try:
run_logger = Run.get_context()
run_logger.log("test_returns",
safe_mean([x for x in returns_train_buf]))
except Exception as e:
print("Failed to import AzureML")
print(e)
return 0
if __name__ == "__main__":
app.run(main)
| [
"wandb.log",
"optax.adam",
"numpy.random.seed",
"algo.update_ppo",
"jax.random.PRNGKey",
"numpy.mean",
"numpy.random.randint",
"absl.flags.DEFINE_boolean",
"glob.glob",
"os.path.join",
"collections.deque",
"importlib.util.module_from_spec",
"algo.extract_latent_factors",
"models.MLP",
"a... | [((1169, 1230), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""env_name"""', '"""empty-easy-rgb"""', '"""Env name"""'], {}), "('env_name', 'empty-easy-rgb', 'Env name')\n", (1188, 1230), False, 'from absl import app, flags\n'), ((1231, 1278), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""seed"""', '(1)', '"""Random seed."""'], {}), "('seed', 1, 'Random seed.')\n", (1251, 1278), False, 'from absl import app, flags\n'), ((1279, 1340), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_envs"""', '(64)', '"""Num of parallel envs."""'], {}), "('num_envs', 64, 'Num of parallel envs.')\n", (1299, 1340), False, 'from absl import app, flags\n'), ((1341, 1417), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_train_levels"""', '(10)', '"""Num of training levels envs."""'], {}), "('num_train_levels', 10, 'Num of training levels envs.')\n", (1361, 1417), False, 'from absl import app, flags\n'), ((1418, 1490), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_test_levels"""', '(500)', '"""Num of test levels envs."""'], {}), "('num_test_levels', 500, 'Num of test levels envs.')\n", (1438, 1490), False, 'from absl import app, flags\n'), ((1491, 1562), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""train_steps"""', '(1000000)', '"""Number of train frames."""'], {}), "('train_steps', 1000000, 'Number of train frames.')\n", (1511, 1562), False, 'from absl import app, flags\n'), ((1565, 1631), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""framestack"""', '(1)', '"""Number of frames to stack"""'], {}), "('framestack', 1, 'Number of frames to stack')\n", (1585, 1631), False, 'from absl import app, flags\n'), ((1632, 1706), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""resolution"""', '(64)', '"""Resolution of pixel observations"""'], {}), "('resolution', 64, 'Resolution of pixel observations')\n", (1652, 1706), False, 'from absl import app, flags\n'), ((1713, 1769), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""max_grad_norm"""', '(10)', '"""Max grad norm"""'], {}), "('max_grad_norm', 10, 'Max grad norm')\n", (1731, 1769), False, 'from absl import app, flags\n'), ((1770, 1813), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""gamma"""', '(0.999)', '"""Gamma"""'], {}), "('gamma', 0.999, 'Gamma')\n", (1788, 1813), False, 'from absl import app, flags\n'), ((1814, 1864), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_steps"""', '(30)', '"""GAE n-steps"""'], {}), "('n_steps', 30, 'GAE n-steps')\n", (1834, 1864), False, 'from absl import app, flags\n'), ((1865, 1932), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""n_minibatch"""', '(4)', '"""Number of PPO minibatches"""'], {}), "('n_minibatch', 4, 'Number of PPO minibatches')\n", (1885, 1932), False, 'from absl import app, flags\n'), ((1933, 1986), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""lr"""', '(0.0001)', '"""PPO learning rate"""'], {}), "('lr', 0.0001, 'PPO learning rate')\n", (1951, 1986), False, 'from absl import app, flags\n'), ((1985, 2063), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""epoch_ppo"""', '(1)', '"""Number of PPO epochs on a single batch"""'], {}), "('epoch_ppo', 1, 'Number of PPO epochs on a single batch')\n", (2005, 2063), False, 'from absl import app, flags\n'), ((2064, 2117), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""clip_eps"""', '(0.2)', '"""Clipping range"""'], {}), "('clip_eps', 0.2, 'Clipping range')\n", (2082, 2117), False, 'from absl import app, flags\n'), ((2118, 2170), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""gae_lambda"""', '(0.95)', '"""GAE lambda"""'], {}), "('gae_lambda', 0.95, 'GAE lambda')\n", (2136, 2170), False, 'from absl import app, flags\n'), ((2171, 2242), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""entropy_coeff"""', '(0.0003)', '"""Entropy loss coefficient"""'], {}), "('entropy_coeff', 0.0003, 'Entropy loss coefficient')\n", (2189, 2242), False, 'from absl import app, flags\n'), ((2241, 2306), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""critic_coeff"""', '(0.1)', '"""Value loss coefficient"""'], {}), "('critic_coeff', 0.1, 'Value loss coefficient')\n", (2259, 2306), False, 'from absl import app, flags\n'), ((2319, 2432), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""probe_latent_factors"""', '(True)', '"""Probe latent factors from the PPO state representation?"""'], {}), "('probe_latent_factors', True,\n 'Probe latent factors from the PPO state representation?')\n", (2339, 2432), False, 'from absl import app, flags\n'), ((2444, 2548), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""add_latent_factors"""', '(False)', '"""Add latent factors to PPO state representation?"""'], {}), "('add_latent_factors', False,\n 'Add latent factors to PPO state representation?')\n", (2464, 2548), False, 'from absl import app, flags\n'), ((2566, 2640), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""log_episodes"""', '(False)', '"""Log episode samples on W&B?"""'], {}), "('log_episodes', False, 'Log episode samples on W&B?')\n", (2586, 2640), False, 'from absl import app, flags\n'), ((2651, 2722), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""checkpoint_interval"""', '(10)', '"""Checkpoint frequency"""'], {}), "('checkpoint_interval', 10, 'Checkpoint frequency')\n", (2671, 2722), False, 'from absl import app, flags\n'), ((2723, 2775), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_dir"""', '"""."""', '"""Output dir"""'], {}), "('output_dir', '.', 'Output dir')\n", (2742, 2775), False, 'from absl import app, flags\n'), ((2776, 2862), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""run_id"""', '"""jax_ppo"""', '"""Run ID. Change that to change W&B name"""'], {}), "('run_id', 'jax_ppo',\n 'Run ID. Change that to change W&B name')\n", (2795, 2862), False, 'from absl import app, flags\n'), ((2879, 2971), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""wandb_mode"""', '"""disabled"""', '"""W&B logging (disabled, online, offline)"""'], {}), "('wandb_mode', 'disabled',\n 'W&B logging (disabled, online, offline)')\n", (2898, 2971), False, 'from absl import app, flags\n'), ((2988, 3037), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""wandb_key"""', 'None', '"""W&B key"""'], {}), "('wandb_key', None, 'W&B key')\n", (3007, 3037), False, 'from absl import app, flags\n'), ((3038, 3133), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""wandb_entity"""', '"""dummy_username"""', '"""W&B entity (username or team name)"""'], {}), "('wandb_entity', 'dummy_username',\n 'W&B entity (username or team name)')\n", (3057, 3133), False, 'from absl import app, flags\n'), ((3150, 3223), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""wandb_project"""', '"""dummy_project"""', '"""W&B project name"""'], {}), "('wandb_project', 'dummy_project', 'W&B project name')\n", (3169, 3223), False, 'from absl import app, flags\n'), ((798, 820), 'importlib.reload', 'importlib.reload', (['site'], {}), '(site)\n', (814, 820), False, 'import importlib\n'), ((832, 865), 'importlib.util.find_spec', 'importlib.util.find_spec', (['"""segar"""'], {}), "('segar')\n", (856, 865), False, 'import importlib\n'), ((891, 928), 'importlib.util.module_from_spec', 'importlib.util.module_from_spec', (['spec'], {}), '(spec)\n', (922, 928), False, 'import importlib\n'), ((3382, 3402), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3396, 3402), True, 'import numpy as np\n'), ((3413, 3426), 'jax.random.PRNGKey', 'PRNGKey', (['seed'], {}), '(seed)\n', (3420, 3426), False, 'from jax.random import PRNGKey\n'), ((3853, 4045), 'wandb.init', 'wandb.init', ([], {'project': 'FLAGS.wandb_project', 'entity': 'FLAGS.wandb_entity', 'config': 'FLAGS', 'group': 'group_name', 'name': 'run_name', 'sync_tensorboard': '(False)', 'mode': 'FLAGS.wandb_mode', 'dir': 'FLAGS.output_dir'}), '(project=FLAGS.wandb_project, entity=FLAGS.wandb_entity, config=\n FLAGS, group=group_name, name=run_name, sync_tensorboard=False, mode=\n FLAGS.wandb_mode, dir=FLAGS.output_dir)\n', (3863, 4045), False, 'import wandb\n'), ((5046, 5198), 'models.TwinHeadModel', 'TwinHeadModel', ([], {'action_dim': 'n_action', 'prefix_critic': '"""vfunction"""', 'prefix_actor': '"""policy"""', 'action_scale': '(1.0)', 'add_latent_factors': 'FLAGS.add_latent_factors'}), "(action_dim=n_action, prefix_critic='vfunction', prefix_actor=\n 'policy', action_scale=1.0, add_latent_factors=FLAGS.add_latent_factors)\n", (5059, 5198), False, 'from models import MLP, TwinHeadModel\n'), ((5776, 5843), 'flax.training.train_state.TrainState.create', 'TrainState.create', ([], {'apply_fn': 'model.apply', 'params': 'params_model', 'tx': 'tx'}), '(apply_fn=model.apply, params=params_model, tx=tx)\n', (5793, 5843), False, 'from flax.training.train_state import TrainState\n'), ((6664, 6884), 'buffer.Batch', 'Batch', ([], {'discount': 'FLAGS.gamma', 'gae_lambda': 'FLAGS.gae_lambda', 'n_steps': '(FLAGS.n_steps + 1)', 'num_envs': 'FLAGS.num_envs', 'n_actions': 'n_action', 'state_shape': 'env.observation_space.shape', 'latent_factors': 'FLAGS.add_latent_factors'}), '(discount=FLAGS.gamma, gae_lambda=FLAGS.gae_lambda, n_steps=FLAGS.\n n_steps + 1, num_envs=FLAGS.num_envs, n_actions=n_action, state_shape=\n env.observation_space.shape, latent_factors=FLAGS.add_latent_factors)\n', (6669, 6884), False, 'from buffer import Batch\n'), ((6963, 6979), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (6968, 6979), False, 'from collections import deque\n'), ((7004, 7020), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (7009, 7020), False, 'from collections import deque\n'), ((7044, 7060), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (7049, 7060), False, 'from collections import deque\n'), ((7085, 7101), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (7090, 7101), False, 'from collections import deque\n'), ((7125, 7141), 'collections.deque', 'deque', ([], {'maxlen': '(10)'}), '(maxlen=10)\n', (7130, 7141), False, 'from collections import deque\n'), ((11964, 12021), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'run_name', '"""model_weights"""'], {}), "(FLAGS.output_dir, run_name, 'model_weights')\n", (11976, 12021), False, 'import os\n'), ((12128, 12252), 'flax.training.checkpoints.save_checkpoint', 'checkpoints.save_checkpoint', ([], {'ckpt_dir': 'model_dir', 'target': 'train_state', 'step': '(step * FLAGS.num_envs)', 'overwrite': '(True)', 'keep': '(1)'}), '(ckpt_dir=model_dir, target=train_state, step=\n step * FLAGS.num_envs, overwrite=True, keep=1)\n', (12155, 12252), False, 'from flax.training import checkpoints\n'), ((12860, 12873), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (12867, 12873), False, 'from absl import app, flags\n'), ((1129, 1139), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (1136, 1139), True, 'import numpy as np\n'), ((3313, 3341), 'numpy.random.randint', 'np.random.randint', (['(100000000)'], {}), '(100000000)\n', (3330, 3341), True, 'import numpy as np\n'), ((5452, 5480), 'algo.extract_latent_factors', 'extract_latent_factors', (['info'], {}), '(info)\n', (5474, 5480), False, 'from algo import extract_latent_factors, get_transition, mse_loss, select_action, update_ppo\n'), ((5657, 5703), 'optax.clip_by_global_norm', 'optax.clip_by_global_norm', (['FLAGS.max_grad_norm'], {}), '(FLAGS.max_grad_norm)\n', (5682, 5703), False, 'import optax\n'), ((5726, 5757), 'optax.adam', 'optax.adam', (['FLAGS.lr'], {'eps': '(1e-05)'}), '(FLAGS.lr, eps=1e-05)\n', (5736, 5757), False, 'import optax\n'), ((6028, 6068), 'models.MLP', 'MLP', ([], {'dims': '[256, 20 * 5]', 'batch_norm': '(True)'}), '(dims=[256, 20 * 5], batch_norm=True)\n', (6031, 6068), False, 'from models import MLP, TwinHeadModel\n'), ((6465, 6555), 'flax.training.train_state.TrainState.create', 'TrainState.create', ([], {'apply_fn': 'predictor.apply', 'params': 'params_predictor', 'tx': 'tx_predictor'}), '(apply_fn=predictor.apply, params=params_predictor, tx=\n tx_predictor)\n', (6482, 6555), False, 'from flax.training.train_state import TrainState\n'), ((7685, 7752), 'algo.get_transition', 'get_transition', (['train_state', 'env', 'state', 'latent_factors', 'batch', 'key'], {}), '(train_state, env, state, latent_factors, batch, key)\n', (7699, 7752), False, 'from algo import extract_latent_factors, get_transition, mse_loss, select_action, update_ppo\n'), ((12033, 12057), 'os.path.isdir', 'os.path.isdir', (['model_dir'], {}), '(model_dir)\n', (12046, 12057), False, 'import os\n'), ((12067, 12089), 'os.makedirs', 'os.makedirs', (['model_dir'], {}), '(model_dir)\n', (12078, 12089), False, 'import os\n'), ((12353, 12402), 'wandb.Artifact', 'wandb.Artifact', (['run_name'], {'type': '"""model_checkpoint"""'}), "(run_name, type='model_checkpoint')\n", (12367, 12402), False, 'import wandb\n'), ((12604, 12621), 'azureml.core.run.Run.get_context', 'Run.get_context', ([], {}), '()\n', (12619, 12621), False, 'from azureml.core.run import Run\n'), ((3806, 3834), 'numpy.random.randint', 'np.random.randint', (['(100000000)'], {}), '(100000000)\n', (3823, 3834), True, 'import numpy as np\n'), ((4566, 4606), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'run_name'], {}), '(FLAGS.output_dir, run_name)\n', (4578, 4606), False, 'import os\n'), ((4896, 4936), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'run_name'], {}), '(FLAGS.output_dir, run_name)\n', (4908, 4936), False, 'import os\n'), ((6117, 6163), 'optax.clip_by_global_norm', 'optax.clip_by_global_norm', (['FLAGS.max_grad_norm'], {}), '(FLAGS.max_grad_norm)\n', (6142, 6163), False, 'import optax\n'), ((6177, 6208), 'optax.adam', 'optax.adam', (['FLAGS.lr'], {'eps': '(1e-05)'}), '(FLAGS.lr, eps=1e-05)\n', (6187, 6208), False, 'import optax\n'), ((8721, 8888), 'algo.update_ppo', 'update_ppo', (['train_state', 'data', 'FLAGS.num_envs', 'FLAGS.n_steps', 'FLAGS.n_minibatch', 'FLAGS.epoch_ppo', 'FLAGS.clip_eps', 'FLAGS.entropy_coeff', 'FLAGS.critic_coeff', 'key'], {}), '(train_state, data, FLAGS.num_envs, FLAGS.n_steps, FLAGS.\n n_minibatch, FLAGS.epoch_ppo, FLAGS.clip_eps, FLAGS.entropy_coeff,\n FLAGS.critic_coeff, key)\n', (8731, 8888), False, 'from algo import extract_latent_factors, get_transition, mse_loss, select_action, update_ppo\n'), ((10286, 10337), 'wandb.log', 'wandb.log', (['renamed_dict'], {'step': '(FLAGS.num_envs * step)'}), '(renamed_dict, step=FLAGS.num_envs * step)\n', (10295, 10337), False, 'import wandb\n'), ((12418, 12456), 'glob.glob', 'glob.glob', (["(model_dir + '/checkpoint_*')"], {}), "(model_dir + '/checkpoint_*')\n", (12427, 12456), False, 'import glob\n'), ((9484, 9526), 'jax.value_and_grad', 'jax.value_and_grad', (['mse_loss'], {'has_aux': '(True)'}), '(mse_loss, has_aux=True)\n', (9502, 9526), False, 'import jax\n'), ((673, 699), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (689, 699), False, 'import os\n'), ((9401, 9420), 'jax.numpy.stack', 'jnp.stack', (['data[-1]'], {}), '(data[-1])\n', (9410, 9420), True, 'import jax.numpy as jnp\n'), ((9267, 9285), 'jax.numpy.stack', 'jnp.stack', (['data[0]'], {}), '(data[0])\n', (9276, 9285), True, 'import jax.numpy as jnp\n')] |
from rubymarshal.ruby import readruby, writeruby
import numpy as np
# Open a ruby map
data = readruby("Map032.rxdata")
# print(data.attributes["@data"].data)
# print(len(data.attributes["@data"].data))
# # DEPRECATED (use numpy instead): Set tile x=3 to 405.
# data.attributes["@data"][3, 0, 0] = 405
# Grab numpy array of map
array = data.attributes["@data"].to_array()
# Set all tiles to 420
# array[:, :, :] = 420
# Write array to map
# data.attributes["@data"].from_array(array)
print(np.unique(array))
# Save to a new file
# writeruby(data, "Map032_copy.rxdata")
| [
"rubymarshal.ruby.readruby",
"numpy.unique"
] | [((95, 120), 'rubymarshal.ruby.readruby', 'readruby', (['"""Map032.rxdata"""'], {}), "('Map032.rxdata')\n", (103, 120), False, 'from rubymarshal.ruby import readruby, writeruby\n'), ((497, 513), 'numpy.unique', 'np.unique', (['array'], {}), '(array)\n', (506, 513), True, 'import numpy as np\n')] |
import string
import time
import fire
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
# helpers
def d(tensor=None):
if tensor is None:
return 'cuda' if torch.cuda.is_available() else 'cpu'
return 'cuda' if tensor.is_cuda else 'cpu'
# preprocessing fn
# read A3M and convert letters into
# integers in the 0..20 range
def parse_a3m(filename):
table = str.maketrans(dict.fromkeys(string.ascii_lowercase))
seqs = [line.strip().translate(table) for line in open(filename, 'r') if line[0] != '>']
alphabet = np.array(list("ARNDCQEGHILKMFPSTWYV-"), dtype='|S1').view(np.uint8)
msa = np.array([list(s) for s in seqs], dtype='|S1').view(np.uint8)
# convert letters into numbers
for i in range(alphabet.shape[0]):
msa[msa == alphabet[i]] = i
# treat all unknown characters as gaps
msa[msa > 20] = 20
return msa
# 1-hot MSA to PSSM
def msa2pssm(msa1hot, w):
beff = w.sum()
f_i = (w[:, None, None] * msa1hot).sum(dim=0) / beff + 1e-9
h_i = (-f_i * torch.log(f_i)).sum(dim=1)
return torch.cat((f_i, h_i[:, None]), dim=1)
# reweight MSA based on cutoff
def reweight(msa1hot, cutoff):
id_min = msa1hot.shape[1] * cutoff
id_mtx = torch.einsum('ikl,jkl->ij', msa1hot, msa1hot)
id_mask = id_mtx > id_min
w = 1. / id_mask.float().sum(dim=-1)
return w
# shrunk covariance inversion
def fast_dca(msa1hot, weights, penalty = 4.5):
device = msa1hot.device
nr, nc, ns = msa1hot.shape
x = msa1hot.view(nr, -1)
num_points = weights.sum() - torch.sqrt(weights.mean())
mean = (x * weights[:, None]).sum(dim=0, keepdims=True) / num_points
x = (x - mean) * torch.sqrt(weights[:, None])
cov = (x.t() @ x) / num_points
cov_reg = cov + torch.eye(nc * ns).to(device) * penalty / torch.sqrt(weights.sum())
inv_cov = torch.inverse(cov_reg)
x1 = inv_cov.view(nc, ns, nc, ns)
x2 = x1.transpose(1, 2).contiguous()
features = x2.reshape(nc, nc, ns * ns)
x3 = torch.sqrt((x1[:, :-1, :, :-1] ** 2).sum(dim=(1, 3))) * (1 - torch.eye(nc).to(device))
apc = x3.sum(dim=0, keepdims=True) * x3.sum(dim=1, keepdims=True) / x3.sum()
contacts = (x3 - apc) * (1 - torch.eye(nc).to(device))
return torch.cat((features, contacts[:, :, None]), dim=2)
def preprocess(msa_file, wmin=0.8, ns=21):
a3m = torch.from_numpy(parse_a3m(msa_file)).long()
nrow, ncol = a3m.shape
msa1hot = F.one_hot(a3m, ns).float().to(d())
w = reweight(msa1hot, wmin).float().to(d())
# 1d sequence
f1d_seq = msa1hot[0, :, :20].float()
f1d_pssm = msa2pssm(msa1hot, w)
f1d = torch.cat((f1d_seq, f1d_pssm), dim=1)
f1d = f1d[None, :, :].reshape((1, ncol, 42))
# 2d sequence
f2d_dca = fast_dca(msa1hot, w) if nrow > 1 else torch.zeros((ncol, ncol, 442)).float()
f2d_dca = f2d_dca[None, :, :, :]
f2d_dca = f2d_dca.to(d())
f2d = torch.cat((
f1d[:, :, None, :].repeat(1, 1, ncol, 1),
f1d[:, None, :, :].repeat(1, ncol, 1, 1),
f2d_dca
), dim=-1)
f2d = f2d.view(1, ncol, ncol, 442 + 2*42)
return f2d.permute((0, 3, 2, 1))
# model code
def instance_norm(filters, eps=1e-6, **kwargs):
return nn.InstanceNorm2d(filters, affine=True, eps=eps, **kwargs)
def conv2d(in_chan, out_chan, kernel_size, dilation=1, **kwargs):
padding = dilation * (kernel_size - 1) // 2
return nn.Conv2d(in_chan, out_chan, kernel_size, padding=padding, dilation=dilation, **kwargs)
def elu():
return nn.ELU(inplace=True)
class trRosettaNetwork(nn.Module):
def __init__(self, filters=64, kernel=3, num_layers=61):
super().__init__()
self.filters = filters
self.kernel = kernel
self.num_layers = num_layers
self.first_block = nn.Sequential(
conv2d(442 + 2 * 42, filters, 1),
instance_norm(filters),
elu()
)
# stack of residual blocks with dilations
cycle_dilations = [1, 2, 4, 8, 16]
dilations = [cycle_dilations[i % len(cycle_dilations)] for i in range(num_layers)]
self.layers = nn.ModuleList([nn.Sequential(
conv2d(filters, filters, kernel, dilation=dilation),
instance_norm(filters),
elu(),
nn.Dropout(p=0.15),
conv2d(filters, filters, kernel, dilation=dilation),
instance_norm(filters)
) for dilation in dilations])
self.activate = elu()
# conv to anglegrams and distograms
self.to_prob_theta = nn.Sequential(conv2d(filters, 25, 1), nn.Softmax())
self.to_prob_phi = nn.Sequential(conv2d(filters, 13, 1), nn.Softmax())
self.to_distance = nn.Sequential(conv2d(filters, 37, 1), nn.Softmax())
self.to_prob_bb = nn.Sequential(conv2d(filters, 3, 1), nn.Softmax())
self.to_prob_omega = nn.Sequential(conv2d(filters, 25, 1), nn.Softmax())
def forward(self, x):
x = self.first_block(x)
for layer in self.layers:
x = self.activate(x + layer(x))
prob_theta = self.to_prob_theta(x) # anglegrams for theta
prob_phi = self.to_prob_phi(x) # anglegrams for phi
x = 0.5 * (x + x.permute((0,1,3,2))) # symmetrize
prob_distance = self.to_distance(x) # distograms
prob_bb = self.to_prob_bb(x) # beta-strand pairings (not used)
prob_omega = self.to_prob_omega(x) # anglegrams for omega
return prob_theta, prob_phi, prob_distance, prob_omega
# cli function for ensemble prediction with pre-trained network
@torch.no_grad()
def get_ensembled_predictions(input_file, output_file=None, model_dir='./'):
net = trRosettaNetwork()
i = preprocess(input_file)
if output_file is None:
input_path = Path(input_file)
output_file = f'{input_path.parents[0] / input_path.stem}.npz'
model_files = [*Path(model_dir).glob('*.pt')]
if len(model_files) == 0:
raise 'No model files can be found'
else:
print("Found %d different models that will be ensembled!" %len(model_files))
outputs = []
for model_file in model_files:
net.load_state_dict(torch.load(model_file, map_location=torch.device(d())))
net.to(d()).eval()
output = net(i)
outputs.append(output)
averaged_outputs = [torch.stack(model_output).mean(dim=0).cpu().numpy() for model_output in zip(*outputs)]
output_dict = dict(zip(['theta', 'phi', 'dist', 'omega'], averaged_outputs))
np.savez_compressed(output_file, **output_dict)
print(f'predictions for {input_file} saved to {output_file}')
if __name__ == '__main__':
fire.Fire(get_ensembled_predictions)
| [
"torch.nn.Dropout",
"torch.eye",
"torch.sqrt",
"torch.cat",
"torch.nn.InstanceNorm2d",
"numpy.savez_compressed",
"pathlib.Path",
"torch.nn.Softmax",
"torch.inverse",
"torch.no_grad",
"torch.zeros",
"torch.log",
"torch.nn.Conv2d",
"torch.einsum",
"torch.nn.ELU",
"torch.cuda.is_available... | [((5631, 5646), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5644, 5646), False, 'import torch\n'), ((1117, 1154), 'torch.cat', 'torch.cat', (['(f_i, h_i[:, None])'], {'dim': '(1)'}), '((f_i, h_i[:, None]), dim=1)\n', (1126, 1154), False, 'import torch\n'), ((1270, 1315), 'torch.einsum', 'torch.einsum', (['"""ikl,jkl->ij"""', 'msa1hot', 'msa1hot'], {}), "('ikl,jkl->ij', msa1hot, msa1hot)\n", (1282, 1315), False, 'import torch\n'), ((1889, 1911), 'torch.inverse', 'torch.inverse', (['cov_reg'], {}), '(cov_reg)\n', (1902, 1911), False, 'import torch\n'), ((2282, 2332), 'torch.cat', 'torch.cat', (['(features, contacts[:, :, None])'], {'dim': '(2)'}), '((features, contacts[:, :, None]), dim=2)\n', (2291, 2332), False, 'import torch\n'), ((2665, 2702), 'torch.cat', 'torch.cat', (['(f1d_seq, f1d_pssm)'], {'dim': '(1)'}), '((f1d_seq, f1d_pssm), dim=1)\n', (2674, 2702), False, 'import torch\n'), ((3243, 3301), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['filters'], {'affine': '(True)', 'eps': 'eps'}), '(filters, affine=True, eps=eps, **kwargs)\n', (3260, 3301), False, 'from torch import nn\n'), ((3428, 3520), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_chan', 'out_chan', 'kernel_size'], {'padding': 'padding', 'dilation': 'dilation'}), '(in_chan, out_chan, kernel_size, padding=padding, dilation=\n dilation, **kwargs)\n', (3437, 3520), False, 'from torch import nn\n'), ((3539, 3559), 'torch.nn.ELU', 'nn.ELU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3545, 3559), False, 'from torch import nn\n'), ((6559, 6606), 'numpy.savez_compressed', 'np.savez_compressed', (['output_file'], {}), '(output_file, **output_dict)\n', (6578, 6606), True, 'import numpy as np\n'), ((6705, 6741), 'fire.Fire', 'fire.Fire', (['get_ensembled_predictions'], {}), '(get_ensembled_predictions)\n', (6714, 6741), False, 'import fire\n'), ((1721, 1749), 'torch.sqrt', 'torch.sqrt', (['weights[:, None]'], {}), '(weights[:, None])\n', (1731, 1749), False, 'import torch\n'), ((5834, 5850), 'pathlib.Path', 'Path', (['input_file'], {}), '(input_file)\n', (5838, 5850), False, 'from pathlib import Path\n'), ((229, 254), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (252, 254), False, 'import torch\n'), ((4605, 4617), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (4615, 4617), False, 'from torch import nn\n'), ((4684, 4696), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (4694, 4696), False, 'from torch import nn\n'), ((4763, 4775), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (4773, 4775), False, 'from torch import nn\n'), ((4840, 4852), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (4850, 4852), False, 'from torch import nn\n'), ((4921, 4933), 'torch.nn.Softmax', 'nn.Softmax', ([], {}), '()\n', (4931, 4933), False, 'from torch import nn\n'), ((1079, 1093), 'torch.log', 'torch.log', (['f_i'], {}), '(f_i)\n', (1088, 1093), False, 'import torch\n'), ((2824, 2854), 'torch.zeros', 'torch.zeros', (['(ncol, ncol, 442)'], {}), '((ncol, ncol, 442))\n', (2835, 2854), False, 'import torch\n'), ((2105, 2118), 'torch.eye', 'torch.eye', (['nc'], {}), '(nc)\n', (2114, 2118), False, 'import torch\n'), ((2245, 2258), 'torch.eye', 'torch.eye', (['nc'], {}), '(nc)\n', (2254, 2258), False, 'import torch\n'), ((2474, 2492), 'torch.nn.functional.one_hot', 'F.one_hot', (['a3m', 'ns'], {}), '(a3m, ns)\n', (2483, 2492), True, 'import torch.nn.functional as F\n'), ((4304, 4322), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': '(0.15)'}), '(p=0.15)\n', (4314, 4322), False, 'from torch import nn\n'), ((5943, 5958), 'pathlib.Path', 'Path', (['model_dir'], {}), '(model_dir)\n', (5947, 5958), False, 'from pathlib import Path\n'), ((1806, 1824), 'torch.eye', 'torch.eye', (['(nc * ns)'], {}), '(nc * ns)\n', (1815, 1824), False, 'import torch\n'), ((6387, 6412), 'torch.stack', 'torch.stack', (['model_output'], {}), '(model_output)\n', (6398, 6412), False, 'import torch\n')] |
import cv2
import numpy as np
"""
"""
def get_hline(image, kernel_size=(2, 20), dx=5, dy=2):
up_line_list = []
down_line_list = []
up_y_list = []
down_y_list = []
shape = image.shape
area_size = kernel_size[0] * kernel_size[1]
w = shape[1]
h = shape[0]
for y in range(0, w - kernel_size[0], dy):
for x in range(0, h - kernel_size[1], dx):
dit_sum = np.sum(image[y:y+kernel_size[0], x:x+kernel_size[1]] == 255)
if (dit_sum / area_size) > 0.8 and not (x > 0.8 * w and y < 0.2 * h): # 手指部分不考虑
if y < 0.2 * h: # 只考虑接近框边缘的线
if y in up_y_list:
ids = up_y_list.index(y)
x = min(x, up_line_list[ids][0])
x_max = max(x+kernel_size[1], up_line_list[ids][2])
up_line_list[ids] = [x, y, x_max, y]
else:
up_line_list.append([x, y, x+kernel_size[1], y])
up_y_list.append(y)
elif y > 0.8 * h:
if y in down_y_list:
ids = down_y_list.index(y)
x = min(x, down_line_list[ids][0])
x_max = max(x+kernel_size[1], down_line_list[ids][2])
down_line_list[ids] = [x, y, x_max, y]
else:
down_line_list.append([x, y, x+kernel_size[1], y])
down_y_list.append(y)
return up_line_list[:2], down_line_list[:2]
def get_vline(image, kernel_size=(20, 2), dx=2, dy=5):
left_line_list = []
right_line_list = []
left_x_list = []
right_x_list = []
shape = image.shape
area_size = kernel_size[0] * kernel_size[1]
w = shape[1]
h = shape[0]
for x in range(0, w - kernel_size[1], dx):
for y in range(0, h - kernel_size[0], dy):
dit_sum = np.sum(image[y:y+kernel_size[0], x:x+kernel_size[1]]==255)
if (dit_sum / area_size) > 0.8 and not (x > 0.8 * w and y < 0.2 * h):
if x < 0.2 * w:
if x in left_x_list:
ids = left_x_list.index(x)
y = min(y, left_line_list[ids][1])
y_max = max(y + kernel_size[0], left_line_list[ids][3])
left_line_list[ids] = [x, y, x, y_max]
else:
left_line_list.append([x, y, x, y+kernel_size[0]])
left_x_list.append(x)
elif x > 0.8 * w:
if x in right_x_list:
ids = right_x_list.index(x)
y = min(y, right_line_list[ids][1])
y_max = max(y + kernel_size[0], right_line_list[ids][3])
right_line_list[ids] = [x, y, x, y_max]
else:
right_line_list.append([x, y, x, y + kernel_size[0]])
right_x_list.append(x)
return left_line_list, right_line_list
def get_card(line_lists):
up_line_list, down_line_list, left_line_list, right_line_list = line_lists
card_box = True
card_ratio = 1.58 # 信用卡长宽比
card = []
index_list = []
ratio_threshold = 0.1
error_threshold = 1
for i, lines in enumerate(line_lists):
if len(lines) == 0:
card_box = False
else:
index_list.append(i)
if card_box:
card_chose = []
for a, up in enumerate(up_line_list):
for b, down in enumerate(down_line_list):
for c, right in enumerate(right_line_list):
for d, left in enumerate(left_line_list):
ratio = (right[0] - left[0]) / (down[1] - up[1])
error = abs(card_ratio - ratio)
if error < error_threshold:
error_threshold = error
card_chose = [left[0], up[1], right[0], down[1]]
if error_threshold < ratio_threshold:
card = card_chose
return card
def get_threshold(img):
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grey = cv2.GaussianBlur(grey, (3, 3), 0)
gradX = cv2.Sobel(grey, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradY = cv2.Sobel(grey, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
ret, thresh = cv2.threshold(gradient, 150, 255, cv2.THRESH_BINARY)
return thresh
cap = cv2.VideoCapture(0)
while True:
_, img = cap.read()
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# grey = cv2.cvtColor(hsv, cv2.COLOR_BGR2GRAY)
grey = cv2.GaussianBlur(grey, (3, 3), 0)
canny = cv2.Canny(grey, 80, 150)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 1))
# kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 3))
opening = cv2.morphologyEx(grey, cv2.MORPH_OPEN, kernel)
# 用Sobel算子计算x,y方向上的梯度,之后在x方向上减去y方向上的梯度,
# 通过这个减法,我们留下具有高水平梯度和低垂直梯度的图像区域。
# https://blog.csdn.net/liqiancao/article/details/55670749 抠蜜蜂
# 梯度抠信用卡 https://blog.csdn.net/g11d111/article/details/78094687
gradX = cv2.Sobel(grey, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradY = cv2.Sobel(grey, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
ret, thresh1 = cv2.threshold(gradient, 200, 255, cv2.THRESH_BINARY)
# thresh1 = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, np.ones((1, 1), np.uint8))
gradient_o = cv2.morphologyEx(gradient, cv2.MORPH_CLOSE, kernel)
# gradient_o = cv2.morphologyEx(gradient_o, cv2.MORPH_CLOSE, kernel2)
# 用自己写的方法提取水平线
lines = get_vline(thresh1)
if len(lines) != 0:
for i in range(len(lines)):
cv2.line(img, (lines[i][0], lines[i][1]), (lines[i][2], lines[i][3]), (0, 0, 255), 3, cv2.LINE_AA)
# 提取水平线
hline = cv2.getStructuringElement(cv2.MORPH_RECT, ((int(img.shape[1] / 16)), 1), (-1, -1))
dst = cv2.morphologyEx(gradient, cv2.MORPH_OPEN, hline)
dst = cv2.bitwise_not(dst)
# 提取垂直线
vline = cv2.getStructuringElement(cv2.MORPH_RECT, (1, (int(img.shape[1] / 16))), (-1, -1))
dst = cv2.morphologyEx(gradient, cv2.MORPH_CLOSE, vline)
dst = cv2.bitwise_not(dst)
# 在这里做一些腐蚀膨胀操作提
dilated = cv2.dilate(gradient, kernel, iterations=1)
result = cv2.bitwise_and(gradient, grey)
blurred = cv2.GaussianBlur(grey, (3, 3), 0)
# cnts = cv2.findContours(opening.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]
# cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[0]
# cv2.drawContours(opening, [cnts], -1, 255, -1)
# _, thresh = cv2.threshold(gradient, 90, 255, cv2.THRESH_BINARY)
canny = cv2.Canny(gradient, 50, 200)
img_2, contours, hei = cv2.findContours(opening, mode=cv2.RETR_EXTERNAL,
method=cv2.CHAIN_APPROX_SIMPLE) # 寻找轮廓
for contour in contours:
if 100 < cv2.contourArea(contour) < 40000:
x, y, w, h = cv2.boundingRect(contour) # 找方框
cv2.rectangle(grey, (x, y), (x + w, y + h), (255, 255, 255), 3)
'''
minLineLength = 10
lines = cv2.HoughLinesP(image=grey, rho=1, theta=np.pi / 180, threshold=1000, lines=np.array([]),
minLineLength=minLineLength, maxLineGap=10)
if lines is None:
continue
a, b, c = lines.shape
for i in range(a):
cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA)
'''
cv2.imshow('1', img)
if cv2.waitKey(50) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
| [
"cv2.GaussianBlur",
"numpy.sum",
"cv2.bitwise_and",
"cv2.rectangle",
"cv2.imshow",
"cv2.line",
"cv2.contourArea",
"cv2.subtract",
"cv2.dilate",
"cv2.cvtColor",
"cv2.convertScaleAbs",
"cv2.destroyAllWindows",
"cv2.boundingRect",
"cv2.Canny",
"cv2.bitwise_not",
"cv2.waitKey",
"cv2.morp... | [((4575, 4594), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (4591, 4594), False, 'import cv2\n'), ((7800, 7823), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7821, 7823), False, 'import cv2\n'), ((4167, 4204), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (4179, 4204), False, 'import cv2\n'), ((4216, 4249), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['grey', '(3, 3)', '(0)'], {}), '(grey, (3, 3), 0)\n', (4232, 4249), False, 'import cv2\n'), ((4262, 4318), 'cv2.Sobel', 'cv2.Sobel', (['grey'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', 'dy': '(0)', 'ksize': '(-1)'}), '(grey, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)\n', (4271, 4318), False, 'import cv2\n'), ((4331, 4387), 'cv2.Sobel', 'cv2.Sobel', (['grey'], {'ddepth': 'cv2.CV_32F', 'dx': '(0)', 'dy': '(1)', 'ksize': '(-1)'}), '(grey, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)\n', (4340, 4387), False, 'import cv2\n'), ((4403, 4429), 'cv2.subtract', 'cv2.subtract', (['gradX', 'gradY'], {}), '(gradX, gradY)\n', (4415, 4429), False, 'import cv2\n'), ((4445, 4474), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', (['gradient'], {}), '(gradient)\n', (4464, 4474), False, 'import cv2\n'), ((4493, 4545), 'cv2.threshold', 'cv2.threshold', (['gradient', '(150)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gradient, 150, 255, cv2.THRESH_BINARY)\n', (4506, 4545), False, 'import cv2\n'), ((4643, 4680), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (4655, 4680), False, 'import cv2\n'), ((4792, 4825), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['grey', '(3, 3)', '(0)'], {}), '(grey, (3, 3), 0)\n', (4808, 4825), False, 'import cv2\n'), ((4838, 4862), 'cv2.Canny', 'cv2.Canny', (['grey', '(80)', '(150)'], {}), '(grey, 80, 150)\n', (4847, 4862), False, 'import cv2\n'), ((4876, 4925), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(3, 1)'], {}), '(cv2.MORPH_RECT, (3, 1))\n', (4901, 4925), False, 'import cv2\n'), ((5006, 5052), 'cv2.morphologyEx', 'cv2.morphologyEx', (['grey', 'cv2.MORPH_OPEN', 'kernel'], {}), '(grey, cv2.MORPH_OPEN, kernel)\n', (5022, 5052), False, 'import cv2\n'), ((5282, 5338), 'cv2.Sobel', 'cv2.Sobel', (['grey'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', 'dy': '(0)', 'ksize': '(-1)'}), '(grey, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)\n', (5291, 5338), False, 'import cv2\n'), ((5351, 5407), 'cv2.Sobel', 'cv2.Sobel', (['grey'], {'ddepth': 'cv2.CV_32F', 'dx': '(0)', 'dy': '(1)', 'ksize': '(-1)'}), '(grey, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)\n', (5360, 5407), False, 'import cv2\n'), ((5423, 5449), 'cv2.subtract', 'cv2.subtract', (['gradX', 'gradY'], {}), '(gradX, gradY)\n', (5435, 5449), False, 'import cv2\n'), ((5465, 5494), 'cv2.convertScaleAbs', 'cv2.convertScaleAbs', (['gradient'], {}), '(gradient)\n', (5484, 5494), False, 'import cv2\n'), ((5514, 5566), 'cv2.threshold', 'cv2.threshold', (['gradient', '(200)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gradient, 200, 255, cv2.THRESH_BINARY)\n', (5527, 5566), False, 'import cv2\n'), ((5670, 5721), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gradient', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(gradient, cv2.MORPH_CLOSE, kernel)\n', (5686, 5721), False, 'import cv2\n'), ((6136, 6185), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gradient', 'cv2.MORPH_OPEN', 'hline'], {}), '(gradient, cv2.MORPH_OPEN, hline)\n', (6152, 6185), False, 'import cv2\n'), ((6196, 6216), 'cv2.bitwise_not', 'cv2.bitwise_not', (['dst'], {}), '(dst)\n', (6211, 6216), False, 'import cv2\n'), ((6335, 6385), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gradient', 'cv2.MORPH_CLOSE', 'vline'], {}), '(gradient, cv2.MORPH_CLOSE, vline)\n', (6351, 6385), False, 'import cv2\n'), ((6396, 6416), 'cv2.bitwise_not', 'cv2.bitwise_not', (['dst'], {}), '(dst)\n', (6411, 6416), False, 'import cv2\n'), ((6452, 6494), 'cv2.dilate', 'cv2.dilate', (['gradient', 'kernel'], {'iterations': '(1)'}), '(gradient, kernel, iterations=1)\n', (6462, 6494), False, 'import cv2\n'), ((6509, 6540), 'cv2.bitwise_and', 'cv2.bitwise_and', (['gradient', 'grey'], {}), '(gradient, grey)\n', (6524, 6540), False, 'import cv2\n'), ((6556, 6589), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['grey', '(3, 3)', '(0)'], {}), '(grey, (3, 3), 0)\n', (6572, 6589), False, 'import cv2\n'), ((6878, 6906), 'cv2.Canny', 'cv2.Canny', (['gradient', '(50)', '(200)'], {}), '(gradient, 50, 200)\n', (6887, 6906), False, 'import cv2\n'), ((6935, 7021), 'cv2.findContours', 'cv2.findContours', (['opening'], {'mode': 'cv2.RETR_EXTERNAL', 'method': 'cv2.CHAIN_APPROX_SIMPLE'}), '(opening, mode=cv2.RETR_EXTERNAL, method=cv2.\n CHAIN_APPROX_SIMPLE)\n', (6951, 7021), False, 'import cv2\n'), ((7708, 7728), 'cv2.imshow', 'cv2.imshow', (['"""1"""', 'img'], {}), "('1', img)\n", (7718, 7728), False, 'import cv2\n'), ((409, 473), 'numpy.sum', 'np.sum', (['(image[y:y + kernel_size[0], x:x + kernel_size[1]] == 255)'], {}), '(image[y:y + kernel_size[0], x:x + kernel_size[1]] == 255)\n', (415, 473), True, 'import numpy as np\n'), ((1931, 1995), 'numpy.sum', 'np.sum', (['(image[y:y + kernel_size[0], x:x + kernel_size[1]] == 255)'], {}), '(image[y:y + kernel_size[0], x:x + kernel_size[1]] == 255)\n', (1937, 1995), True, 'import numpy as np\n'), ((5919, 6021), 'cv2.line', 'cv2.line', (['img', '(lines[i][0], lines[i][1])', '(lines[i][2], lines[i][3])', '(0, 0, 255)', '(3)', 'cv2.LINE_AA'], {}), '(img, (lines[i][0], lines[i][1]), (lines[i][2], lines[i][3]), (0, 0,\n 255), 3, cv2.LINE_AA)\n', (5927, 6021), False, 'import cv2\n'), ((7115, 7139), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (7130, 7139), False, 'import cv2\n'), ((7174, 7199), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (7190, 7199), False, 'import cv2\n'), ((7219, 7282), 'cv2.rectangle', 'cv2.rectangle', (['grey', '(x, y)', '(x + w, y + h)', '(255, 255, 255)', '(3)'], {}), '(grey, (x, y), (x + w, y + h), (255, 255, 255), 3)\n', (7232, 7282), False, 'import cv2\n'), ((7736, 7751), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (7747, 7751), False, 'import cv2\n')] |
import numpy as np
def rev_lookup(dd, val):
key = next(key for key, value in dd.items() if value == val)
return key
def bin(s):
return str(s) if s<=1 else bin(s>>1) + str(s&1)
def test_bit(int_type, offset):
mask = 1 << offset
return ((int_type & mask) >> offset)
def gen_mask(bit_pos):
if not hasattr(bit_pos, '__iter__'):
bit_pos = [bit_pos]
mask = sum([(1 << b) for b in bit_pos])
return mask
def twos_comp(val, bits):
""" compute the 2's complement of int value val
handle an array (list or numpy)
"""
# converts a val into 2's comp
def twos_comp_scalar(val, bits):
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
if hasattr(val, "__len__"):
tmp_arr = np.array([])
for v in val:
tmp_arr = np.append(tmp_arr, twos_comp_scalar(v,bits))
return tmp_arr
else:
return twos_comp_scalar(val, bits)
def two2dec(num): # input the num we want to convert
''' Converts a 2's comp number to its dec. equivalent // two2dec fx
found from stack overflow: https://stackoverflow.com/questions/1604464/twos-complement-in-python '''
num = str(num) # temporarily change to a string so we can use indexing to find the weight of each bit's value on the whole
if num[0] == '1': # if we have a negative number
return -1 * (int(''.join('1' if x == '0' else '0' for x in num), 2) + 1) # find the equvalent of the negative number by evaluating the weight of each bit and concatenate w/negative 1
else:
return int(num, 2) # if pos, just turn into an int
| [
"numpy.array"
] | [((920, 932), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (928, 932), True, 'import numpy as np\n')] |
import numpy as np
import torch
import torch.nn as nn
import utils.network_utils as nu
import utils.tracking_utils as tu
from model import dla_up
from lib.model.roi_layers import ROIAlign, ROIPool
class Model(nn.Module):
def __init__(self, arch_name, roi_name, down_ratio, roi_kernel):
super(Model, self).__init__()
self.base = dla_up.__dict__[arch_name](
pretrained_base='imagenet', down_ratio=down_ratio)
num_channel = self.base.channels[int(np.log2(down_ratio))]
# We use roialign with kernel size = 7 in our experiments
assert ('align' in roi_name or 'pool' in roi_name)
assert (roi_kernel == 7)
if 'align' in roi_name:
print('Using RoIAlign')
self.roi_pool = ROIAlign(
(roi_kernel, roi_kernel),
1.0 / down_ratio,
0)
elif 'pool' in roi_name:
print('Using RoIPool')
self.roi_pool = ROIPool(
(roi_kernel, roi_kernel),
1.0 / down_ratio)
self.dim = nn.Sequential(
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, 3, kernel_size=1,
stride=1, padding=0, bias=True)) # 3 dim
self.rot = nn.Sequential(
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, 8, kernel_size=1,
stride=1, padding=0, bias=True)) # 1 + 1 + 2
self.dep = nn.Sequential(
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, 1, kernel_size=1,
stride=1, padding=0, bias=True),
nn.Sigmoid())
self.cen = nn.Sequential(
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, num_channel,
kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(num_channel),
nn.ReLU(inplace=True),
nn.Conv2d(num_channel, 2, kernel_size=1,
stride=1, padding=0, bias=True))
nu.init_module(self.base)
nu.init_module(self.dim)
nu.init_module(self.rot)
nu.init_module(self.dep)
nu.init_module(self.cen)
def forward(self, image, box_info, device, phase):
# for 3D
rois = box_info['rois_pd']
# Get box info
num_imgs = image.size(0)
n_gt_box = box_info['n_box'].cpu().numpy()
n_pd_box = torch.sum(rois[:, :, 4] > 0, dim=1).cpu().numpy()
# Check number of boxes
num_rois = int(np.sum(n_gt_box)) # get n_gt_box of this frame
if (n_gt_box == 0).any(): print("GT is empty")
num_det = int(np.sum(n_pd_box)) # get n_pd_box of this frame
if (n_pd_box == 0).any(): print("Prediction is empty")
# Make sure if n_gt_box and n_pd_box are the same during training
if phase in ['train', 'val']:
assert (n_pd_box == n_gt_box).any(), \
"Number of pred. bbox ({}) not equals to gt ({})".format(
n_pd_box, n_gt_box)
# Init
image = image.to(device)
boxes = torch.zeros([num_det, 5]).to(device)
cen_pd = torch.zeros([num_det, 2]).to(device)
rois_pd = torch.zeros([num_det, 5]).to(device)
rois_gt = torch.zeros([num_rois, 5]).to(device)
dim_gt = torch.zeros([num_rois, 3]).to(device)
dep_gt = torch.zeros([num_rois]).to(device)
cen_gt = torch.zeros([num_rois, 2]).to(device)
loc_gt = torch.zeros([num_rois, 3]).to(device)
tid_gt = torch.zeros([num_rois]).to(device)
if phase == 'train':
bin_gt = torch.zeros([num_rois, 2]).to(device).long()
res_gt = torch.zeros([num_rois, 2]).to(device)
else:
alpha_gt = torch.zeros([num_rois]).to(device)
ignore = torch.zeros([num_rois]).to(device)
# Feed valid info to gpu
sum_gt = 0
sum_det = 0
for idx in range(num_imgs):
if n_pd_box[idx] > 0:
# indicate which image to get feature
boxes[sum_det:sum_det + n_pd_box[idx], 0] = idx
boxes[sum_det:sum_det + n_pd_box[idx], 1:5] = rois[idx,
:n_pd_box[idx],
0:4] # box
cen_pd[sum_det:sum_det + n_pd_box[idx]] = box_info['cen_pd'][idx,
:n_pd_box[idx]]
rois_pd[sum_det:sum_det + n_pd_box[idx]] = rois[idx,
:n_pd_box[idx],
:] # for tracking
if n_gt_box[idx] > 0:
dim_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['dim_gt'][idx,
:n_gt_box[idx]]
dep_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['depth_gt'][
idx, :n_gt_box[idx]]
cen_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['cen_gt'][idx,
:n_gt_box[idx]]
loc_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['loc_gt'][idx,
:n_gt_box[idx]]
tid_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['tid_gt'][idx,
:n_gt_box[idx]]
rois_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info['rois_gt'][
idx, :n_gt_box[idx]]
if phase == 'train':
bin_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info[
'bin_cls_gt'][
idx, :n_gt_box[idx]]
res_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info[
'bin_res_gt'][
idx, :n_gt_box[idx]]
else:
alpha_gt[sum_gt:sum_gt + n_gt_box[idx]] = box_info[
'alpha_gt'][
idx,
:n_gt_box[idx]]
ignore[sum_gt:sum_gt + n_gt_box[idx]] = box_info['ignore'][
idx, :n_gt_box[idx]]
sum_gt += n_gt_box[idx]
sum_det += n_pd_box[idx]
# Inference of 3D estimation
img_feat = self.base(image)
if num_det > 0:
pooled_feat = self.roi_pool(img_feat, boxes)
dim = self.dim(pooled_feat).flatten(start_dim=1)
cen = self.cen(pooled_feat).flatten(start_dim=1) + cen_pd
orient_ = self.rot(pooled_feat).flatten(start_dim=1)
# bin 1
divider1 = torch.sqrt(orient_[:, 2:3] ** 2 + orient_[:, 3:4] ** 2)
b1sin = orient_[:, 2:3] / divider1
b1cos = orient_[:, 3:4] / divider1
# bin 2
divider2 = torch.sqrt(orient_[:, 6:7] ** 2 + orient_[:, 7:8] ** 2)
b2sin = orient_[:, 6:7] / divider2
b2cos = orient_[:, 7:8] / divider2
rot = torch.cat(
[orient_[:, 0:2], b1sin, b1cos, orient_[:, 4:6], b2sin, b2cos],
1)
dep = nu.get_pred_depth(self.dep(pooled_feat).flatten())
loc_pd = []
sum_l = 0
for l_idx in range(num_imgs):
if n_pd_box[l_idx] == 0:
continue
cam_calib = box_info['cam_calib'][l_idx]
position = box_info['cam_loc'][l_idx]
rotation = box_info['cam_rot'][l_idx]
loc_pd.append(tu.point3dcoord_torch(
cen[sum_l:sum_l + n_pd_box[l_idx]],
dep[sum_l:sum_l + n_pd_box[l_idx]],
cam_calib,
position,
rotation))
sum_l += n_pd_box[l_idx]
loc_pd = torch.cat(loc_pd)
else:
pooled_feat = image.new_zeros(1, 128, 7, 7)
dim = image.new_ones(1, 3)
rot = image.new_ones(1, 8)
dep = image.new_zeros(1)
cen = image.new_zeros(1, 2)
loc_pd = image.new_zeros(1, 3)
# Pack infos
box_output = {'rois': rois_pd,
'feat': pooled_feat.detach(),
'dim': dim.detach(),
'rot': rot.detach(),
'dep': dep.detach(),
'cen': cen.detach(),
'loc': loc_pd.detach(),
}
if phase == 'train':
loss_dim = nu.compute_dim_loss(dim, dim_gt).unsqueeze(0)
loss_rot = nu.compute_rot_loss(rot, bin_gt, res_gt).unsqueeze(0)
loss_dep = nu.compute_dep_loss(dep, dep_gt).unsqueeze(0)
loss_dep += nu.compute_dep_loss(loc_pd, loc_gt).unsqueeze(0)
loss_cen = nu.compute_cen_loss(cen, cen_gt).unsqueeze(0)
targets = (loss_dim, loss_rot, loss_dep, loss_cen)
else:
targets = (rois_gt,
dim_gt,
alpha_gt,
dep_gt,
cen_gt,
loc_gt,
ignore,
tid_gt)
return box_output, targets
| [
"utils.network_utils.compute_cen_loss",
"lib.model.roi_layers.ROIPool",
"torch.nn.ReLU",
"lib.model.roi_layers.ROIAlign",
"numpy.sum",
"utils.network_utils.compute_dep_loss",
"torch.sqrt",
"numpy.log2",
"utils.tracking_utils.point3dcoord_torch",
"torch.nn.Conv2d",
"torch.cat",
"torch.nn.Sigmoi... | [((4125, 4150), 'utils.network_utils.init_module', 'nu.init_module', (['self.base'], {}), '(self.base)\n', (4139, 4150), True, 'import utils.network_utils as nu\n'), ((4159, 4183), 'utils.network_utils.init_module', 'nu.init_module', (['self.dim'], {}), '(self.dim)\n', (4173, 4183), True, 'import utils.network_utils as nu\n'), ((4192, 4216), 'utils.network_utils.init_module', 'nu.init_module', (['self.rot'], {}), '(self.rot)\n', (4206, 4216), True, 'import utils.network_utils as nu\n'), ((4225, 4249), 'utils.network_utils.init_module', 'nu.init_module', (['self.dep'], {}), '(self.dep)\n', (4239, 4249), True, 'import utils.network_utils as nu\n'), ((4258, 4282), 'utils.network_utils.init_module', 'nu.init_module', (['self.cen'], {}), '(self.cen)\n', (4272, 4282), True, 'import utils.network_utils as nu\n'), ((767, 822), 'lib.model.roi_layers.ROIAlign', 'ROIAlign', (['(roi_kernel, roi_kernel)', '(1.0 / down_ratio)', '(0)'], {}), '((roi_kernel, roi_kernel), 1.0 / down_ratio, 0)\n', (775, 822), False, 'from lib.model.roi_layers import ROIAlign, ROIPool\n'), ((1203, 1290), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (1212, 1290), True, 'import torch.nn as nn\n'), ((1322, 1349), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (1336, 1349), True, 'import torch.nn as nn\n'), ((1363, 1384), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1370, 1384), True, 'import torch.nn as nn\n'), ((1398, 1485), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (1407, 1485), True, 'import torch.nn as nn\n'), ((1517, 1544), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (1531, 1544), True, 'import torch.nn as nn\n'), ((1558, 1579), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1565, 1579), True, 'import torch.nn as nn\n'), ((1593, 1680), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (1602, 1680), True, 'import torch.nn as nn\n'), ((1712, 1739), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (1726, 1739), True, 'import torch.nn as nn\n'), ((1753, 1774), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1760, 1774), True, 'import torch.nn as nn\n'), ((1788, 1860), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', '(3)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(num_channel, 3, kernel_size=1, stride=1, padding=0, bias=True)\n', (1797, 1860), True, 'import torch.nn as nn\n'), ((1940, 2027), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (1949, 2027), True, 'import torch.nn as nn\n'), ((2059, 2086), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (2073, 2086), True, 'import torch.nn as nn\n'), ((2100, 2121), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2107, 2121), True, 'import torch.nn as nn\n'), ((2135, 2222), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (2144, 2222), True, 'import torch.nn as nn\n'), ((2254, 2281), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (2268, 2281), True, 'import torch.nn as nn\n'), ((2295, 2316), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2302, 2316), True, 'import torch.nn as nn\n'), ((2330, 2417), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (2339, 2417), True, 'import torch.nn as nn\n'), ((2449, 2476), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (2463, 2476), True, 'import torch.nn as nn\n'), ((2490, 2511), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2497, 2511), True, 'import torch.nn as nn\n'), ((2525, 2597), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', '(8)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(num_channel, 8, kernel_size=1, stride=1, padding=0, bias=True)\n', (2534, 2597), True, 'import torch.nn as nn\n'), ((2681, 2768), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (2690, 2768), True, 'import torch.nn as nn\n'), ((2800, 2827), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (2814, 2827), True, 'import torch.nn as nn\n'), ((2841, 2862), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2848, 2862), True, 'import torch.nn as nn\n'), ((2876, 2963), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (2885, 2963), True, 'import torch.nn as nn\n'), ((2995, 3022), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (3009, 3022), True, 'import torch.nn as nn\n'), ((3036, 3057), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3043, 3057), True, 'import torch.nn as nn\n'), ((3071, 3158), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (3080, 3158), True, 'import torch.nn as nn\n'), ((3190, 3217), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (3204, 3217), True, 'import torch.nn as nn\n'), ((3231, 3252), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3238, 3252), True, 'import torch.nn as nn\n'), ((3266, 3338), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', '(1)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(num_channel, 1, kernel_size=1, stride=1, padding=0, bias=True)\n', (3275, 3338), True, 'import torch.nn as nn\n'), ((3374, 3386), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (3384, 3386), True, 'import torch.nn as nn\n'), ((3435, 3522), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (3444, 3522), True, 'import torch.nn as nn\n'), ((3554, 3581), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (3568, 3581), True, 'import torch.nn as nn\n'), ((3595, 3616), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3602, 3616), True, 'import torch.nn as nn\n'), ((3630, 3717), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (3639, 3717), True, 'import torch.nn as nn\n'), ((3749, 3776), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (3763, 3776), True, 'import torch.nn as nn\n'), ((3790, 3811), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3797, 3811), True, 'import torch.nn as nn\n'), ((3825, 3912), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', 'num_channel'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(num_channel, num_channel, kernel_size=3, stride=1, padding=0,\n bias=False)\n', (3834, 3912), True, 'import torch.nn as nn\n'), ((3944, 3971), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['num_channel'], {}), '(num_channel)\n', (3958, 3971), True, 'import torch.nn as nn\n'), ((3985, 4006), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3992, 4006), True, 'import torch.nn as nn\n'), ((4020, 4092), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_channel', '(2)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(num_channel, 2, kernel_size=1, stride=1, padding=0, bias=True)\n', (4029, 4092), True, 'import torch.nn as nn\n'), ((4625, 4641), 'numpy.sum', 'np.sum', (['n_gt_box'], {}), '(n_gt_box)\n', (4631, 4641), True, 'import numpy as np\n'), ((4750, 4766), 'numpy.sum', 'np.sum', (['n_pd_box'], {}), '(n_pd_box)\n', (4756, 4766), True, 'import numpy as np\n'), ((9216, 9271), 'torch.sqrt', 'torch.sqrt', (['(orient_[:, 2:3] ** 2 + orient_[:, 3:4] ** 2)'], {}), '(orient_[:, 2:3] ** 2 + orient_[:, 3:4] ** 2)\n', (9226, 9271), False, 'import torch\n'), ((9410, 9465), 'torch.sqrt', 'torch.sqrt', (['(orient_[:, 6:7] ** 2 + orient_[:, 7:8] ** 2)'], {}), '(orient_[:, 6:7] ** 2 + orient_[:, 7:8] ** 2)\n', (9420, 9465), False, 'import torch\n'), ((9579, 9655), 'torch.cat', 'torch.cat', (['[orient_[:, 0:2], b1sin, b1cos, orient_[:, 4:6], b2sin, b2cos]', '(1)'], {}), '([orient_[:, 0:2], b1sin, b1cos, orient_[:, 4:6], b2sin, b2cos], 1)\n', (9588, 9655), False, 'import torch\n'), ((10402, 10419), 'torch.cat', 'torch.cat', (['loc_pd'], {}), '(loc_pd)\n', (10411, 10419), False, 'import torch\n'), ((489, 508), 'numpy.log2', 'np.log2', (['down_ratio'], {}), '(down_ratio)\n', (496, 508), True, 'import numpy as np\n'), ((1030, 1081), 'lib.model.roi_layers.ROIPool', 'ROIPool', (['(roi_kernel, roi_kernel)', '(1.0 / down_ratio)'], {}), '((roi_kernel, roi_kernel), 1.0 / down_ratio)\n', (1037, 1081), False, 'from lib.model.roi_layers import ROIAlign, ROIPool\n'), ((5205, 5230), 'torch.zeros', 'torch.zeros', (['[num_det, 5]'], {}), '([num_det, 5])\n', (5216, 5230), False, 'import torch\n'), ((5259, 5284), 'torch.zeros', 'torch.zeros', (['[num_det, 2]'], {}), '([num_det, 2])\n', (5270, 5284), False, 'import torch\n'), ((5314, 5339), 'torch.zeros', 'torch.zeros', (['[num_det, 5]'], {}), '([num_det, 5])\n', (5325, 5339), False, 'import torch\n'), ((5369, 5395), 'torch.zeros', 'torch.zeros', (['[num_rois, 5]'], {}), '([num_rois, 5])\n', (5380, 5395), False, 'import torch\n'), ((5424, 5450), 'torch.zeros', 'torch.zeros', (['[num_rois, 3]'], {}), '([num_rois, 3])\n', (5435, 5450), False, 'import torch\n'), ((5479, 5502), 'torch.zeros', 'torch.zeros', (['[num_rois]'], {}), '([num_rois])\n', (5490, 5502), False, 'import torch\n'), ((5531, 5557), 'torch.zeros', 'torch.zeros', (['[num_rois, 2]'], {}), '([num_rois, 2])\n', (5542, 5557), False, 'import torch\n'), ((5586, 5612), 'torch.zeros', 'torch.zeros', (['[num_rois, 3]'], {}), '([num_rois, 3])\n', (5597, 5612), False, 'import torch\n'), ((5641, 5664), 'torch.zeros', 'torch.zeros', (['[num_rois]'], {}), '([num_rois])\n', (5652, 5664), False, 'import torch\n'), ((5792, 5818), 'torch.zeros', 'torch.zeros', (['[num_rois, 2]'], {}), '([num_rois, 2])\n', (5803, 5818), False, 'import torch\n'), ((5867, 5890), 'torch.zeros', 'torch.zeros', (['[num_rois]'], {}), '([num_rois])\n', (5878, 5890), False, 'import torch\n'), ((5923, 5946), 'torch.zeros', 'torch.zeros', (['[num_rois]'], {}), '([num_rois])\n', (5934, 5946), False, 'import torch\n'), ((10112, 10240), 'utils.tracking_utils.point3dcoord_torch', 'tu.point3dcoord_torch', (['cen[sum_l:sum_l + n_pd_box[l_idx]]', 'dep[sum_l:sum_l + n_pd_box[l_idx]]', 'cam_calib', 'position', 'rotation'], {}), '(cen[sum_l:sum_l + n_pd_box[l_idx]], dep[sum_l:sum_l +\n n_pd_box[l_idx]], cam_calib, position, rotation)\n', (10133, 10240), True, 'import utils.tracking_utils as tu\n'), ((11096, 11128), 'utils.network_utils.compute_dim_loss', 'nu.compute_dim_loss', (['dim', 'dim_gt'], {}), '(dim, dim_gt)\n', (11115, 11128), True, 'import utils.network_utils as nu\n'), ((11165, 11205), 'utils.network_utils.compute_rot_loss', 'nu.compute_rot_loss', (['rot', 'bin_gt', 'res_gt'], {}), '(rot, bin_gt, res_gt)\n', (11184, 11205), True, 'import utils.network_utils as nu\n'), ((11242, 11274), 'utils.network_utils.compute_dep_loss', 'nu.compute_dep_loss', (['dep', 'dep_gt'], {}), '(dep, dep_gt)\n', (11261, 11274), True, 'import utils.network_utils as nu\n'), ((11312, 11347), 'utils.network_utils.compute_dep_loss', 'nu.compute_dep_loss', (['loc_pd', 'loc_gt'], {}), '(loc_pd, loc_gt)\n', (11331, 11347), True, 'import utils.network_utils as nu\n'), ((11384, 11416), 'utils.network_utils.compute_cen_loss', 'nu.compute_cen_loss', (['cen', 'cen_gt'], {}), '(cen, cen_gt)\n', (11403, 11416), True, 'import utils.network_utils as nu\n'), ((4519, 4554), 'torch.sum', 'torch.sum', (['(rois[:, :, 4] > 0)'], {'dim': '(1)'}), '(rois[:, :, 4] > 0, dim=1)\n', (4528, 4554), False, 'import torch\n'), ((5726, 5752), 'torch.zeros', 'torch.zeros', (['[num_rois, 2]'], {}), '([num_rois, 2])\n', (5737, 5752), False, 'import torch\n')] |
"""
======================================
Compute LCMV beamformer on evoked data
======================================
Compute LCMV beamformer solutions on evoked dataset for three different choices
of source orientation and stores the solutions in stc files for visualisation.
"""
# Author: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import numpy as np
import mne
from mne.datasets import sample
from mne.io import Raw
from mne.beamformer import lcmv
print(__doc__)
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
###############################################################################
# Get epochs
event_id, tmin, tmax = 1, -0.2, 0.5
# Setup for reading the raw data
raw = Raw(raw_fname)
raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels
events = mne.read_events(event_fname)
# Set up pick list: EEG + MEG - bad channels (modify to your needs)
left_temporal_channels = mne.read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
exclude='bads', selection=left_temporal_channels)
# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
picks=picks, baseline=(None, 0), preload=True,
reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()
forward = mne.read_forward_solution(fname_fwd, surf_ori=True)
# Read regularized noise covariance and compute regularized data covariance
noise_cov = mne.read_cov(fname_cov)
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
method='shrunk')
plt.close('all')
pick_oris = [None, 'normal', 'max-power']
names = ['free', 'normal', 'max-power']
descriptions = ['Free orientation', 'Normal orientation', 'Max-power '
'orientation']
colors = ['b', 'k', 'r']
for pick_ori, name, desc, color in zip(pick_oris, names, descriptions, colors):
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01,
pick_ori=pick_ori)
# View activation time-series
label = mne.read_label(fname_label)
stc_label = stc.in_label(label)
plt.plot(1e3 * stc_label.times, np.mean(stc_label.data, axis=0), color,
hold=True, label=desc)
plt.xlabel('Time (ms)')
plt.ylabel('LCMV value')
plt.ylim(-0.8, 2.2)
plt.title('LCMV in %s' % label_name)
plt.legend()
plt.show()
| [
"matplotlib.pyplot.title",
"mne.beamformer.lcmv",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"mne.pick_types",
"mne.io.Raw",
"mne.read_selection",
"matplotlib.pyplot.close",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"mne.compute_covariance",
"numpy.mean",
"mne.read_for... | [((521, 539), 'mne.datasets.sample.data_path', 'sample.data_path', ([], {}), '()\n', (537, 539), False, 'from mne.datasets import sample\n'), ((1068, 1082), 'mne.io.Raw', 'Raw', (['raw_fname'], {}), '(raw_fname)\n', (1071, 1082), False, 'from mne.io import Raw\n'), ((1154, 1182), 'mne.read_events', 'mne.read_events', (['event_fname'], {}), '(event_fname)\n', (1169, 1182), False, 'import mne\n'), ((1277, 1312), 'mne.read_selection', 'mne.read_selection', (['"""Left-temporal"""'], {}), "('Left-temporal')\n", (1295, 1312), False, 'import mne\n'), ((1321, 1442), 'mne.pick_types', 'mne.pick_types', (['raw.info'], {'meg': '(True)', 'eeg': '(False)', 'stim': '(True)', 'eog': '(True)', 'exclude': '"""bads"""', 'selection': 'left_temporal_channels'}), "(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude=\n 'bads', selection=left_temporal_channels)\n", (1335, 1442), False, 'import mne\n'), ((1717, 1768), 'mne.read_forward_solution', 'mne.read_forward_solution', (['fname_fwd'], {'surf_ori': '(True)'}), '(fname_fwd, surf_ori=True)\n', (1742, 1768), False, 'import mne\n'), ((1858, 1881), 'mne.read_cov', 'mne.read_cov', (['fname_cov'], {}), '(fname_cov)\n', (1870, 1881), False, 'import mne\n'), ((1893, 1962), 'mne.compute_covariance', 'mne.compute_covariance', (['epochs'], {'tmin': '(0.04)', 'tmax': '(0.15)', 'method': '"""shrunk"""'}), "(epochs, tmin=0.04, tmax=0.15, method='shrunk')\n", (1915, 1962), False, 'import mne\n'), ((1998, 2014), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2007, 2014), True, 'import matplotlib.pyplot as plt\n'), ((2627, 2650), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (ms)"""'], {}), "('Time (ms)')\n", (2637, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2675), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""LCMV value"""'], {}), "('LCMV value')\n", (2661, 2675), True, 'import matplotlib.pyplot as plt\n'), ((2676, 2695), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-0.8)', '(2.2)'], {}), '(-0.8, 2.2)\n', (2684, 2695), True, 'import matplotlib.pyplot as plt\n'), ((2696, 2732), 'matplotlib.pyplot.title', 'plt.title', (["('LCMV in %s' % label_name)"], {}), "('LCMV in %s' % label_name)\n", (2705, 2732), True, 'import matplotlib.pyplot as plt\n'), ((2733, 2745), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2743, 2745), True, 'import matplotlib.pyplot as plt\n'), ((2746, 2756), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2754, 2756), True, 'import matplotlib.pyplot as plt\n'), ((2316, 2387), 'mne.beamformer.lcmv', 'lcmv', (['evoked', 'forward', 'noise_cov', 'data_cov'], {'reg': '(0.01)', 'pick_ori': 'pick_ori'}), '(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori=pick_ori)\n', (2320, 2387), False, 'from mne.beamformer import lcmv\n'), ((2450, 2477), 'mne.read_label', 'mne.read_label', (['fname_label'], {}), '(fname_label)\n', (2464, 2477), False, 'import mne\n'), ((2550, 2581), 'numpy.mean', 'np.mean', (['stc_label.data'], {'axis': '(0)'}), '(stc_label.data, axis=0)\n', (2557, 2581), True, 'import numpy as np\n')] |
#%%
"""
Kalman Filter
Implement single shot estimations for multi sensor localization
April 19, 2018
"""
import numpy as np
import time
import matplotlib.pyplot as plt
import os
#mpl.use('TkAgg')
# import matplotlib.animation as manimation
from numpy import unravel_index
# import mpld3
# mpld3.enable_notebook()
# Add custom classes
from GAutils import objects as ob
from GAutils import proc_est as pr
from GAutils import PCRLB as pcrlb
from GAutils import ml_est as mle
from GAutils import gradient_methods as gm
from GAutils import perf_eval as prfe
from GAutils import config as cfg # Sim parameters
from GAutils import graph_primitives as grpr
from GAutils import est_algo as ea
from GAutils import mcft as mcft
# import importlib
# importlib.reload(cfg)
# def main():
def run_snapshot(scene, sensors, snr, cfgp, seed =int.from_bytes(os.urandom(4), byteorder='little')):
tf_list = np.array([sensor.mcs.tf for sensor in sensors]) # All sensors frame times equal
tfa_list = np.array([sensor.mcs.get_tfa() for sensor in sensors]) # Adjust so that samples vary to keep frame time const.
beat = np.zeros(tfa_list.shape, dtype='complex128')
dt = (1-int(cfgp['static_snapshot'])) * tf_list[0] # make 0 to simulate one shot over Nf>1
signal_mag =1 # TODO: Set this carefully
for sensor in sensors:
sensor.meas_std = 10 **(-snr/20)*signal_mag
gardat = [ob.gardEst() for sensor in enumerate(sensors)]
targets_list = []
for tno, target in enumerate(scene):
target_current, AbsPos = pr.ProcDyms(target, dt, tfa_list)# this adds noise to target state
for sensorID, sensor in enumerate(sensors):
random_number = np.random.rand()
if random_number>cfgp['pmiss']: #Miss target otherwise
pure_beat = pr.get_beat(sensor, target, AbsPos[sensorID])
beat[sensorID, :, :] += pure_beat
garda = pr.get_gard_true(sensor, target)
gardat[sensorID].r=np.append(gardat[sensorID].r,garda.r)
gardat[sensorID].d=np.append(gardat[sensorID].d,garda.d)
gardat[sensorID].g=np.append(gardat[sensorID].g,garda.g)
if not cfgp['static_snapshot']: targets_list.append(target_current)
np.random.seed(seed) # To randomize over parallel runs
for sensorID, sensor in enumerate(sensors):
beat[sensorID, :, :] = pr.add_cnoise(beat[sensorID, :, :], sensor.meas_std) # Add noise
# print('Target{}: x={},y={},vx={},vy={}'.format(tno, target_current.x, target_current.y,target_current.vx,target_current.vy))
runtime = np.zeros(8)
t=time.time()
if cfgp['estalgo'] == 0:
garda_sel = ea.meth2(np.copy(beat), sensors, cfgp['Nsel'], [1,1])
elif cfgp['estalgo'] == 1:
garda_sel = ea.meth2(np.copy(beat), sensors, cfgp['Nsel'], cfgp['osps'], cfgp['n_pfa'])
elif cfgp['estalgo'] == 2:
garda_sel = ea.nomp(np.copy(beat), sensors, cfgp['Nsel'], cfgp['osps'], cfgp['n_Rc'], cfgp['n_pfa'])
runtime[0] = time.time() - t
rd_error = prfe.compute_rd_error(garda_sel, gardat)
rde_pack = prfe.compute_rde_targetwise(garda_sel, gardat, sensors)
#%% Computer phantoms, tracks and llr's
rd_wt = cfgp['rd_wt'] # Range doppler relative weighting for likelihood, NLLS (Selection purposes)
#%% Graph Algo
t=time.time()
G1,runtime[4] = grpr.make_graph(garda_sel, sensors, 0) # was cfgp['rob'] # Total edges before geom. pruning
# runtime[4] = sum([grpr.get_Ntracks(nd) for nd in G1[0]])# All tracks in graph
runtime[1] = time.time() - t
runtime[5] = sum([len(nd.lkf) for g in G1 for nd in g]) # No of edges, get V from glen
# runtime[5],_ = grpr.get_BruteComplexity(G1)
if cfgp['mode']=='MCF':
min_gsigs, glen, runtime[6:8] = mcft.get_mcfsigs(garda_sel, sensors, cfgp)
elif cfgp['mode']=='mcf_all':
min_gsigs, glen, runtime[6:8] = mcft.get_mcfsigs_all(garda_sel, sensors, cfgp)
elif cfgp['mode']=='SAESL':
min_gsigs, glen, runtime[6:8] = mle.iterative_prune_pht(garda_sel, sensors, cfgp, sum(len(g.r) for g in garda_sel)//2)
else:
if cfg.scene_plots:
[graph_sigs, Ngsig]=grpr.enum_graph_sigs(G1, sensors)
pr.plot_graph(G1, graph_sigs, sensors, rd_wt, 12, plt)
min_gsigs, glen, runtime[6:8] = grpr.get_minpaths(G1, sensors, cfgp['mode'], cfgp)
runtime[2] = time.time() - t # Total time (Make graph+traverse graph)
t = time.time()
for sig in min_gsigs:
[dob, nlls_var] = gm.gauss_newton(sig, sensors, sig.state_end.mean , cfgp['gn_steps'], rd_wt)#lm_refine, gauss_newton, huber
sig.state_end.mean = dob
runtime[3] = time.time() - t # Time to Refine
gr_centers = []
for gtr in min_gsigs:
dob = gtr.state_end.mean
gr_centers.append(ob.PointTarget(dob[0], dob[1], dob[2], dob[3]))
# print ('{} detected {} targets in {}s.'.format(cfg.mode, len(min_gsigs),sum(runtime)))
if cfg.scene_plots:
plt.figure(13)
for gtr in min_gsigs:
dob = gtr.state_end.mean
plt.quiver(dob[0], dob[1], dob[2], dob[3],color='b', headwidth = 4)
pr.plot_scene(plt, scene, sensors, 13, 'Graph pruning detects {} targets'.format(len(min_gsigs)))
#%% PLot likelihood maps
if 0:
[xgrid, ygrid, llr_map] = mle.create_llrmap([-9,9,180], [1,12,110], [-5,5,2], [-5,5,2], sensors, garda_sel) # Position
cmap = plt.get_cmap('PiYG')
plt.figure(16)
im1 = plt.pcolormesh(xgrid, ygrid, llr_map, cmap=cmap)
plt.colorbar(im1)
pr.plot_scene(plt, scene, sensors, 3, 'Likelihood Map (Brute Force, Only using r)')
#%% Compute error measures
ospa_error1, pv_error = prfe.compute_ospa(scene, gr_centers, sensors, gardat)
if 1:# RD CRB
[cr,cd, rList, dList]=pcrlb.get_FIMrv(sensors, scene)
else:# RD ZZB
cr = np.zeros((len(scene),len(sensors)))
cd = np.zeros((len(scene),len(sensors)))
for s, sensor in enumerate(sensors):
for t, target in enumerate(scene):
[cr[t,s], cd[t,s]] = pcrlb.ZZBrv(sensor, target)
# # Convert to position, Vel bounds
# crb_conv = pcrlb.CRBconverter()
# [_,_,_,_,crbp, crbv] = crb_conv.get_CRBposvel_from_rd(cr, cd, sensors, scene)
# [St_er[f,:], KF_er[f,:], Auto_er[f,:], sig_indx, sig_indx_auto, track_var, y_est_sig, vy_est_sig] = am.compute_asc_error(signatures, scene, Nsig, sensors) # compute error metrics
results={'RDerror':np.array(rd_error),
'RDpack':rde_pack,
'OSPAerror1': ospa_error1,
'runtime': runtime,
'loc': gr_centers,
'crbrd':np.stack([cr.T**2, cd.T**2],axis=-1),
# 'crbpv': np.stack([np.array(crbp)**2, np.array(crbv)**2],axis=-1),
'crbr':cr,
'crbd':cd,
'glen': glen,
'garda': garda_sel,
'PVerror': pv_error}
results['next_scene'] = targets_list
return results
| [
"numpy.random.seed",
"GAutils.graph_primitives.make_graph",
"matplotlib.pyplot.quiver",
"matplotlib.pyplot.figure",
"GAutils.mcft.get_mcfsigs_all",
"GAutils.proc_est.get_gard_true",
"GAutils.proc_est.plot_scene",
"numpy.copy",
"GAutils.PCRLB.ZZBrv",
"matplotlib.pyplot.colorbar",
"GAutils.graph_p... | [((893, 940), 'numpy.array', 'np.array', (['[sensor.mcs.tf for sensor in sensors]'], {}), '([sensor.mcs.tf for sensor in sensors])\n', (901, 940), True, 'import numpy as np\n'), ((1113, 1157), 'numpy.zeros', 'np.zeros', (['tfa_list.shape'], {'dtype': '"""complex128"""'}), "(tfa_list.shape, dtype='complex128')\n", (1121, 1157), True, 'import numpy as np\n'), ((2236, 2256), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2250, 2256), True, 'import numpy as np\n'), ((2583, 2594), 'numpy.zeros', 'np.zeros', (['(8)'], {}), '(8)\n', (2591, 2594), True, 'import numpy as np\n'), ((2601, 2612), 'time.time', 'time.time', ([], {}), '()\n', (2610, 2612), False, 'import time\n'), ((3036, 3076), 'GAutils.perf_eval.compute_rd_error', 'prfe.compute_rd_error', (['garda_sel', 'gardat'], {}), '(garda_sel, gardat)\n', (3057, 3076), True, 'from GAutils import perf_eval as prfe\n'), ((3092, 3147), 'GAutils.perf_eval.compute_rde_targetwise', 'prfe.compute_rde_targetwise', (['garda_sel', 'gardat', 'sensors'], {}), '(garda_sel, gardat, sensors)\n', (3119, 3147), True, 'from GAutils import perf_eval as prfe\n'), ((3326, 3337), 'time.time', 'time.time', ([], {}), '()\n', (3335, 3337), False, 'import time\n'), ((3358, 3396), 'GAutils.graph_primitives.make_graph', 'grpr.make_graph', (['garda_sel', 'sensors', '(0)'], {}), '(garda_sel, sensors, 0)\n', (3373, 3396), True, 'from GAutils import graph_primitives as grpr\n'), ((4448, 4459), 'time.time', 'time.time', ([], {}), '()\n', (4457, 4459), False, 'import time\n'), ((5709, 5762), 'GAutils.perf_eval.compute_ospa', 'prfe.compute_ospa', (['scene', 'gr_centers', 'sensors', 'gardat'], {}), '(scene, gr_centers, sensors, gardat)\n', (5726, 5762), True, 'from GAutils import perf_eval as prfe\n'), ((842, 855), 'os.urandom', 'os.urandom', (['(4)'], {}), '(4)\n', (852, 855), False, 'import os\n'), ((1397, 1409), 'GAutils.objects.gardEst', 'ob.gardEst', ([], {}), '()\n', (1407, 1409), True, 'from GAutils import objects as ob\n'), ((1541, 1574), 'GAutils.proc_est.ProcDyms', 'pr.ProcDyms', (['target', 'dt', 'tfa_list'], {}), '(target, dt, tfa_list)\n', (1552, 1574), True, 'from GAutils import proc_est as pr\n'), ((2370, 2422), 'GAutils.proc_est.add_cnoise', 'pr.add_cnoise', (['beat[sensorID, :, :]', 'sensor.meas_std'], {}), '(beat[sensorID, :, :], sensor.meas_std)\n', (2383, 2422), True, 'from GAutils import proc_est as pr\n'), ((3000, 3011), 'time.time', 'time.time', ([], {}), '()\n', (3009, 3011), False, 'import time\n'), ((3554, 3565), 'time.time', 'time.time', ([], {}), '()\n', (3563, 3565), False, 'import time\n'), ((3780, 3822), 'GAutils.mcft.get_mcfsigs', 'mcft.get_mcfsigs', (['garda_sel', 'sensors', 'cfgp'], {}), '(garda_sel, sensors, cfgp)\n', (3796, 3822), True, 'from GAutils import mcft as mcft\n'), ((4382, 4393), 'time.time', 'time.time', ([], {}), '()\n', (4391, 4393), False, 'import time\n'), ((4512, 4586), 'GAutils.gradient_methods.gauss_newton', 'gm.gauss_newton', (['sig', 'sensors', 'sig.state_end.mean', "cfgp['gn_steps']", 'rd_wt'], {}), "(sig, sensors, sig.state_end.mean, cfgp['gn_steps'], rd_wt)\n", (4527, 4586), True, 'from GAutils import gradient_methods as gm\n'), ((4669, 4680), 'time.time', 'time.time', ([], {}), '()\n', (4678, 4680), False, 'import time\n'), ((4980, 4994), 'matplotlib.pyplot.figure', 'plt.figure', (['(13)'], {}), '(13)\n', (4990, 4994), True, 'import matplotlib.pyplot as plt\n'), ((5321, 5414), 'GAutils.ml_est.create_llrmap', 'mle.create_llrmap', (['[-9, 9, 180]', '[1, 12, 110]', '[-5, 5, 2]', '[-5, 5, 2]', 'sensors', 'garda_sel'], {}), '([-9, 9, 180], [1, 12, 110], [-5, 5, 2], [-5, 5, 2],\n sensors, garda_sel)\n', (5338, 5414), True, 'from GAutils import ml_est as mle\n'), ((5429, 5449), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""PiYG"""'], {}), "('PiYG')\n", (5441, 5449), True, 'import matplotlib.pyplot as plt\n'), ((5458, 5472), 'matplotlib.pyplot.figure', 'plt.figure', (['(16)'], {}), '(16)\n', (5468, 5472), True, 'import matplotlib.pyplot as plt\n'), ((5487, 5535), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['xgrid', 'ygrid', 'llr_map'], {'cmap': 'cmap'}), '(xgrid, ygrid, llr_map, cmap=cmap)\n', (5501, 5535), True, 'import matplotlib.pyplot as plt\n'), ((5544, 5561), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im1'], {}), '(im1)\n', (5556, 5561), True, 'import matplotlib.pyplot as plt\n'), ((5570, 5657), 'GAutils.proc_est.plot_scene', 'pr.plot_scene', (['plt', 'scene', 'sensors', '(3)', '"""Likelihood Map (Brute Force, Only using r)"""'], {}), "(plt, scene, sensors, 3,\n 'Likelihood Map (Brute Force, Only using r)')\n", (5583, 5657), True, 'from GAutils import proc_est as pr\n'), ((5811, 5842), 'GAutils.PCRLB.get_FIMrv', 'pcrlb.get_FIMrv', (['sensors', 'scene'], {}), '(sensors, scene)\n', (5826, 5842), True, 'from GAutils import PCRLB as pcrlb\n'), ((6481, 6499), 'numpy.array', 'np.array', (['rd_error'], {}), '(rd_error)\n', (6489, 6499), True, 'import numpy as np\n'), ((6623, 6664), 'numpy.stack', 'np.stack', (['[cr.T ** 2, cd.T ** 2]'], {'axis': '(-1)'}), '([cr.T ** 2, cd.T ** 2], axis=-1)\n', (6631, 6664), True, 'import numpy as np\n'), ((1688, 1704), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1702, 1704), True, 'import numpy as np\n'), ((1916, 1948), 'GAutils.proc_est.get_gard_true', 'pr.get_gard_true', (['sensor', 'target'], {}), '(sensor, target)\n', (1932, 1948), True, 'from GAutils import proc_est as pr\n'), ((1980, 2018), 'numpy.append', 'np.append', (['gardat[sensorID].r', 'garda.r'], {}), '(gardat[sensorID].r, garda.r)\n', (1989, 2018), True, 'import numpy as np\n'), ((2049, 2087), 'numpy.append', 'np.append', (['gardat[sensorID].d', 'garda.d'], {}), '(gardat[sensorID].d, garda.d)\n', (2058, 2087), True, 'import numpy as np\n'), ((2118, 2156), 'numpy.append', 'np.append', (['gardat[sensorID].g', 'garda.g'], {}), '(gardat[sensorID].g, garda.g)\n', (2127, 2156), True, 'import numpy as np\n'), ((2671, 2684), 'numpy.copy', 'np.copy', (['beat'], {}), '(beat)\n', (2678, 2684), True, 'import numpy as np\n'), ((3897, 3943), 'GAutils.mcft.get_mcfsigs_all', 'mcft.get_mcfsigs_all', (['garda_sel', 'sensors', 'cfgp'], {}), '(garda_sel, sensors, cfgp)\n', (3917, 3943), True, 'from GAutils import mcft as mcft\n'), ((4808, 4854), 'GAutils.objects.PointTarget', 'ob.PointTarget', (['dob[0]', 'dob[1]', 'dob[2]', 'dob[3]'], {}), '(dob[0], dob[1], dob[2], dob[3])\n', (4822, 4854), True, 'from GAutils import objects as ob\n'), ((5074, 5140), 'matplotlib.pyplot.quiver', 'plt.quiver', (['dob[0]', 'dob[1]', 'dob[2]', 'dob[3]'], {'color': '"""b"""', 'headwidth': '(4)'}), "(dob[0], dob[1], dob[2], dob[3], color='b', headwidth=4)\n", (5084, 5140), True, 'import matplotlib.pyplot as plt\n'), ((1800, 1845), 'GAutils.proc_est.get_beat', 'pr.get_beat', (['sensor', 'target', 'AbsPos[sensorID]'], {}), '(sensor, target, AbsPos[sensorID])\n', (1811, 1845), True, 'from GAutils import proc_est as pr\n'), ((2776, 2789), 'numpy.copy', 'np.copy', (['beat'], {}), '(beat)\n', (2783, 2789), True, 'import numpy as np\n'), ((4314, 4364), 'GAutils.graph_primitives.get_minpaths', 'grpr.get_minpaths', (['G1', 'sensors', "cfgp['mode']", 'cfgp'], {}), "(G1, sensors, cfgp['mode'], cfgp)\n", (4331, 4364), True, 'from GAutils import graph_primitives as grpr\n'), ((6088, 6115), 'GAutils.PCRLB.ZZBrv', 'pcrlb.ZZBrv', (['sensor', 'target'], {}), '(sensor, target)\n', (6099, 6115), True, 'from GAutils import PCRLB as pcrlb\n'), ((2902, 2915), 'numpy.copy', 'np.copy', (['beat'], {}), '(beat)\n', (2909, 2915), True, 'import numpy as np\n'), ((4173, 4206), 'GAutils.graph_primitives.enum_graph_sigs', 'grpr.enum_graph_sigs', (['G1', 'sensors'], {}), '(G1, sensors)\n', (4193, 4206), True, 'from GAutils import graph_primitives as grpr\n'), ((4219, 4273), 'GAutils.proc_est.plot_graph', 'pr.plot_graph', (['G1', 'graph_sigs', 'sensors', 'rd_wt', '(12)', 'plt'], {}), '(G1, graph_sigs, sensors, rd_wt, 12, plt)\n', (4232, 4273), True, 'from GAutils import proc_est as pr\n')] |
# python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""A simple implementation of Bootstrapped DQN with prior networks.
References:
1. "Deep Exploration via Bootstrapped DQN" (Osband et al., 2016)
2. "Deep Exploration via Randomized Value Functions" (Osband et al., 2017)
3. "Randomized Prior Functions for Deep RL" (Osband et al, 2018)
Links:
1. https://arxiv.org/abs/1602.04621
2. https://arxiv.org/abs/1703.07608
3. https://arxiv.org/abs/1806.03335
Notes:
- This agent is implemented with TensorFlow 2 and Sonnet 2. For installation
instructions for these libraries, see the README.md in the parent folder.
- This implementation is potentially inefficient, as it does not parallelise
computation across the ensemble for simplicity and readability.
"""
from typing import Any, Callable, NamedTuple, Sequence
from bsuite.baselines import base
from bsuite.baselines.utils import replay
import dm_env
from dm_env import specs
import haiku as hk
import jax
from jax import lax
from jax.experimental import optix
import jax.numpy as jnp
import numpy as np
import rlax
class TrainingState(NamedTuple):
params: hk.Params
target_params: hk.Params
opt_state: Any
step: int
class BootstrappedDqn(base.Agent):
"""Bootstrapped DQN with additive prior functions."""
def __init__(
self,
obs_spec: specs.Array,
action_spec: specs.DiscreteArray,
network: hk.Transformed,
num_ensemble: int,
batch_size: int,
discount: float,
replay_capacity: int,
min_replay_size: int,
sgd_period: int,
target_update_period: int,
optimizer: optix.InitUpdate,
mask_prob: float,
noise_scale: float,
epsilon_fn: Callable[[int], float] = lambda _: 0.,
seed: int = 1,
):
"""Bootstrapped DQN with randomized prior functions."""
# Define loss function, including bootstrap mask `m_t` & reward noise `z_t`.
def loss(params: hk.Params,
target_params: hk.Params,
transitions: Sequence[jnp.ndarray]) -> jnp.ndarray:
"""Q-learning loss with added reward noise + half-in bootstrap."""
o_tm1, a_tm1, r_t, d_t, o_t, m_t, z_t = transitions
q_tm1 = network.apply(params, o_tm1)
q_t = network.apply(target_params, o_t)
r_t += noise_scale * z_t
batch_q_learning = jax.vmap(rlax.q_learning)
td_error = batch_q_learning(q_tm1, a_tm1, r_t, discount * d_t, q_t)
return jnp.mean(m_t * td_error**2)
# Define update function for each member of ensemble..
@jax.jit
def sgd_step(
state: TrainingState,
transitions: Sequence[jnp.ndarray]) -> TrainingState:
"""Does a step of SGD for the whole ensemble over `transitions`."""
gradients = jax.grad(loss)(state.params, state.target_params, transitions)
updates, new_opt_state = optimizer.update(gradients, state.opt_state)
new_params = optix.apply_updates(state.params, updates)
return TrainingState(
params=new_params,
target_params=state.target_params,
opt_state=new_opt_state,
step=state.step + 1)
# Initialize parameters and optimizer state for an ensemble of Q-networks.
rng = hk.PRNGSequence(seed)
dummy_obs = np.zeros((1, *obs_spec.shape), jnp.float32)
initial_params = [
network.init(next(rng), dummy_obs) for _ in range(num_ensemble)
]
initial_target_params = [
network.init(next(rng), dummy_obs) for _ in range(num_ensemble)
]
initial_opt_state = [optimizer.init(p) for p in initial_params]
# Internalize state.
self._ensemble = [
TrainingState(p, tp, o, step=0) for p, tp, o in zip(
initial_params, initial_target_params, initial_opt_state)
]
self._forward = jax.jit(network.apply)
self._sgd_step = sgd_step
self._num_ensemble = num_ensemble
self._optimizer = optimizer
self._replay = replay.Replay(capacity=replay_capacity)
# Agent hyperparameters.
self._num_actions = action_spec.num_values
self._batch_size = batch_size
self._sgd_period = sgd_period
self._target_update_period = target_update_period
self._min_replay_size = min_replay_size
self._epsilon_fn = epsilon_fn
self._mask_prob = mask_prob
# Agent state.
self._active_head = self._ensemble[0]
self._total_steps = 0
def select_action(self, timestep: dm_env.TimeStep) -> base.Action:
"""Select values via Thompson sampling, then use epsilon-greedy policy."""
self._total_steps += 1
if np.random.rand() < self._epsilon_fn(self._total_steps):
return np.random.randint(self._num_actions)
# Greedy policy, breaking ties uniformly at random.
batched_obs = timestep.observation[None, ...]
q_values = self._forward(self._active_head.params, batched_obs)
action = np.random.choice(np.flatnonzero(q_values == q_values.max()))
return int(action)
def update(
self,
timestep: dm_env.TimeStep,
action: base.Action,
new_timestep: dm_env.TimeStep,
):
"""Update the agent: add transition to replay and periodically do SGD."""
# Thompson sampling: every episode pick a new Q-network as the policy.
if new_timestep.last():
k = np.random.randint(self._num_ensemble)
self._active_head = self._ensemble[k]
# Generate bootstrapping mask & reward noise.
mask = np.random.binomial(1, self._mask_prob, self._num_ensemble)
noise = np.random.randn(self._num_ensemble)
# Make transition and add to replay.
transition = [
timestep.observation,
action,
np.float32(new_timestep.reward),
np.float32(new_timestep.discount),
new_timestep.observation,
mask,
noise,
]
self._replay.add(transition)
if self._replay.size < self._min_replay_size:
return
# Periodically sample from replay and do SGD for the whole ensemble.
if self._total_steps % self._sgd_period == 0:
transitions = self._replay.sample(self._batch_size)
o_tm1, a_tm1, r_t, d_t, o_t, m_t, z_t = transitions
for k, state in enumerate(self._ensemble):
transitions = [o_tm1, a_tm1, r_t, d_t, o_t, m_t[:, k], z_t[:, k]]
self._ensemble[k] = self._sgd_step(state, transitions)
# Periodically update target parameters.
for k, state in enumerate(self._ensemble):
if state.step % self._target_update_period == 0:
self._ensemble[k] = state._replace(target_params=state.params)
def default_agent(obs_spec: specs.Array,
action_spec: specs.DiscreteArray,
seed: int = 0) -> BootstrappedDqn:
"""Initialize a Bootstrapped DQN agent with default parameters."""
# Define network.
prior_scale = 3.
hidden_sizes = [50, 50]
def network(inputs: jnp.ndarray) -> jnp.ndarray:
"""Simple Q-network with randomized prior function."""
net = hk.nets.MLP([*hidden_sizes, action_spec.num_values])
prior_net = hk.nets.MLP([*hidden_sizes, action_spec.num_values])
x = hk.Flatten()(inputs)
return net(x) + prior_scale * lax.stop_gradient(prior_net(x))
optimizer = optix.adam(learning_rate=1e-3)
return BootstrappedDqn(
obs_spec=obs_spec,
action_spec=action_spec,
network=hk.transform(network),
batch_size=128,
discount=.99,
num_ensemble=20,
replay_capacity=10000,
min_replay_size=128,
sgd_period=1,
target_update_period=4,
optimizer=optimizer,
mask_prob=0.5,
noise_scale=0.,
epsilon_fn=lambda _: 0.,
seed=seed,
)
| [
"jax.experimental.optix.apply_updates",
"jax.experimental.optix.adam",
"numpy.random.binomial",
"jax.jit",
"jax.vmap",
"numpy.random.randn",
"bsuite.baselines.utils.replay.Replay",
"numpy.float32",
"numpy.zeros",
"haiku.Flatten",
"haiku.PRNGSequence",
"haiku.transform",
"numpy.random.randint... | [((7794, 7825), 'jax.experimental.optix.adam', 'optix.adam', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (7804, 7825), False, 'from jax.experimental import optix\n'), ((3879, 3900), 'haiku.PRNGSequence', 'hk.PRNGSequence', (['seed'], {}), '(seed)\n', (3894, 3900), True, 'import haiku as hk\n'), ((3917, 3960), 'numpy.zeros', 'np.zeros', (['(1, *obs_spec.shape)', 'jnp.float32'], {}), '((1, *obs_spec.shape), jnp.float32)\n', (3925, 3960), True, 'import numpy as np\n'), ((4444, 4466), 'jax.jit', 'jax.jit', (['network.apply'], {}), '(network.apply)\n', (4451, 4466), False, 'import jax\n'), ((4586, 4625), 'bsuite.baselines.utils.replay.Replay', 'replay.Replay', ([], {'capacity': 'replay_capacity'}), '(capacity=replay_capacity)\n', (4599, 4625), False, 'from bsuite.baselines.utils import replay\n'), ((6049, 6107), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'self._mask_prob', 'self._num_ensemble'], {}), '(1, self._mask_prob, self._num_ensemble)\n', (6067, 6107), True, 'import numpy as np\n'), ((6120, 6155), 'numpy.random.randn', 'np.random.randn', (['self._num_ensemble'], {}), '(self._num_ensemble)\n', (6135, 6155), True, 'import numpy as np\n'), ((7562, 7614), 'haiku.nets.MLP', 'hk.nets.MLP', (['[*hidden_sizes, action_spec.num_values]'], {}), '([*hidden_sizes, action_spec.num_values])\n', (7573, 7614), True, 'import haiku as hk\n'), ((7631, 7683), 'haiku.nets.MLP', 'hk.nets.MLP', (['[*hidden_sizes, action_spec.num_values]'], {}), '([*hidden_sizes, action_spec.num_values])\n', (7642, 7683), True, 'import haiku as hk\n'), ((3002, 3027), 'jax.vmap', 'jax.vmap', (['rlax.q_learning'], {}), '(rlax.q_learning)\n', (3010, 3027), False, 'import jax\n'), ((3115, 3144), 'jax.numpy.mean', 'jnp.mean', (['(m_t * td_error ** 2)'], {}), '(m_t * td_error ** 2)\n', (3123, 3144), True, 'import jax.numpy as jnp\n'), ((3577, 3619), 'jax.experimental.optix.apply_updates', 'optix.apply_updates', (['state.params', 'updates'], {}), '(state.params, updates)\n', (3596, 3619), False, 'from jax.experimental import optix\n'), ((5206, 5222), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5220, 5222), True, 'import numpy as np\n'), ((5275, 5311), 'numpy.random.randint', 'np.random.randint', (['self._num_actions'], {}), '(self._num_actions)\n', (5292, 5311), True, 'import numpy as np\n'), ((5905, 5942), 'numpy.random.randint', 'np.random.randint', (['self._num_ensemble'], {}), '(self._num_ensemble)\n', (5922, 5942), True, 'import numpy as np\n'), ((6271, 6302), 'numpy.float32', 'np.float32', (['new_timestep.reward'], {}), '(new_timestep.reward)\n', (6281, 6302), True, 'import numpy as np\n'), ((6312, 6345), 'numpy.float32', 'np.float32', (['new_timestep.discount'], {}), '(new_timestep.discount)\n', (6322, 6345), True, 'import numpy as np\n'), ((7692, 7704), 'haiku.Flatten', 'hk.Flatten', ([], {}), '()\n', (7702, 7704), True, 'import haiku as hk\n'), ((7921, 7942), 'haiku.transform', 'hk.transform', (['network'], {}), '(network)\n', (7933, 7942), True, 'import haiku as hk\n'), ((3419, 3433), 'jax.grad', 'jax.grad', (['loss'], {}), '(loss)\n', (3427, 3433), False, 'import jax\n')] |
import os
import cv2
import glob
import numpy as np
from utils import make_folder
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
#list1
#label_list = ['skin', 'neck', 'hat', 'eye_g', 'hair', 'ear_r', 'neck_l', 'cloth', 'l_eye', 'r_eye', 'l_brow', 'r_brow', 'nose', 'l_ear', 'r_ear', 'mouth', 'u_lip', 'l_lip']
#list2
#label_list = ['skin', 'nose', 'eye_g', 'l_eye', 'r_eye', 'l_brow', 'r_brow', 'l_ear', 'r_ear', 'mouth', 'u_lip', 'l_lip', 'hair', 'hat', 'ear_r', 'neck_l', 'neck', 'cloth']
# label_list = ['skin', 'nose', 'eye_g', 'l_eye', 'r_eye', 'l_brow', 'r_brow', 'l_ear', 'r_ear', 'mouth', 'u_lip', 'l_lip', 'hair', 'hat', 'neck', 'cloth']
label_list = ['skin','r_brow','l_brow','r_eye','l_eye','nose','u_lip','mouth','l_lip','hair'] # face left and right define does not match in celebA and helen
# gt_label_names = pred_label_names = ['bg','face','lb','rb','le','re','nose','ulip','imouth','llip','hair',]
folder_base = '../../../data/datasets/celebA'
folder_anno = 'CelebAMask-HQ-mask-anno'
folder_save = 'CelebAMask-HQ-mask-face-seg'
img_num = 30000
# folder_raw = 'CelebA-HQ-img'
raw_save = 'CelebA-HA-img-resize'
make_folder(os.path.join(folder_base,folder_save))
# make_folder(raw_save)
image_id_list = open(os.path.join(folder_base,'train_face_seg.lst'), 'w')
for k in range(img_num):
folder_num = k // 2000
im_base = np.zeros((512, 512))
for idx, label in enumerate(label_list):
filename = os.path.join(folder_base,folder_anno, str(folder_num), str(k).rjust(5, '0') + '_' + label + '.png')
if (os.path.exists(filename)):
#print (label, idx+1)
im = cv2.imread(filename)
im = im[:, :, 0]
im_base[im != 0] = (idx + 1)
filename_save = os.path.join(folder_base,folder_save, str(k) + '.png')
print (filename_save)
cv2.imwrite(filename_save, im_base)
raw_name = os.path.join(folder_base,raw_save, str(k) + '.jpg')
if (os.path.exists(raw_name)):
# image=cv2.imread(raw_name)
# image=cv2.resize(image,(512,512),interpolation=cv2.INTER_CUBIC)
# rawname_save = os.path.join(raw_save,str(k)+'.jpg')
# cv2.imwrite(rawname_save,image)
# Read ids of images whose annotations have been converted from specified file
# image_id_list = open(os.path.join('.', 'train.lst'),'w')
list_str = raw_save +'/'+ str(k)+ '.jpg'+'\t'+ folder_save+ '/' + str(k) +'.png'+'\t' + folder_save + '/' + str(k) +'.png'
image_id_list.write(list_str+ '\n')
# # Show image with segmentations
# fig, ax = plt.subplots(figsize=[10,10])
#
# fplot = ax.imshow(plt.imread(raw_save+'/'+'1.jpg'))
# splot = ax.imshow(plt.imread(folder_save+'/'+'1.png'), alpha=0.7) # X*Y*10 imshow auto expand 0-10 to specific color
# # ax.imshow(segs[i%l+2],alpha=0.7)
# plt.show() | [
"cv2.imwrite",
"numpy.zeros",
"os.path.exists",
"cv2.imread",
"os.path.join"
] | [((1184, 1222), 'os.path.join', 'os.path.join', (['folder_base', 'folder_save'], {}), '(folder_base, folder_save)\n', (1196, 1222), False, 'import os\n'), ((1270, 1317), 'os.path.join', 'os.path.join', (['folder_base', '"""train_face_seg.lst"""'], {}), "(folder_base, 'train_face_seg.lst')\n", (1282, 1317), False, 'import os\n'), ((1384, 1404), 'numpy.zeros', 'np.zeros', (['(512, 512)'], {}), '((512, 512))\n', (1392, 1404), True, 'import numpy as np\n'), ((1795, 1830), 'cv2.imwrite', 'cv2.imwrite', (['filename_save', 'im_base'], {}), '(filename_save, im_base)\n', (1806, 1830), False, 'import cv2\n'), ((1901, 1925), 'os.path.exists', 'os.path.exists', (['raw_name'], {}), '(raw_name)\n', (1915, 1925), False, 'import os\n'), ((1566, 1590), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (1580, 1590), False, 'import os\n'), ((1626, 1646), 'cv2.imread', 'cv2.imread', (['filename'], {}), '(filename)\n', (1636, 1646), False, 'import cv2\n')] |
import numpy as np
from bokeh.plotting import *
x = np.linspace(0, 4*np.pi, 200)
y = np.sin(x)
output_file("line.html", title="line.py example")
p = figure(title="simple line example")
p.line(x,y, color="#2222aa", line_with=2)
show(p)
| [
"numpy.sin",
"numpy.linspace"
] | [((54, 84), 'numpy.linspace', 'np.linspace', (['(0)', '(4 * np.pi)', '(200)'], {}), '(0, 4 * np.pi, 200)\n', (65, 84), True, 'import numpy as np\n'), ((87, 96), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (93, 96), True, 'import numpy as np\n')] |
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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.
# ============================================================================
"""Structural Time Series utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import distributions as tfd
from tensorflow_probability.python.distributions.mvn_linear_operator import MultivariateNormalLinearOperator
from tensorflow_probability.python.internal import distribution_util as dist_util
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.sts.internal import missing_values_util
tfl = tf.linalg
def broadcast_batch_shape(distributions):
"""Get broadcast batch shape from distributions, statically if possible."""
# Static case
batch_shape = distributions[0].batch_shape
for distribution in distributions:
batch_shape = tf.broadcast_static_shape(batch_shape,
distribution.batch_shape)
if batch_shape.is_fully_defined():
return batch_shape.as_list()
# Fallback on dynamic.
batch_shape = distributions[0].batch_shape_tensor()
for distribution in distributions:
batch_shape = tf.broadcast_dynamic_shape(batch_shape,
distribution.batch_shape_tensor())
return tf.convert_to_tensor(value=batch_shape)
def pad_batch_dimension_for_multiple_chains(
observed_time_series, model, chain_batch_shape):
""""Expand the observed time series with extra batch dimension(s)."""
# Running with multiple chains introduces an extra batch dimension. In
# general we also need to pad the observed time series with a matching batch
# dimension.
#
# For example, suppose our model has batch shape [3, 4] and
# the observed time series has shape `concat([[5], [3, 4], [100])`,
# corresponding to `sample_shape`, `batch_shape`, and `num_timesteps`
# respectively. The model will produce distributions with batch shape
# `concat([chain_batch_shape, [3, 4]])`, so we pad `observed_time_series` to
# have matching shape `[5, 1, 3, 4, 100]`, where the added `1` dimension
# between the sample and batch shapes will broadcast to `chain_batch_shape`.
[ # Extract mask and guarantee `event_ndims=2`.
observed_time_series,
is_missing
] = canonicalize_observed_time_series_with_mask(observed_time_series)
event_ndims = 2 # event_shape = [num_timesteps, observation_size=1]
model_batch_ndims = (
model.batch_shape.ndims if model.batch_shape.ndims is not None else
tf.shape(model.batch_shape_tensor())[0])
# Compute ndims from chain_batch_shape.
chain_batch_shape = tf.convert_to_tensor(
value=chain_batch_shape, name='chain_batch_shape', dtype=tf.int32)
if not chain_batch_shape.shape.is_fully_defined():
raise ValueError('Batch shape must have static rank. (given: {})'.format(
chain_batch_shape))
if chain_batch_shape.shape.ndims == 0: # expand int `k` to `[k]`.
chain_batch_shape = chain_batch_shape[tf.newaxis]
chain_batch_ndims = tf.compat.dimension_value(chain_batch_shape.shape[0])
def do_padding(observed_time_series_tensor):
current_sample_shape = tf.shape(
observed_time_series_tensor)[:-(model_batch_ndims + event_ndims)]
current_batch_and_event_shape = tf.shape(
observed_time_series_tensor)[-(model_batch_ndims + event_ndims):]
return tf.reshape(
tensor=observed_time_series_tensor,
shape=tf.concat([
current_sample_shape,
tf.ones([chain_batch_ndims], dtype=tf.int32),
current_batch_and_event_shape], axis=0))
# Padding is only needed if the observed time series has sample shape.
observed_time_series = ps.cond(ps.rank(observed_time_series) >
model_batch_ndims + event_ndims,
lambda: do_padding(observed_time_series),
lambda: observed_time_series)
if is_missing is not None:
is_missing = ps.cond(ps.rank(is_missing) >
model_batch_ndims + event_ndims,
lambda: do_padding(is_missing),
lambda: is_missing)
return missing_values_util.MaskedTimeSeries(observed_time_series,
is_missing=is_missing)
def factored_joint_mvn(distributions):
"""Combine MultivariateNormals into a factored joint distribution.
Given a list of multivariate normal distributions
`dist[i] = Normal(loc[i], scale[i])`, construct the joint
distribution given by concatenating independent samples from these
distributions. This is multivariate normal with mean vector given by the
concatenation of the component mean vectors, and block-diagonal covariance
matrix in which the blocks are the component covariances.
Note that for computational efficiency, multivariate normals are represented
by a 'scale' (factored covariance) linear operator rather than the full
covariance matrix.
Args:
distributions: Python `iterable` of MultivariateNormal distribution
instances (e.g., `tfd.MultivariateNormalDiag`,
`tfd.MultivariateNormalTriL`, etc.). These must be broadcastable to a
consistent batch shape, but may have different event shapes
(i.e., defined over spaces of different dimension).
Returns:
joint_distribution: An instance of `tfd.MultivariateNormalLinearOperator`
representing the joint distribution constructed by concatenating
an independent sample from each input distributions.
"""
with tf.name_scope('factored_joint_mvn'):
# We explicitly broadcast the `locs` so that we can concatenate them.
# We don't have direct numerical access to the `scales`, which are arbitrary
# linear operators, but `LinearOperatorBlockDiag` appears to do the right
# thing without further intervention.
dtype = tf.debugging.assert_same_float_dtype(distributions)
broadcast_ones = tf.ones(broadcast_batch_shape(distributions),
dtype=dtype)[..., tf.newaxis]
return MultivariateNormalLinearOperator(
loc=tf.concat([mvn.mean() * broadcast_ones for mvn in distributions],
axis=-1),
scale=tfl.LinearOperatorBlockDiag([mvn.scale for mvn in distributions],
is_square=True))
def sum_mvns(distributions):
"""Attempt to sum MultivariateNormal distributions.
The sum of (multivariate) normal random variables is itself (multivariate)
normal, with mean given by the sum of means and (co)variance given by the
sum of (co)variances. This method exploits this fact to compute the
sum of a list of `tfd.MultivariateNormalDiag` objects.
It may in the future be extended to support summation of other forms of
(Multivariate)Normal distributions.
Args:
distributions: Python `iterable` of `tfd.MultivariateNormalDiag`
distribution instances. These must all have the same event
shape, and broadcast to a consistent batch shape.
Returns:
sum_distribution: A `tfd.MultivariateNormalDiag` instance with mean
equal to the sum of input means and covariance equal to the sum of
input covariances.
"""
with tf.name_scope('sum_mvns'):
if all([isinstance(mvn, tfd.MultivariateNormalDiag)
for mvn in distributions]):
return tfd.MultivariateNormalDiag(
loc=sum([mvn.mean() for mvn in distributions]),
scale_diag=tf.sqrt(sum([
mvn.scale.diag**2 for mvn in distributions])))
else:
raise NotImplementedError(
'Sums of distributions other than MultivariateNormalDiag are not '
'currently implemented. (given: {})'.format(distributions))
def empirical_statistics(observed_time_series):
"""Compute statistics of a provided time series, as heuristic initialization.
If a series is entirely unobserved (all values are masked), default statistics
`mean == 0.`, `stddev == 1.`, and `initial_centered == 0.` are returned.
To avoid degenerate models, a value of `1.` is returned for `stddev` whenever
the input series is entirely constant (when the true `stddev` is `0.`).
Args:
observed_time_series: `Tensor` representing a time series, or batch of time
series, of shape either `batch_shape + [num_timesteps, 1]` or
`batch_shape + [num_timesteps]` (allowed if `num_timesteps > 1`).
Returns:
observed_mean: `Tensor` of shape `batch_shape`, giving the empirical
mean of each time series in the batch.
observed_stddev: `Tensor` of shape `batch_shape`, giving the empirical
standard deviation of each time series in the batch.
observed_initial_centered: `Tensor of shape `batch_shape`, giving the
initial value of each time series in the batch after centering
(subtracting the mean).
"""
with tf.name_scope('empirical_statistics'):
[
observed_time_series,
mask
] = canonicalize_observed_time_series_with_mask(observed_time_series)
squeezed_series = observed_time_series[..., 0]
if mask is None:
observed_mean, observed_variance = tf.nn.moments(
x=squeezed_series, axes=-1)
observed_initial = squeezed_series[..., 0]
else:
broadcast_mask = tf.broadcast_to(tf.cast(mask, tf.bool),
tf.shape(squeezed_series))
observed_mean, observed_variance = (
missing_values_util.moments_of_masked_time_series(
squeezed_series, broadcast_mask=broadcast_mask))
try:
observed_initial = (
missing_values_util.initial_value_of_masked_time_series(
squeezed_series, broadcast_mask=broadcast_mask))
except NotImplementedError:
tf1.logging.warn(
'Cannot compute initial values for a masked time series'
'with dynamic shape; using the mean instead. This will'
'affect heuristic priors and may change the results of'
'inference.')
observed_initial = observed_mean
observed_stddev = tf.sqrt(observed_variance)
observed_initial_centered = observed_initial - observed_mean
# Dividing by zero will estimate `inf` or `nan` for the mean and stddev
# (and thus initial_centered) if a series is entirely masked. Replace these
# with default values.
replace_nans = (
lambda x, v: tf.where(tf.math.is_finite(x), x, tf.cast(v, x.dtype)))
# Avoid stddev of zero from a constant series.
replace_zeros = (
lambda x, v: tf.where(tf.equal(x, 0.), tf.cast(v, x.dtype), x))
return (replace_nans(observed_mean, 0.),
replace_zeros(replace_nans(observed_stddev, 1.), 1.),
replace_nans(observed_initial_centered, 0.))
def _maybe_expand_trailing_dim(observed_time_series_tensor):
"""Ensures `observed_time_series_tensor` has a trailing dimension of size 1.
The `tfd.LinearGaussianStateSpaceModel` Distribution has event shape of
`[num_timesteps, observation_size]`, but canonical BSTS models
are univariate, so their observation_size is always `1`. The extra trailing
dimension gets annoying, so this method allows arguments with or without the
extra dimension. There is no ambiguity except in the trivial special case
where `num_timesteps = 1`; this can be avoided by specifying any unit-length
series in the explicit `[num_timesteps, 1]` style.
Most users should not call this method directly, and instead call
`canonicalize_observed_time_series_with_mask`, which handles converting
to `Tensor` and specifying an optional missingness mask.
Args:
observed_time_series_tensor: `Tensor` of shape
`batch_shape + [num_timesteps, 1]` or `batch_shape + [num_timesteps]`,
where `num_timesteps > 1`.
Returns:
expanded_time_series: `Tensor` of shape `batch_shape + [num_timesteps, 1]`.
"""
with tf.name_scope('maybe_expand_trailing_dim'):
if (observed_time_series_tensor.shape.ndims is not None and
tf.compat.dimension_value(
observed_time_series_tensor.shape[-1]) is not None):
expanded_time_series = (
observed_time_series_tensor
if observed_time_series_tensor.shape[-1] == 1
else observed_time_series_tensor[..., tf.newaxis])
else:
expanded_time_series = tf.cond(
pred=tf.equal(tf.shape(observed_time_series_tensor)[-1], 1),
true_fn=lambda: observed_time_series_tensor,
false_fn=lambda: observed_time_series_tensor[..., tf.newaxis])
return expanded_time_series
def canonicalize_observed_time_series_with_mask(
maybe_masked_observed_time_series):
"""Extract a Tensor with canonical shape and optional mask.
Args:
maybe_masked_observed_time_series: a `Tensor`-like object with shape
`[..., num_timesteps]` or `[..., num_timesteps, 1]`, or a
`tfp.sts.MaskedTimeSeries` containing such an object, or a Pandas
Series or DataFrame instance with set frequency
(i.e., `.index.freq is not None`).
Returns:
masked_time_series: a `tfp.sts.MaskedTimeSeries` namedtuple, in which
the `observed_time_series` is converted to `Tensor` with canonical shape
`[..., num_timesteps, 1]`, and `is_missing` is either `None` or a boolean
`Tensor`.
"""
with tf.name_scope('canonicalize_observed_time_series_with_mask'):
is_missing_is_specified = hasattr(maybe_masked_observed_time_series,
'is_missing')
if is_missing_is_specified:
# Input is a MaskedTimeSeries.
observed_time_series = (
maybe_masked_observed_time_series.time_series)
is_missing = maybe_masked_observed_time_series.is_missing
elif (hasattr(maybe_masked_observed_time_series, 'index') and
hasattr(maybe_masked_observed_time_series, 'to_numpy')):
# Input is a Pandas Series or DataFrame.
index = maybe_masked_observed_time_series.index
if hasattr(index, 'freq') and index.freq is None:
raise ValueError('Pandas DataFrame or Series has a DatetimeIndex with '
'no set frequency, but STS requires regularly spaced '
'observations. Consider using '
'`tfp.sts.regularize_series` to infer a frequency and '
'build a regularly spaced series (by marking '
'unobserved steps as missing observations).')
# When a DataFrame has multiple columns representing a batch of series,
# we want shape `[batch_size, num_steps]` rather than vice versa.
observed_time_series = np.squeeze(np.transpose(
maybe_masked_observed_time_series.to_numpy()))
else:
observed_time_series = maybe_masked_observed_time_series
observed_time_series = tf.convert_to_tensor(value=observed_time_series,
name='observed_time_series')
observed_time_series = _maybe_expand_trailing_dim(observed_time_series)
# Treat `NaN` values as missing.
if not is_missing_is_specified:
is_missing = tf.math.is_nan(observed_time_series[..., 0])
is_missing_static = tf.get_static_value(is_missing)
if is_missing_static is not None and not np.any(is_missing_static):
is_missing = None
if is_missing is not None:
is_missing = tf.convert_to_tensor(
value=is_missing, name='is_missing', dtype_hint=tf.bool)
return missing_values_util.MaskedTimeSeries(observed_time_series,
is_missing=is_missing)
def mix_over_posterior_draws(means, variances):
"""Construct a predictive normal distribution that mixes over posterior draws.
Args:
means: float `Tensor` of shape
`[num_posterior_draws, ..., num_timesteps]`.
variances: float `Tensor` of shape
`[num_posterior_draws, ..., num_timesteps]`.
Returns:
mixture_dist: `tfd.MixtureSameFamily(tfd.Independent(tfd.Normal))` instance
representing a uniform mixture over the posterior samples, with
`batch_shape = ...` and `event_shape = [num_timesteps]`.
"""
# The inputs `means`, `variances` have shape
# `concat([
# [num_posterior_draws],
# sample_shape,
# batch_shape,
# [num_timesteps]])`
# Because MixtureSameFamily mixes over the rightmost batch dimension,
# we need to move the `num_posterior_draws` dimension to be rightmost
# in the batch shape. This requires use of `Independent` (to preserve
# `num_timesteps` as part of the event shape) and `move_dimension`.
# TODO(b/120245392): enhance `MixtureSameFamily` to reduce along an
# arbitrary axis, and eliminate `move_dimension` calls here.
with tf.name_scope('mix_over_posterior_draws'):
num_posterior_draws = ps.shape(means)[0]
component_observations = tfd.Independent(
distribution=tfd.Normal(
loc=dist_util.move_dimension(means, 0, -2),
scale=tf.sqrt(dist_util.move_dimension(variances, 0, -2))),
reinterpreted_batch_ndims=1)
return tfd.MixtureSameFamily(
mixture_distribution=tfd.Categorical(
logits=tf.zeros([num_posterior_draws],
dtype=component_observations.dtype)),
components_distribution=component_observations)
| [
"tensorflow_probability.python.sts.internal.missing_values_util.moments_of_masked_time_series",
"tensorflow_probability.python.internal.prefer_static.shape",
"tensorflow.compat.v2.math.is_finite",
"tensorflow.compat.v2.nn.moments",
"tensorflow.compat.v2.broadcast_static_shape",
"tensorflow_probability.pyt... | [((2039, 2078), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'batch_shape'}), '(value=batch_shape)\n', (2059, 2078), True, 'import tensorflow.compat.v2 as tf\n'), ((3383, 3474), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'chain_batch_shape', 'name': '"""chain_batch_shape"""', 'dtype': 'tf.int32'}), "(value=chain_batch_shape, name='chain_batch_shape',\n dtype=tf.int32)\n", (3403, 3474), True, 'import tensorflow.compat.v2 as tf\n'), ((3782, 3835), 'tensorflow.compat.v2.compat.dimension_value', 'tf.compat.dimension_value', (['chain_batch_shape.shape[0]'], {}), '(chain_batch_shape.shape[0])\n', (3807, 3835), True, 'import tensorflow.compat.v2 as tf\n'), ((4941, 5027), 'tensorflow_probability.python.sts.internal.missing_values_util.MaskedTimeSeries', 'missing_values_util.MaskedTimeSeries', (['observed_time_series'], {'is_missing': 'is_missing'}), '(observed_time_series, is_missing=\n is_missing)\n', (4977, 5027), False, 'from tensorflow_probability.python.sts.internal import missing_values_util\n'), ((1595, 1659), 'tensorflow.compat.v2.broadcast_static_shape', 'tf.broadcast_static_shape', (['batch_shape', 'distribution.batch_shape'], {}), '(batch_shape, distribution.batch_shape)\n', (1620, 1659), True, 'import tensorflow.compat.v2 as tf\n'), ((6325, 6360), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""factored_joint_mvn"""'], {}), "('factored_joint_mvn')\n", (6338, 6360), True, 'import tensorflow.compat.v2 as tf\n'), ((6650, 6701), 'tensorflow.compat.v2.debugging.assert_same_float_dtype', 'tf.debugging.assert_same_float_dtype', (['distributions'], {}), '(distributions)\n', (6686, 6701), True, 'import tensorflow.compat.v2 as tf\n'), ((7996, 8021), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""sum_mvns"""'], {}), "('sum_mvns')\n", (8009, 8021), True, 'import tensorflow.compat.v2 as tf\n'), ((9628, 9665), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""empirical_statistics"""'], {}), "('empirical_statistics')\n", (9641, 9665), True, 'import tensorflow.compat.v2 as tf\n'), ((10842, 10868), 'tensorflow.compat.v2.sqrt', 'tf.sqrt', (['observed_variance'], {}), '(observed_variance)\n', (10849, 10868), True, 'import tensorflow.compat.v2 as tf\n'), ((12655, 12697), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""maybe_expand_trailing_dim"""'], {}), "('maybe_expand_trailing_dim')\n", (12668, 12697), True, 'import tensorflow.compat.v2 as tf\n'), ((14068, 14128), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""canonicalize_observed_time_series_with_mask"""'], {}), "('canonicalize_observed_time_series_with_mask')\n", (14081, 14128), True, 'import tensorflow.compat.v2 as tf\n'), ((15570, 15647), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'observed_time_series', 'name': '"""observed_time_series"""'}), "(value=observed_time_series, name='observed_time_series')\n", (15590, 15647), True, 'import tensorflow.compat.v2 as tf\n'), ((15934, 15965), 'tensorflow.compat.v2.get_static_value', 'tf.get_static_value', (['is_missing'], {}), '(is_missing)\n', (15953, 15965), True, 'import tensorflow.compat.v2 as tf\n'), ((16213, 16299), 'tensorflow_probability.python.sts.internal.missing_values_util.MaskedTimeSeries', 'missing_values_util.MaskedTimeSeries', (['observed_time_series'], {'is_missing': 'is_missing'}), '(observed_time_series, is_missing=\n is_missing)\n', (16249, 16299), False, 'from tensorflow_probability.python.sts.internal import missing_values_util\n'), ((17486, 17527), 'tensorflow.compat.v2.name_scope', 'tf.name_scope', (['"""mix_over_posterior_draws"""'], {}), "('mix_over_posterior_draws')\n", (17499, 17527), True, 'import tensorflow.compat.v2 as tf\n'), ((3911, 3948), 'tensorflow.compat.v2.shape', 'tf.shape', (['observed_time_series_tensor'], {}), '(observed_time_series_tensor)\n', (3919, 3948), True, 'import tensorflow.compat.v2 as tf\n'), ((4031, 4068), 'tensorflow.compat.v2.shape', 'tf.shape', (['observed_time_series_tensor'], {}), '(observed_time_series_tensor)\n', (4039, 4068), True, 'import tensorflow.compat.v2 as tf\n'), ((4460, 4489), 'tensorflow_probability.python.internal.prefer_static.rank', 'ps.rank', (['observed_time_series'], {}), '(observed_time_series)\n', (4467, 4489), True, 'from tensorflow_probability.python.internal import prefer_static as ps\n'), ((9905, 9946), 'tensorflow.compat.v2.nn.moments', 'tf.nn.moments', ([], {'x': 'squeezed_series', 'axes': '(-1)'}), '(x=squeezed_series, axes=-1)\n', (9918, 9946), True, 'import tensorflow.compat.v2 as tf\n'), ((10199, 10300), 'tensorflow_probability.python.sts.internal.missing_values_util.moments_of_masked_time_series', 'missing_values_util.moments_of_masked_time_series', (['squeezed_series'], {'broadcast_mask': 'broadcast_mask'}), '(squeezed_series,\n broadcast_mask=broadcast_mask)\n', (10248, 10300), False, 'from tensorflow_probability.python.sts.internal import missing_values_util\n'), ((15865, 15909), 'tensorflow.compat.v2.math.is_nan', 'tf.math.is_nan', (['observed_time_series[..., 0]'], {}), '(observed_time_series[..., 0])\n', (15879, 15909), True, 'import tensorflow.compat.v2 as tf\n'), ((16112, 16189), 'tensorflow.compat.v2.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'is_missing', 'name': '"""is_missing"""', 'dtype_hint': 'tf.bool'}), "(value=is_missing, name='is_missing', dtype_hint=tf.bool)\n", (16132, 16189), True, 'import tensorflow.compat.v2 as tf\n'), ((17555, 17570), 'tensorflow_probability.python.internal.prefer_static.shape', 'ps.shape', (['means'], {}), '(means)\n', (17563, 17570), True, 'from tensorflow_probability.python.internal import prefer_static as ps\n'), ((4750, 4769), 'tensorflow_probability.python.internal.prefer_static.rank', 'ps.rank', (['is_missing'], {}), '(is_missing)\n', (4757, 4769), True, 'from tensorflow_probability.python.internal import prefer_static as ps\n'), ((10056, 10078), 'tensorflow.compat.v2.cast', 'tf.cast', (['mask', 'tf.bool'], {}), '(mask, tf.bool)\n', (10063, 10078), True, 'import tensorflow.compat.v2 as tf\n'), ((10119, 10144), 'tensorflow.compat.v2.shape', 'tf.shape', (['squeezed_series'], {}), '(squeezed_series)\n', (10127, 10144), True, 'import tensorflow.compat.v2 as tf\n'), ((10365, 10472), 'tensorflow_probability.python.sts.internal.missing_values_util.initial_value_of_masked_time_series', 'missing_values_util.initial_value_of_masked_time_series', (['squeezed_series'], {'broadcast_mask': 'broadcast_mask'}), '(squeezed_series,\n broadcast_mask=broadcast_mask)\n', (10420, 10472), False, 'from tensorflow_probability.python.sts.internal import missing_values_util\n'), ((11169, 11189), 'tensorflow.compat.v2.math.is_finite', 'tf.math.is_finite', (['x'], {}), '(x)\n', (11186, 11189), True, 'import tensorflow.compat.v2 as tf\n'), ((11194, 11213), 'tensorflow.compat.v2.cast', 'tf.cast', (['v', 'x.dtype'], {}), '(v, x.dtype)\n', (11201, 11213), True, 'import tensorflow.compat.v2 as tf\n'), ((11319, 11335), 'tensorflow.compat.v2.equal', 'tf.equal', (['x', '(0.0)'], {}), '(x, 0.0)\n', (11327, 11335), True, 'import tensorflow.compat.v2 as tf\n'), ((11336, 11355), 'tensorflow.compat.v2.cast', 'tf.cast', (['v', 'x.dtype'], {}), '(v, x.dtype)\n', (11343, 11355), True, 'import tensorflow.compat.v2 as tf\n'), ((12771, 12835), 'tensorflow.compat.v2.compat.dimension_value', 'tf.compat.dimension_value', (['observed_time_series_tensor.shape[-1]'], {}), '(observed_time_series_tensor.shape[-1])\n', (12796, 12835), True, 'import tensorflow.compat.v2 as tf\n'), ((16011, 16036), 'numpy.any', 'np.any', (['is_missing_static'], {}), '(is_missing_static)\n', (16017, 16036), True, 'import numpy as np\n'), ((10529, 10729), 'tensorflow.compat.v1.logging.warn', 'tf1.logging.warn', (['"""Cannot compute initial values for a masked time serieswith dynamic shape; using the mean instead. This willaffect heuristic priors and may change the results ofinference."""'], {}), "(\n 'Cannot compute initial values for a masked time serieswith dynamic shape; using the mean instead. This willaffect heuristic priors and may change the results ofinference.'\n )\n", (10545, 10729), True, 'import tensorflow.compat.v1 as tf1\n'), ((4254, 4298), 'tensorflow.compat.v2.ones', 'tf.ones', (['[chain_batch_ndims]'], {'dtype': 'tf.int32'}), '([chain_batch_ndims], dtype=tf.int32)\n', (4261, 4298), True, 'import tensorflow.compat.v2 as tf\n'), ((17670, 17708), 'tensorflow_probability.python.internal.distribution_util.move_dimension', 'dist_util.move_dimension', (['means', '(0)', '(-2)'], {}), '(means, 0, -2)\n', (17694, 17708), True, 'from tensorflow_probability.python.internal import distribution_util as dist_util\n'), ((17919, 17986), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['[num_posterior_draws]'], {'dtype': 'component_observations.dtype'}), '([num_posterior_draws], dtype=component_observations.dtype)\n', (17927, 17986), True, 'import tensorflow.compat.v2 as tf\n'), ((13121, 13158), 'tensorflow.compat.v2.shape', 'tf.shape', (['observed_time_series_tensor'], {}), '(observed_time_series_tensor)\n', (13129, 13158), True, 'import tensorflow.compat.v2 as tf\n'), ((17736, 17778), 'tensorflow_probability.python.internal.distribution_util.move_dimension', 'dist_util.move_dimension', (['variances', '(0)', '(-2)'], {}), '(variances, 0, -2)\n', (17760, 17778), True, 'from tensorflow_probability.python.internal import distribution_util as dist_util\n')] |
print("Composed by Dr <NAME>, CSU. version 3.1.2021.06.22. Xiangya School of Pharmaceutical Science.")
print("Please cite J. Org. Chem. 2020, 85, 17, 11350–11358")
print("作者:王文宣,中南大学,湘雅药学院")
print(" ")
#Parameters table
temp = 298 #termperature for Boltzmann population calculation (K)
threshold_geom = 0.1 #threshold to determine geometery duplicates (Angstrom)
threshold_energy = 0.2 #Gibbs free energy threshold to determine geometery duplicates (kcal/mol)
print("Termperature for Boltzmann population calculation (K) is ", temp)
print("threshold to determine geometery duplicates (Angstrom) is ", threshold_geom)
print("Gibbs free energy threshold to determine geometery duplicates (kcal/mol) is", threshold_energy)
print(" ")
import os
import glob
import numpy as np
import linecache
import pandas as pd
import csv
import math
filenames = []
gibbs_list = []
duplicates_list = []
class Conf_info():
filename = ''
gibbs = 0.0
imaginary = 0
error = ' '
def __init__(self,filename):
self.filename = filename
outfilenames = glob.glob('*.out') #obtain all out file names
logfilenames = glob.glob('*.log') #obtain all log file names
filenames.extend(outfilenames)
filenames.extend(logfilenames) #get the file list
#open files and read the information sequently
if len(filenames) == 0:
print ("No out or log files found")
quit()
else:
conf_list = []
for i in range(len(filenames)):
atom_num = [] #for reading shielding tensors
shielding = [] #for reading shielding tensors
conf = Conf_info(filenames[i])
with open(filenames[i], 'r') as f:
gibbs_line_num = -1
for line_number, key_word in enumerate(f.readlines()):
if ' imaginary frequencies (negative Signs) ******' in key_word:
#read imaginary frequencies
conf.imaginary = 1
elif 'Sum of electronic and thermal Free Energies=' in key_word:
gibbs_line_num = line_number
conf.gibbs = float(key_word.split( )[-1]) #build the Gibbs free energy list
elif '-- Number of steps exceeded' in key_word:
conf.error = 'Optimization failed because max steps exceeded'
elif 'C Isotropic =' in key_word: #read the shielding tensor data of C
shielding_line_num = line_number
shielding_line = linecache.getline(filenames[i], shielding_line_num+1)
atom_num.append(shielding_line.split( )[0])
shielding.append(shielding_line.split( )[4])
if len(atom_num) > 0:
prefix = filenames[i][:-4]
shielding_file = open(prefix+'_C_shielding.txt', 'w')
for j in range(len(atom_num)):
print(atom_num[j], " ", shielding[j], file = shielding_file) #save shielding data into text file
shielding_file.close()
conf_list.append(conf)
del conf
filenames_selected = []
#Remove structures with imaginary frequencies or without gibbs free energy
for i in range(len(conf_list)):
if conf_list[i].imaginary == 1:
print(conf_list[i].filename, " has imaginary frequencies, and will not be considered")
continue
elif conf_list[i].gibbs == 0:
print(conf_list[i].filename, " has no Gibbs free energy information", conf_list[i].error)
continue
else:
filenames_selected.append(conf_list[i].filename)
gibbs_list.append(conf_list[i].gibbs)
filenames_selected = np.array(filenames_selected)
gibbs_list = np.array(gibbs_list,dtype=float)
#sort the information matrix by Gibbs free energy
gibbs_order = np.argsort(gibbs_list)
filenames_sort = filenames_selected[gibbs_order]
gibbs_float_sort = gibbs_list[gibbs_order]
def dis_matrix_cp(file_nameA, file_nameB, threshold):
#This function uses the coordinates for multiple steps calculation to identify duplicates
#read the line number of coordinates
with open(file_nameA, 'r') as A:
line0 = -1
line1 = -1
for line_number, key_word in enumerate(A.readlines()):
if 'Redundant internal coordinates found in file. (old form).' in key_word:
line0 = line_number
if 'Recover connectivity data from disk.' in key_word:
line1 = line_number
if line0 == -1:
print("There may be no coordinates for multiple steps calculation in ", file_nameA)
return 0
with open(file_nameB, 'r') as B:
line2 = -1
line3 = -1
for line_number, key_word in enumerate(B.readlines()):
if 'Redundant internal coordinates found in file. (old form).' in key_word:
line2 = line_number
if 'Recover connectivity data from disk.' in key_word:
line3 = line_number
if line2 == -1:
print("There may be no coordinates for multiple steps calculation in ", file_nameB)
return 0
#read the lines of coordinates and compare the distance between atoms
k = 1 #record the linenumber of the coordinate line for processing
distanceA = []
distanceB = []
for i in range(line0+2, line1-1):
A_coordinate_line1 = linecache.getline(file_nameA, i)
arrayA_atom1 = np.array(A_coordinate_line1.split(',')[2: ])
arrayA_atom1_float = arrayA_atom1.astype(float)
k = k+1
B_coordinate_line1 = linecache.getline(file_nameB, line2+k)
arrayB_atom1 = np.array(B_coordinate_line1.split(',')[2: ])
arrayB_atom1_float = arrayB_atom1.astype(float)
l = 0 #record the linenumber of the coordinate line for processing
for j in range(i, line1):
A_coordinate_line2 = linecache.getline(file_nameA, j+1)
arrayA_atom2 = np.array(A_coordinate_line2.split(',')[2: ])
arrayA_atom2_float = arrayA_atom2.astype(float)
l = l + 1
B_coordinate_line2 = linecache.getline(file_nameB, line2+k+l)
arrayB_atom2 = np.array(B_coordinate_line2.split(',')[2: ])
arrayB_atom2_float = arrayB_atom2.astype(float)
distanceA.append(((arrayA_atom1_float[0]-arrayA_atom2_float[0]) ** 2 + (arrayA_atom1_float[1]-arrayA_atom2_float[1]) ** 2 + (arrayA_atom1_float[2]-arrayA_atom2_float[2]) ** 2) **0.5)
distanceB.append(((arrayB_atom1_float[0]-arrayB_atom2_float[0]) ** 2 + (arrayB_atom1_float[1]-arrayB_atom2_float[1]) ** 2 + (arrayB_atom1_float[2]-arrayB_atom2_float[2]) ** 2) **0.5)
distanceA = np.array(distanceA,dtype='float32')
distanceB = np.array(distanceB,dtype='float32')
distanceA_sort = np.sort(distanceA)
distanceB_sort = np.sort(distanceB)
for i in range(len(distanceA_sort)):
if abs(distanceA_sort[i] - distanceB_sort[i]) > threshold: #Check if the distance matrices of conformers are the same
return 0
return 1
#check duplicates by energy and geometry
for i in range(len(filenames_sort)-1):
gibbs_difference = gibbs_float_sort[i+1] - gibbs_float_sort[i]
if gibbs_difference < (threshold_energy / 627.5094):
if dis_matrix_cp(filenames_sort[i+1],filenames_sort[i],threshold_geom) == 1:
print(filenames_sort[i+1], "is the same as", filenames_sort[i])
duplicates_list.append([i+1])
#remove duplicates
if len(duplicates_list) > 0:
duplicates_list = np.array(duplicates_list)
duplicates_list = duplicates_list.astype(int)
for i in range(len(duplicates_list)):
filenames_sort = np.delete(filenames_sort, (duplicates_list[i]-i))
gibbs_float_sort = np.delete(gibbs_float_sort, (duplicates_list[i]-i))
#save energy information to excel file
gibbs_kcal = []
for i in range(len(gibbs_float_sort)):
gibbs_kcal.append((gibbs_float_sort[i]-gibbs_float_sort[0])*627.5094) #Hatree converted into kcal/mol
gibbs_kcal = np.array(gibbs_kcal)
gibbs_kcal = gibbs_kcal.astype(float)
boltzmann_factor = 2.7182818284590452353602874**(-1*gibbs_kcal/temp/0.0019858775) #calculate Boltzmann factors
sum_boltzmann = 0
for i in range(len(boltzmann_factor)):
sum_boltzmann = boltzmann_factor[i]+sum_boltzmann #sum Boltzmann factors
population = boltzmann_factor/sum_boltzmann #calculate population of each conformer
writer = pd.ExcelWriter(r'population.xlsx')
df1 = pd.DataFrame({'Name':filenames_sort, 'Gibbs free energy (hatree)':gibbs_float_sort, 'ΔG (kcal/mol)':gibbs_kcal, 'Population':population})
df1.to_excel(writer, sheet_name='sheet1')
writer.save() #write energy data into excel file
#average 13C shielding tensors
shielding_average = [0.0]*len(atom_num)
for i in range(len(filenames_sort)):
with open(filenames_sort[i][:-4]+'_C_shielding.txt') as f:
shielding_atom = []
for j in range(len(atom_num)):
shielding_line = linecache.getline(filenames_sort[i][:-4]+'_C_shielding.txt', j+1).split( )[1] #read the file of shielding tensors
shielding_atom.append(float(shielding_line)*population[i]) #weight the shielding tensors with population value
for k in range(len(atom_num)):
shielding_average[k] = shielding_average[k] + shielding_atom[k] #accumulate the weighted shielding tensors
writer = pd.ExcelWriter(r'Averaged_C_shielding.xlsx')
df1 = pd.DataFrame({'Atom number':atom_num, 'Averaged shielding tensors':shielding_average})
df1.to_excel(writer, sheet_name='sheet1')
writer.save() #save the averaged shielding tensors into file
| [
"pandas.DataFrame",
"linecache.getline",
"numpy.argsort",
"numpy.sort",
"numpy.array",
"glob.glob",
"pandas.ExcelWriter",
"numpy.delete"
] | [((1079, 1097), 'glob.glob', 'glob.glob', (['"""*.out"""'], {}), "('*.out')\n", (1088, 1097), False, 'import glob\n'), ((1141, 1159), 'glob.glob', 'glob.glob', (['"""*.log"""'], {}), "('*.log')\n", (1150, 1159), False, 'import glob\n'), ((3612, 3640), 'numpy.array', 'np.array', (['filenames_selected'], {}), '(filenames_selected)\n', (3620, 3640), True, 'import numpy as np\n'), ((3655, 3688), 'numpy.array', 'np.array', (['gibbs_list'], {'dtype': 'float'}), '(gibbs_list, dtype=float)\n', (3663, 3688), True, 'import numpy as np\n'), ((3758, 3780), 'numpy.argsort', 'np.argsort', (['gibbs_list'], {}), '(gibbs_list)\n', (3768, 3780), True, 'import numpy as np\n'), ((7903, 7923), 'numpy.array', 'np.array', (['gibbs_kcal'], {}), '(gibbs_kcal)\n', (7911, 7923), True, 'import numpy as np\n'), ((8307, 8340), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['"""population.xlsx"""'], {}), "('population.xlsx')\n", (8321, 8340), True, 'import pandas as pd\n'), ((8349, 8494), 'pandas.DataFrame', 'pd.DataFrame', (["{'Name': filenames_sort, 'Gibbs free energy (hatree)': gibbs_float_sort,\n 'ΔG (kcal/mol)': gibbs_kcal, 'Population': population}"], {}), "({'Name': filenames_sort, 'Gibbs free energy (hatree)':\n gibbs_float_sort, 'ΔG (kcal/mol)': gibbs_kcal, 'Population': population})\n", (8361, 8494), True, 'import pandas as pd\n'), ((9254, 9297), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['"""Averaged_C_shielding.xlsx"""'], {}), "('Averaged_C_shielding.xlsx')\n", (9268, 9297), True, 'import pandas as pd\n'), ((9306, 9398), 'pandas.DataFrame', 'pd.DataFrame', (["{'Atom number': atom_num, 'Averaged shielding tensors': shielding_average}"], {}), "({'Atom number': atom_num, 'Averaged shielding tensors':\n shielding_average})\n", (9318, 9398), True, 'import pandas as pd\n'), ((6577, 6613), 'numpy.array', 'np.array', (['distanceA'], {'dtype': '"""float32"""'}), "(distanceA, dtype='float32')\n", (6585, 6613), True, 'import numpy as np\n'), ((6628, 6664), 'numpy.array', 'np.array', (['distanceB'], {'dtype': '"""float32"""'}), "(distanceB, dtype='float32')\n", (6636, 6664), True, 'import numpy as np\n'), ((6684, 6702), 'numpy.sort', 'np.sort', (['distanceA'], {}), '(distanceA)\n', (6691, 6702), True, 'import numpy as np\n'), ((6723, 6741), 'numpy.sort', 'np.sort', (['distanceB'], {}), '(distanceB)\n', (6730, 6741), True, 'import numpy as np\n'), ((7406, 7431), 'numpy.array', 'np.array', (['duplicates_list'], {}), '(duplicates_list)\n', (7414, 7431), True, 'import numpy as np\n'), ((5258, 5290), 'linecache.getline', 'linecache.getline', (['file_nameA', 'i'], {}), '(file_nameA, i)\n', (5275, 5290), False, 'import linecache\n'), ((5468, 5508), 'linecache.getline', 'linecache.getline', (['file_nameB', '(line2 + k)'], {}), '(file_nameB, line2 + k)\n', (5485, 5508), False, 'import linecache\n'), ((7548, 7597), 'numpy.delete', 'np.delete', (['filenames_sort', '(duplicates_list[i] - i)'], {}), '(filenames_sort, duplicates_list[i] - i)\n', (7557, 7597), True, 'import numpy as np\n'), ((7623, 7674), 'numpy.delete', 'np.delete', (['gibbs_float_sort', '(duplicates_list[i] - i)'], {}), '(gibbs_float_sort, duplicates_list[i] - i)\n', (7632, 7674), True, 'import numpy as np\n'), ((5784, 5820), 'linecache.getline', 'linecache.getline', (['file_nameA', '(j + 1)'], {}), '(file_nameA, j + 1)\n', (5801, 5820), False, 'import linecache\n'), ((5999, 6043), 'linecache.getline', 'linecache.getline', (['file_nameB', '(line2 + k + l)'], {}), '(file_nameB, line2 + k + l)\n', (6016, 6043), False, 'import linecache\n'), ((8852, 8921), 'linecache.getline', 'linecache.getline', (["(filenames_sort[i][:-4] + '_C_shielding.txt')", '(j + 1)'], {}), "(filenames_sort[i][:-4] + '_C_shielding.txt', j + 1)\n", (8869, 8921), False, 'import linecache\n'), ((2483, 2538), 'linecache.getline', 'linecache.getline', (['filenames[i]', '(shielding_line_num + 1)'], {}), '(filenames[i], shielding_line_num + 1)\n', (2500, 2538), False, 'import linecache\n')] |
#
# ImageViewBokeh.py -- classes implementing a ginga viewer backend for Bokeh
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import time
import numpy as np
# Bokeh imports
from bokeh.plotting import curdoc
from bokeh.models import ColumnDataSource
from bokeh.io import push_notebook
from bokeh import events
from ginga import ImageView
from ginga.canvas import render
from ginga import Mixins, Bindings
class ImageViewBokehError(ImageView.ImageViewError):
pass
class ImageViewBokeh(ImageView.ImageViewBase):
"""
This version does all the graphical overlays on the server side.
"""
def __init__(self, logger=None, rgbmap=None, settings=None):
ImageView.ImageViewBase.__init__(self, logger=logger,
rgbmap=rgbmap,
settings=settings)
self.t_.set_defaults(renderer='cairo')
# Our Bokeh plot
self.figure = None
# Holds the image on the plot
self.bkimage = None
self.d_src = None
self._push_handle = None
# NOTE: Bokeh manages it's Y coordinates by default with
# the origin at the bottom (see base class)
self.origin_upper = True
self._invert_y = True
# override, until we can get access to a timer
self.defer_redraw = True
self.rgb_order = 'RGBA'
# For timing events
self._msg_timer = 0
self._defer_timer = 0
self.renderer = None
# Pick a renderer that can work with us
renderers = ['cairo', 'agg', 'pil', 'opencv']
preferred = self.t_['renderer']
if preferred in renderers:
renderers.remove(preferred)
self.possible_renderers = [preferred] + renderers
self.choose_best_renderer()
def set_figure(self, figure, handle=None):
"""Call this with the Bokeh figure object."""
self.figure = figure
self.bkimage = None
self._push_handle = handle
self._setup_handlers(figure)
wd = figure.plot_width
ht = figure.plot_height
self.configure_window(wd, ht)
doc = curdoc()
doc.add_periodic_callback(self.timer_cb, 20)
self.logger.info("figure set")
def get_figure(self):
return self.figure
def choose_renderer(self, name):
klass = render.get_render_class(name)
self.renderer = klass(self)
#self.renderer.resize((wd, ht))
def choose_best_renderer(self):
for name in self.possible_renderers:
try:
self.choose_renderer(name)
self.logger.info("best renderer available is '{}'".format(name))
return
except Exception as e:
# uncomment to troubleshoot
self.logger.info("can't choose renderer '{}': {}".format(name, e),
exc_info=True)
continue
raise ImageViewBokehError("No valid renderers available: {}".format(str(self.possible_renderers)))
def update_widget(self):
if self.figure is None:
return
wd, ht = self.get_window_size()
# Get surface as a numpy array
data = self.renderer.get_surface_as_array(order='RGBA')
# Casting as a 32-bit uint array type hopefully to get more
# efficient JSON encoding en route to the browser
data = data.view(dtype=np.uint32).reshape((ht, wd))
data = np.flipud(data)
dst_x = dst_y = 0
# Create an Image_RGBA object in the plot
if self.bkimage is None:
self.d_src = ColumnDataSource({'image': [data]})
self.bkimage = self.figure.image_rgba(image='image',
x=dst_x, y=dst_y,
dw=wd, dh=ht,
source=self.d_src)
#self._setup_handlers(self.d_src)
else:
# note: get the data source (a ColumnDataSource) and update
# the values
self.logger.info("Updating image")
update = dict(image=[data], x=[dst_x], y=[dst_y],
dw=[wd], dh=[ht])
self.d_src.data = update
if self._push_handle is not None:
self.logger.info("pushing to notebook...")
#self.d_src.push_notebook(self._push_handle)
push_notebook(self._push_handle)
self.logger.info("Image updated")
def reschedule_redraw(self, time_sec):
self._defer_timer = time.time() + time_sec
def configure_window(self, width, height):
self.configure_surface(width, height)
def _setup_handlers(self, source):
pass
def set_cursor(self, cursor):
pass
def timer_cb(self, *args):
self.logger.debug("timer")
cur_time = time.time()
if (self._defer_timer > 0) and (cur_time > self._defer_timer):
self._defer_timer = 0
self.logger.info("redrawing")
self.delayed_redraw()
if (self._msg_timer > 0) and (cur_time > self._msg_timer):
self._msg_timer = 0
self.set_onscreen_message(None)
def onscreen_message(self, text, delay=None):
if text is not None:
self.set_onscreen_message(text)
if delay:
self._msg_timer = time.time() + delay
def onscreen_message_off(self):
self.set_onscreen_message(None)
class ImageViewEvent(ImageViewBokeh):
def __init__(self, logger=None, rgbmap=None, settings=None):
ImageViewBokeh.__init__(self, logger=logger, rgbmap=rgbmap,
settings=settings)
# last known window mouse position
self.last_win_x = 0
self.last_win_y = 0
# last known data mouse position
self.last_data_x = 0
self.last_data_y = 0
# @$%&^(_)*&^ gnome!!
self._keytbl = {
'shift': 'shift_l',
'control': 'control_l',
'alt': 'alt_l',
'win': 'super_l',
'`': 'backquote',
'"': 'doublequote',
"'": 'singlequote',
'\\': 'backslash',
' ': 'space',
# NOTE: not working
'escape': 'escape',
'enter': 'return',
# NOTE: not working
'tab': 'tab',
# NOTE: all Fn keys not working
'f1': 'f1',
'f2': 'f2',
'f3': 'f3',
'f4': 'f4',
'f5': 'f5',
'f6': 'f6',
'f7': 'f7',
'f8': 'f8',
'f9': 'f9',
'f10': 'f10',
'f11': 'f11',
'f12': 'f12',
}
# Define cursors for pick and pan
#hand = openHandCursor()
hand = 0
self.define_cursor('pan', hand)
#cross = thinCrossCursor('aquamarine')
cross = 1
self.define_cursor('pick', cross)
for name in ('motion', 'button-press', 'button-release',
'key-press', 'key-release', 'drag-drop',
'scroll', 'map', 'focus', 'enter', 'leave',
'pinch', 'pan', 'press', 'tap',
):
self.enable_callback(name)
def set_figure(self, figure, handle=None):
super(ImageViewEvent, self).set_figure(figure, handle=handle)
def _setup_handlers(self, source):
fig = self.figure
# TODO: lots of events that are supported by other backends!
## #connect("map_event", self.map_event)
fig.on_event(events.MouseEnter, self.enter_notify_event)
fig.on_event(events.MouseLeave, self.leave_notify_event)
fig.on_event(events.MouseMove, self.motion_notify_event)
## #connect("focus_in_event", self.focus_event, True)
## #connect("focus_out_event", self.focus_event, False)
## connect("button_press_event", self.button_press_event)
## connect("button_release_event", self.button_release_event)
## connect("key_press_event", self.key_press_event)
## connect("key_release_event", self.key_release_event)
fig.on_event(events.MouseWheel, self.scroll_event)
fig.on_event(events.Tap, self.tap_event)
#fig.on_event(events.Press, self.press_down_event)
#fig.on_event(events.PressUp, self.press_up_event)
# NOTE: currently using these for button press events
fig.on_event(events.PanStart, self.pan_start_event)
fig.on_event(events.Pan, self.pan_event)
fig.on_event(events.PanEnd, self.pan_end_event)
#fig.on_event(events.Pinch, self.pinch_event)
self.logger.info("setup event handlers")
def transkey(self, keyname):
self.logger.debug("bokeh keyname='%s'" % (keyname))
if keyname is None:
return keyname
try:
return self._keytbl[keyname.lower()]
except KeyError:
return keyname
def get_key_table(self):
return self._keytbl
def focus_event(self, event, hasFocus):
return self.make_callback('focus', hasFocus)
def enter_notify_event(self, event):
self.logger.info("entering widget...")
enter_focus = self.t_.get('enter_focus', False)
if enter_focus:
self.focus_event(event, True)
return self.make_callback('enter')
def leave_notify_event(self, event):
self.logger.info("leaving widget...")
enter_focus = self.t_.get('enter_focus', False)
if enter_focus:
self.focus_event(event, False)
return self.make_callback('leave')
def key_press_event(self, event):
keyname = event.key
keyname = self.transkey(keyname)
if keyname is not None:
self.logger.debug("key press event, key=%s" % (keyname))
return self.make_ui_callback_viewer(self, 'key-press', keyname)
def key_release_event(self, event):
keyname = event.key
keyname = self.transkey(keyname)
if keyname is not None:
self.logger.debug("key release event, key=%s" % (keyname))
return self.make_ui_callback_viewer(self, 'key-release', keyname)
def motion_notify_event(self, event):
button = 0
x, y = int(event.sx), int(event.sy)
self.logger.debug("motion event at %dx%d, button=%x" % (x, y, button))
self.last_win_x, self.last_win_y = x, y
data_x, data_y = self.check_cursor_location()
self.last_data_x, self.last_data_y = data_x, data_y
return self.make_ui_callback_viewer(self, 'motion', button,
data_x, data_y)
def scroll_event(self, event):
x, y = int(event.x), int(event.y)
# bokeh only gives us the number of steps of the scroll,
# positive for up and negative for down. No horizontal scrolling.
direction = None
if event.delta > 0:
direction = 0.0
elif event.delta < 0:
direction = 180.0
#amount = abs(event.delta) * 15.0
amount = int(abs(event.delta))
self.logger.info("scroll deg=%f direction=%f" % (
amount, direction))
self.last_win_x, self.last_win_y = x, y
data_x, data_y = self.check_cursor_location()
self.last_data_x, self.last_data_y = data_x, data_y
return self.make_ui_callback_viewer(self, 'scroll', direction, amount,
data_x, data_y)
def pinch_event(self, event):
# no rotation (seemingly) in the Bokeh pinch event
rot = 0.0
scale = event.scale
self.logger.debug("pinch gesture rot=%f scale=%f" % (rot, scale))
return self.make_ui_callback_viewer(self, 'pinch', 'move', rot, scale)
def pan_start_event(self, event):
# event attrs: x, y, sx, sy
x, y = int(event.sx), int(event.sy)
button = 0x1
self.last_win_x, self.last_win_y = x, y
self.logger.debug("button down event at %dx%d, button=%x" % (x, y, button))
data_x, data_y = self.check_cursor_location()
return self.make_ui_callback_viewer(self, 'button-press', button,
data_x, data_y)
def pan_event(self, event):
# event attrs: x, y, sx, sy, delta_x, delta_y
x, y = int(event.sx), int(event.sy)
button = 0x1
self.last_win_x, self.last_win_y = x, y
data_x, data_y = self.check_cursor_location()
return self.make_ui_callback_viewer(self, 'motion', button,
data_x, data_y)
def pan_end_event(self, event):
# event attrs: x, y, sx, sy
x, y = int(event.sx), int(event.sy)
button = 0x1
self.last_win_x, self.last_win_y = x, y
data_x, data_y = self.check_cursor_location()
self.logger.debug("button up event at %dx%d, button=%x" % (x, y, button))
return self.make_ui_callback_viewer(self, 'button-release', button,
data_x, data_y)
def tap_event(self, event):
x, y = int(event.x), int(event.y)
button = 0
self.logger.debug("tap event at %dx%d, button=%x" % (x, y, button))
self.last_win_x, self.last_win_y = x, y
data_x, data_y = self.check_cursor_location()
return self.make_ui_callback('button-press', button, data_x, data_y)
def press_down_event(self, event):
x, y = int(event.x), int(event.y)
self.logger.debug("press down event at %dx%d" % (x, y))
def press_up_event(self, event):
x, y = int(event.x), int(event.y)
self.logger.debug("press up event at %dx%d" % (x, y))
class ImageViewZoom(Mixins.UIMixin, ImageViewEvent):
# class variables for binding map and bindings can be set
bindmapClass = Bindings.BindingMapper
bindingsClass = Bindings.ImageViewBindings
@classmethod
def set_bindingsClass(cls, klass):
cls.bindingsClass = klass
@classmethod
def set_bindmapClass(cls, klass):
cls.bindmapClass = klass
def __init__(self, logger=None, rgbmap=None, settings=None,
bindmap=None, bindings=None):
ImageViewEvent.__init__(self, logger=logger, rgbmap=rgbmap,
settings=settings)
Mixins.UIMixin.__init__(self)
self.ui_set_active(True, viewer=self)
if bindmap is None:
bindmap = ImageViewZoom.bindmapClass(self.logger)
self.bindmap = bindmap
bindmap.register_for_events(self)
if bindings is None:
bindings = ImageViewZoom.bindingsClass(self.logger)
self.set_bindings(bindings)
def get_bindmap(self):
return self.bindmap
def get_bindings(self):
return self.bindings
def set_bindings(self, bindings):
self.bindings = bindings
bindings.set_bindings(self)
class CanvasView(ImageViewZoom):
def __init__(self, logger=None, settings=None, rgbmap=None,
bindmap=None, bindings=None):
ImageViewZoom.__init__(self, logger=logger, settings=settings,
rgbmap=rgbmap,
bindmap=bindmap, bindings=bindings)
# Needed for UIMixin to propagate events correctly
self.objects = [self.private_canvas]
def set_canvas(self, canvas, private_canvas=None):
super(CanvasView, self).set_canvas(canvas,
private_canvas=private_canvas)
self.objects[0] = self.private_canvas
| [
"ginga.ImageView.ImageViewBase.__init__",
"bokeh.models.ColumnDataSource",
"ginga.canvas.render.get_render_class",
"numpy.flipud",
"time.time",
"bokeh.io.push_notebook",
"ginga.Mixins.UIMixin.__init__",
"bokeh.plotting.curdoc"
] | [((743, 834), 'ginga.ImageView.ImageViewBase.__init__', 'ImageView.ImageViewBase.__init__', (['self'], {'logger': 'logger', 'rgbmap': 'rgbmap', 'settings': 'settings'}), '(self, logger=logger, rgbmap=rgbmap,\n settings=settings)\n', (775, 834), False, 'from ginga import ImageView\n'), ((2219, 2227), 'bokeh.plotting.curdoc', 'curdoc', ([], {}), '()\n', (2225, 2227), False, 'from bokeh.plotting import curdoc\n'), ((2428, 2457), 'ginga.canvas.render.get_render_class', 'render.get_render_class', (['name'], {}), '(name)\n', (2451, 2457), False, 'from ginga.canvas import render\n'), ((3553, 3568), 'numpy.flipud', 'np.flipud', (['data'], {}), '(data)\n', (3562, 3568), True, 'import numpy as np\n'), ((4993, 5004), 'time.time', 'time.time', ([], {}), '()\n', (5002, 5004), False, 'import time\n'), ((14529, 14558), 'ginga.Mixins.UIMixin.__init__', 'Mixins.UIMixin.__init__', (['self'], {}), '(self)\n', (14552, 14558), False, 'from ginga import Mixins, Bindings\n'), ((3705, 3740), 'bokeh.models.ColumnDataSource', 'ColumnDataSource', (["{'image': [data]}"], {}), "({'image': [data]})\n", (3721, 3740), False, 'from bokeh.models import ColumnDataSource\n'), ((4689, 4700), 'time.time', 'time.time', ([], {}), '()\n', (4698, 4700), False, 'import time\n'), ((4538, 4570), 'bokeh.io.push_notebook', 'push_notebook', (['self._push_handle'], {}), '(self._push_handle)\n', (4551, 4570), False, 'from bokeh.io import push_notebook\n'), ((5502, 5513), 'time.time', 'time.time', ([], {}), '()\n', (5511, 5513), False, 'import time\n')] |
# Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
# SPDX-License-Identifier: MIT
"""Contains helper functions that can be used across the example apps."""
import os
import errno
from pathlib import Path
import numpy as np
import pyarmnn as ann
def dict_labels(labels_file_path: str, include_rgb=False) -> dict:
"""Creates a dictionary of labels from the input labels file.
Args:
labels_file: Path to file containing labels to map model outputs.
include_rgb: Adds randomly generated RGB values to the values of the
dictionary. Used for plotting bounding boxes of different colours.
Returns:
Dictionary with classification indices for keys and labels for values.
Raises:
FileNotFoundError:
Provided `labels_file_path` does not exist.
"""
labels_file = Path(labels_file_path)
if not labels_file.is_file():
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), labels_file_path
)
labels = {}
with open(labels_file, "r") as f:
for idx, line in enumerate(f, 0):
if include_rgb:
labels[idx] = line.strip("\n"), tuple(np.random.random(size=3) * 255)
else:
labels[idx] = line.strip("\n")
return labels
def prepare_input_tensors(audio_data, input_binding_info, mfcc_preprocessor):
"""
Takes a block of audio data, extracts the MFCC features, quantizes the array, and uses ArmNN to create the
input tensors.
Args:
audio_data: The audio data to process
mfcc_instance: the mfcc class instance
input_binding_info: the model input binding info
mfcc_preprocessor: the mfcc preprocessor instance
Returns:
input_tensors: the prepared input tensors, ready to be consumed by the ArmNN NetworkExecutor
"""
data_type = input_binding_info[1].GetDataType()
input_tensor = mfcc_preprocessor.extract_features(audio_data)
if data_type != ann.DataType_Float32:
input_tensor = quantize_input(input_tensor, input_binding_info)
input_tensors = ann.make_input_tensors([input_binding_info], [input_tensor])
return input_tensors
def quantize_input(data, input_binding_info):
"""Quantize the float input to (u)int8 ready for inputting to model."""
if data.ndim != 2:
raise RuntimeError("Audio data must have 2 dimensions for quantization")
quant_scale = input_binding_info[1].GetQuantizationScale()
quant_offset = input_binding_info[1].GetQuantizationOffset()
data_type = input_binding_info[1].GetDataType()
if data_type == ann.DataType_QAsymmS8:
data_type = np.int8
elif data_type == ann.DataType_QAsymmU8:
data_type = np.uint8
else:
raise ValueError("Could not quantize data to required data type")
d_min = np.iinfo(data_type).min
d_max = np.iinfo(data_type).max
for row in range(data.shape[0]):
for col in range(data.shape[1]):
data[row, col] = (data[row, col] / quant_scale) + quant_offset
data[row, col] = np.clip(data[row, col], d_min, d_max)
data = data.astype(data_type)
return data
def dequantize_output(data, output_binding_info):
"""Dequantize the (u)int8 output to float"""
if output_binding_info[1].IsQuantized():
if data.ndim != 2:
raise RuntimeError("Data must have 2 dimensions for quantization")
quant_scale = output_binding_info[1].GetQuantizationScale()
quant_offset = output_binding_info[1].GetQuantizationOffset()
data = data.astype(float)
for row in range(data.shape[0]):
for col in range(data.shape[1]):
data[row, col] = (data[row, col] - quant_offset)*quant_scale
return data
| [
"pyarmnn.make_input_tensors",
"numpy.iinfo",
"numpy.clip",
"pathlib.Path",
"numpy.random.random",
"os.strerror"
] | [((854, 876), 'pathlib.Path', 'Path', (['labels_file_path'], {}), '(labels_file_path)\n', (858, 876), False, 'from pathlib import Path\n'), ((2134, 2194), 'pyarmnn.make_input_tensors', 'ann.make_input_tensors', (['[input_binding_info]', '[input_tensor]'], {}), '([input_binding_info], [input_tensor])\n', (2156, 2194), True, 'import pyarmnn as ann\n'), ((2872, 2891), 'numpy.iinfo', 'np.iinfo', (['data_type'], {}), '(data_type)\n', (2880, 2891), True, 'import numpy as np\n'), ((2908, 2927), 'numpy.iinfo', 'np.iinfo', (['data_type'], {}), '(data_type)\n', (2916, 2927), True, 'import numpy as np\n'), ((970, 995), 'os.strerror', 'os.strerror', (['errno.ENOENT'], {}), '(errno.ENOENT)\n', (981, 995), False, 'import os\n'), ((3115, 3152), 'numpy.clip', 'np.clip', (['data[row, col]', 'd_min', 'd_max'], {}), '(data[row, col], d_min, d_max)\n', (3122, 3152), True, 'import numpy as np\n'), ((1203, 1227), 'numpy.random.random', 'np.random.random', ([], {'size': '(3)'}), '(size=3)\n', (1219, 1227), True, 'import numpy as np\n')] |
from copy import deepcopy
import numpy as np
import libs.state_node as STTREE
class IterativeDeepeningSearch:
def __init__(self, initialPuzzle, answerPuzzle, totalExpansions=0):
self.totalExpansions = totalExpansions
self.initialPuzzle = initialPuzzle
self.answerPuzzle = answerPuzzle
self.frontier = []
self.frontier.append(
(STTREE.StateNode(initialPuzzle.puzzle, initialPuzzle.n), 0, 0)
)
def checkNodeSolution(self, nodePuzzle):
return np.array_equal(nodePuzzle, self.answerPuzzle.puzzle)
def insertNodeToFrontier(self, node, actualCost, actualLevel):
# If the node action exists and it's not already included in the tree
if node:
self.frontier.append((node, actualCost + 1, actualLevel + 1))
def execute(self):
actualMaxLevel = 0
while True:
while len(self.frontier) > 0:
# Make the actual level infinite so the while can take effect
actualLevel = float("inf")
while actualLevel > actualMaxLevel and len(self.frontier) > 0:
actualNode, actualCost, actualLevel = self.frontier.pop()
if actualLevel <= actualMaxLevel:
if self.checkNodeSolution(actualNode.puzzle):
return actualNode, self.totalExpansions, actualCost
else:
actualNode.expand()
self.totalExpansions += 1
# Inverted the insert logic, so it becomes a stack
self.insertNodeToFrontier(
actualNode.right, actualCost, actualLevel
)
self.insertNodeToFrontier(
actualNode.left, actualCost, actualLevel
)
self.insertNodeToFrontier(
actualNode.down, actualCost, actualLevel
)
self.insertNodeToFrontier(
actualNode.up, actualCost, actualLevel
)
# If no answer has been found on actual maximum level, try again with +1 level
actualMaxLevel += 1
# Restarts the search from the first state
self.__init__(
deepcopy(self.initialPuzzle),
deepcopy(self.answerPuzzle),
self.totalExpansions,
)
| [
"numpy.array_equal",
"copy.deepcopy",
"libs.state_node.StateNode"
] | [((521, 573), 'numpy.array_equal', 'np.array_equal', (['nodePuzzle', 'self.answerPuzzle.puzzle'], {}), '(nodePuzzle, self.answerPuzzle.puzzle)\n', (535, 573), True, 'import numpy as np\n'), ((387, 442), 'libs.state_node.StateNode', 'STTREE.StateNode', (['initialPuzzle.puzzle', 'initialPuzzle.n'], {}), '(initialPuzzle.puzzle, initialPuzzle.n)\n', (403, 442), True, 'import libs.state_node as STTREE\n'), ((2397, 2425), 'copy.deepcopy', 'deepcopy', (['self.initialPuzzle'], {}), '(self.initialPuzzle)\n', (2405, 2425), False, 'from copy import deepcopy\n'), ((2443, 2470), 'copy.deepcopy', 'deepcopy', (['self.answerPuzzle'], {}), '(self.answerPuzzle)\n', (2451, 2470), False, 'from copy import deepcopy\n')] |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import os
import random
import numpy as np
from ruamel.yaml import YAML
import torch
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def set_random_seed(seed):
assert isinstance(
seed, int
), 'Expected "seed" to be an integer, but it is "{}".'.format(type(seed))
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def makedirs(directory, exist_ok=False):
"""A method that replicates the functionality of os.makedirs that works for both Python 2 and Python 3."""
if os.path.exists(directory):
assert exist_ok, 'Specified directory "{}" already exists.'.format(directory)
else:
os.makedirs(directory)
return
def is_ndds_dataset(input_dir, data_extension="json"):
# Input argument handling
# Expand user shortcut if it exists
input_dir = os.path.expanduser(input_dir)
assert os.path.exists(
input_dir
), 'Expected path "{}" to exist, but it does not.'.format(input_dir)
assert isinstance(
data_extension, str
), 'Expected "data_extension" to be a string, but it is "{}".'.format(
type(data_extension)
)
data_full_ext = "." + data_extension
dirlist = os.listdir(input_dir)
# Find json files
data_filenames = [f for f in dirlist if f.endswith(data_full_ext)]
# Extract name from json file
data_names = [os.path.splitext(f)[0] for f in data_filenames if f[0].isdigit()]
is_ndds_dataset = True if data_names else False
return is_ndds_dataset
def find_ndds_data_in_dir(
input_dir,
data_extension="json",
image_extension="png",
predictive=False,
requested_image_types="all",
):
# Input argument handling
# Expand user shortcut if it exists
input_dir = os.path.expanduser(input_dir)
assert os.path.exists(
input_dir
), 'Expected path "{}" to exist, but it does not.'.format(input_dir)
assert isinstance(
data_extension, str
), 'Expected "data_extension" to be a string, but it is "{}".'.format(
type(data_extension)
)
assert isinstance(
image_extension, str
), 'Expected "image_extension" to be a string, but it is "{}".'.format(
type(image_extension)
)
assert (
requested_image_types is None
or requested_image_types == "all"
or isinstance(requested_image_types, list)
), "Expected \"requested_image_types\" to be None, 'all', or a list of requested_image_types."
data_full_ext = "." + data_extension
image_full_ext = "." + image_extension
dirlist = os.listdir(input_dir)
# Read in json files
data_filenames = [f for f in dirlist if f.endswith(data_full_ext)]
# Sort candidate data files by name
data_filenames.sort()
data_names = [os.path.splitext(f)[0] for f in data_filenames if f[0].isdigit()]
# If there are no matching json files -- this is not an NDDS dataset -- return None
if not data_names:
return None, None
data_paths = [os.path.join(input_dir, f) for f in data_filenames if f[0].isdigit()]
if requested_image_types == "all":
# Detect based on first entry
first_entry_name = data_names[0]
matching_image_names = [
f
for f in dirlist
if f.startswith(first_entry_name) and f.endswith(image_full_ext)
]
find_rgb = (
True
if first_entry_name + ".rgb" + image_full_ext in matching_image_names
else False
)
find_depth = (
True
if first_entry_name + ".depth" + image_full_ext in matching_image_names
else False
)
find_cs = (
True
if first_entry_name + ".cs" + image_full_ext in matching_image_names
else False
)
if len(matching_image_names) > 3:
print("Image types detected that are not yet implemented in this function.")
elif requested_image_types:
# Check based on known data types
known_image_types = ["rgb", "depth", "cs"]
for this_image_type in requested_image_types:
assert (
this_image_type in known_image_types
), 'Image type "{}" not recognized.'.format(this_image_type)
find_rgb = True if "rgb" in requested_image_types else False
find_depth = True if "depth" in requested_image_types else False
find_cs = True if "cs" in requested_image_types else False
else:
find_rgb = False
find_depth = False
find_cs = False
dict_of_lists_images = {}
n_samples = len(data_names)
if find_rgb:
rgb_paths = [
os.path.join(input_dir, f + ".rgb" + image_full_ext) for f in data_names
]
for n in range(n_samples):
assert os.path.exists(
rgb_paths[n]
), 'Expected image "{}" to exist, but it does not.'.format(rgb_paths[n])
dict_of_lists_images["rgb"] = rgb_paths
if find_depth:
depth_paths = [
os.path.join(input_dir, f + ".depth" + image_full_ext) for f in data_names
]
for n in range(n_samples):
assert os.path.exists(
depth_paths[n]
), 'Expected image "{}" to exist, but it does not.'.format(depth_paths[n])
dict_of_lists_images["depth"] = depth_paths
if find_cs:
cs_paths = [
os.path.join(input_dir, f + ".cs" + image_full_ext) for f in data_names
]
for n in range(n_samples):
assert os.path.exists(
cs_paths[n]
), 'Expected image "{}" to exist, but it does not.'.format(cs_paths[n])
dict_of_lists_images["class_segmentation"] = cs_paths
found_images = [
dict(zip(dict_of_lists_images, t)) for t in zip(*dict_of_lists_images.values())
]
# Create output dictionaries
dict_of_lists = {"name": data_names, "data_path": data_paths}
if find_rgb or find_depth or find_cs:
dict_of_lists["image_paths"] = found_images
found_data = [dict(zip(dict_of_lists, t)) for t in zip(*dict_of_lists.values())]
# Process config files, which are data files that don't have an associated image
found_configs = {"camera": None, "object": None, "unsorted": []}
data_filenames_without_images = [f for f in data_filenames if not f[0].isdigit()]
for data_filename in data_filenames_without_images:
if data_filename == "_camera_settings" + data_full_ext:
found_configs["camera"] = os.path.join(input_dir, data_filename)
elif data_filename == "_object_settings" + data_full_ext:
found_configs["object"] = os.path.join(input_dir, data_filename)
else:
found_configs["unsorted"].append(os.path.join(input_dir, data_filename))
return found_data, found_configs
def load_camera_intrinsics(camera_data_path):
# Input argument handling
assert os.path.exists(
camera_data_path
), 'Expected path "{}" to exist, but it does not.'.format(camera_data_path)
# Create YAML/json parser
data_parser = YAML(typ="safe")
with open(camera_data_path, "r") as f:
cam_settings_data = data_parser.load(f)
camera_fx = cam_settings_data["camera_settings"][0]["intrinsic_settings"]["fx"]
camera_fy = cam_settings_data["camera_settings"][0]["intrinsic_settings"]["fy"]
camera_cx = cam_settings_data["camera_settings"][0]["intrinsic_settings"]["cx"]
camera_cy = cam_settings_data["camera_settings"][0]["intrinsic_settings"]["cy"]
camera_K = np.array(
[[camera_fx, 0.0, camera_cx], [0.0, camera_fy, camera_cy], [0.0, 0.0, 1.0]]
)
return camera_K
def load_image_resolution(camera_data_path):
# Input argument handling
assert os.path.exists(
camera_data_path
), 'Expected path "{}" to exist, but it does not.'.format(camera_data_path)
# Create YAML/json parser
data_parser = YAML(typ="safe")
with open(camera_data_path, "r") as f:
cam_settings_data = data_parser.load(f)
image_width = cam_settings_data["camera_settings"][0]["captured_image_size"][
"width"
]
image_height = cam_settings_data["camera_settings"][0]["captured_image_size"][
"height"
]
image_resolution = (image_width, image_height)
return image_resolution
def load_keypoints(data_path, object_name, keypoint_names):
assert os.path.exists(
data_path
), 'Expected data_path "{}" to exist, but it does not.'.format(data_path)
# Set up output structure
keypoint_data = {"positions_wrt_cam": [], "projections": []}
# Load keypoints for a particular object for now
parser = YAML(typ="safe")
with open(data_path, "r") as f:
data = parser.load(f)
assert (
"objects" in data.keys()
), 'Expected "objects" key to exist in data file, but it does not.'
object_names = [o["class"] for o in data["objects"]]
assert (
object_name in object_names
), 'Requested object_name "{}" does not exist in the data file objects.'.format(
object_name
)
idx_object = object_names.index(object_name)
object_data = data["objects"][idx_object]
object_keypoints = object_data["keypoints"]
object_keypoint_names = [kp["name"] for kp in object_keypoints]
# Process in same order as keypoint_names to retain same order
for kp_name in keypoint_names:
assert (
kp_name in object_keypoint_names
), "Expected keypoint '{}' to exist in the data file '{}', but it does not. Rather, the keypoints are '{}'".format(
kp_name, data_path, object_keypoint_names
)
idx_kp = object_keypoint_names.index(kp_name)
kp_data = object_keypoints[idx_kp]
kp_position_wrt_cam = kp_data["location"]
kp_projection = kp_data["projected_location"]
keypoint_data["positions_wrt_cam"].append(kp_position_wrt_cam)
keypoint_data["projections"].append(kp_projection)
return keypoint_data
| [
"numpy.random.seed",
"os.makedirs",
"os.path.join",
"torch.manual_seed",
"torch.cuda.manual_seed",
"os.path.exists",
"ruamel.yaml.YAML",
"torch.cuda.manual_seed_all",
"random.seed",
"numpy.array",
"os.path.splitext",
"os.path.expanduser",
"os.listdir"
] | [((500, 517), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (511, 517), False, 'import random\n'), ((567, 587), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (581, 587), True, 'import numpy as np\n'), ((592, 615), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (609, 615), False, 'import torch\n'), ((620, 648), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (642, 648), False, 'import torch\n'), ((653, 685), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (679, 685), False, 'import torch\n'), ((936, 961), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (950, 961), False, 'import os\n'), ((1245, 1274), 'os.path.expanduser', 'os.path.expanduser', (['input_dir'], {}), '(input_dir)\n', (1263, 1274), False, 'import os\n'), ((1286, 1311), 'os.path.exists', 'os.path.exists', (['input_dir'], {}), '(input_dir)\n', (1300, 1311), False, 'import os\n'), ((1611, 1632), 'os.listdir', 'os.listdir', (['input_dir'], {}), '(input_dir)\n', (1621, 1632), False, 'import os\n'), ((2170, 2199), 'os.path.expanduser', 'os.path.expanduser', (['input_dir'], {}), '(input_dir)\n', (2188, 2199), False, 'import os\n'), ((2211, 2236), 'os.path.exists', 'os.path.exists', (['input_dir'], {}), '(input_dir)\n', (2225, 2236), False, 'import os\n'), ((2987, 3008), 'os.listdir', 'os.listdir', (['input_dir'], {}), '(input_dir)\n', (2997, 3008), False, 'import os\n'), ((7376, 7408), 'os.path.exists', 'os.path.exists', (['camera_data_path'], {}), '(camera_data_path)\n', (7390, 7408), False, 'import os\n'), ((7546, 7562), 'ruamel.yaml.YAML', 'YAML', ([], {'typ': '"""safe"""'}), "(typ='safe')\n", (7550, 7562), False, 'from ruamel.yaml import YAML\n'), ((8007, 8097), 'numpy.array', 'np.array', (['[[camera_fx, 0.0, camera_cx], [0.0, camera_fy, camera_cy], [0.0, 0.0, 1.0]]'], {}), '([[camera_fx, 0.0, camera_cx], [0.0, camera_fy, camera_cy], [0.0, \n 0.0, 1.0]])\n', (8015, 8097), True, 'import numpy as np\n'), ((8217, 8249), 'os.path.exists', 'os.path.exists', (['camera_data_path'], {}), '(camera_data_path)\n', (8231, 8249), False, 'import os\n'), ((8387, 8403), 'ruamel.yaml.YAML', 'YAML', ([], {'typ': '"""safe"""'}), "(typ='safe')\n", (8391, 8403), False, 'from ruamel.yaml import YAML\n'), ((8860, 8885), 'os.path.exists', 'os.path.exists', (['data_path'], {}), '(data_path)\n', (8874, 8885), False, 'import os\n'), ((9135, 9151), 'ruamel.yaml.YAML', 'YAML', ([], {'typ': '"""safe"""'}), "(typ='safe')\n", (9139, 9151), False, 'from ruamel.yaml import YAML\n'), ((1067, 1089), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (1078, 1089), False, 'import os\n'), ((3415, 3441), 'os.path.join', 'os.path.join', (['input_dir', 'f'], {}), '(input_dir, f)\n', (3427, 3441), False, 'import os\n'), ((1780, 1799), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (1796, 1799), False, 'import os\n'), ((3192, 3211), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (3208, 3211), False, 'import os\n'), ((5098, 5150), 'os.path.join', 'os.path.join', (['input_dir', "(f + '.rgb' + image_full_ext)"], {}), "(input_dir, f + '.rgb' + image_full_ext)\n", (5110, 5150), False, 'import os\n'), ((5235, 5263), 'os.path.exists', 'os.path.exists', (['rgb_paths[n]'], {}), '(rgb_paths[n])\n', (5249, 5263), False, 'import os\n'), ((5469, 5523), 'os.path.join', 'os.path.join', (['input_dir', "(f + '.depth' + image_full_ext)"], {}), "(input_dir, f + '.depth' + image_full_ext)\n", (5481, 5523), False, 'import os\n'), ((5608, 5638), 'os.path.exists', 'os.path.exists', (['depth_paths[n]'], {}), '(depth_paths[n])\n', (5622, 5638), False, 'import os\n'), ((5844, 5895), 'os.path.join', 'os.path.join', (['input_dir', "(f + '.cs' + image_full_ext)"], {}), "(input_dir, f + '.cs' + image_full_ext)\n", (5856, 5895), False, 'import os\n'), ((5980, 6007), 'os.path.exists', 'os.path.exists', (['cs_paths[n]'], {}), '(cs_paths[n])\n', (5994, 6007), False, 'import os\n'), ((6967, 7005), 'os.path.join', 'os.path.join', (['input_dir', 'data_filename'], {}), '(input_dir, data_filename)\n', (6979, 7005), False, 'import os\n'), ((7110, 7148), 'os.path.join', 'os.path.join', (['input_dir', 'data_filename'], {}), '(input_dir, data_filename)\n', (7122, 7148), False, 'import os\n'), ((7208, 7246), 'os.path.join', 'os.path.join', (['input_dir', 'data_filename'], {}), '(input_dir, data_filename)\n', (7220, 7246), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pickle
import datetime
import argparse
import re
import glob
from obj.RBM import RBM
import tensorflow as tf
import numpy as np
import matplotlib.image as mpimg
from skimage.transform import resize
################################
# train RBM from input data
################################
def trainRBM(data, learning_rate, k1, k2, epochs, batch_size, dims):
# import data
print("importing training data")
if data == "fashion_mnist":
fashion_mnist = tf.keras.datasets.fashion_mnist
(x_train, _), (_,_) = fashion_mnist.load_data()
elif data == "mnist":
mnist = tf.keras.datasets.mnist
(x_train, _), (_,_) = mnist.load_data()
elif data == "faces":
x_train = [resize(mpimg.imread(file),(28,28)) for file in glob.glob("data/faces/*")]
x_train = np.asarray(x_train)
# make images sparse for easier distinctions
for img in x_train:
img[img < np.mean(img)+0.5*np.std(img)] = 0
else:
raise NameError("unknown data type: %s" % data)
if data == "mnist" or data == "fashion_mnist":
x_train = x_train/255.0
x_train = [tf.cast(tf.reshape(x,shape=(784,1)),"float32") for x in x_train]
elif data == "faces":
# auto conversion to probabilities in earlier step
x_train = [tf.cast(tf.reshape(x,shape=(784,1)),"float32") for x in x_train]
# create log directory
current_time = getCurrentTime()+"_"+re.sub(",","_",dims)+"_"+data+"_rbm"
os.makedirs("pickles/"+current_time)
# parse string input into integer list
dims = [int(el) for el in dims.split(",")]
rbm = RBM(dims[0], dims[1], learning_rate, k1, k2, epochs, batch_size)
rbm.persistive_contrastive_divergence_k(x_train)
# dump rbm pickle
f = open("pickles/"+current_time+"/rbm.pickle", "wb")
pickle.dump(rbm, f, protocol=pickle.HIGHEST_PROTOCOL)
f.close()
def getCurrentTime():
return datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
####################################
# main command call
####################################
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default="mnist",
help="data source to train RBM, possibilities are 'mnist', 'fashion_mnist' and 'faces' <default: 'mnist'>")
parser.add_argument("--learning-rate", type=float, default=0.01,
help="learning rate for stacked RBMs <default: 0.01>")
parser.add_argument("--k1", type=int, default=1,
help="number of Gibbs-sampling steps pre-PCD-k algorithm <default: 1>")
parser.add_argument("--k2", type=int, default=5,
help="number of Gibbs-sampling steps during PCD-k algorithm <default: 5>")
parser.add_argument("--epochs", type=int, default=1,
help="number of overall training data passes for each RBM <default: 1>")
parser.add_argument("--batch-size", type=int, default=5,
help="size of training data batches <default: 5>")
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-d', '--dimensions', type=str,
help="consecutive enumeration of visible and hidden units separated by a comma character, eg. 784,500",
required=True)
args = parser.parse_args()
# train RBM based on parameters
trainRBM(args.data,args.learning_rate,args.k1,args.k2,args.epochs,args.batch_size,args.dimensions) | [
"pickle.dump",
"matplotlib.image.imread",
"os.makedirs",
"argparse.ArgumentParser",
"numpy.std",
"numpy.asarray",
"tensorflow.reshape",
"obj.RBM.RBM",
"numpy.mean",
"glob.glob",
"datetime.datetime.now",
"re.sub"
] | [((1545, 1583), 'os.makedirs', 'os.makedirs', (["('pickles/' + current_time)"], {}), "('pickles/' + current_time)\n", (1556, 1583), False, 'import os\n'), ((1682, 1746), 'obj.RBM.RBM', 'RBM', (['dims[0]', 'dims[1]', 'learning_rate', 'k1', 'k2', 'epochs', 'batch_size'], {}), '(dims[0], dims[1], learning_rate, k1, k2, epochs, batch_size)\n', (1685, 1746), False, 'from obj.RBM import RBM\n'), ((1884, 1937), 'pickle.dump', 'pickle.dump', (['rbm', 'f'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(rbm, f, protocol=pickle.HIGHEST_PROTOCOL)\n', (1895, 1937), False, 'import pickle\n'), ((2176, 2201), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2199, 2201), False, 'import argparse\n'), ((1986, 2009), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2007, 2009), False, 'import datetime\n'), ((878, 897), 'numpy.asarray', 'np.asarray', (['x_train'], {}), '(x_train)\n', (888, 897), True, 'import numpy as np\n'), ((1211, 1240), 'tensorflow.reshape', 'tf.reshape', (['x'], {'shape': '(784, 1)'}), '(x, shape=(784, 1))\n', (1221, 1240), True, 'import tensorflow as tf\n'), ((1380, 1409), 'tensorflow.reshape', 'tf.reshape', (['x'], {'shape': '(784, 1)'}), '(x, shape=(784, 1))\n', (1390, 1409), True, 'import tensorflow as tf\n'), ((1504, 1526), 're.sub', 're.sub', (['""","""', '"""_"""', 'dims'], {}), "(',', '_', dims)\n", (1510, 1526), False, 'import re\n'), ((793, 811), 'matplotlib.image.imread', 'mpimg.imread', (['file'], {}), '(file)\n', (805, 811), True, 'import matplotlib.image as mpimg\n'), ((833, 858), 'glob.glob', 'glob.glob', (['"""data/faces/*"""'], {}), "('data/faces/*')\n", (842, 858), False, 'import glob\n'), ((1001, 1013), 'numpy.mean', 'np.mean', (['img'], {}), '(img)\n', (1008, 1013), True, 'import numpy as np\n'), ((1018, 1029), 'numpy.std', 'np.std', (['img'], {}), '(img)\n', (1024, 1029), True, 'import numpy as np\n')] |
import losses.triplet_loss as l
import numpy as np
import scipy.spatial as sp
import torch
from torch.autograd import Variable
from losses.triplet_loss import topk, active
from losses.multi_loss import LinearWeightedLoss, WeightModule, MultiLoss, DynamicFocalLoss, DynamicFocalLossModule
from losses.regression import MSELoss, L1Loss, L2Loss
from dataflow import DataFlowConfig, DataFlowController
from losses.dummy import DummyLoss
import pytest
def test_cdist_different():
a = np.random.randn(10, 20)
b = np.random.randn(30, 20)
for metric in ('euclidean', 'sqeuclidean', 'cityblock'):
D_my = l.calc_cdist(torch.from_numpy(a), torch.from_numpy(b), metric).numpy()
D_sp = sp.distance.cdist(a, b, metric)
np.testing.assert_allclose(D_my, D_sp, rtol=1e-5, atol=1e-5)
def test_cdist_same():
a = np.random.randn(10, 20)
for metric in ('euclidean', 'sqeuclidean', 'cityblock'):
D_my = l.calc_cdist(torch.from_numpy(a), torch.from_numpy(a), metric).numpy()
D_sp = sp.distance.cdist(a, a, metric)
np.testing.assert_allclose(D_my, D_sp, rtol=1e-5, atol=1e-5)
def test_active():
x = np.array([0.1, 0.0, 0.3, 1, 0.4])
x = torch.from_numpy(x)
a = active(x)
assert a == 4/5
@pytest.mark.parametrize("cuda", [True, False])
def test_batch_hard(cuda):
pids = np.array([0, 0, 1, 0, 1, 1], dtype=np.float32)
features = np.array([
[5.0],
[6.0],
[1.0],
[7.0],
[9.5],
[1.0]
], np.float32)
pids = Variable(torch.from_numpy(pids))
data = {'pid': pids}
features = torch.from_numpy(features)
if cuda:
features = features.cuda()
features = Variable(features)
loss_fn = l.BatchHard("none")
endpoints = {"triplet": [features]}
loss = loss_fn(endpoints, data)
result = np.array([2.0 - 4.0, 1.0 - 3.5, 8.5 - 4.0, 2.0 - 2.5, 8.5 - 2.5, 8.5 - 4.0], dtype=np.float32)
if cuda:
loss = loss.data.cpu().numpy()
else:
loss = loss.data.numpy()
np.testing.assert_array_equal(result, loss)
def test_topk():
pids = np.array([0, 0, 1, 0, 1], dtype=np.float32)
features = np.array([
[5.0],
[6.0],
[1.0],
[7.0],
[9.5],
], np.float32)
pids = Variable(torch.from_numpy(pids))
features = Variable(torch.from_numpy(features))
cdist = l.calc_cdist(features, features)
topks = topk(cdist, pids, 4)
np.testing.assert_almost_equal(topks[0], 3/5)
np.testing.assert_almost_equal(topks[1], 3/5)
np.testing.assert_almost_equal(topks[2], 3/5)
np.testing.assert_almost_equal(topks[3], 5/5)
def test_weighted_loss():
endpoint_name = "dummy"
weight = LinearWeightedLoss(0.5, DummyLoss())
losses = {"loss1": weight, "loss2": weight}
linear_weighted_loss = WeightModule(losses)
features_np = np.array([
[5.0],
[6.0],
[1.0],
[7.0],
[9.5],
], np.float32)
features = torch.from_numpy(features_np)
endpoints = {endpoint_name: [features]}
split_endpoints = {"loss1": endpoints, "loss2": endpoints}
split_data = {"loss1": None, "loss2": None}
loss = linear_weighted_loss(split_endpoints, split_data)
np.testing.assert_array_equal(loss, np.sum(features_np))
def test_dynamic_focal_loss():
endpoint_name = "dummy"
weight = DynamicFocalLoss(1, 1, 1e-6, DummyLoss(), "dynamic")
id_loss =("loss1", weight)
tr_loss = ("loss2", weight)
dynamic_focal_loss = DynamicFocalLossModule(0, tr_loss, id_loss)
split_data = {"loss1": None, "loss2": None}
for i in range(10):
features = np.random.rand(10, 1) * 10
features = features.astype(np.float32)
features = torch.from_numpy(features)
endpoints = {endpoint_name: [features]}
split_endpoints = {"loss1": endpoints, "loss2": endpoints}
loss = dynamic_focal_loss(split_endpoints, split_data)
test_cfgs = [
DataFlowConfig("dummy1", "loss"),
DataFlowConfig("dummy2", "loss"),
DataFlowConfig("all", "loss"),
DataFlowConfig(["dummy1", "dummy2"], "loss")
]
@pytest.mark.parametrize("cfg", test_cfgs)
def test_multi_loss(cfg):
head = "dummy"
weight = LinearWeightedLoss(1, DummyLoss())
losses = {"loss": weight}
linear_weighted_loss = WeightModule(losses)
data_controller = DataFlowController([cfg])
multi_loss = MultiLoss(linear_weighted_loss, data_controller)
features_np = np.array([
[5.0],
[6.0],
[1.0],
[7.0],
[9.5],
], np.float32)
features = torch.from_numpy(features_np)
endpoints = {head: [features]}
idxs1 = [0, 1, 2]
idxs2 = [3, 4]
dataset1 = "dummy1"
dataset2 = "dummy2"
split_info = {
dataset1: idxs1,
dataset2: idxs2
}
data = {'split_info': split_info}
loss = multi_loss(endpoints, data)
if cfg.targets[0] == "all":
np.testing.assert_array_equal(loss, np.sum(features_np))
else:
correct = 0
for d in cfg.targets:
idxs = split_info[d]
correct += features[idxs].sum()
print(loss, correct)
np.testing.assert_array_equal(loss, correct)
def n2t(array):
return torch.from_numpy(array)
def test_mse_loss():
loss = MSELoss('l2', 'target')
l2 = np.array(
[[1.0, 0.0],
[0.0, 1.0],
[1.0, 1.0],
[0.0, 0.0]], dtype=np.float32)
endpoints = {'l2': n2t(l2)}
target = np.array(
[[0.0, 0.0],
[1.0, 1.0],
[np.nan, np.nan],
[0.0, 0.0]], dtype=np.float32)
data = {'target': n2t(target)}
result = loss(endpoints, data)
np.testing.assert_array_equal(result.numpy(), np.array(2/6, dtype=np.float32))
def test_l2_loss():
loss = L2Loss('l2', 'target')
l2 = np.array(
[[[1.0, 0.0],
[0.0, 1.0],
[1.0, 1.0],
[0.0, 0.0]]], dtype=np.float32)
endpoints = {'l2': n2t(l2)}
target = np.array(
[[[0.0, 0.0],
[1.0, 1.0],
[np.nan, np.nan],
[0.0, 0.0]]], dtype=np.float32)
data = {'target': n2t(target)}
result = loss(endpoints, data)
np.testing.assert_array_equal(result.numpy(), np.array(2/3, dtype=np.float32))
from losses.softmax import get_topk_percent
def test_get_topk_percent():
tensor = torch.tensor([[[4, 3, 8, 2], [8, 5, 1, -1]]])
values, indices = get_topk_percent(tensor, 0.5)
np.testing.assert_array_equal(values.numpy(), np.array([[8, 8, 5, 4]]))
| [
"numpy.sum",
"losses.multi_loss.DynamicFocalLossModule",
"pytest.mark.parametrize",
"losses.regression.MSELoss",
"numpy.random.randn",
"numpy.random.rand",
"numpy.testing.assert_almost_equal",
"dataflow.DataFlowController",
"losses.triplet_loss.BatchHard",
"losses.dummy.DummyLoss",
"losses.tripl... | [((1255, 1301), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""cuda"""', '[True, False]'], {}), "('cuda', [True, False])\n", (1278, 1301), False, 'import pytest\n'), ((4143, 4184), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""cfg"""', 'test_cfgs'], {}), "('cfg', test_cfgs)\n", (4166, 4184), False, 'import pytest\n'), ((485, 508), 'numpy.random.randn', 'np.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (500, 508), True, 'import numpy as np\n'), ((517, 540), 'numpy.random.randn', 'np.random.randn', (['(30)', '(20)'], {}), '(30, 20)\n', (532, 540), True, 'import numpy as np\n'), ((837, 860), 'numpy.random.randn', 'np.random.randn', (['(10)', '(20)'], {}), '(10, 20)\n', (852, 860), True, 'import numpy as np\n'), ((1152, 1185), 'numpy.array', 'np.array', (['[0.1, 0.0, 0.3, 1, 0.4]'], {}), '([0.1, 0.0, 0.3, 1, 0.4])\n', (1160, 1185), True, 'import numpy as np\n'), ((1194, 1213), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (1210, 1213), False, 'import torch\n'), ((1222, 1231), 'losses.triplet_loss.active', 'active', (['x'], {}), '(x)\n', (1228, 1231), False, 'from losses.triplet_loss import topk, active\n'), ((1340, 1386), 'numpy.array', 'np.array', (['[0, 0, 1, 0, 1, 1]'], {'dtype': 'np.float32'}), '([0, 0, 1, 0, 1, 1], dtype=np.float32)\n', (1348, 1386), True, 'import numpy as np\n'), ((1402, 1466), 'numpy.array', 'np.array', (['[[5.0], [6.0], [1.0], [7.0], [9.5], [1.0]]', 'np.float32'], {}), '([[5.0], [6.0], [1.0], [7.0], [9.5], [1.0]], np.float32)\n', (1410, 1466), True, 'import numpy as np\n'), ((1606, 1632), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (1622, 1632), False, 'import torch\n'), ((1696, 1714), 'torch.autograd.Variable', 'Variable', (['features'], {}), '(features)\n', (1704, 1714), False, 'from torch.autograd import Variable\n'), ((1730, 1749), 'losses.triplet_loss.BatchHard', 'l.BatchHard', (['"""none"""'], {}), "('none')\n", (1741, 1749), True, 'import losses.triplet_loss as l\n'), ((1840, 1938), 'numpy.array', 'np.array', (['[2.0 - 4.0, 1.0 - 3.5, 8.5 - 4.0, 2.0 - 2.5, 8.5 - 2.5, 8.5 - 4.0]'], {'dtype': 'np.float32'}), '([2.0 - 4.0, 1.0 - 3.5, 8.5 - 4.0, 2.0 - 2.5, 8.5 - 2.5, 8.5 - 4.0],\n dtype=np.float32)\n', (1848, 1938), True, 'import numpy as np\n'), ((2034, 2077), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['result', 'loss'], {}), '(result, loss)\n', (2063, 2077), True, 'import numpy as np\n'), ((2108, 2151), 'numpy.array', 'np.array', (['[0, 0, 1, 0, 1]'], {'dtype': 'np.float32'}), '([0, 0, 1, 0, 1], dtype=np.float32)\n', (2116, 2151), True, 'import numpy as np\n'), ((2167, 2224), 'numpy.array', 'np.array', (['[[5.0], [6.0], [1.0], [7.0], [9.5]]', 'np.float32'], {}), '([[5.0], [6.0], [1.0], [7.0], [9.5]], np.float32)\n', (2175, 2224), True, 'import numpy as np\n'), ((2381, 2413), 'losses.triplet_loss.calc_cdist', 'l.calc_cdist', (['features', 'features'], {}), '(features, features)\n', (2393, 2413), True, 'import losses.triplet_loss as l\n'), ((2426, 2446), 'losses.triplet_loss.topk', 'topk', (['cdist', 'pids', '(4)'], {}), '(cdist, pids, 4)\n', (2430, 2446), False, 'from losses.triplet_loss import topk, active\n'), ((2451, 2498), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['topks[0]', '(3 / 5)'], {}), '(topks[0], 3 / 5)\n', (2481, 2498), True, 'import numpy as np\n'), ((2501, 2548), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['topks[1]', '(3 / 5)'], {}), '(topks[1], 3 / 5)\n', (2531, 2548), True, 'import numpy as np\n'), ((2551, 2598), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['topks[2]', '(3 / 5)'], {}), '(topks[2], 3 / 5)\n', (2581, 2598), True, 'import numpy as np\n'), ((2601, 2648), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['topks[3]', '(5 / 5)'], {}), '(topks[3], 5 / 5)\n', (2631, 2648), True, 'import numpy as np\n'), ((2828, 2848), 'losses.multi_loss.WeightModule', 'WeightModule', (['losses'], {}), '(losses)\n', (2840, 2848), False, 'from losses.multi_loss import LinearWeightedLoss, WeightModule, MultiLoss, DynamicFocalLoss, DynamicFocalLossModule\n'), ((2867, 2924), 'numpy.array', 'np.array', (['[[5.0], [6.0], [1.0], [7.0], [9.5]]', 'np.float32'], {}), '([[5.0], [6.0], [1.0], [7.0], [9.5]], np.float32)\n', (2875, 2924), True, 'import numpy as np\n'), ((2987, 3016), 'torch.from_numpy', 'torch.from_numpy', (['features_np'], {}), '(features_np)\n', (3003, 3016), False, 'import torch\n'), ((3509, 3552), 'losses.multi_loss.DynamicFocalLossModule', 'DynamicFocalLossModule', (['(0)', 'tr_loss', 'id_loss'], {}), '(0, tr_loss, id_loss)\n', (3531, 3552), False, 'from losses.multi_loss import LinearWeightedLoss, WeightModule, MultiLoss, DynamicFocalLoss, DynamicFocalLossModule\n'), ((3966, 3998), 'dataflow.DataFlowConfig', 'DataFlowConfig', (['"""dummy1"""', '"""loss"""'], {}), "('dummy1', 'loss')\n", (3980, 3998), False, 'from dataflow import DataFlowConfig, DataFlowController\n'), ((4008, 4040), 'dataflow.DataFlowConfig', 'DataFlowConfig', (['"""dummy2"""', '"""loss"""'], {}), "('dummy2', 'loss')\n", (4022, 4040), False, 'from dataflow import DataFlowConfig, DataFlowController\n'), ((4050, 4079), 'dataflow.DataFlowConfig', 'DataFlowConfig', (['"""all"""', '"""loss"""'], {}), "('all', 'loss')\n", (4064, 4079), False, 'from dataflow import DataFlowConfig, DataFlowController\n'), ((4089, 4133), 'dataflow.DataFlowConfig', 'DataFlowConfig', (["['dummy1', 'dummy2']", '"""loss"""'], {}), "(['dummy1', 'dummy2'], 'loss')\n", (4103, 4133), False, 'from dataflow import DataFlowConfig, DataFlowController\n'), ((4335, 4355), 'losses.multi_loss.WeightModule', 'WeightModule', (['losses'], {}), '(losses)\n', (4347, 4355), False, 'from losses.multi_loss import LinearWeightedLoss, WeightModule, MultiLoss, DynamicFocalLoss, DynamicFocalLossModule\n'), ((4379, 4404), 'dataflow.DataFlowController', 'DataFlowController', (['[cfg]'], {}), '([cfg])\n', (4397, 4404), False, 'from dataflow import DataFlowConfig, DataFlowController\n'), ((4422, 4470), 'losses.multi_loss.MultiLoss', 'MultiLoss', (['linear_weighted_loss', 'data_controller'], {}), '(linear_weighted_loss, data_controller)\n', (4431, 4470), False, 'from losses.multi_loss import LinearWeightedLoss, WeightModule, MultiLoss, DynamicFocalLoss, DynamicFocalLossModule\n'), ((4489, 4546), 'numpy.array', 'np.array', (['[[5.0], [6.0], [1.0], [7.0], [9.5]]', 'np.float32'], {}), '([[5.0], [6.0], [1.0], [7.0], [9.5]], np.float32)\n', (4497, 4546), True, 'import numpy as np\n'), ((4609, 4638), 'torch.from_numpy', 'torch.from_numpy', (['features_np'], {}), '(features_np)\n', (4625, 4638), False, 'import torch\n'), ((5261, 5284), 'torch.from_numpy', 'torch.from_numpy', (['array'], {}), '(array)\n', (5277, 5284), False, 'import torch\n'), ((5319, 5342), 'losses.regression.MSELoss', 'MSELoss', (['"""l2"""', '"""target"""'], {}), "('l2', 'target')\n", (5326, 5342), False, 'from losses.regression import MSELoss, L1Loss, L2Loss\n'), ((5352, 5428), 'numpy.array', 'np.array', (['[[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]'], {'dtype': 'np.float32'}), '([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]], dtype=np.float32)\n', (5360, 5428), True, 'import numpy as np\n'), ((5526, 5613), 'numpy.array', 'np.array', (['[[0.0, 0.0], [1.0, 1.0], [np.nan, np.nan], [0.0, 0.0]]'], {'dtype': 'np.float32'}), '([[0.0, 0.0], [1.0, 1.0], [np.nan, np.nan], [0.0, 0.0]], dtype=np.\n float32)\n', (5534, 5613), True, 'import numpy as np\n'), ((5848, 5870), 'losses.regression.L2Loss', 'L2Loss', (['"""l2"""', '"""target"""'], {}), "('l2', 'target')\n", (5854, 5870), False, 'from losses.regression import MSELoss, L1Loss, L2Loss\n'), ((5880, 5958), 'numpy.array', 'np.array', (['[[[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]]'], {'dtype': 'np.float32'}), '([[[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]], dtype=np.float32)\n', (5888, 5958), True, 'import numpy as np\n'), ((6056, 6145), 'numpy.array', 'np.array', (['[[[0.0, 0.0], [1.0, 1.0], [np.nan, np.nan], [0.0, 0.0]]]'], {'dtype': 'np.float32'}), '([[[0.0, 0.0], [1.0, 1.0], [np.nan, np.nan], [0.0, 0.0]]], dtype=np\n .float32)\n', (6064, 6145), True, 'import numpy as np\n'), ((6434, 6479), 'torch.tensor', 'torch.tensor', (['[[[4, 3, 8, 2], [8, 5, 1, -1]]]'], {}), '([[[4, 3, 8, 2], [8, 5, 1, -1]]])\n', (6446, 6479), False, 'import torch\n'), ((6502, 6531), 'losses.softmax.get_topk_percent', 'get_topk_percent', (['tensor', '(0.5)'], {}), '(tensor, 0.5)\n', (6518, 6531), False, 'from losses.softmax import get_topk_percent\n'), ((704, 735), 'scipy.spatial.distance.cdist', 'sp.distance.cdist', (['a', 'b', 'metric'], {}), '(a, b, metric)\n', (721, 735), True, 'import scipy.spatial as sp\n'), ((744, 806), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['D_my', 'D_sp'], {'rtol': '(1e-05)', 'atol': '(1e-05)'}), '(D_my, D_sp, rtol=1e-05, atol=1e-05)\n', (770, 806), True, 'import numpy as np\n'), ((1023, 1054), 'scipy.spatial.distance.cdist', 'sp.distance.cdist', (['a', 'a', 'metric'], {}), '(a, a, metric)\n', (1040, 1054), True, 'import scipy.spatial as sp\n'), ((1063, 1125), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['D_my', 'D_sp'], {'rtol': '(1e-05)', 'atol': '(1e-05)'}), '(D_my, D_sp, rtol=1e-05, atol=1e-05)\n', (1089, 1125), True, 'import numpy as np\n'), ((1542, 1564), 'torch.from_numpy', 'torch.from_numpy', (['pids'], {}), '(pids)\n', (1558, 1564), False, 'import torch\n'), ((2293, 2315), 'torch.from_numpy', 'torch.from_numpy', (['pids'], {}), '(pids)\n', (2309, 2315), False, 'import torch\n'), ((2341, 2367), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (2357, 2367), False, 'import torch\n'), ((2740, 2751), 'losses.dummy.DummyLoss', 'DummyLoss', ([], {}), '()\n', (2749, 2751), False, 'from losses.dummy import DummyLoss\n'), ((3273, 3292), 'numpy.sum', 'np.sum', (['features_np'], {}), '(features_np)\n', (3279, 3292), True, 'import numpy as np\n'), ((3397, 3408), 'losses.dummy.DummyLoss', 'DummyLoss', ([], {}), '()\n', (3406, 3408), False, 'from losses.dummy import DummyLoss\n'), ((3737, 3763), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (3753, 3763), False, 'import torch\n'), ((4265, 4276), 'losses.dummy.DummyLoss', 'DummyLoss', ([], {}), '()\n', (4274, 4276), False, 'from losses.dummy import DummyLoss\n'), ((5187, 5231), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['loss', 'correct'], {}), '(loss, correct)\n', (5216, 5231), True, 'import numpy as np\n'), ((5782, 5815), 'numpy.array', 'np.array', (['(2 / 6)'], {'dtype': 'np.float32'}), '(2 / 6, dtype=np.float32)\n', (5790, 5815), True, 'import numpy as np\n'), ((6314, 6347), 'numpy.array', 'np.array', (['(2 / 3)'], {'dtype': 'np.float32'}), '(2 / 3, dtype=np.float32)\n', (6322, 6347), True, 'import numpy as np\n'), ((6582, 6606), 'numpy.array', 'np.array', (['[[8, 8, 5, 4]]'], {}), '([[8, 8, 5, 4]])\n', (6590, 6606), True, 'import numpy as np\n'), ((3644, 3665), 'numpy.random.rand', 'np.random.rand', (['(10)', '(1)'], {}), '(10, 1)\n', (3658, 3665), True, 'import numpy as np\n'), ((4992, 5011), 'numpy.sum', 'np.sum', (['features_np'], {}), '(features_np)\n', (4998, 5011), True, 'import numpy as np\n'), ((631, 650), 'torch.from_numpy', 'torch.from_numpy', (['a'], {}), '(a)\n', (647, 650), False, 'import torch\n'), ((652, 671), 'torch.from_numpy', 'torch.from_numpy', (['b'], {}), '(b)\n', (668, 671), False, 'import torch\n'), ((950, 969), 'torch.from_numpy', 'torch.from_numpy', (['a'], {}), '(a)\n', (966, 969), False, 'import torch\n'), ((971, 990), 'torch.from_numpy', 'torch.from_numpy', (['a'], {}), '(a)\n', (987, 990), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 7 09:16:41 2021
@author: jhask
"""
import numpy as np
import csv
import re
import sys
from pyatlab import * # Tools for making things MATLAB compliant.
sys.path.insert(0,'C:/Users/jhask/OneDrive/Documents/Research/Projects/MIT/pOrgNO3/code/MCM_RCIM_SMILES/python/pyMCM/')
from utils import *
def read_F0AM_mech(file, tag='', map_dict=dict({}), check=True,
sort_rxn_i=False, sort_rxn_list=False, return_comments=False):
"""Function to read in a F0AM mechanism .m file...and return things like
the "Species List", the "RO2" list, the reactions, the rates (k), the gstr and the f
that are on each line... allows you to later parse these as lists in python
with the same indices to do things like find their chem families, look for dupes, etc.
Inputs
------
file = path to .m file holding reactions for a F0AM mechanism.
check (optional) - boolean of whether to check the file for errors that might
make F0AM throw errors...
sort_rxn_i (optional) - Boolean of whether you want to sort items in the rxn.
(e.g. OH + APINENE --> becomes APINENE + OH --> )
sort_rxn_list (optional) - boolean of whether you want to sort all reactions
by reactant (e.g. all APINENE + XXX --> will appear together in
alphabetical order. This makes it easy to see all fates of a reactant in the mech.
tag (optional) = A MATLAB comment to add on to the Rnames line that says what
mechanism this reaction is from. Useful if combining mechanisms- as tag
set to 'Some Mech Name" can tell you where this rxn came from.
map_dict (optional) - dictionary to map names in mech to dif ones. Useful if
you are using an MCM based mech with another that has dif var names (like GEOS-Chem)...
Outputs
-------
n_species - integer number of unique species in the mechanism.
n_rxns - integer number of reactions in the mechanism.
species- list of all species in the mechanism (EXCEPT "RO2", don't declare this in F0AM!!!).
ro2- list of all species that are "RO2" in the mechanism. EXCEPT "RO2" ^^
rxn- list of all reactions in the mechanism. This is the "Rnames" line in F0AM.
k - list of all rates of reactions in the mehcanism. This is k(i,:)= line in F0AM.
g - list of all reactants in each reaction. This is Gstr{i,:}= line in F0AM.
f - list of stoichiometry each reaction changes in mech. This is fOH(i)=fOH(i)+1 line in F0AM.
rct_cmpds- nested list of all reactants in a reaction_i in the reaction list.
rct_ylds- nested list of the yields/stoichiometry of rct_cmpds for reaction_i
prd_cmpds- nested list of all products in a reaction_i in the reaction list.
prd_ylds- nested list of the yields/stoichiometry of prd_cmpds for reaction_i
rxn, k, g, f, rct_cmpds, rct_yields, prd_cmpds, prd_ylds, should all be the same size.
If n_rxns declared in header is correct, then they should be size (n_rxns x 1).
If n_species declared in header is correct, then "species" should be size (N-species x 1).
Custom Functions Referenced:
check_mech_n_map()
Author: Dr. <NAME> (<EMAIL>) GitHub: @jdhask
1/18/2022: JDH Created
"""
with open(file, "r",errors="ignore") as f: # read line by line.
reader = csv.reader(f, delimiter=' ')
# Initialize vars we fill in reading the file.
n_species=np.inf; n_rxns=np.inf; # Hold # of species and # of rxns
ln_num = 0; knext=-99; gnext=-99; fnext=-99; in_species_list=False; in_ro2_list=False
species=[]; ro2=[]; rxn=[]; k=[]; g=[]; f=[]; comments=[];
insert_cmt=[]; insert_ind=[]; pass_go=False
for row in reader:
line0= " ".join(row) # read in the .m file line by line, keep original line!
line=line0 # and keep a copy to mod later.
comment_line=False
if len(line)>0: # Decide if it's a commented out line or not. (MATLAB Comments = "%")
if line[0]=='%': comment_line=True
# Decide if its a comment at the top of the file or not.
if comment_line is True and 'species' not in line and 'reaction' not in line and '#' not in line and pass_go is False:
comments.append(line)
# Sometimes top level comments have # of species and # of rxns...
if comment_line is True and '#' in line and pass_go is False:
col_name, sep, after = line.rpartition("=")
if 'species' in line: n_species=int(after.strip()) # Save # of species..
if 'reaction' in line: n_rxns=int(after.strip()) # Save # of reactions.
if comment_line is False: # Don't parse commented out lines for mech data.
annotations=''
if '%' in line: # Line has a comment at the end of it...
line_listy=line.split('%') # Split into data and the annotation.
line=line_listy[0]; annotations=line_listy[1]
if 'SpeciesToAdd' in line: in_species_list = True ; pass_go=True# If we're in species list
if 'RO2ToAdd' in line: in_ro2_list = True # If we're in RO2 list
# --------- Populate list of Species/ RO2s in mechanism.-------------
# List of things to remove from these lines...
remove=['SpeciesToAdd', 'RO2ToAdd', '{', '=', '}', '...', "'"]
if (in_species_list is True) or (in_ro2_list is True):
for item in remove: # Remove things we don't want.
if item in line: line =line.replace(item, '').strip()
# Split line along semicolon which divides lists in Matlab, remove spaces.
list_line = line.split(";")
value= [item.strip() for item in list_line if len(item.replace(' ', ''))>0]
if (in_species_list is True) : # Append unique vals into the species list.
species=species+ [v for v in value if v not in species]
if (in_ro2_list is True) : # Append unique vals into the RO2 list.
ro2=ro2+ [v for v in value if v not in ro2]
# --------- Populate list of rxns, ks, rcts, and yields in mechanism.-----------
if (in_species_list is False) and (in_ro2_list is False):
line=line.replace(' ', '') # remove any spaces from the line.
# Check if this line is just some kind of extra, unexpected
# line which isn't a comment but doesn't contain mech info.
if len(line)>0 and \
'i=i+1;' not in line and \
'Rnames{i}=' not in line and \
'k(:,i)=' not in line and \
'Gstr{i,1}=' not in line and \
'(i)=f' not in line and \
any(['(i)=f' not in strr for strr in line]) \
and pass_go is True:
insert_cmt.append(line0); insert_ind.append(len(f))
else:
# Append the whole line to our lists of Rnames, K, or Gstr.
add=' % ' if annotations !='' or tag != '' else ''
add= add+ annotations+' # '+tag if tag!='' else add+annotations
if 'Rnames' in line: rxn.append(line +add); knext=ln_num+1;
if knext==ln_num : k.append(line+add); gnext=ln_num+1
if gnext==ln_num: g.append(line+add); fnext=ln_num+1;
if fnext==ln_num: f.append(line+add);
# Set exit flags For species, list, ro2 lists only after you
# added the lines to the correct list.
if (in_species_list is True) and ('};' in line0): in_species_list = False
if (in_ro2_list is True) and ('};' in line0): in_ro2_list = False
elif comment_line is True and pass_go is True: # Found a comment in the middle of the file...
insert_cmt.append(line0); insert_ind.append(len(f))
ln_num=ln_num+1 # Update the line number.
for c in range(0, len(rxn)):
# Some photolysis rxns don't have +hv in them which makes it hard to plot later... fix here.
if ('J' in k[c]) and ('+hv' not in rxn[c]):
[rnames, rcts, prds] = rxn[c].split("=")
rcts=rcts+'+hv' # add '+hv' !
rxn[c]= rnames+'='+ rcts+'='+prds
if check is True:
# Preform some checks!, and map names to the appropriate ones in map dict if provided.
cors, info= check_mech(species, ro2, rxn, k, g, f, n_species=n_species,
n_rxns=n_rxns, mech_name=file, map_dict=map_dict,
sort_rxn_i=sort_rxn_i, sort_rxn_list=sort_rxn_list, verbose=True)
# Unpack all the new stuff.
[species,ro2,rxn,k,g,f, n_species, n_rxns,rct_cmpds, prd_cmpds, rct_ylds, prd_ylds] = info
else:
rct_cmpds=[]; prd_cmpds=[]; rct_ylds=[]; prd_ylds=[];
mech_title=' '.join(comments); #Steal comments from orign.
if return_comments==False:
# Return lists of everything we got out of the mechanism.
return [n_species, n_rxns, species, ro2, rxn, k, g, f, rct_cmpds, prd_cmpds, rct_ylds, prd_ylds]
else:
return [n_species, n_rxns, species, ro2, rxn, k, g, f, rct_cmpds, prd_cmpds, rct_ylds, prd_ylds, mech_title,
insert_cmt, insert_ind]
def write_mech_to_file(filename, species_list,ro2_list,rxn_list,k_list,g_list,f_list,
mech_title='', overwrite= False, insert_cmt=[], insert_ind=[]):
""" Function to take species lists, ro2 lists, rxn list, k list, g list and f list and
write them to a F0AM compliant .m file that can be used in MATALB.
Inputs:
-------
filename - path+ name of the file the mechanism will be written to.
species_list - list of all species in the mechanism
ro2_list- list of all species that are "RO2" in the mechanism. EXCEPT "RO2" ^^
rxn_list- list of all reactions in the mechanism. This is the "Rnames" line in MATLAB.
k_list - list of all rates of reactions in the mehcanism. This is k(i,:)= line in MATALB.
g_list - list of all reactants in each reaction. This is Gstr{i,:}= line in MATALB.
f_list - list of stoichiometry each reaction changes in mech. This is fOH(i)=fOH(i)+1 line in MATALB.
mech_title (optional) - comment at top of F0AM mechanism stating what
kind of mech this is... e.g. "% MCMv331 ISOPRENE +INORG rxns"
overwrite (optional) - Boolean of whether to overwrite an existing
file or apend a "_1" to it...
NOTE: rxn_list, k_list, g_list, f_list should all be the same size.
ro2_list must be subset of species_list.
Outputs:
--------
filename.m - mechanism written to a .m file for use in F0AM.
Custom Functions Referenced:
---------------------------
check_lens()
check_filename()
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
# Check the path + filename exists / has correct extension.
outfile= check_filename(filename, overwrite=overwrite, ext= '.m', return_full=True)
# Open the output file and write headers line by line.
outF = open(outfile, "w"); write_file= True; ln_num=0; rct_ct=0
check_lens(rxn_list,k_list,g_list,f_list, 'ERROR : Input to write to file does not match lens. ' )
# Break up comments on %, add line break char for all comments...
cmts=mech_title.split('%'); big_title=''; title_lines=len(cmts)
for l in cmts[0:]:
big_title=big_title+'%'+l+'\n'
species_list=["'"+sp+"'" for sp in species_list ]
ro2_list=["'"+sp+"'" for sp in ro2_list ]
# Turn species list & RO2 list into a MATLAB formatted cell array as a single string!
sps_lines= 'SpeciesToAdd = {'+ join_list_for_MATLAB(';', species_list, comment=False, add_semicolon=False)+ '};\n'
ro2_lines= 'RO2ToAdd = {'+ join_list_for_MATLAB(';', ro2_list, comment=False, add_semicolon=False)+ '};'
if ro2_lines =="RO2ToAdd = {''};": ro2_lines='RO2ToAdd = {};';
while write_file== True:
blank= '' ; line=blank ;
if ln_num ==0:line= big_title
if ln_num ==1: line= '% # of species ='+ str(len(species_list))
if ln_num ==2: line= '% # of reactions ='+ str(len(rxn_list))
if ln_num ==3: line= blank
if ln_num ==4: line= sps_lines
if ln_num ==5: line= ro2_lines;
if ln_num ==6: line= blank
if ln_num == 7: line= 'AddSpecies'
if ln_num == 8: line= blank
if (ln_num >8) and (rct_ct<= len(rxn_list)):
line=[]
if rct_ct in insert_ind: # If you have a comment to insert here...
insertion=[insert_cmt[i]+'\n' for i,ind in enumerate(insert_ind) if ind==rct_ct]
for idv,lnn in enumerate(insertion):
if 'if' in lnn: lnn='\n'+lnn
if 'end' in lnn: lnn= lnn+'\n'
if idv==0 and lnn[0]=='%' : lnn= '\n'+lnn
if idv==len(insertion)-1 and lnn[0]=='%' : lnn= lnn+'\n'
line.append(lnn) #append the insertion to the line.
if rct_ct< len(rxn_list): # Append all the info for this rxn.
line.append('i=i+1;\n')
line.append(rxn_list[rct_ct]+'\n')
line.append(k_list[rct_ct]+'\n')
line.append(g_list[rct_ct]+'\n')
line.append(f_list[rct_ct]+'\n') if rct_ct+1 not in insert_ind else line.append(f_list[rct_ct])
line=''.join(line) # make it a big long char.
rct_ct=rct_ct+1
outF.write(line)
outF.write("\n")
if rct_ct > len(rxn_list):
break
write_file=False
ln_num=ln_num+1
outF.close() # Close the output file.
print('Mechanism written to file: ' , outfile)
return
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# The rest of the functions are utility functions for the main two above!
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
def toDecimal(x, n_decimals): # x is a float.
"""Function to take a number or list of numbers and force it to have
a certain # of sig figs.
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
import decimal
# Decide if you got a list or a single number....
if type(x) == type(['']) or type(x)==type(np.arange(0,2)):
x2=[np.float64(value) if type(value)!=type(np.float64(1)) else x for value in x]
else:
x2=[np.float64(x)] if type(x)!=type(np.float64(1)) else [x]
d=[]
for value in x2:
if not np.isnan(value):
val='1.'+''.join(['0']*n_decimals)
d_i= decimal.Decimal(str(value)).quantize(decimal.Decimal(val))
else:
d_i=value
d.append(d_i)
if len(d)==1: d=d[0]
return d
def sort_rxn_indv(rct_cmpds,prd_cmpds,rct_ylds,prd_ylds):
"""
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
# Get indices that would sort reactants and products:
rcts_indx= list(np.argsort(rct_cmpds)); prds_indx= list(np.argsort(prd_cmpds))
# Make a list of items in a reaction you wan to appear at the "end" of the half of the rct/prd
move2end=dict({'MGLYOX':1, 'GLYOX':2, 'CH3CO2':3, 'CH3CO3':4,'CH3O2':5,
'HCHO':6, 'NO2':7,'O3':8,' NO':9, 'NO3':10, 'Cl':11,
'Br':12,'RO2':13, 'CO':14, 'OH':15, 'HO2':16, 'O':17,
'CO2':18, 'H2':19, 'O2':20,'hv':21})
for do in [0,1]:
if do==0: cmpds= rct_cmpds; sort_indx_list= rcts_indx;
if do==1: cmpds= prd_cmpds; sort_indx_list= prds_indx;
# List of indexes to remove from sort_indx_list and move2end
to_pop0=[cmpds.index(m) for m in cmpds if m in list(move2end.keys())]
if len(to_pop0) >0:
# Heirarchy of "where" to move those...
heirarchy = [move2end[m] for m in cmpds if m in list(move2end.keys())]
order=np.argsort(heirarchy)
# Pop and append in specific order determined by heirarch in move2end dict....
to_pop=[to_pop0[val] for val in order]
for v in to_pop:
sort_indx_list.pop(sort_indx_list.index(v))
sort_indx_list.append(v)
if do==0: rcts_sort_i=sort_indx_list
if do==1: prds_sort_i=sort_indx_list
[rct_cmpds_o, rct_ylds_o]=enforce_list_inds(rcts_sort_i,[rct_cmpds, rct_ylds])
[prd_cmpds_o, prd_ylds_o]=enforce_list_inds(prds_sort_i,[prd_cmpds, prd_ylds])
return rct_cmpds_o,prd_cmpds_o,rct_ylds_o,prd_ylds_o
def check_fline(rnames_line, fline_in, f_should_have, f_replaced, f_removed,
verbose= True, map_dict=dict({})):
"""Function to take a reaction line and a fstr line and make sure that the
amount made in the fstr line is what is actually made in the rxn line.
Inputs:
-------
rnames_line- String from a rxn list that has an indv reaction on it:
rnames_line= "Rnames{i}='14Z+ C= 12V + 3.45G'; % Comment stuff here "
fline_in - String from a f_list that has fractional stoichiometry for rxn on it. (Can be empty)...
fline_in= 'fZ(i)=fZ(i)-14; fC(i)=fC(i)-1; fV(i)=fV(i)+12; fG(i)=fG(i)+3.45; % V impt comment'
f_shoulds - A list of fs you "should" have based on the rxn.
f_replaced - A list of fs that that should be there but were replaced with a combo yield
f_removed - A list of fs that should be there but were removed b/c no net prod.
verbose (opt) - Boolean of whether to print errors if found or not.
map_dict(opt) - A dictionary used to map compoudns from one name to another.
Outputs:
--------
fline_out - A string corresponding to fline in where the fractions used in the fline
have been verified against the product & reactant stoichiometry in the rnames line.
If sort_indx is passed, it will also be sorted so that things appear in the fline
as they would in the sorted reaction.(Obv with rcts before prods still)...
'fC(i)=fC(i)-1; fZ(i)=fZ(i)-14; fG(i)=fG(i)+3.45; fV(i)=fV(i)+12;
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
if len(fline_in) >0:
fs_cmts= fline_in.split('%') # Look for any comments after line
else:
fs_cmts=['','']
comments=' % '+' '.join(fs_cmts[1:]) if len(fs_cmts) >1 else '' # Store it if you got one.
# Get a list of the fstrs you have in fline_in for this rx
fs_have=[f.replace(' ', '')+';' for f in fs_cmts[0].split(';') if f.replace(' ', '')+';' != ';']
# Map f variables to a different name if map_dict is passed.
for fi, fstr in enumerate(fs_have) :
for old in map_dict.keys():
if 'f'+old+'(i)' in fstr:
fs_have[fi]=fstr.replace('f'+old+'(i)', 'f'+str(map_dict[old])+'(i)')
# Flag any f-strings that are dif from what you should have (and ones that
# werent replaced or removed because they were dupes or combined)....
missing_f=[indd for indd, fstr in enumerate(fs_have) if (fstr not in f_should_have) and \
(fstr not in f_replaced) and (fstr not in f_removed) and \
'fRO2(i)' not in fstr and 'fH2O(i)' not in fstr]
if len(missing_f) >0:
# Don't flag things for having different # of decimal places between rxn str and fline.
sh_brk= []
for ct, sh in enumerate(f_should_have):
for op in ['+', '-']:
if op in sh:
num= np.float64(sh.split(op)[1].split(';')[0])
fi=sh.split('=')[0] # Get just the fDETLMUNO3(i) operator.
sh_brk.append([fi, op, num])
ind2pop=[];
for ct, baddie in enumerate(missing_f):
for op in ['+', '-']: # Get # only ... # fDETLMUNO3(i)=fDETLMUNO3(i)-0.45; becomes --> '0.45'
if op in fs_have[baddie]:
num= np.float64(fs_have[baddie].split(op)[1].split(';')[0])
fi=fs_have[baddie].split('=')[0] # Get just the fDETLMUNO3(i) operator.
ind, ls= find_in_list([fi, op, num], sh_brk)
if len(ind) > 0: # We found a match. things are just dif decimals!
ind2pop.append(ct)
[missing_f]=drop_indxs_from_lists([missing_f], ind2pop)
if len(missing_f) >0:
if verbose is True:
print ('Bad F-string found in rxn: ', "'"+rnames_line+"'", "\n ", fs_cmts[0] , '\n')
[print(' This string:', "'"+fs_have[baddie]+"'", 'should be in:', "'",f_should_have, f_replaced, f_removed,"' \n \n") for baddie in missing_f]
if len(missing_f) >0: input()
# Never keep RO2 in the fline... will deplete RO2 and thats bad / will break F0AM!
[f_should_have.remove(ln) for ln in f_should_have if 'fRO2(i)' in ln]
# Now craft the F-List based on what you should have....
fline_out= ' '. join(f_should_have)+ comments
return fline_out
def check_gline(rnames_line, gline_in, rct_cmpds, sort_rcts=[], verbose= True, map_dict=dict({})):
"""Function to take a reaction line and a Gstr line and make sure that the
reactants in the Gstr line is what are actually are the rcts in the rxn line!!!
Will OVERWRITE the Gs-line if differences are found.
Inputs:
-------
rnames_line- String from a rxn list that has an indv reaction on it:
rnames_line= "Rnames{i}='14Z+ C= 12V + 3.45G'; % Comment v important "
gline_in - String from a f_list that has fractional stoichiometry for rxn on it. Can be empty.
gline_in= 'Gstr{i,1} ='Z'; Gstr{i,2} ='C'; % V impt comment'
rct_cmpds - A list of reactants in the rnames_line. = ['Z','C']
sort_rcts - A list of indices that sort rct_cmpds.
verbose - Boolean of whether to print errors if found or not.
Outputs:
--------
gline_out - A string corresponding to gline in where the reactants used in the gline
have been verified against the reactants in the rnames line.
If sort_indx is passed, it will also be sorted so that things appear in the gline
as they would in the sorted reaction.(Obv with rcts before prods still)...
' Gstr{i,1} ='C'; Gstr{i,2} ='Z'; % V impt comment'
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
if len(gline_in )>0:
gs_cmts= gline_in.split('%') # Look for any comments after line
else:
gs_cmts=['', ''];
comments=' % '+' '.join(gs_cmts[1:]) if len(gs_cmts) >1 else '' # Store it if you got one.
# Get a list of the gstrs you have in gline_in for this rx
gs_have=[g.replace(' ', '')+';' for g in gs_cmts[0].split(';') if g.replace(' ', '')+';' != ';']
# Map gs you have to what they'd be using map dict so comparison to mapped shoulds isn't wonky.
for gi, gstr in enumerate(gs_have) :
for old in map_dict.keys():
if "'"+old+"';" in gstr:
gs_have[gi]=gstr.replace("'"+old+"'", "'"+str(map_dict[old])+"'")
# Build a list of what you *should* have for all the Gstrs on this line.
should_have= ["Gstr{i,"+str(ii+1)+"}='"+cmpd_i+"';" for ii, cmpd_i in enumerate(rct_cmpds) if cmpd_i != 'hv']
# Don't pop an error just because the items in G are sorted in a dif way
for n, rct_i in enumerate(rct_cmpds):
for indxx, gstr in enumerate(gs_have):
if rct_i in gstr:
current_ind= [h.group() for h in re.finditer(r"(?<=Gstr{i,).*?(?=}\=\'"+rct_i+"\';)", gstr) if h.group() !='']
if len(current_ind) >0:
indd=current_ind[0]
gs_have[indxx]=gstr.replace("{i,"+str(indd)+"}","{i,"+str(n+1)+"}")
# Check whether you have all the Gstrs you should have.... Is True if Invalid found
invalid=[indd for indd, gstr in enumerate(gs_have) if gstr not in should_have]
if len(invalid) >0 and verbose is True:
print ('Bad G-string found in rxn: ', "'"+rnames_line+"'", "\n", 'Original: ',gs_cmts[0], "\n" )
[print(' This string:', "'"+gs_have[baddie]+"'", 'should be in', "'",should_have,"' \n \n") for baddie in invalid]
# Now Craft the G-List based on what you should have....
gline_out= ' '. join(should_have)+ comments
return gline_out
def combo_dupes(rcts, rct_yld, prds, prd_yld):
"""
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
fs=[]; f_should_have=[]; f_removed=[]; f_replaced=[];# Build list of fs for each and every reactant & product
[fs.append('f'+cmpd_i+'(i)=f'+cmpd_i+'(i)-'+str(rct_yld[j])+';') for j,cmpd_i in enumerate(rcts)]
[fs.append('f'+cmpd_i+'(i)=f'+cmpd_i+'(i)+'+str(prd_yld[j])+';') for j,cmpd_i in enumerate(prds)]
rct_dupes= list_dupes(rcts) # Get duplicates in rcts or prds.
prd_dupes= list_dupes(prds)
rct_2_drop=[];
cmb_rct_yld=rct_yld.copy();
for rct_i in rct_dupes.keys():
tote_r_yld=np.sum([rct_yld[ind] for ind in rct_dupes[rct_i] ]) # Add yield of duplicates
if np.mod(tote_r_yld,1)==0:
tote_r_yld=np.int64(tote_r_yld)
else:
tote_r_yld=toDecimal(tote_r_yld,2)
[rct_2_drop.append(y) for x,y in enumerate(rct_dupes[rct_i]) if x>0] # index of all duplicates that aren't 1st occurance
[f_replaced.append(fs[y]) for y in rct_dupes[rct_i]]
cmb_rct_yld[rct_dupes[rct_i][0]]=tote_r_yld; # Update first occurance to the total yield.
prd_2_drop=[];
for prd_i in prd_dupes.keys():
tote_p_yld=np.sum([prd_yld[ind] for ind in prd_dupes[prd_i] ]) # Add yield of duplicates
if np.mod(tote_p_yld,1)==0:
tote_p_yld=np.int64(tote_p_yld)
else:
tote_p_yld=toDecimal(tote_p_yld,2)
[prd_2_drop.append(y) for x,y in enumerate(prd_dupes[prd_i]) if x>0] # index of all duplicates that aren't 1st occurance
[f_replaced.append(fs[np.int64(y)+np.int64(len(rcts))]) for y in prd_dupes[prd_i]]
prd_yld[prd_dupes[prd_i][0]]=tote_p_yld; # Update first occurance to the total yield.
# Indicies to drop are for rct+prd, so need to add len(rct) to prd) before dropping those for any duplicates!
f2drop=rct_2_drop+[np.int64(ind)+np.int64(len(rct_2_drop)) for ind in prd_2_drop]
# Drop indices from rcts, ylds, and "ideal" fstrs.
fs= drop_indxs_from_lists([fs], f2drop)
[C_rcts, C_rct_yld]= drop_indxs_from_lists([rcts, cmb_rct_yld], rct_2_drop)
[prds, prd_yld]= drop_indxs_from_lists([prds, prd_yld], prd_2_drop)
# If compounds are in reactants and products, combine into ONLY ONE f_str.
# Otherwise write an F-str that is should be based on its yield stripped from rxn.
for cmpd_i in list(C_rcts+prds):
f_of='f'+cmpd_i+'(i)'
if cmpd_i in C_rcts:
yld_r=C_rct_yld[C_rcts.index(cmpd_i)]
f_str=f_of+'='+f_of+'-'+str(yld_r)+';'
if cmpd_i in prds:
yld_p=prd_yld[prds.index(cmpd_i)]
f_str=f_of+'='+f_of+'+'+str(yld_p)+';'
if cmpd_i in C_rcts and cmpd_i in prds:
if yld_p== yld_r: # conc does not change from rx.
f_removed.append(f_of+'='+f_of+'-'+str(yld_r)+';')
f_removed.append(f_of+'='+f_of+'+'+str(yld_p)+';')
f_str=''
else:
if yld_r > yld_p: # Net lose stuff to this rx
yld_c=yld_r- yld_p; op = '-'
f_removed.append(f_of+'='+f_of+'+'+str(yld_p)+';')
f_replaced.append(f_of+'='+f_of+'-'+str(yld_r)+';')
if yld_p > yld_r: # Net make stuff from this rx
yld_c=yld_p- yld_r; op = '+'
f_removed.append(f_of+'='+f_of+'-'+str(yld_r)+';')
f_replaced.append(f_of+'='+f_of+'+'+str(yld_p)+';')
if np.mod(yld_c,1)==0:
yld_c=np.int64(yld_c)
else:
yld_cs=[toDecimal(yld_c,n) for n in range(1,4)]
[f_removed.append(f_of+'='+f_of+op+str(i)+';') for i in yld_cs]
yld_c=yld_cs[2]
f_str=f_of+'='+f_of+op+str(yld_c)+';'
# List of f_strs that are ONLY the ones you actually need.
if f_str!= '': f_should_have.append(f_str)
# Never keep RO2 in the Fline... will depete RO2 and thats bad.
[f_should_have.remove(ln) for ln in f_should_have if ('fRO2(i)' in ln) or ('fhv(i)' in ln)]
loss= [i for i, fstr in enumerate(f_should_have) if '-' in fstr]
plus= [i for i in range(0, len(f_should_have)) if i not in loss]
f_shoulds=[];
for v in loss+plus: # Force losses to be before pluses!
f_shoulds.append(f_should_have[v]);
return rcts, rct_yld,prds, prd_yld, f_shoulds, f_replaced, f_removed
def sep_stoich_vs_tracer(rxn_str:str, seps:list=['+','=', '->', '-->', '<->'] ):
"""Seperate all stoichiometry from compounds in a string into 2 lists.
Inputs:
rxn_str='TOLU + OH = TRO2 + 1.920CH2O + 0.260GLYX + 0.215MGLY + OH'
seps= ['+', '=']
Outputs:
cmpds= ['TOLU', 'OH', 'TRO2', 'CH2O', 'GLYX', 'MGLY', 'OH']
stoich= [1, 1, 1, 1.920, 0.260, 0.215, 1]
Notes: Don't have to passa whole rxn. Can pass just rcts or prds.
Function won't work properly if chem compounds can begin with numbers.
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
ls=[]; cmpds=[]; stoich=[]
for sep in seps: # Split input string at the input seperators:
ls=ls+rxn_str.replace(' ' , '').split(sep) # ls =['TOLU','OH','TRO2','1.920CH2O','0.260GLYX','0.215MGLY','OH']
for grp in ls: # Loop over all groupings in the list split at seps
if len(grp) > 0:
if grp[0].isalpha(): # If str begins with a letter, then its a tracer name (e.g. 'TOLU').
cmpds.append(grp); stoich.append(1) # Save the compound, save the stoichiometry.
else: # Otherwise, loop over the chars in the grp til you find a letter.
yld=grp[0]; ind=1; found_yld=False #Set yileld= to first char (not-a letter!)
while found_yld==False: #lopo til you find a letter.
if grp[ind].isnumeric() or grp[ind]=='.': # Found a letter or decimal place.
yld=yld+grp[ind]; # Add to str containing all stoichiometry.
elif grp[ind].isalpha() or ind==len(grp)-1: # Found beginning of compound name.
cmpds.append(grp[ind:]) # Store it
stoich.append(np.float64(yld)) # and the #s making up the yield as a #
found_yld=True
break
ind=ind+1
return cmpds, stoich
def build_all_from_rxns(rxn_list:list, k_list:list, f_list:list=[], g_list:list=[],
sort_rxn_i=True, sort_rxn_list=False, verbose=True,map_dict= dict({}), ):
"""Function to bulid a F0AM Compliant mechanism from a list of reactions & rates .
Inputs:
-------
rxn_list- list of all reactions to write to the F0AM mechanism.
k_list - list of all rates of reactions in the mechanism.
f_list (optional) - list of stoichiometry for rxn. This is fOH=fOH(i) +1; line in F0AM.
If provided, input f_list is compared to what it should be based on input rxn_list.
g_list (optional) - list of all reactants in each reaction. This is Gstr{i,:}= line in F0AM..
If provided, input g_list is compared to what it should be based on input rxn_list.
sort_rxn_i (optional) - Boolean of whether you want to sort items in the rxn.
(e.g. OH + APINENE --> becomes APINENE + OH --> )
sort_rxn_list (optional) - Boolean of whether you want to sort all reactions
by reactant (e.g. all APINENE + XXX --> will appear together in
alphabetical order. This makes it easy to see all fates of a reactant in the mech.
map_dict (optional) - Dictionary to map names in mech to dif ones. Useful if
you are using an MCM based mech with another that has dif var names (like GEOS-Chem)...
verbose (optional) - Boolean of whether to print errors when found...
Outputs:
--------
sp_list - list of all species in any rxn in mechanism
rxns_all- list of strings formatted to be the the "Rnames" line in F0AM.
ks_all - list of strings formatted to be the k(i,:)= line in F0AM.
gs_all - list of strings formatted to be the Gstr{i,:}= line in F0AM.
fs_all - list of strings formatted to be the fOH(i)=fOH(i)+1 line in F0AM.
rct_cmpds- nested list of all reactants in a reaction_i in the reaction list.
rct_stoich- nested list of the yields/stoichiometry of rct_cmpds for reaction_i
prd_cmpds- nested list of all products in a reaction_i in the reaction list.
prd_stoich- nested list of the yields/stoichiometry of prd_cmpds for reaction_i
rxn_list, ks_all, gs_all, fs_all, should all be size (n_rxns x 1).
rct_cmpds, rct_yields, prd_cmpds, prd_ylds, should all be size (n_rxns x 1:n_cmpds).
Custom Functions:
-----------------
to_Decimal()
sep_stoich_vs_tracer()
combo_dupes()
sort_rxn_indv()
check_flin()
check_gline()
enforce_list_inds() -> (in list_utils_f0am.py)
str_multi_replace() -> (in list_utils_f0am.py)
find_in_list() -> (in list_utils_f0am.py)
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
-----------
1/18/2022 JDH Created
"""
# Set up empty lists to hold outputs.
sp_list=[]; rct_stoich=[]; rcts=[]; prd_stoich=[]; prds=[]
rx_all=[]; fs_all=[]; gs_all=[]; ks_all=[];
for indx, rxn_i in enumerate(rxn_list):
line=rxn_i.split("'") # Reactions in Rnames lines have apostrophes around them.
comments=line[2] if len(line)>1 else '' # Anything that comes after the ' is a comment!
rx=line[1]
if len(rx)>1:# Make sure we actually have some data in this line. No spaces.
rx_only=rx.replace(' ', '')
# Split reaction into reactant & product halves
rct_half=rx_only.split('=')[0];
prd_half=rx_only.split('=')[1]
# Pass to function to seperate rct and prd halfs into stoich & compounds.
rct_cmpds, rct_ylds= sep_stoich_vs_tracer(rct_half, seps=['+']) # '+' is delimitor that seperates them.
prd_cmpds, prd_ylds= sep_stoich_vs_tracer(prd_half, seps=['+'])
# Map the compound name if asked. (Will propogate into f and g lists sincemapping is done here).
if len(list(map_dict.keys())) > 0:
for cmpd_i in rct_cmpds:
if cmpd_i in list(map_dict.keys()):
d, rct_cmpds_= find_in_list(cmpd_i, rct_cmpds, replace_with=str(map_dict[cmpd_i]))
for cmpd_i in prd_cmpds:
if cmpd_i in list(map_dict.keys()):
d, prd_cmpds= find_in_list(cmpd_i, prd_cmpds, replace_with=str(map_dict[cmpd_i]))
# Sort the reaction to have move things like "+OH, '+hv" to the ned of the rxn.
if sort_rxn_i is True:
rct_cmpds,prd_cmpds,rct_ylds,prd_ylds= sort_rxn_indv(rct_cmpds,prd_cmpds,rct_ylds,prd_ylds)
# Combine any products that are listed twice .... (not rcts!)
outs=combo_dupes(rct_cmpds, rct_ylds, prd_cmpds, prd_ylds)
[rct_cmpds, rct_ylds,prd_cmpds, prd_ylds, f_shoulds, f_replaced, f_removed]= outs
# Make reaction rate lists into correct format:
kline= k_list[indx]
kline=str_multi_replace(kline, dict({'^':'.^', '*':'.*', '/':'./', '..*':'.*', '../':'./', '..^':'.^'}))
if 'k(:,i)=' not in kline.replace(' ', ''):
new_kline='k(:,i)='+kline + ';'
else:
new_kline= kline
# If f-list is provided, compare it against what it "should" be.
fin=f_list[indx] if len(f_list) > 0 else ''
new_fline=check_fline(rxn_i, fin, f_shoulds, f_replaced, f_removed,
verbose=verbose, map_dict=map_dict)
# If g-list is provided, compare it against what it "should" be.
gin=g_list[indx] if len(g_list) > 0 else ''
new_gline= check_gline(rxn_i, gin, rct_cmpds, verbose=verbose,
map_dict=map_dict)
# Convert rct/ prd stoichiometry to strings. Keep 3 decimal spaces.
rct_ylds_strs=[str(yll) if yll!= 1 else '' for yll in rct_ylds]
prd_ylds_strs=[str(yll) if yll!= 1 else '' for yll in prd_ylds]
# Put stoichiometry and compounds back together into a rxn
rct_half= '+'.join([rct_ylds_strs[ind] + rct_cmpds[ind] for ind in range(0, len(rct_cmpds))])
prd_half= '+'.join([prd_ylds_strs[ind] + prd_cmpds[ind] for ind in range(0, len(prd_cmpds))])
new_rx="Rnames{i}='"+rct_half+'='+prd_half+"'"+comments
# Save the species in this line to the bigger list if they're not in it already.
[sp_list.append(sp) for sp in rct_cmpds+ prd_cmpds if sp not in sp_list and sp not in['RO2', 'hv']]
sp_list.sort()
# Now save everything to output lists:
rcts.append(rct_cmpds); prds.append(prd_cmpds)
rct_stoich.append(rct_ylds); prd_stoich.append(prd_ylds)
rx_all.append(new_rx); fs_all.append(new_fline);
gs_all.append(new_gline); ks_all.append(new_kline)
if sort_rxn_list is True: # Sort reactions alphabetically if asked so all APINENE + X rxns appear together.
sort_ind=np.argsort(rx_all)
sout= enforce_list_inds(sort_ind,[rx_all, fs_all, gs_all, k_list, rcts, prds, rct_stoich, prd_stoich])
[rx_all, fs_all, gs_all, ks_all, rcts, prds, rct_stoich, prd_stoich] = sout
return [sp_list, rx_all, fs_all, gs_all, ks_all, rcts, prds, rct_stoich, prd_stoich]
def check_mech(species_list,ro2_list,rxn_list,k_list,g_list,f_list, n_species=-1, n_rxns=-1,
fix_errors=True, sort_rxn_i=False, sort_rxn_list=False,
verbose=True, mech_name='', map_dict=dict({}),):
"""Function to parse lists about a F0AM mechanism and check that they are formatted correctly
Author: Dr. <NAME> (<EMAIL>) GitHub: @jdhask
1/18/2022: JDH Created """
if verbose is True: print(' Checking ... ', mech_name)
check_lens(rxn_list,k_list,g_list,f_list, 'ERROR : Found in Check: rxn, k, f, g, not same len. ' )
cor=False # Boolean of whether output should be corrected...
# Check that the species List, f-list and g-list are consistent with the reaction list by "building"
# what they should be from the reaction list. Fix_errors=True will use the "built" lists...
out=build_all_from_rxns(rxn_list,k_list=k_list, f_list= f_list, g_list=g_list, map_dict= map_dict,
sort_rxn_i=sort_rxn_i, sort_rxn_list=sort_rxn_list)
[sps_declared,rxn_list, f_list, g_list, k_list, rct_cmpds, prd_cmpds, rct_ylds, prd_ylds]= out
# Look for species that are in mech but not declared (and remove any changed from mapping!)
missing= list(set(sps_declared) - set(species_list)) # list of sp not declared.
[missing.pop(missing.index(n)) for n in list(missing) if n in list(map_dict.values())+['hv', 'RO2'] and n in missing]
extra= list(set(species_list) - set(sps_declared)) # list of sp declared & not used.
[extra.pop(extra.index(n)) for n in list(extra) if n in list(map_dict.keys())+['hv', 'RO2'] and n in extra]
if len(missing) > 0:
if verbose is True: print('Species_list is missing the following:', missing); cor=True;
species_list=species_list+missing; n_species=len(species_list)
if len(extra) > 0:
if verbose is True: print('Species_list has the following extras:', extra); cor=True;
for this in extra: species_list.remove(this)
n_species=len(species_list);
for v in ['RO2', 'hv']: # Can't declare RO2 in species or RO2 list or F0AM will crash.
if v in species_list:
species_list.remove(v); cor=True
if verbose is True and v=='RO2': print('CRITICAL: Found "RO2" in species_list. Removing or F0AM will crash!');
if verbose is True and v=='hv': print('Found "hv" in species_list. Removing .')
if v in ro2_list:
ro2_list= ro2_list.remove(v); cor=True
if verbose is True and v=='RO2': print('CRITICAL: Found "RO2" in ro2_list. Removing or F0AM will crash!');
if verbose is True and v=='hv': print('Found "hv" in ro2_list. Removing .')
if n_rxns != -1 and n_rxns!= len(rxn_list):
if verbose is True: print('Header stating # of reactions', n_rxns,' is incorrect. n_rxns is:', len(rxn_list) );
n_rxns= len(rxn_list); cor=True;
if n_species != -1 and n_species!= len(species_list):
if verbose is True: print('Header stating # of species', n_species,' is incorrect. n_species is:', len(species_list) );
n_species= len(species_list); cor=True;
if n_species ==-1: n_species=len(species_list)
if n_rxns ==-1: n_rxns =len(rxn_list)
species_list=[map_dict[sp] if sp in map_dict.keys() else sp for sp in species_list]
return cor, [species_list,ro2_list,rxn_list,k_list,g_list,f_list, n_species, n_rxns,
rct_cmpds, prd_cmpds, rct_ylds, prd_ylds]
def check_lens(rxn, k, g, f, error ):
""" Function to check the lengths of the rxn, k g, and f lists. Should always be same len.
Author:
-------
Dr. <NAME> (<EMAIL>) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
"""
if any(x !=len(rxn) for x in [ len(k), len(g), len(f)] ):
print (error)
print('Len (rxns)= ',len(rxn))
print('Len (k)= ', len(k))
print('Len (g)= ', len(g))
print('Len (f)= ', len(f))
return
| [
"numpy.sum",
"csv.reader",
"decimal.Decimal",
"re.finditer",
"sys.path.insert",
"numpy.isnan",
"numpy.mod",
"numpy.argsort",
"numpy.arange",
"numpy.int64",
"numpy.float64"
] | [((221, 350), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""C:/Users/jhask/OneDrive/Documents/Research/Projects/MIT/pOrgNO3/code/MCM_RCIM_SMILES/python/pyMCM/"""'], {}), "(0,\n 'C:/Users/jhask/OneDrive/Documents/Research/Projects/MIT/pOrgNO3/code/MCM_RCIM_SMILES/python/pyMCM/'\n )\n", (236, 350), False, 'import sys\n'), ((3738, 3766), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""" """'}), "(f, delimiter=' ')\n", (3748, 3766), False, 'import csv\n'), ((16918, 16939), 'numpy.argsort', 'np.argsort', (['rct_cmpds'], {}), '(rct_cmpds)\n', (16928, 16939), True, 'import numpy as np\n'), ((16959, 16980), 'numpy.argsort', 'np.argsort', (['prd_cmpds'], {}), '(prd_cmpds)\n', (16969, 16980), True, 'import numpy as np\n'), ((27960, 28010), 'numpy.sum', 'np.sum', (['[rct_yld[ind] for ind in rct_dupes[rct_i]]'], {}), '([rct_yld[ind] for ind in rct_dupes[rct_i]])\n', (27966, 28010), True, 'import numpy as np\n'), ((28563, 28613), 'numpy.sum', 'np.sum', (['[prd_yld[ind] for ind in prd_dupes[prd_i]]'], {}), '([prd_yld[ind] for ind in prd_dupes[prd_i]])\n', (28569, 28613), True, 'import numpy as np\n'), ((41869, 41887), 'numpy.argsort', 'np.argsort', (['rx_all'], {}), '(rx_all)\n', (41879, 41887), True, 'import numpy as np\n'), ((16353, 16368), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (16361, 16368), True, 'import numpy as np\n'), ((17878, 17899), 'numpy.argsort', 'np.argsort', (['heirarchy'], {}), '(heirarchy)\n', (17888, 17899), True, 'import numpy as np\n'), ((28051, 28072), 'numpy.mod', 'np.mod', (['tote_r_yld', '(1)'], {}), '(tote_r_yld, 1)\n', (28057, 28072), True, 'import numpy as np\n'), ((28100, 28120), 'numpy.int64', 'np.int64', (['tote_r_yld'], {}), '(tote_r_yld)\n', (28108, 28120), True, 'import numpy as np\n'), ((28654, 28675), 'numpy.mod', 'np.mod', (['tote_p_yld', '(1)'], {}), '(tote_p_yld, 1)\n', (28660, 28675), True, 'import numpy as np\n'), ((28703, 28723), 'numpy.int64', 'np.int64', (['tote_p_yld'], {}), '(tote_p_yld)\n', (28711, 28723), True, 'import numpy as np\n'), ((16109, 16124), 'numpy.arange', 'np.arange', (['(0)', '(2)'], {}), '(0, 2)\n', (16118, 16124), True, 'import numpy as np\n'), ((16140, 16157), 'numpy.float64', 'np.float64', (['value'], {}), '(value)\n', (16150, 16157), True, 'import numpy as np\n'), ((16243, 16256), 'numpy.float64', 'np.float64', (['x'], {}), '(x)\n', (16253, 16256), True, 'import numpy as np\n'), ((16472, 16492), 'decimal.Decimal', 'decimal.Decimal', (['val'], {}), '(val)\n', (16487, 16492), False, 'import decimal\n'), ((29270, 29283), 'numpy.int64', 'np.int64', (['ind'], {}), '(ind)\n', (29278, 29283), True, 'import numpy as np\n'), ((16275, 16288), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (16285, 16288), True, 'import numpy as np\n'), ((31005, 31021), 'numpy.mod', 'np.mod', (['yld_c', '(1)'], {}), '(yld_c, 1)\n', (31011, 31021), True, 'import numpy as np\n'), ((31053, 31068), 'numpy.int64', 'np.int64', (['yld_c'], {}), '(yld_c)\n', (31061, 31068), True, 'import numpy as np\n'), ((16179, 16192), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (16189, 16192), True, 'import numpy as np\n'), ((26314, 26376), 're.finditer', 're.finditer', (['("(?<=Gstr{i,).*?(?=}\\\\=\\\\\'" + rct_i + "\';)")', 'gstr'], {}), '("(?<=Gstr{i,).*?(?=}\\\\=\\\\\'" + rct_i + "\';)", gstr)\n', (26325, 26376), False, 'import re\n'), ((28949, 28960), 'numpy.int64', 'np.int64', (['y'], {}), '(y)\n', (28957, 28960), True, 'import numpy as np\n'), ((34001, 34016), 'numpy.float64', 'np.float64', (['yld'], {}), '(yld)\n', (34011, 34016), True, 'import numpy as np\n')] |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
"""Generic implementation of the potential+stationarity computation.
Depending on how this is integrated, it can run the computation with
double-float numpy arrays, mpmath numpy arrays, or TensorFlow 1.x graph-objects.
"""
import collections
import itertools
import numpy
import scipy.linalg
from dim4.so8_supergravity_extrema.code import algebra
ScalarInfo = collections.namedtuple(
'ScalarInfo',
['stationarity',
'potential',
'potential_a1',
'potential_a2',
'generator',
'vielbein',
't_tensor',
'a1',
'a2',
# 70-vector, with entries corresponding to the orthonormal bases of
# (anti)self-dual [ijkl] +/- {complement}.
'grad_potential',
])
def get_unscaled_proj_35_8888_sd_asd(dtype=numpy.int32):
"""Computes the [35, 8, 8, 8, 8]-projector to the (anti)self-dual 4-forms."""
# In principle, we could use the so8.gamma_vvvvss and so8.gamma_vvvvcc here,
# but we opt for instead constructing some explicit orthonormal bases for the
# 35-dimensional irreps as this makes it easier to stay exact despite using
# floating point numbers.
#
# We first need some basis for the 35 self-dual 4-forms.
# Our convention is that we lexicographically list those 8-choose-4
# combinations that contain the index 0.
ret_sd = numpy.zeros([35, 8, 8, 8, 8], dtype=dtype)
ret_asd = numpy.zeros([35, 8, 8, 8, 8], dtype=dtype)
#
def get_complementary(ijkl):
mnpq = tuple(n for n in range(8) if n not in ijkl)
return (algebra.permutation_sign(ijkl + mnpq), ijkl, mnpq)
#
complements = [get_complementary(ijkl)
for ijkl in itertools.combinations(range(8), 4)
if 0 in ijkl]
for num_sd, (sign, ijkl, mnpq) in enumerate(complements):
for abcd in itertools.permutations(range(4)):
sign_abcd = algebra.permutation_sign(abcd)
for r, part2_sign in ((ret_sd, 1), (ret_asd, -1)):
r[num_sd,
ijkl[abcd[0]], ijkl[abcd[1]],
ijkl[abcd[2]], ijkl[abcd[3]]] = sign_abcd
r[num_sd,
mnpq[abcd[0]], mnpq[abcd[1]], mnpq[abcd[2]],
mnpq[abcd[3]]] = sign_abcd * sign * part2_sign
return ret_sd, ret_asd
def _t_tensor(t_u_ijIJ, t_u_klKL,
t_v_ijKL, t_v_klIJ,
einsum):
t_uv = t_u_klKL + t_v_klIJ
t_uuvv = (
einsum('lmJK,kmKI->lkIJ', t_u_ijIJ, t_u_klKL) -
einsum('lmJK,kmKI->lkIJ', t_v_ijKL, t_v_klIJ))
return einsum('ijIJ,lkIJ->lkij', t_uv, t_uuvv)
def get_scalar_manifold_evaluator(
frac=lambda p, q: p / float(q),
to_scaled_constant=lambda x, scale=1: numpy.array(x) * scale,
expm=scipy.linalg.expm,
einsum=numpy.einsum,
eye=lambda n: numpy.eye(n, dtype=numpy.complex128),
# We need tracing-over-last-two-indices as a separate operation, as
# tf.einsum() cannot trace.
# TODO(tfish): Remove `trace` arg once TF can do this.
# Caution: numpy.trace() by default traces over the first two indices,
# but tf.trace() traces over the last two indices.
trace=lambda x: numpy.trace(x, axis1=-1, axis2=-2),
concatenate=numpy.concatenate,
complexify=lambda a: a.astype(numpy.complex128),
re=lambda z: z.real,
im=lambda z: z.imag,
conjugate=lambda z: z.conj()):
"""Wraps up the potential and stationarity computation.
This allows writing the potential and stationarity expressions only once,
but going through the computation in different ways, producing e.g.
- numpy arrays (complex-valued).
- numpy arrays (mpmath.mpc high-precision complex-valued)
- TensorFlow 1.x 'tensor' graph components.
- TensorFlow 2.x Tensors.
As this needs to first wrap up some constants, we return a function
that maps an object representing a 70-vector location to a pair of
(potential, stationarity).
Args:
frac: Function mapping two integers to a fraction (to be overridden for
high-precision computations).
to_scaled_constant: Function mapping an array-like to a scaled constant.
(To be overridden with tf.constant() for TensorFlow).
expm: Matrix exponentiation function.
einsum: Generalized Einstein summation. A function that is compatible
with tf.einsum() or numpy.einsum() calling conventions.
eye: Generalized `numpy.eye()` function returning a complex identity-matrix.
trace: Function mapping a rank-(N+2) array to a rank-N array by tracing
over the last two indices (needed as tf.einsum() does not support this
operation.)
concatenate: Concatenation function compatible with numpy.concatenate.
complexify: A function that maps a real array to a corresponding complex
array.
re: Function mapping a number to its real part. Needed as
numpy.array([mpmath.mpc(1+1j)]).imag does not propagate the `.imag`
method to the dtype=object numbers.
im: Like `re`, but extracts the imaginary part.
Returns: A function f(v70) -> ScalarInfo that maps a 70-vector of
e7/su(8) generator-coefficients in the (35s+35c)-basis to a `ScalarInfo`
object with information about the corresponding point on the scalar
manifold.
"""
t_28_8_8 = to_scaled_constant(algebra.su8.m_28_8_8.astype(numpy.complex128))
t_e7_a_ij_kl = to_scaled_constant(algebra.e7.t_a_ij_kl[:70, :, :])
uproj_35_8888_sd, uproj_35_8888_asd = get_unscaled_proj_35_8888_sd_asd()
proj_35_8888_sd = to_scaled_constant(uproj_35_8888_sd, scale=frac(1, 24))
proj_35_8888_asd = to_scaled_constant(uproj_35_8888_asd, scale=frac(1, 24))
#
def expand_ijkl(t_ab):
"""Index-expands 28, 28 -> [8, 8] [8, 8]."""
return frac(1, 2) * einsum(
'ijB,BIJ->ijIJ',
einsum('AB,Aij->ijB', t_ab, t_28_8_8), t_28_8_8)
#
def evaluator(t_v70, t_left=None, t_right_vielbein=None):
# t_left, if provided, is exponentiated to 2nd degree in the Taylor series
# and multiplies the V-matrix from the left. Taking the 2nd derivative
# w.r.t. `t_left` hence gives us the scalar mass matrix as appropriate for
# a canonically normalized kinetic term.
# t_right_vielbein, if provided, is a Vielbein matrix that overrides
# the exponentiated Vielbein. This is useful for quickly exploring around
# a background (but we cannot do mass matrices then).
t_gen_56_56 = None
if t_right_vielbein is None:
t_gen_56_56 = einsum('v,vIJ->JI', complexify(t_v70), t_e7_a_ij_kl)
t_mid_vielbein = expm(t_gen_56_56)
t_mr_vielbein = t_mid_vielbein
else:
t_mr_vielbein = t_right_vielbein # Actually override.
if t_left is None:
t_vielbein = t_mr_vielbein
else:
t_gen_left = einsum('v,vIJ->JI', t_left, t_e7_a_ij_kl)
t_left_degree2 = (
eye(56) + t_gen_left
+ 0.5 * einsum('ab,bc->ac', t_gen_left, t_gen_left))
t_vielbein = einsum('ab,bc->ac', t_left_degree2, t_mr_vielbein)
t_u_ijIJ = expand_ijkl(t_vielbein[:28, :28])
t_u_klKL = conjugate(t_u_ijIJ)
t_v_ijKL = expand_ijkl(t_vielbein[:28, 28:])
t_v_klIJ = conjugate(t_v_ijKL)
t_t = _t_tensor(t_u_ijIJ, t_u_klKL,
t_v_ijKL, t_v_klIJ,
einsum)
t_a1 = frac(-4, 21) * trace(einsum('mijn->ijmn', t_t))
t_a2 = frac(-4, 3 * 3) * (
# Antisymmetrize in last 3 indices, but using antisymmetry in last 2.
# Note factor 1/3 above (in -4/(3*3) rather than -4/3).
t_t + einsum('lijk->ljki', t_t) + einsum('lijk->lkij', t_t))
t_a1_real = re(t_a1)
t_a1_imag = im(t_a1)
t_a2_real = re(t_a2)
t_a2_imag = im(t_a2)
t_potential_a1 = frac(-3, 4) * (
einsum('ij,ij->', t_a1_real, t_a1_real) +
einsum('ij,ij->', t_a1_imag, t_a1_imag))
t_potential_a2 = frac(1, 24) * (
einsum('ijkl,ijkl->', t_a2_real, t_a2_real) +
einsum('ijkl,ijkl->', t_a2_imag, t_a2_imag))
t_potential = t_potential_a1 + t_potential_a2
t_x0 = (+frac(4, 1) * einsum('mi,mjkl->ijkl', t_a1, t_a2)
-frac(3, 1) * einsum('mnij,nklm->ijkl', t_a2, t_a2))
t_x0_real = re(t_x0)
t_x0_imag = im(t_x0)
t_x0_real_sd = einsum('aijkl,ijkl->a', proj_35_8888_sd, t_x0_real)
t_x0_imag_asd = einsum('aijkl,ijkl->a', proj_35_8888_asd, t_x0_imag)
t_stationarity = frac(1, 2) * (
einsum('a,a->', t_x0_real_sd, t_x0_real_sd) +
einsum('a,a->', t_x0_imag_asd, t_x0_imag_asd))
return ScalarInfo(
stationarity=t_stationarity,
potential=t_potential,
# It makes sense to also expose the a1-potential and a2-potential.
potential_a1=t_potential_a1,
potential_a2=t_potential_a2,
generator=t_gen_56_56,
vielbein=t_vielbein,
t_tensor=t_t,
a1=t_a1,
a2=t_a2,
grad_potential=concatenate([t_x0_real_sd,
t_x0_imag_asd]))
return evaluator
numpy_scalar_manifold_evaluator = get_scalar_manifold_evaluator()
def get_a3_56x56_from_a2(a2,
sqrt2=2**.5,
einsum=numpy.einsum,
conjugate=lambda z: z.conj()):
"""Computes the spin-1/2 fermion "naive" mass matrix A3 from A2.
Args:
a2: The A2^i_[jkl] tensor.
sqrt2: The square root of 2.
(Overridable for high-precision numerical computations.)
einsum: `einsum` operation to use.
(Overridable for high-precision numerical computations.)
conjugate: array-conjugation function to use.
(Overridable for high-precision numerical computations.)
Returns: The [56, 56]-array of (complex) fermion masses.
"""
# complex-conjugate this to get the same conventions as (4.30) in
# https://arxiv.org/pdf/0705.2101.pdf
a2_nP = einsum('nijk,Pijk->nP', conjugate(a2),
algebra.su8.m_56_8_8_8)
return (sqrt2 / 24.0) * (
einsum('Almn,Blmn->AB',
einsum('APlm,nP->Almn',
algebra.su8.eps_56_56_8_8, a2_nP),
algebra.su8.m_56_8_8_8))
| [
"numpy.trace",
"dim4.so8_supergravity_extrema.code.algebra.su8.m_28_8_8.astype",
"numpy.zeros",
"dim4.so8_supergravity_extrema.code.algebra.permutation_sign",
"numpy.array",
"collections.namedtuple",
"numpy.eye"
] | [((973, 1147), 'collections.namedtuple', 'collections.namedtuple', (['"""ScalarInfo"""', "['stationarity', 'potential', 'potential_a1', 'potential_a2', 'generator',\n 'vielbein', 't_tensor', 'a1', 'a2', 'grad_potential']"], {}), "('ScalarInfo', ['stationarity', 'potential',\n 'potential_a1', 'potential_a2', 'generator', 'vielbein', 't_tensor',\n 'a1', 'a2', 'grad_potential'])\n", (995, 1147), False, 'import collections\n'), ((1912, 1954), 'numpy.zeros', 'numpy.zeros', (['[35, 8, 8, 8, 8]'], {'dtype': 'dtype'}), '([35, 8, 8, 8, 8], dtype=dtype)\n', (1923, 1954), False, 'import numpy\n'), ((1967, 2009), 'numpy.zeros', 'numpy.zeros', (['[35, 8, 8, 8, 8]'], {'dtype': 'dtype'}), '([35, 8, 8, 8, 8], dtype=dtype)\n', (1978, 2009), False, 'import numpy\n'), ((3281, 3317), 'numpy.eye', 'numpy.eye', (['n'], {'dtype': 'numpy.complex128'}), '(n, dtype=numpy.complex128)\n', (3290, 3317), False, 'import numpy\n'), ((3632, 3666), 'numpy.trace', 'numpy.trace', (['x'], {'axis1': '(-1)', 'axis2': '(-2)'}), '(x, axis1=-1, axis2=-2)\n', (3643, 3666), False, 'import numpy\n'), ((5737, 5782), 'dim4.so8_supergravity_extrema.code.algebra.su8.m_28_8_8.astype', 'algebra.su8.m_28_8_8.astype', (['numpy.complex128'], {}), '(numpy.complex128)\n', (5764, 5782), False, 'from dim4.so8_supergravity_extrema.code import algebra\n'), ((2112, 2149), 'dim4.so8_supergravity_extrema.code.algebra.permutation_sign', 'algebra.permutation_sign', (['(ijkl + mnpq)'], {}), '(ijkl + mnpq)\n', (2136, 2149), False, 'from dim4.so8_supergravity_extrema.code import algebra\n'), ((2432, 2462), 'dim4.so8_supergravity_extrema.code.algebra.permutation_sign', 'algebra.permutation_sign', (['abcd'], {}), '(abcd)\n', (2456, 2462), False, 'from dim4.so8_supergravity_extrema.code import algebra\n'), ((3186, 3200), 'numpy.array', 'numpy.array', (['x'], {}), '(x)\n', (3197, 3200), False, 'import numpy\n')] |
import sys
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Flatten, Activation
from keras.layers import Convolution1D
from keras.layers import MaxPooling1D
from keras.layers import Embedding
from keras.layers import ThresholdedReLU
from keras.layers import Dropout
from keras.optimizers import Adam
import numpy as np
config_file = sys.argv[1]
def shuffle_weights(model, weights=None):
"""Randomly permute the weights in `model`, or the given `weights`.
This is a fast approximation of re-initializing the weights of a model.
Assumes weights are distributed independently of the dimensions of the weight tensors
(i.e., the weights have the same distribution along each dimension).
:param Model model: Modify the weights of the given model.
:param list(ndarray) weights: The model's weights will be replaced by a random permutation of these weights.
If `None`, permute the model's current weights.
"""
if weights is None:
weights = model.get_weights()
weights = [np.random.permutation(w.flat).reshape(w.shape) for w in weights]
# Faster, but less random: only permutes along the first dimension
# weights = [np.random.permutation(w) for w in weights]
model.set_weights(weights)
print("Loading the configurations...")
exec(open(config_file).read())
conv_layers = config.model.conv_layers
fully_layers = config.model.fully_connected_layers
l0 = config.l0
alphabet_size = config.alphabet_size
embedding_size = config.model.embedding_size
num_of_classes = config.num_of_classes
th = config.model.th
p = config.dropout_p
print("Loaded")
# Input layer
inputs = Input(shape=(l0,), name='sent_input', dtype='int64')
# Embedding layer
x = Embedding(alphabet_size + 1, embedding_size, input_length=l0)(inputs)
# Convolution layers
for cl in conv_layers:
x = Convolution1D(cl[0], cl[1])(x)
x = ThresholdedReLU(th)(x)
if not cl[2] is None:
x = MaxPooling1D(cl[2])(x)
x = Flatten()(x)
#Fully connected layers
for fl in fully_layers:
x = Dense(fl)(x)
x = ThresholdedReLU(th)(x)
x = Dropout(0.5)(x)
predictions = Dense(num_of_classes, activation='softmax')(x)
model = Model(input=inputs, output=predictions)
optimizer = Adam()
model.compile(optimizer=optimizer, loss='categorical_crossentropy')
print("New model built")
print("Loading the data sets...")
from data_utils import Data
train_data = Data(data_source = config.train_data_source,
alphabet = config.alphabet,
l0 = config.l0,
batch_size = 0,
no_of_classes = config.num_of_classes)
train_data.loadData()
X_train, y_train = train_data.getAllData()
train_length = X_train.shape[0]
print("Loadded")
slices = 10
step = int(train_length/slices)
start_weights = model.get_weights()
for a in range(0, train_length, step):
X_val = X_train[a:a+step]
y_val = y_train[a:a+step]
subset_X_train = np.concatenate((X_train[:a], X_train[a+step:]), axis=0)
subset_y_train = np.concatenate((y_train[:a], y_train[a+step:]), axis=0)
print("\nTraining without {}-{}".format(a, a+step))
shuffle_weights(model, start_weights)
print('Weights shuffled')
model.fit(subset_X_train, subset_y_train, epochs=config.training.epochs,
batch_size=config.batch_size) #, validation_data=(X_val, y_val))
print(model.evaluate(X_val, y_val, verbose=0))
print("Done!\n")
| [
"keras.layers.Convolution1D",
"keras.layers.ThresholdedReLU",
"keras.layers.Dropout",
"keras.optimizers.Adam",
"keras.layers.Flatten",
"keras.models.Model",
"keras.layers.MaxPooling1D",
"keras.layers.Dense",
"keras.layers.Embedding",
"data_utils.Data",
"numpy.random.permutation",
"keras.layers... | [((1659, 1711), 'keras.layers.Input', 'Input', ([], {'shape': '(l0,)', 'name': '"""sent_input"""', 'dtype': '"""int64"""'}), "(shape=(l0,), name='sent_input', dtype='int64')\n", (1664, 1711), False, 'from keras.layers import Input, Dense, Flatten, Activation\n'), ((2198, 2237), 'keras.models.Model', 'Model', ([], {'input': 'inputs', 'output': 'predictions'}), '(input=inputs, output=predictions)\n', (2203, 2237), False, 'from keras.models import Model, Sequential\n'), ((2250, 2256), 'keras.optimizers.Adam', 'Adam', ([], {}), '()\n', (2254, 2256), False, 'from keras.optimizers import Adam\n'), ((2429, 2567), 'data_utils.Data', 'Data', ([], {'data_source': 'config.train_data_source', 'alphabet': 'config.alphabet', 'l0': 'config.l0', 'batch_size': '(0)', 'no_of_classes': 'config.num_of_classes'}), '(data_source=config.train_data_source, alphabet=config.alphabet, l0=\n config.l0, batch_size=0, no_of_classes=config.num_of_classes)\n', (2433, 2567), False, 'from data_utils import Data\n'), ((1736, 1797), 'keras.layers.Embedding', 'Embedding', (['(alphabet_size + 1)', 'embedding_size'], {'input_length': 'l0'}), '(alphabet_size + 1, embedding_size, input_length=l0)\n', (1745, 1797), False, 'from keras.layers import Embedding\n'), ((1988, 1997), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1995, 1997), False, 'from keras.layers import Input, Dense, Flatten, Activation\n'), ((2143, 2186), 'keras.layers.Dense', 'Dense', (['num_of_classes'], {'activation': '"""softmax"""'}), "(num_of_classes, activation='softmax')\n", (2148, 2186), False, 'from keras.layers import Input, Dense, Flatten, Activation\n'), ((2978, 3035), 'numpy.concatenate', 'np.concatenate', (['(X_train[:a], X_train[a + step:])'], {'axis': '(0)'}), '((X_train[:a], X_train[a + step:]), axis=0)\n', (2992, 3035), True, 'import numpy as np\n'), ((3055, 3112), 'numpy.concatenate', 'np.concatenate', (['(y_train[:a], y_train[a + step:])'], {'axis': '(0)'}), '((y_train[:a], y_train[a + step:]), axis=0)\n', (3069, 3112), True, 'import numpy as np\n'), ((1859, 1886), 'keras.layers.Convolution1D', 'Convolution1D', (['cl[0]', 'cl[1]'], {}), '(cl[0], cl[1])\n', (1872, 1886), False, 'from keras.layers import Convolution1D\n'), ((1898, 1917), 'keras.layers.ThresholdedReLU', 'ThresholdedReLU', (['th'], {}), '(th)\n', (1913, 1917), False, 'from keras.layers import ThresholdedReLU\n'), ((2060, 2069), 'keras.layers.Dense', 'Dense', (['fl'], {}), '(fl)\n', (2065, 2069), False, 'from keras.layers import Input, Dense, Flatten, Activation\n'), ((2081, 2100), 'keras.layers.ThresholdedReLU', 'ThresholdedReLU', (['th'], {}), '(th)\n', (2096, 2100), False, 'from keras.layers import ThresholdedReLU\n'), ((2112, 2124), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2119, 2124), False, 'from keras.layers import Dropout\n'), ((1959, 1978), 'keras.layers.MaxPooling1D', 'MaxPooling1D', (['cl[2]'], {}), '(cl[2])\n', (1971, 1978), False, 'from keras.layers import MaxPooling1D\n'), ((1050, 1079), 'numpy.random.permutation', 'np.random.permutation', (['w.flat'], {}), '(w.flat)\n', (1071, 1079), True, 'import numpy as np\n')] |
"""
This module contains classes to handle datasets consisting of many files.
Created by <NAME>, June 2017
"""
import atexit
from collections import Counter, deque, OrderedDict
from copy import deepcopy
from datetime import datetime, timedelta
import gc
from itertools import tee
import json
import logging
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
import os.path
import posixpath
import re
import shutil
from sys import platform
import traceback
import warnings
import numpy as np
import pandas as pd
from fsspec.implementations.local import LocalFileSystem
import typhon.files
from typhon.trees import IntervalTree
from typhon.utils import unique
from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta
from .handlers import expects_file_info, FileInfo
from .handlers import CSV, NetCDF4
__all__ = [
"FileSet",
"FileSetManager",
"InhomogeneousFilesError",
"NoFilesError",
"NoHandlerError",
"UnknownPlaceholderError",
"PlaceholderRegexError",
]
logger = logging.getLogger(__name__)
class InhomogeneousFilesError(Exception):
"""Should be raised if the files of a fileset do not have the same internal
structure but it is required.
"""
def __init__(self, *args):
Exception.__init__(self, *args)
class NoFilesError(Exception):
"""Should be raised if no files were found by the :meth:`find`
method.
"""
def __init__(self, fileset, start, end, *args):
if start == datetime.min and end >= datetime.max-timedelta(seconds=1):
message = f"Found no files for {fileset.name}!"
else:
message = f"Found no files for {fileset.name} between {start} " \
f"and {end}!"
message += f"\nPath: {fileset.path}\nCheck the path for misspellings" \
f" and whether there are files in this time period."
Exception.__init__(self, message, *args)
class NoHandlerError(Exception):
"""Should be raised if no file handler is specified in a fileset object but
a handler is required.
"""
def __init__(self, msg, *args):
message = f"{msg} I do not know which file handler to " \
f"use. Set one by yourself."
Exception.__init__(self, message, *args)
class UnfilledPlaceholderError(Exception):
"""Should be raised if a placeholder was found that cannot be filled.
"""
def __init__(self, name, placeholder_name=None, *args):
if placeholder_name is None:
message = \
"The path of '%s' contains a unfilled placeholder!" % (name,)
else:
message = \
"The fileset '%s' could not fill the placeholder %s!" % (
name, placeholder_name)
Exception.__init__(self, message, *args)
class UnknownPlaceholderError(Exception):
"""Should be raised if a placeholder was found that was not defined before.
"""
def __init__(self, name, placeholder_name=None, *args):
if placeholder_name is None:
message = \
"The path of '%s' contains a unknown placeholder!" % (name,)
else:
message = \
"The fileset '%s' does not know the placeholder %s!" % (
name, placeholder_name)
Exception.__init__(self, message, *args)
class PlaceholderRegexError(Exception):
"""Should be raised if the regex of a placeholder is broken.
"""
def __init__(self, name, msg):
Exception.__init__(
self, f"The path of '{name}' contains syntax errors: {msg}"
)
class AlignError(Exception):
"""Should be raised if two filesets could not be aligned to each other.
"""
def __init__(self, msg):
Exception.__init__(self, msg)
class FileSet:
"""Provide methods to handle a set of multiple files
For more examples and an user guide, look at this tutorial_.
.. _tutorial: http://radiativetransfer.org/misc/typhon/doc-trunk/tutorials/fileset.html
Examples:
FileSet with multiple files:
.. code-block:: python
from typhon.files import FileSet
# Define a fileset consisting of multiple files:
files = FileSet(
path="/dir/{year}/{month}/{day}/{hour}{minute}{second}.nc",
name="TestData",
# If the time coverage of the data cannot be retrieved from the
# filename, you should set this to "handler" and giving a file
# handler to this object:
info_via="filename"
)
# Find some files of the fileset:
for file in files.find("2017-01-01", "2017-01-02"):
# Should print the path of the file and its time coverage:
print(file)
FileSet with a single file:
.. code-block:: python
# Define a fileset consisting of a single file:
file = FileSet(
# Simply use the path without placeholders:
path="/path/to/file.nc",
name="TestData2",
# The time coverage of the data cannot be retrieved from the
# filename (because there are no placeholders). You can use the
# file handler get_info() method with info_via="handler" or you
# can define the time coverage here directly:
time_coverage=("2007-01-01 13:00:00", "2007-01-14 13:00:00")
)
FileSet to open MHS files:
.. code-block:: python
from typhon.files import FileSet, MHS_HDF
# Define a fileset consisting of multiple files:
files = FileSet(
path="/dir/{year}/{month}/{day}/{hour}{minute}{second}.nc",
name="MHS",
handler=MHS_HDF(),
)
# Find some files of the fileset:
for file in files.find("2017-01-01", "2017-01-02"):
# Should print the path of the file and its time coverage:
print(file)
References:
The FileSet class is inspired by the implemented dataset classes in
atmlab_ developed by <NAME>.
.. _atmlab: http://www.radiativetransfer.org/tools/
"""
# Required temporal placeholders that can be overridden by the user but
# not deleted:
_time_placeholder = {
# "placeholder_name": [regex to find the placeholder]
"year": r"\d{4}",
"year2": r"\d{2}",
"month": r"\d{2}",
"day": r"\d{2}",
"doy": r"\d{3}",
"hour": r"\d{2}",
"minute": r"\d{2}",
"second": r"\d{2}",
"decisecond": r"\d{1}",
"centisecond": r"\d{2}",
"millisecond": r"\d{3}",
"microsecond": r"\d{6}",
#"nanosecond": r"\d{9}",
"end_year": r"\d{4}",
"end_year2": r"\d{2}",
"end_month": r"\d{2}",
"end_day": r"\d{2}",
"end_doy": r"\d{3}",
"end_hour": r"\d{2}",
"end_minute": r"\d{2}",
"end_second": r"\d{2}",
"end_decisecond": r"\d{1}",
"end_centisecond": r"\d{2}",
"end_millisecond": r"\d{3}",
"end_microsecond": r"\d{6}",
#"end_nanosecond": r"\d{9}",
}
_temporal_resolution = OrderedDict({
# time placeholder: [pandas frequency, resolution rank]
"year": timedelta(days=366),
"month": timedelta(days=31),
"day": timedelta(days=1),
"hour": timedelta(hours=1),
"minute": timedelta(minutes=1),
"second": timedelta(seconds=1),
"decisecond": timedelta(microseconds=100000),
"centisecond": timedelta(microseconds=10000),
"millisecond": timedelta(microseconds=1000),
"microsecond": timedelta(microseconds=1),
})
# If one has a year with two-digit representation, all years equal or
# higher than this threshold are based onto 1900, all years below are based
# onto 2000.
year2_threshold = 65
# Default handler
default_handler = {
"nc": NetCDF4,
"h5": NetCDF4, #HDF5,
"txt": CSV,
"csv": CSV,
"asc": CSV,
}
# Special characters that show whether a path contains a regex or
# placeholder:
_special_chars = ["{", "*", "[", "<", "(", "?", "!", "|"]
# FIXME OLE: On windows we can't have backslash here because it is the
# directory separator. Not sure if we need the \\ on Unix
# in _special_chars, but left it here to not break anything
if platform != "win32":
_special_chars += "\\"
def __init__(
self, path, handler=None, name=None, info_via=None,
time_coverage=None, info_cache=None, exclude=None,
placeholder=None, max_threads=None, max_processes=None,
worker_type=None, read_args=None, write_args=None,
post_reader=None, compress=True, decompress=True, temp_dir=None,
fs=None
):
"""Initialize a FileSet object.
Args:
path: A string with the complete path to the files. The
string can contain placeholder such as {year}, {month},
etc. See below for a complete list. The direct use of
restricted regular expressions is also possible. Please note
that instead of dots '.' the asterisk '\\*' is interpreted as
wildcard. If no placeholders are given, the path must point to
a file. This fileset is then seen as a single file set.
You can also define your own placeholders by using the
parameter *placeholder*.
name: The name of the fileset.
handler: An object which can handle the fileset files.
This fileset class does not care which format its files have
when this file handler object is given. You can use a file
handler class from typhon.files, use
:class:`~typhon.files.handlers.common.FileHandler` or write
your own class. If no file handler is given, an adequate one is
automatically selected for the most common filename suffixes.
Please note that if no file handler is specified (and none
could set automatically), this fileset's functionality is
restricted.
info_via: Defines how further information about the file will
be retrieved (e.g. time coverage). Possible options are
*filename*, *handler* or *both*. Default is *filename*. That
means that the placeholders in the file's path will be parsed
to obtain information. If this is *handler*, the
:meth:`~typhon.files.handlers.common.FileInfo.get_info` method
is used. If this is *both*, both options will be executed but
the information from the file handler overwrites conflicting
information from the filename.
info_cache: Retrieving further information (such as time coverage)
about a file may take a while, especially when *get_info* is
set to *handler*. Therefore, if the file information is cached,
multiple calls of :meth:`find` (for time periods that
are close) are significantly faster. Specify a name to a file
here (which need not exist) if you wish to save the information
data to a file. When restarting your script, this cache is
used.
time_coverage: If this fileset consists of multiple files, this
parameter is the relative time coverage (i.e. a timedelta, e.g.
"1 hour") of each file. If the ending time of a file cannot be
retrieved by its file handler or filename, it is then its
starting time + *time_coverage*. Can be a timedelta object or
a string with time information (e.g. "2 seconds"). Otherwise
the missing ending time of each file will be set to its
starting time. If this fileset consists of a single file, then
this is its absolute time coverage. Set this to a tuple of
timestamps (datetime objects or strings). Otherwise the period
between year 1 and 9999 will be used as a default time
coverage.
exclude: A list of time periods (tuples of two timestamps) or
filenames (strings) that will be excluded when searching for
files of this fileset.
placeholder: A dictionary with pairs of placeholder name and a
regular expression matching its content. These are user-defined
placeholders, the standard temporal placeholders do not have to
be defined.
max_threads: Maximal number of threads that will be used to
parallelise some methods (e.g. writing in background). This
sets also the default for
:meth:`~typhon.files.fileset.FileSet.map`-like methods
(default is 3).
max_processes: Maximal number of processes that will be used to
parallelise some methods. This sets also the default for
:meth:`~typhon.files.fileset.FileSet.map`-like methods
(default is 8).
worker_type: The type of the workers that will be used to
parallelise some methods. Can be *process* (default) or
*thread*.
read_args: Additional keyword arguments in a dictionary that should
always be passed to :meth:`read`.
write_args: Additional keyword arguments in a dictionary that
should always be passed to :meth:`write`.
post_reader: A reference to a function that will be called *after*
reading a file. Can be used for post-processing or field
selection, etc. Its signature must be
`callable(file_info, file_data)`.
temp_dir: You can set here your own temporary directory that this
FileSet object should use for compressing and decompressing
files. Per default it uses the tempdir given by
`tempfile.gettempdir` (see :func:`tempfile.gettempdir`).
compress: If true and `path` ends with a compression
suffix (such as *.zip*, *.gz*, *.b2z*, etc.), newly created
files will be compressed after writing them to disk. Default
value is true.
decompress: If true and `path` ends with a compression
suffix (such as *.zip*, *.gz*, *.b2z*, etc.), files will be
decompressed before reading them. Default value is true.
fs: Instance of implementation of fsspec.spec.AbstractFileSystem.
By passing a remote filesystem implementation this allows for
searching for and opening files on remote file systems such as
Amazon S3 using s3fs.S3FileSystem.
You can use regular expressions or placeholders in `path` to
generalize the files path. Placeholders are going to be captured and
returned by file-finding methods such as :meth:`find`. Temporal
placeholders will be converted to datetime objects and represent a
file's time coverage. Allowed temporal placeholders in the `path`
argument are:
+-------------+------------------------------------------+------------+
| Placeholder | Description | Example |
+=============+==========================================+============+
| year | Four digits indicating the year. | 1999 |
+-------------+------------------------------------------+------------+
| year2 | Two digits indicating the year. [1]_ | 58 (=2058) |
+-------------+------------------------------------------+------------+
| month | Two digits indicating the month. | 09 |
+-------------+------------------------------------------+------------+
| day | Two digits indicating the day. | 08 |
+-------------+------------------------------------------+------------+
| doy | Three digits indicating the day of | 002 |
| | the year. | |
+-------------+------------------------------------------+------------+
| hour | Two digits indicating the hour. | 22 |
+-------------+------------------------------------------+------------+
| minute | Two digits indicating the minute. | 58 |
+-------------+------------------------------------------+------------+
| second | Two digits indicating the second. | 58 |
+-------------+------------------------------------------+------------+
| millisecond | Three digits indicating the millisecond. | 999 |
+-------------+------------------------------------------+------------+
.. [1] Numbers lower than 65 are interpreted as 20XX while numbers
equal or greater are interpreted as 19XX (e.g. 65 = 1965,
99 = 1999)
All those place holders are also allowed to have the prefix *end*
(e.g. *end_year*). They represent the end of the time coverage.
Moreover, you are allowed do define your own placeholders by using the
parameter `placeholder` or :meth:`set_placeholders`. Their names
must consist of alphanumeric signs (underscores are also allowed).
"""
# Initialize member variables:
self._name = None
self.name = name
# Flag whether this is a single file fileset (will be derived in the
# path setter method automatically):
self.single_file = None
# Complete the standard time placeholders. This must be done before
# setting the path to the fileset's files.
self._time_placeholder = self._complete_placeholders_regex(
self._time_placeholder
)
# Placeholders that can be changed by the user:
self._user_placeholder = {}
# Filesystem support for searching remotely or in archives
self.file_system = fs or LocalFileSystem()
self.has_root = isinstance(self.file_system, LocalFileSystem)
# The path parameters (will be set and documented in the path setter
# method):
self._path = None
self._path_placeholders = None
self._end_time_superior = None
self._path_extension = None
self._filled_path = None
self._base_dir = None
self._sub_dir = ""
self._sub_dir_chunks = []
self._sub_dir_time_resolution = None
self.path = path
# Add user-defined placeholders:
if placeholder is not None:
self.set_placeholders(**placeholder)
if handler is None:
# Try to derive the file handler from the files extension but
# before we might remove potential compression suffixes:
basename, extension = os.path.splitext(self.path)
if typhon.files.is_compression_format(extension.lstrip(".")):
_, extension = os.path.splitext(basename)
extension = extension.lstrip(".")
self.handler = self.default_handler.get(extension, None)
if self.handler is not None:
self.handler = self.handler()
else:
self.handler = handler
# Defines which method will be used by .get_info():
if info_via is None or info_via == "filename":
self.info_via = "filename"
else:
if self.handler is None:
raise NoHandlerError(f"Cannot set 'info_via' to '{info_via}'!")
else:
self.info_via = info_via
# A list of time periods that will be excluded when searching files:
self._exclude_times = None
self._exclude_files = {}
if exclude is not None:
self.exclude_files(
[file for file in exclude if isinstance(file, str)]
)
self.exclude_times(
[times for times in exclude if isinstance(times, tuple)]
)
# The default worker settings for map-like functions
self.max_threads = 3 if max_threads is None else max_threads
self.max_processes = 4 if max_processes is None else max_processes
self.worker_type = "process" if worker_type is None else worker_type
# The default settings for read and write methods
self.read_args = {} if read_args is None else read_args
self.write_args = {} if write_args is None else write_args
self.post_reader = post_reader
self.compress = compress
self.decompress = decompress
self.temp_dir = temp_dir
self._time_coverage = None
self.time_coverage = time_coverage
# Multiple calls of .find() can be very slow when using the handler as
# as information retrieving method. Hence, we use a cache to store the
# names and time coverages of already touched files in this dictionary.
self.info_cache_filename = info_cache
self.info_cache = {}
if self.info_cache_filename is not None:
try:
# Load the time coverages from a file:
self.load_cache(self.info_cache_filename)
except Exception as e:
raise e
else:
# Save the time coverages cache into a file before exiting.
# This will be executed as well when the python code is
# aborted due to an exception. This is normally okay, but what
# happens if the error occurs during the loading of the time
# coverages? We would overwrite the cache with nonsense.
# Therefore, we need this code in this else block.
atexit.register(FileSet.save_cache,
self, self.info_cache_filename)
# Writing processes can be moved to background threads. But we do want
# to have too many backgrounds threads running at the same time, so we
# create FIFO queue. The queue limits the number of parallel threads
# to a maximum. The users can also make sure that all writing threads
# are finished before they move on in the code.
# TODO: We cannot use queues as attributes for FileSet because they
# TODO: cannot be pickled.
# self._write_queue = Queue(max_threads)
# Dictionary for holding links to other filesets:
self._link = {}
def __iter__(self):
return iter(self.find())
def __contains__(self, item):
"""Checks whether a timestamp is covered by this fileset.
Notes:
This only gives proper results if the fileset consists of
continuous data (files that covers a time span instead of only one
timestamp).
Args:
item: Either a string with time information or datetime object.
Can be also a tuple or list of strings / datetime objects that
will be checked.
Returns:
True if timestamp is covered.
"""
if isinstance(item, (tuple, list)):
if len(item) != 2:
raise ValueError("Can only test single timestamps or time "
"periods consisting of two timestamps")
start = to_datetime(item[0])
end = to_datetime(item[1])
else:
start = to_datetime(item)
end = start + timedelta(microseconds=1)
try:
next(self.find(start, end, no_files_error=False, sort=False,))
return True
except StopIteration:
return False
def __getitem__(self, item):
if isinstance(item, (tuple, list)):
time_args = item[0]
filters = item[1]
else:
time_args = item
filters = None
if isinstance(time_args, slice):
return self.collect(
time_args.start, time_args.stop, filters=filters,
)
elif isinstance(time_args, (datetime, str)):
filename = self.find_closest(time_args, filters=filters)
if filename is None:
return None
return self.read(filename)
def __len__(self):
return sum(1 for _ in self.find())
def __setitem__(self, key, value):
if isinstance(key, (tuple, list)):
time_args = key[0]
fill = key[1]
else:
time_args = key
fill = None
if isinstance(time_args, slice):
start = time_args.start
end = time_args.stop
else:
start = end = time_args
filename = self.get_filename((start, end), fill=fill)
self.write(value, filename)
def __repr__(self):
return str(self)
def __str__(self):
dtype = "Single-File" if self.single_file else "Multi-Files"
info = "Name:\t" + self.name
info += "\nType:\t" + dtype
info += "\nFiles path:\t" + self.path
if self._user_placeholder:
info += "\nUser placeholder:\t" + str(self._user_placeholder)
return info
def align(self, other, start=None, end=None, matches=None,
max_interval=None, return_info=True, compact=False,
skip_errors=False):
"""Collect files from this fileset and a matching other fileset
Warnings:
The name of this method may change in future.
This generator finds the matches between two filesets (the files that
overlap each other in time), reads their content and yields them. The
reading is done in parallel threads to enhance the performance.
Args:
other: Another fileset object.
start: Start date either as datetime object or as string
("YYYY-MM-DD hh:mm:ss"). Year, month and day are required.
Hours, minutes and seconds are optional. If not given, it is
datetime.min per default.
end: End date. Same format as "start". If not given, it is
datetime.max per default.
matches: A list of matches between this fileset and `other`.
Normally, this is just the return value of :meth:`match`. These
matches will be used for aligning. If `matches` is given,
`start`, `end` and `max_interval` will be ignored.
max_interval: A time interval (as string, number or timedelta
object) that expands the search time period for secondaries.
return_info: Additionally, to the file content also its info object
will be returned.
compact: Not yet implemented. Decides how the collected data will
be returned.
skip_errors: Normally, when an exception is raised during
reading a file, the program stops. But if this parameter is
True, the error will be only printed as warning and this and
its matching file are skipped.
Yields:
If `return_info` False, it yields two objects: the primary and
secondary file content.
.. code-block:: python
fileset = FileSet(
"old/path/{year}/{month}/{day}/{hour}{minute}{second}.nc",
)
# Delete all files in this fileset:
fileset.delete()
"""
start = None if start is None else to_datetime(start)
end = None if end is None else to_datetime(end)
# Find all overlapping files. Or has the user already given some
# matches to us?
if matches is None:
matches = list(
self.match(other, start, end, max_interval=max_interval)
)
primaries, secondaries = zip(*matches)
# We have to consider the following to make the align method work
# properly:
# A) Load the files in parallel loading queues (done by icollect) and
# read them only once even if it might be used by multiple primaries.
# B) Secondaries that are going to be used by multiple primaries must
# be cached until we are sure that they won't be needed any longer.
# This deals with part A:
# We need the list flattened and without duplicates.
unique_secondaries = unique(
secondary for match in secondaries for secondary in match
)
# Prepare the loader for the primaries and secondaries:
primary_loader = self.icollect(
files=primaries, error_to_warning=skip_errors
)
secondary_loader = other.icollect(
files=unique_secondaries, return_info=True,
error_to_warning=skip_errors
)
# Here we prepare part B:
# We count how often we need the secondaries (some primaries may need
# the same secondary). Later, we decrease the counter for the
# secondary for each use. If the counter reaches zero, we can delete it
# from the cache.
secondary_usage = Counter(
secondary for match in secondaries for secondary in match
)
# We will need this cache for secondaries that are used by multiple
# primaries:
cache = {}
for match_id, primary_data in enumerate(primary_loader):
if return_info:
primary = [primaries[match_id], primary_data]
else:
primary = primary_data
# We only need to load the secondary files that have not been
# cached earlier:
for secondary_file in matches[match_id][1]:
if secondary_file not in cache:
secondary_loaded, secondary_data = next(secondary_loader)
if secondary_file != secondary_loaded:
raise AlignError(
f"Expected '{secondary_file}'\nbut "
f"'{secondary_loaded}' was loaded!\nDoes your "
f"fileset '{self.name}' contain files between that"
f"are completely overlapped by other files? "
f"Please exclude them via `exclude`."
)
# Add the loaded secondary to the cache
cache[secondary_file] = secondary_data
else:
secondary_data = cache[secondary_file]
# Decrease the counter for this secondary:
secondary_usage[secondary_file] -= 1
# Apparently, this secondary won't be needed any longer. Delete
# it from the cache:
if not secondary_usage[secondary_file]:
del cache[secondary_file]
# Tell the python interpreter explicitly to free up memory
# to improve performance (see
# https://stackoverflow.com/q/1316767/9144990):
gc.collect()
# Check whether something went wrong:
if primary_data is None or secondary_data is None \
and skip_errors:
# There was an exception during reading the primary or
# secondary file, therefore we skip this match:
continue
if return_info:
secondary = [secondary_file, secondary_data]
else:
secondary = secondary_data
# Yield the primary and secondary to the user:
yield primary, secondary
@staticmethod
def _pseudo_passer(*args):
return args[0]
def collect(self, start=None, end=None, files=None, return_info=False,
**kwargs):
"""Load all files between two dates sorted by their starting time
Notes
This does not constrain the loaded data to the time period given by
`start` and `end`. This fully loads all files that contain data in
that time period, i.e. it returns also data that may exceed the
time period.
This parallelizes the reading of the files by using threads. This
should give a speed up if the file handler's read function internally
uses CPython code that releases the GIL. Note that this method is
faster than :meth:`icollect` but also more memory consuming.
Use this if you need all files at once but if want to use a for-loop
consider using :meth:`icollect` instead.
Args:
start: The same as in :meth:`find`.
end: The same as in :meth:`find`.
files: If you have already a list of files that you want to
process, pass it here. The list can contain filenames or lists
(bundles) of filenames. If this parameter is given, it is not
allowed to set `start` and `end` then.
return_info: If true, return a FileInfo object with each content
value indicating to which file the function was applied.
**kwargs: Additional keyword arguments that are allowed
for :meth:`map`. Some might be overwritten by this method.
Returns:
If `return_info` is True, two list are going to be returned:
one with FileInfo objects of the files and one with the read
content objects. Otherwise, the list with the read content objects
only. The lists are sorted by the starting times of the files.
Examples:
.. code-block:: python
## Load all files between two dates:
# Note: data may contain timestamps exceeding the given time period
data = fileset.collect("2018-01-01", "2018-01-02")
# The above is equivalent to this magic slicing:
data = fileset["2018-01-01":"2018-01-02"]
## If you want to iterate through the files in a for loop, e.g.:
for content in fileset.collect("2018-01-01", "2018-01-02"):
# do something with file and content...
# Then you should rather use icollect, which uses less memory:
for content in fileset.icollect("2018-01-01", "2018-01-02"):
# do something with file and content...
"""
# Actually, this method is nothing else than a customized alias for the
# map method:
map_args = {
**kwargs,
"files": files,
"start": start,
"end": end,
"worker_type": "thread",
"on_content": True,
"return_info": True,
}
if "func" not in map_args:
map_args["func"] = self._pseudo_passer
# If we used map with processes, it would need to pickle the data
# coming from all workers. This would be very inefficient. Threads
# are better because sharing data does not cost much and a file
# reading function is typically IO-bound. However, if the reading
# function consists mainly of pure python code that does not
# release the GIL, this will slow down the performance.
results = self.map(**map_args)
# Tell the python interpreter explicitly to free up memory to improve
# performance (see https://stackoverflow.com/q/1316767/9144990):
gc.collect()
# We do not want to have any None as data
files, data = zip(*[
[info, content]
for info, content in results
if content is not None
])
if return_info:
return list(files), list(data)
else:
return list(data)
def icollect(self, start=None, end=None, files=None,
**kwargs):
"""Load all files between two dates sorted by their starting time
Does the same as :meth:`collect` but works as a generator. Instead of
loading all files at the same time, it loads them in chunks (the chunk
size is defined by `max_workers`). Hence, this method is less memory
space consuming but slower than :meth:`collect`. Simple hint: use this
in for-loops but if you need all files at once, use :meth:`collect`
instead.
Args:
start: The same as in :meth:`find`.
end: The same as in :meth:`find`.
files: If you have already a list of files that you want to
process, pass it here. The list can contain filenames or lists
(bundles) of filenames. If this parameter is given, it is not
allowed to set *start* and *end* then.
**kwargs: Additional keyword arguments that are allowed
for :meth:`imap`. Some might be overwritten by this method.
Yields:
A tuple of the FileInfo object of a file and its content. These
tuples are yielded sorted by its file starting time.
Examples:
.. code-block:: python
## Perfect for iterating over many files.
for content in fileset.icollect("2018-01-01", "2018-01-02"):
# do something with file and content...
## If you want to have all files at once, do not use this:
data_list = list(fileset.icollect("2018-01-01", "2018-01-02"))
# This version is faster:
data_list = fileset.collect("2018-01-01", "2018-01-02")
"""
# Actually, this method is nothing else than a customized alias for the
# imap method:
map_args = {
**kwargs,
"files": files,
"start": start,
"end": end,
"worker_type": "thread",
"on_content": True,
}
if "func" not in map_args:
map_args["func"] = self._pseudo_passer
yield from self.imap(**map_args)
def copy(self):
"""Create a so-called deep-copy of this fileset object
Notes
This method does not copy any files. If you want to do so, use
:meth:`move` with the parameter `copy=True`.
Returns:
The copied fileset object
"""
return deepcopy(self)
def delete(self, dry_run=False, **kwargs):
"""Remove files in this fileset from the disk
Warnings:
The deleting of the files cannot be undone! There is no prompt
before deleting the files. Use this function with caution!
Args:
dry_run: If true, all files that would be deleted are printed.
**kwargs: Additional keyword arguments that are allowed
for :meth:`find` such as `start`, `end` or `files`.
Returns:
Nothing
Examples:
.. code-block:: python
fileset = FileSet(
"old/path/{year}/{month}/{day}/{hour}{minute}{second}.nc",
)
# Delete all files in this fileset:
fileset.delete()
"""
if dry_run:
self.map(FileSet._dry_delete, **kwargs)
else:
# Delete the files
self.map(
FileSet._delete_single_file, **kwargs
)
@staticmethod
def _delete_single_file(file):
logger.info(f"Delete '{file}'!")
os.remove(file)
@staticmethod
def _dry_delete(file):
print(f"[Dry] Delete '{file}'!")
def detect(self, test, *args, **kwargs):
"""Search for anomalies in fileset
Args:
test: Can be *duplicates*, *overlaps*, *enclosed* or a reference
to your own function that expects two :class:`FileInfo` objects
as parameters.
*args: Positional arguments for :meth:`find`.
**kwargs: Keyword arguments for :meth:`find`.
Yields:
A :class:`FileInfo` object of each file that fulfilled the test.
"""
if not callable(test):
if test == "enclosed":
yield from self._detect_enclosed(*args, **kwargs)
if test is None:
raise ValueError("Need a valid test function or name!")
previous = None
for file in self.find(*args, **kwargs):
if previous is None:
continue
if test(previous, file):
yield file
def _detect_enclosed(self, *args, **kwargs):
yield None
def exclude_times(self, periods):
if periods is None or not periods:
self._exclude_times = None
else:
self._exclude_times = IntervalTree(periods)
def exclude_files(self, filenames):
self._exclude_files = set(filenames)
def is_excluded(self, file):
"""Checks whether a file is excluded from this FileSet.
Args:
file: A file info object.
Returns:
True or False
"""
if file.path in self._exclude_files:
return True
if self._exclude_times is None:
return False
return file.times in self._exclude_times
def find(
self, start=None, end=None, sort=True, only_path=False,
bundle=None, filters=None, no_files_error=True,
):
""" Find all files of this fileset in a given time period.
The *start* and *end* parameters build a semi-open interval: only the
files that are equal or newer than *start* and older than *end* are
going to be found.
While searching this method checks whether the file lies in the time
periods given by `exclude` while initializing.
Args:
start: Start date either as datetime object or as string
("YYYY-MM-DD hh:mm:ss"). Year, month and day are required.
Hours, minutes and seconds are optional. If not given, it is
datetime.min per default.
end: End date. Same format as "start". If not given, it is
datetime.max per default.
sort: If true, all files will be yielded sorted by their starting
and ending time. Default is true.
only_path: If true, only the paths of the files will be returned
not their :class:`~typhon.files.handlers.common.FileInfo`
object.
bundle: Instead of only yielding one file at a time, you can get a
bundle of files. There are two possibilities: by setting this
to an integer, you can define the size of the bundle directly
or by setting this to a string (e.g. *1H*),
you can define the time period of one bundle. See
http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
for allowed time specifications. Default value is 1. This
argument will be ignored when having a single-file fileset.
When using *bundle*, the returned files will always be sorted
ignoring the state of the *sort* argument.
filters: Limits user-defined placeholder to certain values.
Must be a dictionary where the keys are the names of
user-defined placeholders and the values either strings or
lists of strings with allowed placeholder values (can be
represented by regular expressions). If the key name starts
with a *!* (exclamation mark), the value represent a black
list (values that are not allowed).
no_files_error: If true, raises an NoFilesError when no
files are found.
Yields:
Either a :class:`~typhon.files.handlers.common.FileInfo` object for
each found file or - if *bundle_size* is not None - a list of
:class:`~typhon.files.handlers.common.FileInfo` objects.
Examples:
.. code-block:: python
# Define a fileset consisting of multiple files:
fileset = FileSet(
"/dir/{year}/{month}/{day}/{hour}{minute}{second}.nc"
)
# Find some files of the fileset:
for file in fileset.find("2017-01-01", "2017-01-02"):
# file is a FileInfo object that has the attribute path
# and times.
print(file.path) # e.g. "/dir/2017/01/01/120000.nc"
print(file.times) # list of two datetime objects
"""
# The user can give strings instead of datetime objects:
start = datetime.min if start is None else to_datetime(start)
end = datetime.max if end is None else to_datetime(end)
# We want to have a semi-open interval as explained in the doc string.
end -= timedelta(microseconds=1)
if end < start:
raise ValueError(
"The start must be smaller than the end parameter!")
logger.info(
f"Find files for {self.name:s} "
f"between {start:%Y-%m-%d %H:%M:%S} "
f"and {end:%Y-%m-%d %H:%M:%S}")
logger.debug(
f"Searching {self.path:s} via "
f"file system {self.file_system!s}")
# Special case: the whole fileset consists of one file only.
if self.single_file:
if self.file_system.isfile(self.path):
file_info = self.get_info(self.path)
if IntervalTree.interval_overlaps(
file_info.times, (start, end)):
yield file_info
elif no_files_error:
raise NoFilesError(self, start, end)
return
else:
raise ValueError(
"The path of '%s' neither contains placeholders"
" nor is a path to an existing file!" % self.name)
# Files may exceed the time coverage of their directories. For example,
# a file located in the directory of 2018-01-13 contains data from
# 2018-01-13 18:00:00 to 2018-01-14 02:00:00. In order to find them, we
# must include the previous sub directory into the search range:
if self._sub_dir_time_resolution is None or start == datetime.min:
dir_start = start
else:
dir_start = start - self._sub_dir_time_resolution
# Filter handling:
if filters is None:
# We can apply the standard path regex:
regex = re.compile(self._filled_path)
white_list = {}
black_list = {}
else:
# Complete the regexes of the filters (simply adding curls around
# them):
white_list = self._complete_placeholders_regex(
{f: v for f, v in filters.items() if not f.startswith("!")}
)
# The new regex for all files:
regex = self._fill_placeholders(
self.path,
extra_placeholder=white_list,
compile=True,
)
def convert(value):
if value is None:
return None
elif isinstance(value, (tuple, list)):
return re.compile(f"{'|'.join(value)}")
else:
return re.compile(f"{value}")
black_list = {
f.lstrip("!"): convert(v)
for f, v in filters.items()
if f.startswith("!")
}
if filters is not None:
logger.info(f"Loaded filters:\nWhitelist: {white_list}"
f"\nBlacklist: {black_list}")
# Find all files by iterating over all searching paths and check
# whether they match the path regex and the time period.
file_finder = (
file_info
for path, _ in self._get_search_dirs(dir_start, end, white_list)
for file_info in self._get_matching_files(path, regex, start, end,)
if not black_list or self._check_file(black_list, file_info.attr)
)
# Even if no files were found, the user does not want to know.
if not no_files_error:
yield from self._prepare_find_return(
file_finder, sort, only_path, bundle
)
return
# The users wants an error to be raised if no files were found. Since
# the file_finder is an iterator, we have to check whether it is empty.
# I do not know whether there is a more pythonic way but Matthew
# Flaschen shows how to do it with itertools.tee:
# https://stackoverflow.com/a/3114423
return_files, check_files = tee(file_finder)
try:
next(check_files)
# We have found some files and can return them
yield from self._prepare_find_return(
return_files, sort, only_path, bundle
)
except StopIteration as err:
raise NoFilesError(self, start, end)
def _get_search_dirs(self, start, end, white_list):
"""Yields all searching directories for a time period.
Args:
start: Datetime that defines the start of a time interval.
end: Datetime that defines the end of a time interval. The time
coverage of the files should overlap with this interval.
white_list: A dictionary that limits placeholders to certain
values.
Returns:
A tuple of path as string and parsed placeholders as dictionary.
"""
# Goal: Search for all directories that match the path regex and is
# between start and end date.
# Strategy: Go through each folder in the hierarchy and find the ones
# that match the regex so far. Filter out folders that does not overlap
# with the given time interval.
search_dirs = [(self._base_dir, {}), ]
# If the directory does not contain regex or placeholders, we simply
# return the base directory
if not self._sub_dir:
return search_dirs
for subdir_chunk in self._sub_dir_chunks:
# Sometimes there is a sub directory part that has no
# regex/placeholders:
if not any(True for ch in subdir_chunk
if ch in self._special_chars):
# We can add this sub directory part because it will always
# match to our path
# NB: using posixpath rather than os.path because
# AbstractFileSystem objects always work with / not \
search_dirs = [
(posixpath.join(old_dir, subdir_chunk), attr)
for old_dir, attr in search_dirs
]
continue
# The sub directory covers a certain time coverage, we make
# sure that it is included into the search range.
start_check = set_time_resolution(
start, self._get_time_resolution(subdir_chunk)[0]
)
end_check = set_time_resolution(
end, self._get_time_resolution(subdir_chunk)[0]
)
# compile the regex for this sub directory:
regex = self._fill_placeholders(
subdir_chunk, extra_placeholder=white_list, compile=True
)
search_dirs = [
(new_dir, attr)
for search_dir in search_dirs
for new_dir, attr in self._get_matching_dirs(search_dir, regex)
if self._check_placeholders(attr, start_check, end_check)
]
return search_dirs
def _get_matching_dirs(self, dir_with_attrs, regex):
base_dir, dir_attr = dir_with_attrs
for new_dir in self.file_system.glob(posixpath.join(base_dir + "*", "")):
# some/all (?) file_system implementations do not end directories
# in a /, glob.glob does
if not (new_dir.endswith(os.sep) or new_dir.endswith("/")) and self.file_system.isdir(new_dir):
new_dir += "/" # always / with AbstractFileSystem, not os.sep
# The glob function yields full paths, but we want only to check
# the new pattern that was added:
basename = new_dir[len(base_dir):].rstrip(os.sep + "/")
try:
new_attr = {
**dir_attr,
**self.parse_filename(basename, regex)
}
yield new_dir, new_attr
except ValueError:
pass
def _check_placeholders(self, attr, start, end):
attr_start, attr_end = self._to_datetime_args(attr)
attr_end = {**attr_start, **attr_end}
year = attr_start.get("year", None)
if year is not None:
try:
return datetime(**attr_start) >= start \
and datetime(**attr_end) <= end
except:
return year >= start.year and attr_end["year"] <= end.year
return True
def _get_matching_files(self, path, regex, start, end,):
"""Yield files that matches the search conditions.
Args:
path: Path to the directory that contains the files that should be
checked.
regex: A regular expression that should match the filename.
start: Datetime that defines the start of a time interval.
end: Datetime that defines the end of a time interval. The time
coverage of the file should overlap with this interval.
Yields:
A FileInfo object with the file path and time coverage
"""
for filename in self.file_system.glob(posixpath.join(path, "*")):
if regex.match(filename):
file_info = self.get_info(
FileInfo(filename, fs=self.file_system))
# Test whether the file is overlapping the interval between
# start and end date.
if IntervalTree.interval_overlaps(
file_info.times, (start, end))\
and not self.is_excluded(file_info):
yield file_info
@staticmethod
def _check_file(black_list, placeholders):
"""Check whether placeholders are filled with something forbidden
Args:
black_list: A dictionary with placeholder name and content that
should be filtered out.
placeholders: A dictionary with placeholders and their fillings.
Returns:
False if the placeholders are filled with something that is
forbidden due to the filters. True otherwise.
"""
for placeholder, forbidden in black_list.items():
value = placeholders.get(placeholder, None)
if value is None:
continue
if forbidden.match(value):
return False
return True
@staticmethod
def _prepare_find_return(file_iterator, sort, only_path, bundle_size):
"""Prepares the return value of the find method.
Args:
file_iterator: Generator function that yields the found files.
sort: If true, all found files will be sorted according to their
starting and ending times.
only_path:
bundle_size: See the documentation of the *bundle* argument in
:meth:`find` method.
Yields:
Either one FileInfo object or - if bundle_size is set - a list of
FileInfo objects.
"""
# We always want to have sorted files if we want to bundle them.
if sort or isinstance(bundle_size, int):
# Sort the files by starting and ending time:
file_iterator = sorted(
file_iterator, key=lambda x: (x.times[0], x.times[1])
)
if bundle_size is None:
yield from file_iterator
return
# The argument bundle was defined. Either it sets the bundle size
# directly via a number or indirectly by setting time periods.
if isinstance(bundle_size, int):
files = list(file_iterator)
yield from (
files[i:i + bundle_size]
for i in range(0, len(files), bundle_size)
)
elif isinstance(bundle_size, str):
files = list(file_iterator)
# We want to split the files into hourly (or daily, etc.) bundles.
# pandas provides a practical grouping function.
time_series = pd.Series(
files,
[file.times[0] for file in files]
)
yield from (
bundle[1].values.tolist()
for bundle in time_series.groupby(
pd.Grouper(freq=bundle_size))
if bundle[1].any()
)
else:
raise ValueError(
"The parameter bundle must be a integer or string!")
def find_closest(self, timestamp, filters=None):
"""Find the closest file to a timestamp
Args:
timestamp: date either as datetime object or as string
("YYYY-MM-DD hh:mm:ss"). Year, month and day are required.
Hours, minutes and seconds are optional.
filters: The same filter argument that is allowed for
:meth:`find`.
Returns:
The FileInfo object of the found file. If no file was found, a
NoFilesError is raised.
"""
# Special case: the whole fileset consists of one file only.
if self.single_file:
if self.file_system.isfile(self.path):
# We do not have to check the time coverage since there this is
# automatically the closest file to the timestamp.
return self.path
else:
raise ValueError(
"The path parameter of '%s' does not contain placeholders"
" and is not a path to an existing file!" % self.name)
timestamp = to_datetime(timestamp)
# We might need some more fillings than given by the user therefore
# we need the error catching:
try:
# Maybe there is a file with exact this timestamp?
path = self.get_filename(timestamp, )
if self.file_system.isfile(path):
return self.get_info(path)
except (UnknownPlaceholderError, UnfilledPlaceholderError):
pass
# We need to find all files that are around the given timestamp. Hence,
# we use the sub directory time resolution to specify a time period
# within the file should possibly be:
if self._sub_dir_time_resolution is None:
start = datetime.min
end = datetime.max
else:
start = timestamp - self._sub_dir_time_resolution
end = timestamp + self._sub_dir_time_resolution
files = list(self.find(start, end, sort=False, filters=filters))
if not files:
return None
times = [file.times for file in files]
# Either we find a file that covers the certain timestamp:
for index, time_coverage in enumerate(times):
if IntervalTree.interval_contains(time_coverage, timestamp):
return files[index]
# Or we find the closest file.
intervals = np.min(np.abs(np.asarray(times) - timestamp), axis=1)
return files[np.argmin(intervals)]
def get_filename(
self, times, template=None, fill=None):
"""Generate the full path and name of a file for a time period
Use :meth:`parse_filename` if you want retrieve information from the
filename instead.
Args:
times: Either a tuple of two datetime objects representing start
and end time or simply one datetime object (for discrete
files).
template: A string with format placeholders such as {year} or
{day}. If not given, the template in `FileSet.path` is used.
fill: A dictionary with fillings for user-defined placeholder.
Returns:
A string containing the full path and name of the file.
Example:
.. code-block:: python
fileset.get_filename(
datetime(2016, 1, 1),
"{year2}/{month}/{day}.dat",
)
# Returns "16/01/01.dat"
fileset.get_filename(
("2016-01-01", "2016-12-31"),
"{year}{month}{day}-{end_year}{end_month}{end_day}.dat",
)
# Returns "20160101-20161231.dat"
"""
if isinstance(times, (tuple, list)):
start_time = to_datetime(times[0])
end_time = to_datetime(times[1])
else:
start_time = to_datetime(times)
end_time = start_time
if template is None:
template = self.path
# Remove the automatic regex completion from the user placeholders and
# use them as default fillings
default_fill = {
p: self._remove_group_capturing(p, v)
for p, v in self._user_placeholder.items()
}
if fill is None:
fill = default_fill
else:
fill = {**default_fill, **fill}
try:
# Fill all placeholders variables with values
filename = template.format(
year=start_time.year, year2=str(start_time.year)[-2:],
month="{:02d}".format(start_time.month),
day="{:02d}".format(start_time.day),
doy="{:03d}".format(
(start_time - datetime(start_time.year, 1, 1)).days
+ 1),
hour="{:02d}".format(start_time.hour),
minute="{:02d}".format(start_time.minute),
second="{:02d}".format(start_time.second),
millisecond="{:03d}".format(
int(start_time.microsecond / 1000)),
end_year=end_time.year, end_year2=str(end_time.year)[-2:],
end_month="{:02d}".format(end_time.month),
end_day="{:02d}".format(end_time.day),
end_doy="{:03d}".format(
(end_time - datetime(end_time.year, 1, 1)).days
+ 1),
end_hour="{:02d}".format(end_time.hour),
end_minute="{:02d}".format(end_time.minute),
end_second="{:02d}".format(end_time.second),
end_millisecond="{:03d}".format(
int(end_time.microsecond/1000)),
**fill,
)
# Some placeholders might be unfilled:
if any((c in self._special_chars) for c in filename):
raise UnfilledPlaceholderError(self.name, filename)
return filename
except KeyError:
raise UnknownPlaceholderError(self.name)
@expects_file_info()
def get_info(self, file_info, retrieve_via=None):
"""Get information about a file.
How the information will be retrieved is defined by
Args:
file_info: A string, path-alike object or a
:class:`~typhon.files.handlers.common.FileInfo` object.
retrieve_via: Defines how further information about the file will
be retrieved (e.g. time coverage). Possible options are
*filename*, *handler* or *both*. Default is the value of the
*info_via* parameter during initialization of this FileSet
object. If this is *filename*, the placeholders in the file's
path will be parsed to obtain information. If this is
*handler*, the
:meth:`~typhon.files.handlers.common.FileInfo.get_info` method
is used. If this is *both*, both options will be executed but
the information from the file handler overwrites conflicting
information from the filename.
Returns:
A :meth:`~typhon.files.handlers.common.FileInfo` object.
"""
# We want to save time in this routine, therefore we first check
# whether we cached this file already.
if file_info.path in self.info_cache:
return self.info_cache[file_info.path]
# We have not processed this file before.
info = file_info.copy()
if self.single_file:
info.times = self.time_coverage
if retrieve_via is None:
retrieve_via = self.info_via
# Parsing the filename
if retrieve_via in ("filename", "both"):
filled_placeholder = self.parse_filename(info.path)
filename_info = FileInfo(
info.path, self._retrieve_time_coverage(filled_placeholder),
# Filter out all placeholder that are not coming from the user
{k: v for k, v in filled_placeholder.items()
if k in self._user_placeholder},
self.file_system
)
info.update(filename_info)
# Using the handler for getting more information
if retrieve_via in ("handler", "both"):
with typhon.files.decompress(info.path, tmpdir=self.temp_dir) as \
decompressed_path:
decompressed_file = info.copy()
decompressed_file.path = decompressed_path
handler_info = self.handler.get_info(decompressed_file)
info.update(handler_info)
if info.times[0] is None:
if info.times[1] is None:
# This is obviously a non-temporal fileset, set the times to
# minimum and maximum so we have no problem to find it
info.times = [datetime.min, datetime.max]
else:
# Something went wrong, we need a starting time if we have an
# ending time.
raise ValueError(
"Could not retrieve the starting time information from "
"the file '%s' from the %s fileset!"
% (info.path, self.name)
)
elif info.times[1] is None:
# Sometimes the files have only a starting time. But if the user
# has defined a timedelta for the coverage, the ending time can be
# calculated from this. Otherwise this is a FileSet that has only
# files that are discrete in time
if isinstance(self.time_coverage, timedelta):
info.times[1] = info.times[0] + self.time_coverage
else:
info.times[1] = info.times[0]
self.info_cache[info.path] = info
return info
def dislink(self, name_or_fileset):
"""Remove the link between this and another fileset
Args:
name_or_fileset: Name of a fileset or the FileSet object itself. It
must be linked to this fileset. Otherwise a KeyError will be
raised.
Returns:
None
"""
if isinstance(name_or_fileset, FileSet):
del self._link[name_or_fileset.name]
else:
del self._link[name_or_fileset]
def link(self, other_fileset, linker=None):
"""Link this fileset with another FileSet
If one file is read from this fileset, its corresponding file from
`other_fileset` will be read, too. Their content will then be merged by
using the file handler's data merging function. If it is not
implemented, it tries to derive a standard merging function from known
data types.
Args:
other_fileset: Other FileSet-like object.
linker: Reference to a function that searches for the corresponding
file in *other_fileset* for a given file from this fileset.
Must accept *other_fileset* as first and a
:class:`~typhon.files.handlers.common.FileInfo` object as
parameters. It must return a FileInfo of the corresponding
file. If none is given,
:meth:`~typhon.files.fileset.FileSet.get_filename`
will be used as default.
Returns:
None
"""
self._link[other_fileset.name] = {
"target": other_fileset,
"linker": linker,
}
def load_cache(self, filename):
"""Load the information cache from a JSON file
Returns:
None
"""
if filename is not None and os.path.exists(filename):
try:
with open(filename) as file:
json_info_cache = json.load(file)
# Create FileInfo objects from json dictionaries:
info_cache = {
json_dict["path"]: FileInfo.from_json_dict(json_dict)
for json_dict in json_info_cache
}
self.info_cache.update(info_cache)
except Exception as err:
warnings.warn(
"Could not load the file information from cache file "
f"'{filename}':\n{err}."
)
def make_dirs(self, filename):
self.file_system.makedirs(
posixpath.dirname(filename),
exist_ok=True
)
def map(
self, func, args=None, kwargs=None, files=None, on_content=False,
pass_info=None, read_args=None, output=None,
max_workers=None, worker_type=None,
return_info=False, error_to_warning=False, **find_kwargs
):
"""Apply a function on files of this fileset with parallel workers
This method can use multiple workers processes / threads to boost the
procedure significantly. Depending on which system you work, you should
try different numbers for `max_workers`.
Use this if you need to process the files as fast as possible without
needing to retrieve the results immediately. Otherwise you should
consider using :meth:`imap` in a for-loop.
Notes:
This method sorts the results after the starting time of the files
unless *sort* is False.
Args:
func: A reference to a function that should be applied.
args: A list/tuple with positional arguments that should be passed
to `func`. It will be extended with the file arguments, i.e.
a FileInfo object if `on_content` is false or - if `on_content`
and `pass_info` are true - the read content of a file and its
corresponding FileInfo object.
kwargs: A dictionary with keyword arguments that should be passed
to `func`.
files: If you have already a list of files that you want to
process, pass it here. The list can contain filenames or lists
(bundles) of filenames. If this parameter is given, it is not
allowed to set `start` and `end` then.
on_content: If true, the file will be read before `func` will be
applied. The content will then be passed to `func`.
pass_info: If `on_content` is true, this decides whether also the
`FileInfo` object of the read file should be passed to `func`.
Default is false.
read_args: Additional keyword arguments that will be passed
to the reading function (see :meth:`read` for more
information). Will be ignored if `on_content` is False.
output: Set this to a path containing placeholders or a FileSet
object and the return value of `func` will be copied there if
it is not None.
max_workers: Max. number of parallel workers to use. When
lacking performance, you should change this number.
worker_type: The type of the workers that will be used to
parallelize `func`. Can be `process` or `thread`. If `func` is
a function that needs to share a lot of data with its
parallelized copies, you should set this to `thread`. Note that
this may reduce the performance due to Python's Global
Interpreter Lock (`GIL <https://stackoverflow.com/q/1294382>`).
worker_initializer: DEPRECATED! Must be a reference to a function
that is called once when initialising a new worker. Can be used
to preload variables into a worker's workspace. See also
https://docs.python.org/3.1/library/multiprocessing.html#module-multiprocessing.pool
for more information.
worker_initargs: DEPRECATED! A tuple with arguments for
`worker_initializer`.
return_info: If true, return a FileInfo object with each return
value indicating to which file the function was applied.
error_to_warning: Normally, if an exception is raised during
reading of a file, this method is aborted. However, if you set
this to *true*, only a warning is given and None is returned.
This parameter will be ignored if `on_content=True`.
**find_kwargs: Additional keyword arguments that are allowed
for :meth:`find` such as `start` or `end`.
Returns:
A list with tuples of a FileInfo object and the return value of the
function applied to this file. If *output* is set, the second
element is not the return value but a boolean values indicating
whether the return value was not None.
Examples:
.. code-block:: python
## Imaging you want to calculate some statistical values from the
## data of the files
def calc_statistics(content, file_info):
# return the mean and maximum value
return content["data"].mean(), content["data"].max()
results = fileset.map(
calc_statistics, start="2018-01-01", end="2018-01-02",
on_content=True, return_info=True,
)
# This will be run after processing all files...
for file, result in results
print(file) # prints the FileInfo object
print(result) # prints the mean and maximum value
## If you need the results directly, you can use imap instead:
results = fileset.imap(
calc_statistics, start="2018-01-01", end="2018-01-02",
on_content=True,
)
for result in results
# After the first file has been processed, this will be run
# immediately ...
print(result) # prints the mean and maximum value
If you need to pass some args to the function, use the parameters
*args* and *kwargs*:
.. code-block:: python
def calc_statistics(arg1, content, kwarg1=None):
# return the mean and maximum value
return content["data"].mean(), content["data"].max()
# Note: If you do not use the start or the end parameter, all
# files in the fileset are going to be processed:
results = fileset.map(
calc_statistics, args=("value1",),
kwargs={"kwarg1": "value2"}, on_content=True,
)
"""
pool_class, pool_args, worker_args = \
self._configure_pool_and_worker_args(
func, args, kwargs, files, on_content, pass_info, read_args,
output, max_workers, worker_type,
#worker_initializer, worker_initargs,
return_info, error_to_warning, **find_kwargs
)
with pool_class(**pool_args) as pool:
# Process all found files with the arguments:
return list(pool.map(
self._call_map_function, worker_args,
))
def imap(self, *args, **kwargs):
"""Apply a function on files and return the result immediately
This method does exact the same as :meth:`map` but works as a generator
and is therefore less memory space consuming.
Args:
*args: The same positional arguments as for :meth:`map`.
**kwargs: The same keyword arguments as for :meth:`map`.
Yields:
A tuple with the FileInfo object of the processed file and the
return value of the applied function. If `output` is set, the
second element is not the return value but a boolean values
indicating whether the return value was not None.
"""
pool_class, pool_args, worker_args = \
self._configure_pool_and_worker_args(*args, **kwargs)
worker_queue = deque()
with pool_class(**pool_args) as pool:
workers = pool_args["max_workers"]
if workers is None:
workers = 1
for func_args in worker_args:
wait = len(worker_queue) >= workers
if wait:
yield worker_queue.popleft().result()
worker_queue.append(
pool.submit(
self._call_map_function,
func_args,
)
)
# Flush the rest:
while worker_queue:
yield worker_queue.popleft().result()
def _configure_pool_and_worker_args(
self, func, args=None, kwargs=None, files=None,
on_content=False, pass_info=None, read_args=None, output=None,
max_workers=None, worker_type=None,
#worker_initializer=None, worker_initargs=None,
return_info=False, error_to_warning=False, **find_args
):
if func is None:
raise ValueError("The parameter `func` must be given!")
if files is not None \
and (find_args.get("start", None) is not None
or find_args.get("end", None) is not None):
raise ValueError(
"Either `files` or `start` and `end` must be given. Not all of"
" them!")
# Convert the path to a FileSet object:
if isinstance(output, str):
output_path = output
output = self.copy()
output.path = output_path
if worker_type is None:
# If the output is directly stored to a new FileSet, it is always
# better to use processes
if output is None:
worker_type = self.worker_type
else:
worker_type = "process"
if worker_type == "process":
pool_class = ProcessPoolExecutor
if max_workers is None:
max_workers = self.max_processes
elif worker_type == "thread":
pool_class = ThreadPoolExecutor
if max_workers is None:
max_workers = self.max_threads
else:
raise ValueError(f"Unknown worker type '{worker_type}!")
pool_args = {
"max_workers": max_workers,
#"initializer": worker_initializer,
#"initargs": worker_initargs,
}
if kwargs is None:
kwargs = {}
if read_args is None:
read_args = {}
if files is None:
files = self.find(**find_args)
worker_args = (
(self, file, func, args, kwargs, pass_info, output,
on_content, read_args, return_info, error_to_warning)
for file in files
)
return pool_class, pool_args, worker_args
@staticmethod
def _call_map_function(all_args):
""" This is a small wrapper function to call the function that is
called on fileset files via .map().
Args:
all_args: A tuple containing following elements:
(FileSet object, file_info, function,
args, kwargs, output, on_content, read_args, return_info)
Returns:
The return value of *function* called with the arguments *args* and
*kwargs*. This arguments have been extended by file info (and file
content).
"""
fileset, file_info, func, args, kwargs, pass_info, output, \
on_content, read_args, return_info, error_to_warning = all_args
args = [] if args is None else list(args)
def _return(file_info, return_value):
"""Small helper for return / not return the file info object."""
if return_info:
return file_info, return_value
else:
return return_value
if on_content:
try:
# file_info could be a bundle of files
if isinstance(file_info, FileInfo):
file_content = fileset.read(file_info, **read_args)
else:
file_content = \
fileset.collect(files=file_info, read_args=read_args)
args.append(file_content)
except Exception as e:
if error_to_warning:
msg = f"[ERROR] Could not read the file(s):\n{file_info}\n"
msg += str(e) + "\n"
warnings.warn(
msg + "".join(traceback.format_tb(e.__traceback__)),
RuntimeWarning
)
return _return(file_info, None)
raise e
if not on_content or pass_info:
args.append(file_info)
# Call the function:
return_value = func(*args, **kwargs)
if output is None:
# No output is needed, simply return the file info and the
# function's return value
return _return(file_info, return_value)
if return_value is None:
# We cannot write a file with the content None, hence simply return
# the file info and False indicating that we did not write a file.
return _return(file_info, False)
# file_info could be a bundle of files
if isinstance(file_info, FileInfo):
new_filename = output.get_filename(
file_info.times, fill=file_info.attr
)
else:
start_times, end_times = zip(
*(file.times for file in file_info)
)
new_filename = output.get_filename(
(min(start_times), max(end_times)), fill=file_info[0].attr
)
output.write(return_value, new_filename, in_background=False)
return _return(file_info, True)
def match(
self, other, start=None, end=None, max_interval=None,
filters=None, other_filters=None):
"""Find matching files between two filesets
Matching files are files that overlap each in their time coverage.
Args:
other: Another FileSet object.
start: Start date either as datetime object or as string
("YYYY-MM-DD hh:mm:ss"). Year, month and day are required.
Hours, minutes and seconds are optional.
end: End date. Same format as "start".
max_interval: Maximal time interval between two overlapping files.
If it is an integer or float, it will be interpreted as
seconds.
filters: The same filter argument that is allowed for
:meth:`find`.
other_filters: The same as `filter` but it will be applied to
`other`.
Yields:
A tuple with the :class:`FileInfo` object from this fileset and a
list with matching files from the other fileset.
Examples:
TODO: Add example
"""
if max_interval is not None:
max_interval = to_timedelta(max_interval, numbers_as="seconds")
start = to_datetime(start) - max_interval
end = to_datetime(end) + max_interval
files1 = list(
self.find(start, end, filters=filters)
)
files2 = list(
other.find(start, end, filters=other_filters)
)
# Convert the times (datetime objects) to seconds (integer)
times1 = np.asarray([
file.times
for file in files1
]).astype("M8[s]").astype(int).tolist()
times2 = np.asarray([
file.times
for file in files2
]).astype("M8[s]").astype(int)
if max_interval is not None:
# Expand the intervals of the secondary fileset to close-in-time
# intervals.
times2[:, 0] -= int(max_interval.total_seconds())
times2[:, 1] += int(max_interval.total_seconds())
# Search for all overlapping intervals:
tree = IntervalTree(times2)
results = tree.query(times1)
for i, overlapping_files in enumerate(results):
matches = [files2[oi] for oi in sorted(overlapping_files)]
if matches:
yield files1[i], matches
def move(
self, target=None, convert=None, copy=False, **kwargs,
):
"""Move (or copy) files from this fileset to another location
Args:
target: Either a FileSet object or the path (containing
placeholders) where the files should be moved to.
convert: If true, the files will be read by the old fileset's file
handler and written to their new location by using the new file
handler from `target`. Both file handlers must be compatible,
i.e. the object that the old file handler's read method returns
must handable for the new file handler's write method. You
can also set this to a function that converts the return value
of the read method into something else before it will be passed
to the write method. Default is false, i.e. the file will be
simply moved without converting.
copy: If true, then the original files will be copied instead of
moved.
**kwargs: Additional keyword arguments that are allowed
for :meth:`find` such as `start`, `end` or `files`.
Returns:
New FileSet object with the new files.
Examples:
.. code-block:: python
## Copy all files between two dates to another location
old_fileset = FileSet(
"old/path/{year}/{month}/{day}/{hour}{minute}{second}.nc",
)
# New fileset with other path
new_fileset = FileSet(
"new/path/{year}/{doy}/{hour}{minute}{second}.nc",
)
old_fileset.move(
new_fileset, start="2017-09-15", end="2017-09-23",
)
.. code-block:: python
## Copy all files between two dates to another location and convert
## them to a different format
from typhon.files import CSV, NetCDF4
old_fileset = FileSet(
"old/path/{year}/{month}/{day}/{hour}{minute}{second}.nc"
)
new_fileset = FileSet(
"new/path/{year}/{doy}/{hour}{minute}{second}.csv"
)
# Note that this only works if both file handlers are compatible
new_fileset = old_fileset.move(
new_fileset, convert=True, start="2017-09-15",
end="2017-09-23",
)
# It is also possible to set the new path directly:
new_fileset = old_fileset.move(
"new/path/{year}/{doy}/{hour}{minute}{second}.csv",
convert=True, start="2017-09-15", end="2017-09-23",
)
"""
# Convert the path to a FileSet object:
if not isinstance(target, FileSet):
destination = self.copy()
destination.path = target
else:
destination = target
if convert is None:
convert = False
if self.single_file:
file_info = self.get_info(self.path)
FileSet._move_single_file(
file_info, self, destination, convert, copy
)
else:
if destination.single_file:
raise ValueError(
"Cannot move files from multi-file to single-file set!")
move_args = {
"fileset": self,
"destination": destination,
"convert": convert,
"copy": copy
}
# Copy the files
self.map(FileSet._move_single_file, kwargs=move_args, **kwargs)
return destination
def _move_single_file(self,
file_info, fileset, destination, convert, copy):
"""This is a small wrapper function for moving files. It is better to
use :meth:`FileSet.move` directly.
Args:
fileset:
file_info: FileInfo object of the file that should be to copied.
destination:
convert:
copy:
Returns:
None
"""
# Generate the new file name
new_filename = destination.get_filename(
file_info.times, fill=file_info.attr
)
# Shall we simply move or even convert the files?
if convert:
# Read the file with the current file handler
data = fileset.read(file_info)
# Maybe the user has given us a converting function?
if callable(convert):
data = convert(data)
# Store the data of the file with the new file handler
destination.write(data, new_filename)
if not copy:
os.remove(file_info.path)
else:
# Create the new directory if necessary.
self.file_system.makedirs(
posixpath.dirname(new_filename), exist_ok=True)
if copy:
self.file_system.copy(file_info.path, new_filename)
else:
self.file_system.move(file_info.path, new_filename)
@property
def name(self):
"""Get or set the fileset's name.
Returns:
A string with the fileset's name.
"""
return self._name
@name.setter
def name(self, value):
if value is None:
value = str(id(self))
self._name = value
def _to_datetime_args(self, placeholder):
"""Get datetime args from placeholders for start and end date.
Args:
placeholder: A dictionary containing time placeholders.
Returns:
A tuple of two dictionaries
"""
start_args = {
p: int(value)
for p, value in placeholder.items()
if not p.startswith("end_") and p in self._time_placeholder
}
end_args = {
p[len("end_"):]: int(value)
for p, value in placeholder.items()
if p.startswith("end_") and p in self._time_placeholder
}
start_datetime_args = self._standardise_datetime_args(start_args)
# If temporal placeholders are set, we need at least year, month and day
if (start_datetime_args
and not {'year', 'month', 'day'} & set(start_datetime_args.keys())):
raise ValueError('Cannot use temporal placeholders if year, month '
'and day are not set.')
end_datetime_args = self._standardise_datetime_args(end_args)
return start_datetime_args, end_datetime_args
def _standardise_datetime_args(self, args):
"""Replace some placeholders to datetime-conform placeholder.
Args:
args: A dictionary of placeholders.
Returns:
The standardised placeholder dictionary.
"""
year2 = args.pop("year2", None)
if year2 is not None:
if year2 < self.year2_threshold:
args["year"] = 2000 + year2
else:
args["year"] = 1900 + year2
# There is only microseconds as parameter for datetime for sub-seconds.
# So if one of them is set, we replace them and setting microsecond
# instead.
if {'decisecond', 'centisecond', 'millisecond', 'microsecond'} & set(args.keys()): # noqa
args["microsecond"] = \
100000*args.pop("decisecond", 0) \
+ 10000*args.pop("centisecond", 0) \
+ 1000*args.pop("millisecond", 0) \
+ args.pop("microsecond", 0)
doy = args.pop("doy", None)
if doy is not None:
date = datetime(args["year"], 1, 1) + timedelta(doy - 1)
args["month"] = date.month
args["day"] = date.day
return args
def parse_filename(self, filename, template=None,):
"""Parse the filename with temporal and additional regular expressions.
This method uses the standard temporal placeholders which might be
overwritten by the user-defined placeholders.
Args:
filename: Path and name of the file.
template: Template with regex/placeholders that should be used.
Default is *FileSet.path*.
Returns:
A dictionary with filled placeholders.
"""
if template is None:
regex = re.compile(self._filled_path)
else:
if isinstance(template, str):
regex = self._fill_placeholders(template, compile=True)
else:
regex = template
results = regex.match(filename)
if not results:
raise ValueError(
"Could not parse the filename; it does not match the given "
"template.")
else:
return results.groupdict()
@property
def path(self):
"""Gets or sets the path to the fileset's files.
Returns:
A string with the path (can contain placeholders or wildcards.)
"""
if self.has_root:
# We need the absolute path if it exists:
# (but still with normal path separators)
# can't use posixpath.abspath, that (1) won't recognise c: as
# absolute and (2) still keep \\, so explicitly replace instead
return os.path.abspath(self._path).replace(os.sep, "/")
else:
# Or we don't, because on other file systems, such as s3fs or zip,
# there are no absolute paths
return self._path
@path.setter
def path(self, value):
if value is None:
raise ValueError("The path parameter cannot be None!")
self._path = value
# The path consists of three parts: the base directory, the sub
# directory and the filename. The sub directory and filename may
# contain regex/placeholder, the base directory not. We need to split
# the path into these three parts to enable file finding.
directory = posixpath.dirname(self.path)
index_of_sub_directory = \
next(
(i for i, ch in enumerate(directory)
if ch in self._special_chars), None
)
if index_of_sub_directory is None:
# There is no sub directory
self._base_dir = directory
else:
self._base_dir = directory[:index_of_sub_directory]
self._sub_dir = directory[index_of_sub_directory:]
# Later, we iterate over all possible sub directories and find
# those that match the regex / placeholders. Hence, we split the
# sub directory into chunks for each hierarchy level:
# (with posixpath, because fsspec always uses this)
self._sub_dir_chunks = self._sub_dir.split(posixpath.sep)
# The sub directory time resolution is needed for find_closest:
self._sub_dir_time_resolution = self._get_time_resolution(
self._sub_dir
)[1]
# Retrieve the used placeholder names from the path:
self._path_placeholders = set(re.findall(r"{(\w+)}", self.path))
# Set additional user-defined placeholders to default values (
# non-greedy wildcards).
self.set_placeholders(**{
p: ".+?"
for p in self._path_placeholders.difference(self._time_placeholder)
})
# Get all temporal placeholders from the path (for ending time):
end_time_placeholders = {
p[len("end_"):] for p in self._path_placeholders
if p.startswith("end") and p in self._time_placeholder
}
# If the end time retrieved from the path is younger than the start
# time, the end time will be incremented by this value:
self._end_time_superior = \
self._get_superior_time_resolution(end_time_placeholders)
# Flag whether this is a single file fileset or not. We simply check
# whether the path contains special characters:
self.single_file = not any(
True for ch in self.path
if ch in self._special_chars
)
self._path_extension = os.path.splitext(self.path)[0].lstrip(".")
@staticmethod
def _get_superior_time_resolution(placeholders, ):
"""Get the superior time resolution of all placeholders.
Examples:
The superior time resolution of seconds are minutes, of hours are
days, etc.
Args:
placeholders: A list or dictionary with placeholders.
Returns:
A pandas compatible frequency string or None if the superior time
resolution is higher than a year.
"""
# All placeholders from which we know the resolution:
placeholders = set(placeholders).intersection(
FileSet._temporal_resolution
)
if not placeholders:
return None
highest_resolution = max(
(FileSet._temporal_resolution[tp] for tp in placeholders),
)
highest_resolution_index = list(
FileSet._temporal_resolution.values()).index(highest_resolution)
if highest_resolution_index == 0:
return None
resolutions = list(FileSet._temporal_resolution.values())
superior_resolution = resolutions[highest_resolution_index - 1]
return pd.Timedelta(superior_resolution).to_pytimedelta()
@staticmethod
def _get_time_resolution(path_or_dict, highest=True):
"""Get the lowest/highest time resolution of all placeholders
Seconds have a higher time resolution than minutes, etc. If our path
contains seconds, minutes and hours, this will return a timedelta
object representing 1 second if *highest* is True otherwise 1 hour.
Args:
path_or_dict: A path or dictionary with placeholders.
highest: If true, search for the highest time resolution instead of
the lowest.
Returns:
The placeholder name with the lowest / highest resolution and
the representing timedelta object.
"""
if isinstance(path_or_dict, str):
placeholders = set(re.findall(r"{(\w+)}", path_or_dict))
if "doy" in placeholders:
placeholders.remove("doy")
placeholders.add("day")
if "year2" in placeholders:
placeholders.remove("year2")
placeholders.add("year")
else:
placeholders = set(path_or_dict.keys())
# All placeholders from which we know the resolution:
placeholders = set(placeholders).intersection(
FileSet._temporal_resolution
)
if not placeholders:
# There are no placeholders in the path, therefore we return the
# highest time resolution automatically
return "year", FileSet._temporal_resolution["year"]
# E.g. if we want to find the temporal placeholder with the lowest
# resolution, we have to search for the maximum of their values because
# they are represented as timedelta objects, i.e. month > day > hour,
# etc. expect
if highest:
placeholder = min(
placeholders, key=lambda k: FileSet._temporal_resolution[k]
)
else:
placeholder = max(
placeholders, key=lambda k: FileSet._temporal_resolution[k]
)
return placeholder, FileSet._temporal_resolution[placeholder]
def _fill_placeholders(self, path, extra_placeholder=None, compile=False):
"""Fill all placeholders in a path with its RegExes and compile it.
Args:
path:
extra_placeholder:
compile: Compile as regex before return
Returns:
"""
if extra_placeholder is None:
extra_placeholder = {}
placeholder = {
**self._time_placeholder,
**self._user_placeholder,
**extra_placeholder,
}
# Mask all dots and convert the asterisk to regular expression syntax:
path = path.replace("\\", "\\\\").replace(".", r"\.").replace("*", ".*?")
# due to support for external file systems, file separators could be
# either local (os.sep) or forward / (always on s3fs, ftp, elsewhere).
# Therefore, let's make \ also match / on Windows.
if os.sep != "/":
path = path.replace("\\\\", "[\\\\/]")
# Python's standard regex module (re) cannot handle multiple groups
# with the same name. Hence, we need to cover duplicated placeholders
# so that only the first of them does group capturing.
path_placeholders = re.findall(r"{(\w+)}", path)
duplicated_placeholders = {
p: self._remove_group_capturing(p, placeholder[p])
for p in path_placeholders if path_placeholders.count(p) > 1
}
if duplicated_placeholders:
for p, v in duplicated_placeholders.items():
split_index = path.index("{"+p+"}") + len(p) + 2
# The value of the placeholder might contain a { or } as regex.
# We have to escape them because we use the formatting function
# later.
v = v.replace("{", "{{").replace("}", "}}")
changed_part = path[split_index:].replace("{" + p + "}", v)
path = path[:split_index] + changed_part
try:
# Prepare the regex for the template, convert it to an exact match:
regex_string = "^" + path.format(**placeholder) + "$"
except KeyError as err:
raise UnknownPlaceholderError(self.name, err.args[0])
except ValueError as err:
raise PlaceholderRegexError(self.name, str(err))
if compile:
return re.compile(regex_string)
else:
return regex_string
@staticmethod
def _complete_placeholders_regex(placeholder):
"""Complete placeholders' regexes to capture groups.
Args:
placeholder: A dictionary of placeholders and their matching
regular expressions
Returns:
"""
return {
name: FileSet._add_group_capturing(name, value)
for name, value in placeholder.items()
}
@staticmethod
def _add_group_capturing(placeholder, value):
"""Complete placeholder's regex to capture groups.
Args:
placeholder: A dictionary of placeholders and their matching
regular expressions
Returns:
"""
if value is None:
return None
elif isinstance(value, (tuple, list)):
return f"(?P<{placeholder}>{'|'.join(value)})"
else:
return f"(?P<{placeholder}>{value})"
@staticmethod
def _remove_group_capturing(placeholder, value):
if f"(?P<{placeholder}>" not in value:
return value
else:
# The last character is the closing parenthesis:
return value[len(f"(?P<{placeholder}>"):-1]
@expects_file_info()
def read(self, file_info, **read_args):
"""Open and read a file
Notes:
You need to specify a file handler for this fileset before you
can use this method.
Args:
file_info: A string, path-alike object or a
:class:`~typhon.files.handlers.common.FileInfo` object.
**read_args: Additional key word arguments for the
*read* method of the used file handler class.
Returns:
The content of the read file.
"""
if self.handler is None:
raise NoHandlerError(f"Could not read '{file_info.path}'!")
read_args = {**self.read_args, **read_args}
if self.decompress:
with typhon.files.decompress(file_info.path, tmpdir=self.temp_dir)\
as decompressed_path:
decompressed_file = file_info.copy()
decompressed_file.path = decompressed_path
data = self.handler.read(decompressed_file, **read_args)
else:
data = self.handler.read(file_info, **read_args)
# Maybe the user wants to do some post-processing?
if self.post_reader is not None:
data = self.post_reader(file_info, data)
return data
def _retrieve_time_coverage(self, filled_placeholder,):
"""Retrieve the time coverage from a dictionary of placeholders.
Args:
filled_placeholder: A dictionary with placeholders and their
fillings.
Returns:
A tuple of two datetime objects.
"""
if not filled_placeholder:
return None
start_args, end_args = self._to_datetime_args(filled_placeholder)
if start_args:
start_date = datetime(**start_args)
else:
start_date = None
if end_args:
end_args = {**start_args, **end_args}
end_date = datetime(**end_args)
# Sometimes the filename does not explicitly provide the complete
# end date. Imagine there is only hour and minute given, then day
# change would not be noticed. Therefore, make sure that the end
# date is always bigger (later) than the start date.
if end_date < start_date:
end_date += self._end_time_superior
else:
end_date = None
return start_date, end_date
def reset_cache(self):
"""Reset the information cache
Returns:
None
"""
self.info_cache = {}
def save_cache(self, filename):
"""Save the information cache to a JSON file
Returns:
None
"""
if filename is not None:
# First write all to a backup file. If something happens, only the
# backup file will be overwritten.
with open(filename+".backup", 'w') as file:
# We cannot save datetime objects with json directly. We have
# to convert them to strings first:
info_cache = [
info.to_json_dict()
for info in self.info_cache.values()
]
json.dump(info_cache, file)
# Then rename the backup file
shutil.move(filename+".backup", filename)
def get_placeholders(self):
"""Get placeholders for this FileSet.
Returns:
A dictionary of placeholder names set by the user (i.e. excluding
the temporal placeholders) and their regexes.
"""
return self._user_placeholder.copy()
def set_placeholders(self, **placeholders):
"""Set placeholders for this FileSet.
Args:
**placeholders: Placeholders as keyword arguments.
Returns:
None
"""
self._user_placeholder.update(
self._complete_placeholders_regex(placeholders)
)
# Update the path regex (uses automatically the user-defined
# placeholders):
self._filled_path = self._fill_placeholders(self.path)
@property
def time_coverage(self):
"""Get and set the time coverage of the files of this fileset
Setting the time coverage after initialisation resets the info cache of
the fileset object.
Returns:
The time coverage of the whole fileset (if it is a single file) as
tuple of datetime objects or (if it is a multi file fileset) the
fixed time duration of each file as timedelta object.
"""
return self._time_coverage
@time_coverage.setter
def time_coverage(self, value):
if self.single_file:
if value is None:
# The default for single file filesets:
self._time_coverage = [
datetime.min,
datetime.max
]
else:
self._time_coverage = [
to_datetime(value[0]),
to_datetime(value[1]),
]
elif value is not None:
self._time_coverage = to_timedelta(value)
else:
self._time_coverage = None
# Reset the info cache because some file information may have changed
# now
self.info_cache = {}
def to_dataframe(self, include_times=False, **kwargs):
"""Create a pandas.Dataframe from this FileSet
This method creates a pandas.DataFrame containing all the filenames in this
FileSet as row indices and the placeholders as columns.
Args:
include_times: If True, also the start and end time of each file are
included. Default: False.
**kwargs: Additional keyword arguments which are allowed for
:meth:`~typhon.files.filset.FileSet.find`.
Returns:
A pandas.DataFrame with the filenames as row indices and the
placeholders as columns.
Examples:
.. code-block:: python
# Example directory:
# dir/
# Satellite-A/
# 20190101-20190201.nc
# 20190201-20190301.nc
# Satellite-B/
# 20190101-20190201.nc
# 20190201-20190301.nc
from typhon.files import FileSet
files = FileSet(
'dir/{satellite}/{year}{month}{day}'
'-{end_year}{end_month}{end_day}.nc'
)
df = files.to_dataframe()
# Content of df:
# satellite
# /dir/Satellite-B/20190101-20190201.nc Satellite-B
# /dir/Satellite-A/20190101-20190201.nc Satellite-A
# /dir/Satellite-B/20190201-20190301.nc Satellite-B
# /dir/Satellite-A/20190201-20190301.nc Satellite-A
"""
if include_times:
data = [
(file.path, *file.times, *file.attr.values())
for file in self.find(**kwargs)
]
columns = ['start_time', 'end_time']
else:
data = [
(file.path, *file.attr.values())
for file in self.find(**kwargs)
]
columns = []
df = pd.DataFrame(data).set_index(0)
columns += list(self.get_placeholders().keys())
df.columns = columns
del df.index.name
return df
def write(self, data, file_info, in_background=False, **write_args):
"""Write content to a file by using the FileSet's file handler.
If the filename extension is a compression format (such as *zip*,
etc.) and *FileSet.compress* is set to true, the file will be
compressed afterwards.
Notes:
You need to specify a file handler for this fileset before you
can use this method.
Args:
data: An object that can be stored by the used file handler class.
file_info: A string, path-alike object or a
:class:`~typhon.files.handlers.common.FileInfo` object.
in_background: If true (default), this runs the writing process in
a background thread so it does not pause the main process.
**write_args: Additional key word arguments for the *write* method
of the used file handler object.
Returns:
None
Examples:
.. code-block:: python
import matplotlib.pyplot as plt
from typhon.files import FileSet, Plotter
# Define a fileset consisting of multiple files:
plots = FileSet(
path="/dir/{year}/{month}/{day}/{hour}{minute}{second}.png",
handler=Plotter,
)
# Let's create a plot example
fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])
ax.set_title("Data from 2018-01-01")
## To save the plot as a file of the fileset, you have two options:
# Use this simple expression:
plots["2018-01-01"] = fig
# OR use write in combination with get_filename
filename = plots.get_filename("2018-01-01")
plots.write(fig, filename)
# Hint: If saving the plot takes a lot of time but you want to
# continue with the program in the meanwhile, you can use the
# *in_background* option. This saves the plot in a background
# thread.
plots.write(fig, filename, in_background=True)
# continue with other stuff immediately and do not wait until the
# plot is saved...
do_other_stuff(...)
"""
if isinstance(file_info, str):
file_info = FileInfo(file_info)
if self.handler is None:
raise NoHandlerError(
f"Could not write data to '{file_info.path}'!"
)
if in_background:
warnings.warn("in_background option is deprecated!")
# Run this function again but as a background thread in a queue:
#threading.Thread(
# target=FileSet.write, args=(self, data, file_info),
# kwargs=write_args.update(in_background=False),
#).start()
#return
write_args = {**self.write_args, **write_args}
# The users should not be bothered with creating directories by
# themselves.
self.make_dirs(file_info.path)
if self.compress:
with typhon.files.compress(file_info.path, tmpdir=self.temp_dir) \
as compressed_path:
compressed_file = file_info.copy()
compressed_file.path = compressed_path
self.handler.write(data, compressed_file, **write_args)
else:
self.handler.write(data, file_info, **write_args)
class FileSetManager(dict):
def __init__(self, *args, **kwargs):
"""Simple container for multiple FileSet objects.
You can use it as a native dictionary.
More functionality will be added in future.
Example:
.. code-block:: python
filesets = FileSetManager()
filesets += FileSet(
name="images",
files="path/to/files.png",
)
# do something with it
for name, fileset in filesets.items():
fileset.find(...)
"""
super(FileSetManager, self).__init__(*args, **kwargs)
def __iadd__(self, fileset):
if fileset.name in self:
warnings.warn(
"FileSetManager: Overwrite fileset with name '%s'!"
% fileset.name, RuntimeWarning)
self[fileset.name] = fileset
return self
| [
"atexit.register",
"posixpath.dirname",
"traceback.format_tb",
"numpy.argmin",
"gc.collect",
"pandas.Grouper",
"typhon.utils.timeutils.to_datetime",
"collections.deque",
"pandas.DataFrame",
"typhon.utils.unique",
"re.findall",
"datetime.timedelta",
"pandas.Timedelta",
"collections.Counter"... | [((1046, 1073), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1063, 1073), False, 'import logging\n'), ((29011, 29076), 'typhon.utils.unique', 'unique', (['(secondary for match in secondaries for secondary in match)'], {}), '(secondary for match in secondaries for secondary in match)\n', (29017, 29076), False, 'from typhon.utils import unique\n'), ((29737, 29803), 'collections.Counter', 'Counter', (['(secondary for match in secondaries for secondary in match)'], {}), '(secondary for match in secondaries for secondary in match)\n', (29744, 29803), False, 'from collections import Counter, deque, OrderedDict\n'), ((36097, 36109), 'gc.collect', 'gc.collect', ([], {}), '()\n', (36107, 36109), False, 'import gc\n'), ((38929, 38943), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (38937, 38943), False, 'from copy import deepcopy\n'), ((45507, 45532), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(1)'}), '(microseconds=1)\n', (45516, 45532), False, 'from datetime import datetime, timedelta\n'), ((49422, 49438), 'itertools.tee', 'tee', (['file_finder'], {}), '(file_finder)\n', (49425, 49438), False, 'from itertools import tee\n'), ((58924, 58946), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['timestamp'], {}), '(timestamp)\n', (58935, 58946), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((78113, 78120), 'collections.deque', 'deque', ([], {}), '()\n', (78118, 78120), False, 'from collections import Counter, deque, OrderedDict\n'), ((86231, 86251), 'typhon.trees.IntervalTree', 'IntervalTree', (['times2'], {}), '(times2)\n', (86243, 86251), False, 'from typhon.trees import IntervalTree\n'), ((96566, 96594), 'posixpath.dirname', 'posixpath.dirname', (['self.path'], {}), '(self.path)\n', (96583, 96594), False, 'import posixpath\n'), ((103369, 103397), 're.findall', 're.findall', (['"""{(\\\\w+)}"""', 'path'], {}), "('{(\\\\w+)}', path)\n", (103379, 103397), False, 'import re\n'), ((7417, 7436), 'datetime.timedelta', 'timedelta', ([], {'days': '(366)'}), '(days=366)\n', (7426, 7436), False, 'from datetime import datetime, timedelta\n'), ((7455, 7473), 'datetime.timedelta', 'timedelta', ([], {'days': '(31)'}), '(days=31)\n', (7464, 7473), False, 'from datetime import datetime, timedelta\n'), ((7490, 7507), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (7499, 7507), False, 'from datetime import datetime, timedelta\n'), ((7525, 7543), 'datetime.timedelta', 'timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (7534, 7543), False, 'from datetime import datetime, timedelta\n'), ((7563, 7583), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(1)'}), '(minutes=1)\n', (7572, 7583), False, 'from datetime import datetime, timedelta\n'), ((7603, 7623), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(1)'}), '(seconds=1)\n', (7612, 7623), False, 'from datetime import datetime, timedelta\n'), ((7647, 7677), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(100000)'}), '(microseconds=100000)\n', (7656, 7677), False, 'from datetime import datetime, timedelta\n'), ((7702, 7731), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(10000)'}), '(microseconds=10000)\n', (7711, 7731), False, 'from datetime import datetime, timedelta\n'), ((7756, 7784), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(1000)'}), '(microseconds=1000)\n', (7765, 7784), False, 'from datetime import datetime, timedelta\n'), ((7809, 7834), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(1)'}), '(microseconds=1)\n', (7818, 7834), False, 'from datetime import datetime, timedelta\n'), ((18619, 18636), 'fsspec.implementations.local.LocalFileSystem', 'LocalFileSystem', ([], {}), '()\n', (18634, 18636), False, 'from fsspec.implementations.local import LocalFileSystem\n'), ((23946, 23966), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['item[0]'], {}), '(item[0])\n', (23957, 23966), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((23985, 24005), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['item[1]'], {}), '(item[1])\n', (23996, 24005), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((24040, 24057), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['item'], {}), '(item)\n', (24051, 24057), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((28117, 28135), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['start'], {}), '(start)\n', (28128, 28135), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((28175, 28191), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['end'], {}), '(end)\n', (28186, 28191), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((41325, 41346), 'typhon.trees.IntervalTree', 'IntervalTree', (['periods'], {}), '(periods)\n', (41337, 41346), False, 'from typhon.trees import IntervalTree\n'), ((45329, 45347), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['start'], {}), '(start)\n', (45340, 45347), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((45395, 45411), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['end'], {}), '(end)\n', (45406, 45411), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((47226, 47255), 're.compile', 're.compile', (['self._filled_path'], {}), '(self._filled_path)\n', (47236, 47255), False, 'import re\n'), ((52561, 52595), 'posixpath.join', 'posixpath.join', (["(base_dir + '*')", '""""""'], {}), "(base_dir + '*', '')\n", (52575, 52595), False, 'import posixpath\n'), ((54487, 54512), 'posixpath.join', 'posixpath.join', (['path', '"""*"""'], {}), "(path, '*')\n", (54501, 54512), False, 'import posixpath\n'), ((60121, 60177), 'typhon.trees.IntervalTree.interval_contains', 'IntervalTree.interval_contains', (['time_coverage', 'timestamp'], {}), '(time_coverage, timestamp)\n', (60151, 60177), False, 'from typhon.trees import IntervalTree\n'), ((60350, 60370), 'numpy.argmin', 'np.argmin', (['intervals'], {}), '(intervals)\n', (60359, 60370), True, 'import numpy as np\n'), ((61639, 61660), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['times[0]'], {}), '(times[0])\n', (61650, 61660), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((61684, 61705), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['times[1]'], {}), '(times[1])\n', (61695, 61705), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((61745, 61763), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['times'], {}), '(times)\n', (61756, 61763), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((70293, 70320), 'posixpath.dirname', 'posixpath.dirname', (['filename'], {}), '(filename)\n', (70310, 70320), False, 'import posixpath\n'), ((85250, 85298), 'typhon.utils.timeutils.to_timedelta', 'to_timedelta', (['max_interval'], {'numbers_as': '"""seconds"""'}), "(max_interval, numbers_as='seconds')\n", (85262, 85298), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((94910, 94939), 're.compile', 're.compile', (['self._filled_path'], {}), '(self._filled_path)\n', (94920, 94939), False, 'import re\n'), ((97680, 97713), 're.findall', 're.findall', (['"""{(\\\\w+)}"""', 'self.path'], {}), "('{(\\\\w+)}', self.path)\n", (97690, 97713), False, 'import re\n'), ((104511, 104535), 're.compile', 're.compile', (['regex_string'], {}), '(regex_string)\n', (104521, 104535), False, 'import re\n'), ((107592, 107614), 'datetime.datetime', 'datetime', ([], {}), '(**start_args)\n', (107600, 107614), False, 'from datetime import datetime, timedelta\n'), ((107754, 107774), 'datetime.datetime', 'datetime', ([], {}), '(**end_args)\n', (107762, 107774), False, 'from datetime import datetime, timedelta\n'), ((109113, 109156), 'shutil.move', 'shutil.move', (["(filename + '.backup')", 'filename'], {}), "(filename + '.backup', filename)\n", (109124, 109156), False, 'import shutil\n'), ((115875, 115927), 'warnings.warn', 'warnings.warn', (['"""in_background option is deprecated!"""'], {}), "('in_background option is deprecated!')\n", (115888, 115927), False, 'import warnings\n'), ((117521, 117623), 'warnings.warn', 'warnings.warn', (['("FileSetManager: Overwrite fileset with name \'%s\'!" % fileset.name)', 'RuntimeWarning'], {}), '("FileSetManager: Overwrite fileset with name \'%s\'!" % fileset\n .name, RuntimeWarning)\n', (117534, 117623), False, 'import warnings\n'), ((22365, 22432), 'atexit.register', 'atexit.register', (['FileSet.save_cache', 'self', 'self.info_cache_filename'], {}), '(FileSet.save_cache, self, self.info_cache_filename)\n', (22380, 22432), False, 'import atexit\n'), ((24084, 24109), 'datetime.timedelta', 'timedelta', ([], {'microseconds': '(1)'}), '(microseconds=1)\n', (24093, 24109), False, 'from datetime import datetime, timedelta\n'), ((46175, 46236), 'typhon.trees.IntervalTree.interval_overlaps', 'IntervalTree.interval_overlaps', (['file_info.times', '(start, end)'], {}), '(file_info.times, (start, end))\n', (46205, 46236), False, 'from typhon.trees import IntervalTree\n'), ((57386, 57437), 'pandas.Series', 'pd.Series', (['files', '[file.times[0] for file in files]'], {}), '(files, [file.times[0] for file in files])\n', (57395, 57437), True, 'import pandas as pd\n'), ((85319, 85337), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['start'], {}), '(start)\n', (85330, 85337), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((85371, 85387), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['end'], {}), '(end)\n', (85382, 85387), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((91400, 91431), 'posixpath.dirname', 'posixpath.dirname', (['new_filename'], {}), '(new_filename)\n', (91417, 91431), False, 'import posixpath\n'), ((94184, 94212), 'datetime.datetime', 'datetime', (["args['year']", '(1)', '(1)'], {}), "(args['year'], 1, 1)\n", (94192, 94212), False, 'from datetime import datetime, timedelta\n'), ((94215, 94233), 'datetime.timedelta', 'timedelta', (['(doy - 1)'], {}), '(doy - 1)\n', (94224, 94233), False, 'from datetime import datetime, timedelta\n'), ((99965, 99998), 'pandas.Timedelta', 'pd.Timedelta', (['superior_resolution'], {}), '(superior_resolution)\n', (99977, 99998), True, 'import pandas as pd\n'), ((100804, 100840), 're.findall', 're.findall', (['"""{(\\\\w+)}"""', 'path_or_dict'], {}), "('{(\\\\w+)}', path_or_dict)\n", (100814, 100840), False, 'import re\n'), ((109030, 109057), 'json.dump', 'json.dump', (['info_cache', 'file'], {}), '(info_cache, file)\n', (109039, 109057), False, 'import json\n'), ((110975, 110994), 'typhon.utils.timeutils.to_timedelta', 'to_timedelta', (['value'], {}), '(value)\n', (110987, 110994), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((113155, 113173), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (113167, 113173), True, 'import pandas as pd\n'), ((1541, 1561), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(1)'}), '(seconds=1)\n', (1550, 1561), False, 'from datetime import datetime, timedelta\n'), ((31685, 31697), 'gc.collect', 'gc.collect', ([], {}), '()\n', (31695, 31697), False, 'import gc\n'), ((54795, 54856), 'typhon.trees.IntervalTree.interval_overlaps', 'IntervalTree.interval_overlaps', (['file_info.times', '(start, end)'], {}), '(file_info.times, (start, end))\n', (54825, 54856), False, 'from typhon.trees import IntervalTree\n'), ((60289, 60306), 'numpy.asarray', 'np.asarray', (['times'], {}), '(times)\n', (60299, 60306), True, 'import numpy as np\n'), ((69671, 69686), 'json.load', 'json.load', (['file'], {}), '(file)\n', (69680, 69686), False, 'import json\n'), ((70057, 70161), 'warnings.warn', 'warnings.warn', (['f"""Could not load the file information from cache file \'{filename}\':\n{err}."""'], {}), '(\n f"""Could not load the file information from cache file \'{filename}\':\n{err}."""\n )\n', (70070, 70161), False, 'import warnings\n'), ((110825, 110846), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['value[0]'], {}), '(value[0])\n', (110836, 110846), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((110868, 110889), 'typhon.utils.timeutils.to_datetime', 'to_datetime', (['value[1]'], {}), '(value[1])\n', (110879, 110889), False, 'from typhon.utils.timeutils import set_time_resolution, to_datetime, to_timedelta\n'), ((48044, 48066), 're.compile', 're.compile', (['f"""{value}"""'], {}), "(f'{value}')\n", (48054, 48066), False, 'import re\n'), ((51397, 51434), 'posixpath.join', 'posixpath.join', (['old_dir', 'subdir_chunk'], {}), '(old_dir, subdir_chunk)\n', (51411, 51434), False, 'import posixpath\n'), ((53611, 53633), 'datetime.datetime', 'datetime', ([], {}), '(**attr_start)\n', (53619, 53633), False, 'from datetime import datetime, timedelta\n'), ((53669, 53689), 'datetime.datetime', 'datetime', ([], {}), '(**attr_end)\n', (53677, 53689), False, 'from datetime import datetime, timedelta\n'), ((85797, 85840), 'numpy.asarray', 'np.asarray', (['[file.times for file in files2]'], {}), '([file.times for file in files2])\n', (85807, 85840), True, 'import numpy as np\n'), ((57622, 57650), 'pandas.Grouper', 'pd.Grouper', ([], {'freq': 'bundle_size'}), '(freq=bundle_size)\n', (57632, 57650), True, 'import pandas as pd\n'), ((85665, 85708), 'numpy.asarray', 'np.asarray', (['[file.times for file in files1]'], {}), '([file.times for file in files1])\n', (85675, 85708), True, 'import numpy as np\n'), ((62599, 62630), 'datetime.datetime', 'datetime', (['start_time.year', '(1)', '(1)'], {}), '(start_time.year, 1, 1)\n', (62607, 62630), False, 'from datetime import datetime, timedelta\n'), ((63200, 63229), 'datetime.datetime', 'datetime', (['end_time.year', '(1)', '(1)'], {}), '(end_time.year, 1, 1)\n', (63208, 63229), False, 'from datetime import datetime, timedelta\n'), ((82698, 82734), 'traceback.format_tb', 'traceback.format_tb', (['e.__traceback__'], {}), '(e.__traceback__)\n', (82717, 82734), False, 'import traceback\n')] |
# Copyright 2020 The HuggingFace Team. All rights reserved.
# Copyright 2020 Google LLC
# Modified from the original HuggingFace version.
#
# 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.
"""Implements a T5 trainer class doing training and evaluation."""
import collections
import torch
import numpy as np
from torch import nn
from torch.utils.data.dataloader import DataLoader
from transformers import PreTrainedModel, logging
from transformers.configuration_fsmt import FSMTConfig
from transformers.file_utils import is_torch_tpu_available
from transformers.optimization import (
Adafactor,
AdamW,
get_constant_schedule,
get_constant_schedule_with_warmup,
get_cosine_schedule_with_warmup,
get_cosine_with_hard_restarts_schedule_with_warmup,
get_linear_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
)
from typing import Any, Dict, Optional, Tuple, Union
from torch.utils.data.dataset import Dataset
from seq2seq.adapters import MetaAdapterConfig
from seq2seq.utils import use_task_specific_params, reset_config
from seq2seq.data import MultiTaskBatchSampler
from .trainer import Trainer
logger = logging.get_logger(__name__)
arg_to_scheduler = {
"linear": get_linear_schedule_with_warmup,
"cosine": get_cosine_schedule_with_warmup,
"cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup,
"polynomial": get_polynomial_decay_schedule_with_warmup,
"constant": get_constant_schedule,
"constant_w_warmup": get_constant_schedule_with_warmup,
}
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
class T5Trainer(Trainer):
def __init__(self, config=None, data_args=None, dataset_sizes=None, adapter_config=None, multi_task_compute_metrics=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if config is None:
assert isinstance(
self.model, PreTrainedModel
), f"If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is {self.model.__class__}"
self.config = self._actual_model(self.model).config
else:
self.config = config
self.adapter_config = adapter_config
self. multi_task_compute_metrics = multi_task_compute_metrics
self.dataset_sizes = dataset_sizes
self.data_args = data_args
self.vocab_size = self.config.tgt_vocab_size if isinstance(self.config, FSMTConfig) else self.config.vocab_size
if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss):
assert (
self.config.pad_token_id is not None
), "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss calculation or doing label smoothing."
if self.config.pad_token_id is None and self.config.eos_token_id is not None:
logger.warn(
f"The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for padding.."
)
if self.args.label_smoothing == 0:
self.loss_fn = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
else:
# dynamically import label_smoothed_nll_loss
from third_party.utils import label_smoothed_nll_loss
self.loss_fn = label_smoothed_nll_loss
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use
something else, you can pass a tuple in the Trainer's init through
:obj:`optimizers`, or subclass and override this method in a subclass.
"""
if self.optimizer is None:
no_decay = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
if self.args.adafactor:
self.optimizer = Adafactor(
optimizer_grouped_parameters,
lr=self.args.learning_rate,
scale_parameter=False,
relative_step=False,
)
else:
self.optimizer = AdamW(
optimizer_grouped_parameters, lr=self.args.learning_rate, eps=self.args.adam_epsilon
)
if self.lr_scheduler is None:
self.lr_scheduler = self._get_lr_scheduler(num_training_steps)
else: # ignoring --lr_scheduler
logger.warn("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.")
def _get_lr_scheduler(self, num_training_steps):
schedule_func = arg_to_scheduler[self.args.lr_scheduler]
if self.args.lr_scheduler == "constant":
scheduler = schedule_func(self.optimizer)
elif self.args.lr_scheduler == "constant_w_warmup":
scheduler = schedule_func(self.optimizer, num_warmup_steps=self.args.warmup_steps)
else:
scheduler = schedule_func(
self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps
)
return scheduler
def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:
if is_torch_tpu_available() and xm.xrt_world_size() > 1:
num_replicas = xm.xrt_world_size()
rank = xm.get_ordinal()
elif self.args.local_rank != -1:
num_replicas = torch.distributed.get_world_size()
rank = self.args.local_rank
else:
num_replicas = 1
rank = 0
return MultiTaskBatchSampler(self.dataset_sizes, self.args.train_batch_size,
self.args.temperature, rank=rank,
num_replicas=num_replicas)
def _compute_loss(self, model, inputs, labels):
if self.args.label_smoothing == 0:
if self.data_args is not None and self.data_args.ignore_pad_token_for_loss:
# force training to ignore pad token
logits = model(**inputs, use_cache=False)[0]
loss = self.loss_fn(logits.view(-1, logits.shape[-1]), labels.view(-1))
else:
# compute usual loss via models
loss, logits = model(**inputs, labels=labels, use_cache=False)[:2]
else:
# compute label smoothed loss
logits = model(**inputs, use_cache=False)[0]
lprobs = torch.nn.functional.log_softmax(logits, dim=-1)
loss, _ = self.loss_fn(lprobs, labels, self.args.label_smoothing, ignore_index=self.config.pad_token_id)
return loss, logits
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted
to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
"""
multitask_sampler = self._get_train_sampler()
return DataLoader(self.train_dataset, batch_sampler=multitask_sampler,
collate_fn=self.data_collator)
def compute_loss(self, model, inputs):
labels = inputs.pop("labels")
loss, _ = self._compute_loss(model, inputs, labels)
return loss
def evaluate(self, eval_datasets: Optional[Dict[str, Dataset]] = None, metric_key_prefix: str = "eval") -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the
:obj:`__len__` method.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.
"""
results = {}
if eval_datasets is None:
eval_datasets = self.eval_dataset
for eval_task, eval_dataset in eval_datasets.items():
self.compute_metrics = self.multi_task_compute_metrics[eval_task]
model_config = self.model.config
use_task_specific_params(self.model, eval_task)
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
eval_dataloader = self.get_eval_dataloader(eval_dataset)
output = self.prediction_loop(
eval_dataloader,
description="Evaluation",
# No point gathering the predictions if there are no metrics, otherwise we defer to
# self.args.prediction_loss_only
prediction_loss_only=True if self.compute_metrics is None else None,
metric_key_prefix=metric_key_prefix
)
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
tasks_metric = {eval_task + "_" + k: v for k, v in output.metrics.items()}
for key in sorted(tasks_metric.keys()):
logger.info(f" {key} = {tasks_metric[key]}")
results.update(tasks_metric)
reset_config(self.model, model_config)
# Computes the average metrics across all the tasks without their corresponding losses.
metrics = [results[key] for key in results.keys() if "loss" not in key]
results[metric_key_prefix+'_average_metrics'] = np.mean(metrics)
self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, results)
return results
def prediction_step(
self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool
) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model.
Most models expect the targets under the argument :obj:`labels`.
Check your model's documentation for all accepted arguments.
prediction_loss_only (:obj:`bool`):
Whether or not to return the loss only.
Return:
Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
A tuple with the loss, logits and labels (each being optional).
"""
inputs = self._prepare_inputs(inputs)
gen_kwargs = {
"max_length": self.config.max_length,
"num_beams": self.config.num_beams
}
gen_kwargs["task"] = inputs["task"]
gen_kwargs["task_embedding"] = model.task_embedding_controller(inputs["task"]) if \
(self.config.train_adapters and isinstance(self.adapter_config, MetaAdapterConfig)) else None
if self.args.predict_with_generate and not self.args.prediction_loss_only:
generated_tokens = self.model.generate(
inputs["input_ids"],
attention_mask=inputs["attention_mask"],
**gen_kwargs,
)
# in case the batch is shorter than max length, the output should be padded
if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_kwargs["max_length"])
labels = inputs.pop("labels")
with torch.no_grad():
# compute loss on predict data
loss, logits = self._compute_loss(model, inputs, labels)
loss = loss.mean().detach()
if self.args.prediction_loss_only:
return (loss, None, None)
logits = generated_tokens if self.args.predict_with_generate else logits
if labels.shape[-1] < gen_kwargs["max_length"]:
labels = self._pad_tensors_to_max_len(labels, gen_kwargs["max_length"])
return (loss, logits, labels)
def _pad_tensors_to_max_len(self, tensor, max_length):
# If PAD token is not defined at least EOS token has to be defined
pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id
if pad_token_id is None:
raise ValueError(
f"Make sure that either `config.pad_token_id` or `config.eos_token_id`"
f" is defined if tensor has to be padded to `max_length`={max_length}"
)
padded_tensor = pad_token_id * torch.ones(
(tensor.shape[0], max_length), dtype=tensor.dtype, device=tensor.device
)
padded_tensor[:, : tensor.shape[-1]] = tensor
return padded_tensor
| [
"torch_xla.core.xla_model.xrt_world_size",
"torch.ones",
"seq2seq.utils.reset_config",
"transformers.file_utils.is_torch_tpu_available",
"torch.nn.CrossEntropyLoss",
"transformers.optimization.Adafactor",
"torch_xla.debug.metrics.metrics_report",
"torch_xla.core.xla_model.get_ordinal",
"transformers... | [((1648, 1676), 'transformers.logging.get_logger', 'logging.get_logger', (['__name__'], {}), '(__name__)\n', (1666, 1676), False, 'from transformers import PreTrainedModel, logging\n'), ((2036, 2060), 'transformers.file_utils.is_torch_tpu_available', 'is_torch_tpu_available', ([], {}), '()\n', (2058, 2060), False, 'from transformers.file_utils import is_torch_tpu_available\n'), ((6633, 6768), 'seq2seq.data.MultiTaskBatchSampler', 'MultiTaskBatchSampler', (['self.dataset_sizes', 'self.args.train_batch_size', 'self.args.temperature'], {'rank': 'rank', 'num_replicas': 'num_replicas'}), '(self.dataset_sizes, self.args.train_batch_size, self.\n args.temperature, rank=rank, num_replicas=num_replicas)\n', (6654, 6768), False, 'from seq2seq.data import MultiTaskBatchSampler\n'), ((8175, 8274), 'torch.utils.data.dataloader.DataLoader', 'DataLoader', (['self.train_dataset'], {'batch_sampler': 'multitask_sampler', 'collate_fn': 'self.data_collator'}), '(self.train_dataset, batch_sampler=multitask_sampler, collate_fn=\n self.data_collator)\n', (8185, 8274), False, 'from torch.utils.data.dataloader import DataLoader\n'), ((11513, 11529), 'numpy.mean', 'np.mean', (['metrics'], {}), '(metrics)\n', (11520, 11529), True, 'import numpy as np\n'), ((3693, 3757), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'ignore_index': 'self.config.pad_token_id'}), '(ignore_index=self.config.pad_token_id)\n', (3718, 3757), False, 'import torch\n'), ((6274, 6298), 'transformers.file_utils.is_torch_tpu_available', 'is_torch_tpu_available', ([], {}), '()\n', (6296, 6298), False, 'from transformers.file_utils import is_torch_tpu_available\n'), ((6355, 6374), 'torch_xla.core.xla_model.xrt_world_size', 'xm.xrt_world_size', ([], {}), '()\n', (6372, 6374), True, 'import torch_xla.core.xla_model as xm\n'), ((6394, 6410), 'torch_xla.core.xla_model.get_ordinal', 'xm.get_ordinal', ([], {}), '()\n', (6408, 6410), True, 'import torch_xla.core.xla_model as xm\n'), ((7507, 7554), 'torch.nn.functional.log_softmax', 'torch.nn.functional.log_softmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (7538, 7554), False, 'import torch\n'), ((10057, 10104), 'seq2seq.utils.use_task_specific_params', 'use_task_specific_params', (['self.model', 'eval_task'], {}), '(self.model, eval_task)\n', (10081, 10104), False, 'from seq2seq.utils import use_task_specific_params, reset_config\n'), ((11241, 11279), 'seq2seq.utils.reset_config', 'reset_config', (['self.model', 'model_config'], {}), '(self.model, model_config)\n', (11253, 11279), False, 'from seq2seq.utils import use_task_specific_params, reset_config\n'), ((13775, 13790), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (13788, 13790), False, 'import torch\n'), ((14830, 14918), 'torch.ones', 'torch.ones', (['(tensor.shape[0], max_length)'], {'dtype': 'tensor.dtype', 'device': 'tensor.device'}), '((tensor.shape[0], max_length), dtype=tensor.dtype, device=tensor\n .device)\n', (14840, 14918), False, 'import torch\n'), ((4953, 5068), 'transformers.optimization.Adafactor', 'Adafactor', (['optimizer_grouped_parameters'], {'lr': 'self.args.learning_rate', 'scale_parameter': '(False)', 'relative_step': '(False)'}), '(optimizer_grouped_parameters, lr=self.args.learning_rate,\n scale_parameter=False, relative_step=False)\n', (4962, 5068), False, 'from transformers.optimization import Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup\n'), ((5216, 5312), 'transformers.optimization.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'self.args.learning_rate', 'eps': 'self.args.adam_epsilon'}), '(optimizer_grouped_parameters, lr=self.args.learning_rate, eps=self.\n args.adam_epsilon)\n', (5221, 5312), False, 'from transformers.optimization import Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup\n'), ((6303, 6322), 'torch_xla.core.xla_model.xrt_world_size', 'xm.xrt_world_size', ([], {}), '()\n', (6320, 6322), True, 'import torch_xla.core.xla_model as xm\n'), ((6479, 6513), 'torch.distributed.get_world_size', 'torch.distributed.get_world_size', ([], {}), '()\n', (6511, 6513), False, 'import torch\n'), ((10964, 10984), 'torch_xla.debug.metrics.metrics_report', 'met.metrics_report', ([], {}), '()\n', (10982, 10984), True, 'import torch_xla.debug.metrics as met\n')] |
import numpy as np
import torch
import trimesh
from scipy.spatial import cKDTree as KDTree
from inside_mesh.triangle_hash import TriangleHash as _TriangleHash
'''
Some code included from 'inside_mesh' library of Occupancy Networks
https://github.com/autonomousvision/occupancy_networks
'''
def define_grid_3d(N, voxel_origin=[-1, -1, -1], voxel_size=None):
''' define NxNxN coordinate grid across [-1, 1]
voxel_origin is the (bottom, left, down) corner, not the middle '''
if not voxel_size:
voxel_size = 2.0 / (N - 1)
# initialize empty tensors
overall_index = torch.arange(0, N ** 3, 1, out=torch.LongTensor())
grid = torch.zeros(N ** 3, 3)
# transform first 3 columns to be x, y, z voxel index
# every possible comb'n of [0..N,0..N,0..N]
grid[:, 2] = overall_index % N # [0,1,2,...,N-1,N,0,1,2,...,N]
grid[:, 1] = (overall_index.long() // N) % N # [N [N 0's, ..., N N's]]
grid[:, 0] = ((overall_index.long() // N) // N) % N # [N*N 0's,...,N*N N's]
# transform first 3 columns: voxel indices --> voxel coordinates
grid[:, 0] = (grid[:, 0] * voxel_size) + voxel_origin[2]
grid[:, 1] = (grid[:, 1] * voxel_size) + voxel_origin[1]
grid[:, 2] = (grid[:, 2] * voxel_size) + voxel_origin[0]
return grid
def compute_iou(path_gt, path_pr, N=128, sphere=False, sphere_radius=0.25):
''' compute iou score
parameters
path_gt: path to ground-truth mesh (.ply or .obj)
path_pr: path to predicted mesh (.ply or .obj)
N: NxNxN grid resolution at which to compute iou '''
# define NxNxN coordinate grid across [-1,1]
grid = np.array(define_grid_3d(N))
# load mesh
occ_pr = MeshDataset(path_pr)
# compute occupancy at specified grid points
if sphere:
occ_gt = torch.from_numpy(np.linalg.norm(grid, axis=-1) <= sphere_radius)
else:
occ_gt = MeshDataset(path_gt)
occ_gt = torch.tensor(check_mesh_contains(occ_gt.mesh, grid))
occ_pr = torch.tensor(check_mesh_contains(occ_pr.mesh, grid))
# compute iou
area_union = torch.sum((occ_gt | occ_pr).float())
area_intersect = torch.sum((occ_gt & occ_pr).float())
iou = area_intersect / area_union
return iou.item()
def compute_trimesh_chamfer(mesh1, mesh2, num_mesh_samples=300000):
"""
This function computes a symmetric chamfer distance, i.e. the sum of both chamfers.
gt_points: trimesh.points.PointCloud of just poins, sampled from the surface (see
compute_metrics.ply for more documentation)
gen_mesh: trimesh.base.Trimesh of output mesh from whichever autoencoding reconstruction
method (see compute_metrics.py for more)
"""
gen_points_sampled = trimesh.sample.sample_surface(mesh1, num_mesh_samples)[0]
gt_points_np = trimesh.sample.sample_surface(mesh2, num_mesh_samples)[0]
# one direction
gen_points_kd_tree = KDTree(gen_points_sampled)
one_distances, one_vertex_ids = gen_points_kd_tree.query(gt_points_np)
gt_to_gen_chamfer = np.mean(np.square(one_distances))
# other direction
gt_points_kd_tree = KDTree(gt_points_np)
two_distances, two_vertex_ids = gt_points_kd_tree.query(gen_points_sampled)
gen_to_gt_chamfer = np.mean(np.square(two_distances))
chamfer_dist = gt_to_gen_chamfer + gen_to_gt_chamfer
return chamfer_dist
class MeshDataset():
def __init__(self, path_mesh, sample=False, num_pts=0):
if not path_mesh:
return
self.mesh = trimesh.load(path_mesh, process=False,
force='mesh', skip_materials=True)
def check_mesh_contains(mesh, points, hash_resolution=512):
intersector = MeshIntersector(mesh, hash_resolution)
contains = intersector.query(points)
return contains
class MeshIntersector:
def __init__(self, mesh, resolution=512):
triangles = mesh.vertices[mesh.faces].astype(np.float64)
n_tri = triangles.shape[0]
self.resolution = resolution
self.bbox_min = triangles.reshape(3 * n_tri, 3).min(axis=0)
self.bbox_max = triangles.reshape(3 * n_tri, 3).max(axis=0)
# Tranlate and scale it to [0.5, self.resolution - 0.5]^3
self.scale = (resolution - 1) / (self.bbox_max - self.bbox_min)
self.translate = 0.5 - self.scale * self.bbox_min
self._triangles = triangles = self.rescale(triangles)
triangles2d = triangles[:, :, :2]
self._tri_intersector2d = TriangleIntersector2d(
triangles2d, resolution)
def query(self, points):
# Rescale points
points = self.rescale(points)
# placeholder result with no hits we'll fill in later
contains = np.zeros(len(points), dtype=np.bool)
# cull points outside of the axis aligned bounding box
# this avoids running ray tests unless points are close
inside_aabb = np.all(
(0 <= points) & (points <= self.resolution), axis=1)
if not inside_aabb.any():
return contains
# Only consider points inside bounding box
mask = inside_aabb
points = points[mask]
# Compute intersection depth and check order
points_indices, tri_indices = self._tri_intersector2d.query(points[:, :2])
triangles_intersect = self._triangles[tri_indices]
points_intersect = points[points_indices]
depth_intersect, abs_n_2 = self.compute_intersection_depth(
points_intersect, triangles_intersect)
# Count number of intersections in both directions
smaller_depth = depth_intersect >= points_intersect[:, 2] * abs_n_2
bigger_depth = depth_intersect < points_intersect[:, 2] * abs_n_2
points_indices_0 = points_indices[smaller_depth]
points_indices_1 = points_indices[bigger_depth]
nintersect0 = np.bincount(points_indices_0, minlength=points.shape[0])
nintersect1 = np.bincount(points_indices_1, minlength=points.shape[0])
# Check if point contained in mesh
contains1 = (np.mod(nintersect0, 2) == 1)
contains2 = (np.mod(nintersect1, 2) == 1)
contains[mask] = (contains1 & contains2)
return contains
def compute_intersection_depth(self, points, triangles):
t1 = triangles[:, 0, :]
t2 = triangles[:, 1, :]
t3 = triangles[:, 2, :]
v1 = t3 - t1
v2 = t2 - t1
normals = np.cross(v1, v2)
alpha = np.sum(normals[:, :2] * (t1[:, :2] - points[:, :2]), axis=1)
n_2 = normals[:, 2]
t1_2 = t1[:, 2]
s_n_2 = np.sign(n_2)
abs_n_2 = np.abs(n_2)
mask = (abs_n_2 != 0)
depth_intersect = np.full(points.shape[0], np.nan)
depth_intersect[mask] = \
t1_2[mask] * abs_n_2[mask] + alpha[mask] * s_n_2[mask]
return depth_intersect, abs_n_2
def rescale(self, array):
array = self.scale * array + self.translate
return array
class TriangleIntersector2d:
def __init__(self, triangles, resolution=128):
self.triangles = triangles
self.tri_hash = _TriangleHash(triangles, resolution)
def query(self, points):
point_indices, tri_indices = self.tri_hash.query(points)
point_indices = np.array(point_indices, dtype=np.int64)
tri_indices = np.array(tri_indices, dtype=np.int64)
points = points[point_indices]
triangles = self.triangles[tri_indices]
mask = self.check_triangles(points, triangles)
point_indices = point_indices[mask]
tri_indices = tri_indices[mask]
return point_indices, tri_indices
def check_triangles(self, points, triangles):
contains = np.zeros(points.shape[0], dtype=np.bool)
A = triangles[:, :2] - triangles[:, 2:]
A = A.transpose([0, 2, 1])
y = points - triangles[:, 2]
detA = A[:, 0, 0] * A[:, 1, 1] - A[:, 0, 1] * A[:, 1, 0]
mask = (np.abs(detA) != 0.)
A = A[mask]
y = y[mask]
detA = detA[mask]
s_detA = np.sign(detA)
abs_detA = np.abs(detA)
u = (A[:, 1, 1] * y[:, 0] - A[:, 0, 1] * y[:, 1]) * s_detA
v = (-A[:, 1, 0] * y[:, 0] + A[:, 0, 0] * y[:, 1]) * s_detA
sum_uv = u + v
contains[mask] = (
(0 < u) & (u < abs_detA) & (0 < v) & (v < abs_detA)
& (0 < sum_uv) & (sum_uv < abs_detA)
)
return contains
| [
"numpy.full",
"trimesh.sample.sample_surface",
"trimesh.load",
"numpy.sum",
"numpy.abs",
"torch.LongTensor",
"numpy.square",
"numpy.cross",
"numpy.zeros",
"numpy.mod",
"numpy.sign",
"numpy.array",
"numpy.linalg.norm",
"scipy.spatial.cKDTree",
"torch.zeros",
"numpy.bincount",
"inside_... | [((663, 685), 'torch.zeros', 'torch.zeros', (['(N ** 3)', '(3)'], {}), '(N ** 3, 3)\n', (674, 685), False, 'import torch\n'), ((2935, 2961), 'scipy.spatial.cKDTree', 'KDTree', (['gen_points_sampled'], {}), '(gen_points_sampled)\n', (2941, 2961), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((3142, 3162), 'scipy.spatial.cKDTree', 'KDTree', (['gt_points_np'], {}), '(gt_points_np)\n', (3148, 3162), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((2754, 2808), 'trimesh.sample.sample_surface', 'trimesh.sample.sample_surface', (['mesh1', 'num_mesh_samples'], {}), '(mesh1, num_mesh_samples)\n', (2783, 2808), False, 'import trimesh\n'), ((2831, 2885), 'trimesh.sample.sample_surface', 'trimesh.sample.sample_surface', (['mesh2', 'num_mesh_samples'], {}), '(mesh2, num_mesh_samples)\n', (2860, 2885), False, 'import trimesh\n'), ((3069, 3093), 'numpy.square', 'np.square', (['one_distances'], {}), '(one_distances)\n', (3078, 3093), True, 'import numpy as np\n'), ((3275, 3299), 'numpy.square', 'np.square', (['two_distances'], {}), '(two_distances)\n', (3284, 3299), True, 'import numpy as np\n'), ((3533, 3606), 'trimesh.load', 'trimesh.load', (['path_mesh'], {'process': '(False)', 'force': '"""mesh"""', 'skip_materials': '(True)'}), "(path_mesh, process=False, force='mesh', skip_materials=True)\n", (3545, 3606), False, 'import trimesh\n'), ((4923, 4982), 'numpy.all', 'np.all', (['((0 <= points) & (points <= self.resolution))'], {'axis': '(1)'}), '((0 <= points) & (points <= self.resolution), axis=1)\n', (4929, 4982), True, 'import numpy as np\n'), ((5880, 5936), 'numpy.bincount', 'np.bincount', (['points_indices_0'], {'minlength': 'points.shape[0]'}), '(points_indices_0, minlength=points.shape[0])\n', (5891, 5936), True, 'import numpy as np\n'), ((5959, 6015), 'numpy.bincount', 'np.bincount', (['points_indices_1'], {'minlength': 'points.shape[0]'}), '(points_indices_1, minlength=points.shape[0])\n', (5970, 6015), True, 'import numpy as np\n'), ((6453, 6469), 'numpy.cross', 'np.cross', (['v1', 'v2'], {}), '(v1, v2)\n', (6461, 6469), True, 'import numpy as np\n'), ((6486, 6546), 'numpy.sum', 'np.sum', (['(normals[:, :2] * (t1[:, :2] - points[:, :2]))'], {'axis': '(1)'}), '(normals[:, :2] * (t1[:, :2] - points[:, :2]), axis=1)\n', (6492, 6546), True, 'import numpy as np\n'), ((6616, 6628), 'numpy.sign', 'np.sign', (['n_2'], {}), '(n_2)\n', (6623, 6628), True, 'import numpy as np\n'), ((6647, 6658), 'numpy.abs', 'np.abs', (['n_2'], {}), '(n_2)\n', (6653, 6658), True, 'import numpy as np\n'), ((6717, 6749), 'numpy.full', 'np.full', (['points.shape[0]', 'np.nan'], {}), '(points.shape[0], np.nan)\n', (6724, 6749), True, 'import numpy as np\n'), ((7137, 7173), 'inside_mesh.triangle_hash.TriangleHash', '_TriangleHash', (['triangles', 'resolution'], {}), '(triangles, resolution)\n', (7150, 7173), True, 'from inside_mesh.triangle_hash import TriangleHash as _TriangleHash\n'), ((7293, 7332), 'numpy.array', 'np.array', (['point_indices'], {'dtype': 'np.int64'}), '(point_indices, dtype=np.int64)\n', (7301, 7332), True, 'import numpy as np\n'), ((7355, 7392), 'numpy.array', 'np.array', (['tri_indices'], {'dtype': 'np.int64'}), '(tri_indices, dtype=np.int64)\n', (7363, 7392), True, 'import numpy as np\n'), ((7731, 7771), 'numpy.zeros', 'np.zeros', (['points.shape[0]'], {'dtype': 'np.bool'}), '(points.shape[0], dtype=np.bool)\n', (7739, 7771), True, 'import numpy as np\n'), ((8079, 8092), 'numpy.sign', 'np.sign', (['detA'], {}), '(detA)\n', (8086, 8092), True, 'import numpy as np\n'), ((8112, 8124), 'numpy.abs', 'np.abs', (['detA'], {}), '(detA)\n', (8118, 8124), True, 'import numpy as np\n'), ((632, 650), 'torch.LongTensor', 'torch.LongTensor', ([], {}), '()\n', (648, 650), False, 'import torch\n'), ((6081, 6103), 'numpy.mod', 'np.mod', (['nintersect0', '(2)'], {}), '(nintersect0, 2)\n', (6087, 6103), True, 'import numpy as np\n'), ((6131, 6153), 'numpy.mod', 'np.mod', (['nintersect1', '(2)'], {}), '(nintersect1, 2)\n', (6137, 6153), True, 'import numpy as np\n'), ((7975, 7987), 'numpy.abs', 'np.abs', (['detA'], {}), '(detA)\n', (7981, 7987), True, 'import numpy as np\n'), ((1836, 1865), 'numpy.linalg.norm', 'np.linalg.norm', (['grid'], {'axis': '(-1)'}), '(grid, axis=-1)\n', (1850, 1865), True, 'import numpy as np\n')] |
"""
PipelineExome.py - Tasks for variant calling
============================================
Reference
---------
"""
# Import modules
import os
import CGATCore.IOTools as IOTools
from CGATCore import Pipeline as P
import CGATCore.Experiment as E
from CGATCore.Pipeline import cluster_runnable
import numpy as np
import pandas as pd
import CGATCore.CSV as csv
import CGAT.VCF as VCF
import collections
import re
from urllib.request import urlopen
import itertools
from bs4 import BeautifulSoup, NavigableString
from rpy2.robjects import pandas2ri
from rpy2.robjects import r as R
import copy
# Set PARAMS in calling module
PARAMS = {}
def getGATKOptions():
return "-l mem_free=1.4G"
def makeSoup(address):
sock = urlopen(address)
htmlSource = sock.read()
soup = BeautifulSoup(htmlSource)
return soup
##############################################################################
def GATKReadGroups(infile, outfile, genome,
library="unknown", platform="Illumina",
platform_unit="1", track="unknown"):
'''Reorders BAM according to reference fasta and adds read groups'''
if track == 'unknown':
track = P.snip(os.path.basename(infile), ".bam")
tmpdir_gatk = P.get_temp_dir('.')
job_options = getGATKOptions()
job_threads = 3
statement = '''picard ReorderSam
INPUT=%(infile)s
OUTPUT=%(tmpdir_gatk)s/%(track)s.reordered.bam
REFERENCE=%(genome)s
ALLOW_INCOMPLETE_DICT_CONCORDANCE=true
VALIDATION_STRINGENCY=SILENT ;''' % locals()
statement += '''samtools index %(tmpdir_gatk)s/%(track)s.reordered.bam ;
''' % locals()
statement += '''picard AddOrReplaceReadGroups
INPUT=%(tmpdir_gatk)s/%(track)s.reordered.bam
OUTPUT=%(outfile)s
RGLB=%(library)s
RGPL=%(platform)s
RGPU=%(platform_unit)s
RGSM=%(track)s
VALIDATION_STRINGENCY=SILENT ;''' % locals()
statement += '''samtools index %(outfile)s ;
''' % locals()
statement += '''rm -rf %(tmpdir_gatk)s ;''' % locals()
P.run(statement)
##############################################################################
def GATKIndelRealign(infile, outfile, genome, intervals, padding, threads=4):
'''Realigns BAMs around indels using GATK'''
intervalfile = outfile.replace(".bam", ".intervals")
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK
-T RealignerTargetCreator
-o %(intervalfile)s
--num_threads %(threads)s
-R %(genome)s
-L %(intervals)s
-ip %(padding)s
-I %(infile)s; ''' % locals()
statement += '''GenomeAnalysisTK
-T IndelRealigner
-o %(outfile)s
-R %(genome)s
-I %(infile)s
-targetIntervals %(intervalfile)s;''' % locals()
P.run(statement)
##############################################################################
def GATKBaseRecal(infile, outfile, genome, intervals, padding, dbsnp,
solid_options=""):
'''Recalibrates base quality scores using GATK'''
track = P.snip(os.path.basename(infile), ".bam")
tmpdir_gatk = P.get_temp_dir('.')
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK
-T BaseRecalibrator
--out %(tmpdir_gatk)s/%(track)s.recal.grp
-R %(genome)s
-L %(intervals)s
-ip %(padding)s
-I %(infile)s
--knownSites %(dbsnp)s %(solid_options)s ;
''' % locals()
statement += '''GenomeAnalysisTK
-T PrintReads -o %(outfile)s
-BQSR %(tmpdir_gatk)s/%(track)s.recal.grp
-R %(genome)s
-I %(infile)s ;
''' % locals()
statement += '''rm -rf %(tmpdir_gatk)s ;''' % locals()
P.run(statement)
##############################################################################
def haplotypeCaller(infile, outfile, genome,
dbsnp, intervals, padding, options):
'''Call SNVs and indels using GATK HaplotypeCaller in all members of a
family together'''
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK
-T HaplotypeCaller
-ERC GVCF
-variant_index_type LINEAR
-variant_index_parameter 128000
-o %(outfile)s
-R %(genome)s
-I %(infile)s
--dbsnp %(dbsnp)s
-L %(intervals)s
-ip %(padding)s
%(options)s''' % locals()
P.run(statement)
##############################################################################
def genotypeGVCFs(inputfiles, outfile, genome, options):
'''Joint genotyping of all samples together'''
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK
-T GenotypeGVCFs
-o %(outfile)s
-R %(genome)s
--variant %(inputfiles)s''' % locals()
P.run(statement)
##############################################################################
def mutectSNPCaller(infile, outfile, mutect_log, genome, cosmic,
dbsnp, call_stats_out, job_memory, job_threads,
quality=20, max_alt_qual=150, max_alt=5,
max_fraction=0.05, tumor_LOD=6.3, strand_LOD=2,
normal_panel=None,
infile_matched=None,
gatk_key=None,
artifact=False):
'''Call SNVs using Broad's muTect'''
# TS. this is currently CGAT specific. How to generalise?
job_memory_java = job_memory.lower()
job_threads = 1
statement = '''module load apps/java/jre1.6.0_26;
java -Xmx%(job_memory_java)s -jar
/ifs/apps/bio/muTect-1.1.4/muTect-1.1.4.jar
--analysis_type MuTect
--reference_sequence %(genome)s
--cosmic %(cosmic)s
--dbsnp %(dbsnp)s
--input_file:tumor %(infile)s
--out %(call_stats_out)s
--enable_extended_output
--vcf %(outfile)s
''' % locals()
if artifact:
statement += ''' --artifact_detection_mode '''
if infile_matched:
statement += '''--min_qscore %(quality)s
--gap_events_threshold 2
--max_alt_alleles_in_normal_qscore_sum %(max_alt_qual)s
--max_alt_alleles_in_normal_count %(max_alt)s
--max_alt_allele_in_normal_fraction %(max_fraction)s
--tumor_lod %(tumor_LOD)s
--input_file:normal %(infile_matched)s ''' % locals()
if normal_panel:
statement += ''' --normal_panel %(normal_panel)s ''' % locals()
if gatk_key:
statement += " -et NO_ET -K %(gatk_key)s " % locals()
statement += " > %(mutect_log)s " % locals()
P.run(statement)
##############################################################################
def strelkaINDELCaller(infile_control, infile_tumor, outfile, genome, config,
outdir, job_memory, job_threads):
'''Call INDELs using Strelka'''
statement = '''
rm -rf %(outdir)s;
/ifs/apps/bio/strelka-1.0.14/bin/configureStrelkaWorkflow.pl
--normal=%(infile_control)s --tumor=%(infile_tumor)s
--ref=%(genome)s --config=%(config)s --output-dir=%(outdir)s;
make -j %(job_threads)s -C %(outdir)s''' % locals()
P.run(statement)
##############################################################################
def variantAnnotator(vcffile, bamlist, outfile, genome,
dbsnp, annotations="", snpeff_file=""):
'''Annotate variant file using GATK VariantAnnotator'''
job_options = getGATKOptions()
job_threads = 3
if "--useAllAnnotations" in annotations:
anno = "--useAllAnnotations"
elif annotations:
anno = " -A " + " -A ".join(annotations)
else:
anno = ""
statement = '''GenomeAnalysisTK -T VariantAnnotator
-R %(genome)s
-I %(bamlist)s
-A SnpEff
--snpEffFile %(snpeff_file)s
-o %(outfile)s
--variant %(vcffile)s
-L %(vcffile)s
--dbsnp %(dbsnp)s
%(anno)s''' % locals()
P.run(statement)
##############################################################################
def variantRecalibrator(infile, outfile, genome, mode, dbsnp=None,
kgenomes=None, hapmap=None, omni=None, mills=None):
'''Create variant recalibration file'''
job_options = getGATKOptions()
job_threads = 3
track = P.snip(outfile, ".recal")
if mode == 'SNP':
statement = '''GenomeAnalysisTK -T VariantRecalibrator
-R %(genome)s
-input %(infile)s
-resource:hapmap,known=false,training=true,truth=true,prior=15.0 %(hapmap)s
-resource:omni,known=false,training=true,truth=true,prior=12.0 %(omni)s
-resource:dbsnp,known=true,training=false,truth=false,prior=2.0 %(dbsnp)s
-resource:1000G,known=false,training=true,truth=false,prior=10.0 %(kgenomes)s
-an QD -an SOR -an MQRankSum
-an ReadPosRankSum -an FS -an MQ
--maxGaussians 4
-mode %(mode)s
-recalFile %(outfile)s
-tranchesFile %(track)s.tranches
-rscriptFile %(track)s.plots.R ''' % locals()
P.run(statement)
elif mode == 'INDEL':
statement = '''GenomeAnalysisTK -T VariantRecalibrator
-R %(genome)s
-input %(infile)s
-resource:mills,known=true,training=true,truth=true,prior=12.0 %(mills)s
-an QD -an MQRankSum
-an ReadPosRankSum -an FS -an MQ
--maxGaussians 4
--minNumBadVariants 5000
-mode %(mode)s
-recalFile %(outfile)s
-tranchesFile %(track)s.tranches
-rscriptFile %(track)s.plots.R ''' % locals()
P.run(statement)
##############################################################################
def applyVariantRecalibration(vcf, recal, tranches, outfile, genome, mode):
'''Perform variant quality score recalibration using GATK '''
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK -T ApplyRecalibration
-R %(genome)s
-input:VCF %(vcf)s
-recalFile %(recal)s
-tranchesFile %(tranches)s
--ts_filter_level 99.0
-mode %(mode)s
-o %(outfile)s ''' % locals()
P.run(statement)
##############################################################################
def vcfToTable(infile, outfile, genome, columns):
'''Converts vcf to tab-delimited file'''
job_options = getGATKOptions()
job_threads = 3
statement = '''GenomeAnalysisTK -T VariantsToTable
-R %(genome)s
-V %(infile)s
--showFiltered
--allowMissingData
%(columns)s
-o %(outfile)s''' % locals()
P.run(statement)
##############################################################################
def selectVariants(infile, outfile, genome, select):
'''Filter de novo variants based on provided jexl expression'''
statement = '''GenomeAnalysisTK -T SelectVariants
-R %(genome)s
--variant %(infile)s
-select '%(select)s'
-log %(outfile)s.log
-o %(outfile)s''' % locals()
P.run(statement)
##############################################################################
def buildSelectStatementfromPed(filter_type, pedfile, template):
'''Build a select statement from a template and a pedigree file'''
pedigree = csv.DictReader(
IOTools.open_file(pedfile), delimiter='\t', fieldnames=[
'family', 'sample', 'father', 'mother', 'sex', 'status'])
affecteds = []
unaffecteds = []
parents = []
select = None
# loop over pedigree file and establish relationships
for row in pedigree:
if row['status'] == '2':
if filter_type == "denovo":
father = row['father']
mother = row['mother']
proband = row['sample']
elif filter_type == "dominant" or filter_type == "recessive":
affecteds += [row['sample']]
if filter_type == "recessive":
parents += [row['father'], row['mother']]
if row['status'] == '1':
if filter_type == "dominant":
unaffecteds += [row['sample']]
elif filter_type == "recessive":
if row['sample'] not in parents:
unaffecteds += [row['sample']]
# Build select statement from template
if filter_type == "denovo":
select = template.replace("father", father)
select = select.replace("mother", mother)
select = select.replace("proband", proband)
elif filter_type == "dominant":
affecteds_exp = '").getPL().1==0&&vc.getGenotype("'.join(affecteds)
if len(unaffecteds) == 0:
unaffecteds_exp = ''
else:
unaffecteds_exp = '&&vc.getGenotype("' + \
('").isHomRef()&&vc.getGenotype("'.join(unaffecteds)) + \
'").isHomRef()'
select = template.replace("affecteds_exp", affecteds_exp)
select = select.replace("unaffecteds_exp", unaffecteds_exp)
elif filter_type == "recessive":
affecteds_exp = '").getPL().2==0&&vc.getGenotype("'.join(affecteds)
unaffecteds_exp = '").getPL().2!=0&&vc.getGenotype("'.join(unaffecteds)
if len(parents) == 0:
parents_exp = ''
else:
parents_exp = '&&vc.getGenotype("' + \
('").getPL().1==0&&vc.getGenotype("'.join(parents)) + \
'").getPL().1==0'
select = template.replace("affecteds_exp", affecteds_exp)
select = select.replace("unaffecteds_exp", unaffecteds_exp)
select = select.replace("parents_exp", parents_exp)
return select
##############################################################################
def guessSex(infile, outfile):
'''Guess the sex of a sample based on ratio of reads
per megabase of sequence on X and Y'''
statement = '''calc `samtools idxstats %(infile)s
| grep 'X'
| awk '{print $3/($2/1000000)}'`
/`samtools idxstats %(infile)s | grep 'Y'
| awk '{print $3/($2/1000000)}'`
| tr -d " " | tr "=" "\\t" | tr "/" "\\t"
> %(outfile)s'''
P.run(statement)
##############################################################################
def filterMutect(infile, outfile, logfile,
control_id, tumour_id,
min_t_alt, min_n_depth,
max_n_alt_freq, min_t_alt_freq,
min_ratio):
''' filter the mutect snps'''
reasons = collections.Counter()
def comp(base):
'''return complementary base'''
comp_dict = {"C": "G", "G": "C", "A": "T", "T": "A"}
return comp_dict[base]
with IOTools.open_file(outfile, "w") as outf:
with IOTools.open_file(infile, "r") as inf:
for line in inf.readlines():
# need to find location of control and tumor columns
if line.startswith('#CHROM'):
columns = line.split("\t")
for x in range(0, len(columns)):
if control_id in columns[x]:
control_col = x
elif tumour_id in columns[x]:
tumor_col = x
if line.startswith('#'):
# write out all comment lines
outf.write(line)
else:
values = line.split("\t")
if values[6] == "PASS":
t_values = values[tumor_col].split(":")
t_ref, t_alt = list(
map(float, (t_values[2].split(","))))
t_depth = t_alt + t_ref
n_values = values[control_col].split(":")
n_ref, n_alt = list(
map(float, (n_values[2].split(","))))
n_depth = n_alt + n_ref
np.seterr(divide='ignore')
t_freq = np.divide(t_alt, t_depth)
n_freq = np.divide(n_alt, n_depth)
# filter
if not t_alt > min_t_alt:
reasons["Low_tumour_alt_count"] += 1
continue
if not t_freq >= min_t_alt_freq:
reasons["Low_tumour_alt_freq"] += 1
continue
if not n_depth >= min_n_depth:
reasons["Low_normal_depth"] += 1
continue
if not n_freq <= max_n_alt_freq:
reasons["high_normal_alt_freq"] += 1
continue
if (np.divide(t_freq, n_freq) >= min_ratio or n_freq == 0):
outf.write(line)
else:
reasons["Mutect_reject"] += 1
with IOTools.open_file(logfile, "w") as outf:
outf.write("%s\n" % "\t".join(("reason", "count")))
for reason in reasons:
outf.write("%s\t%i\n" % (reason, reasons[reason]))
# the following two functions should be generalised
# currently they operate only on mutect output
def compileMutationalSignature(infiles, outfiles):
'''takes a list of mutect output files and compiles per sample mutation
signatures'''
delim = ":"
def lookup(b1, b2):
'''return lookup key for a pair of bases'''
return(b1 + delim + b2)
def breakKey(key):
'''take a lookup key and return the elements'''
return key.split(delim)
def comp(base):
'''return complementary base'''
comp_dict = {"C": "G", "G": "C", "A": "T", "T": "A"}
return comp_dict[base]
def getID(infile):
return P.snip(os.path.basename(infile),
".mutect.snp.annotated.filtered.vcf")
outfile1 = IOTools.open_file(outfiles[0], "w")
mutations = ["C:T", "C:A", "C:G", "A:C", "A:T", "A:G"]
outfile1.write("%s\t%s\t%s\t%s\t%s\n" % ("patient_id", "base_change",
"ref", "alt", "frequency"))
patient_freq = {}
for infile in infiles:
patient_id = getID(infile)
mut_dict = {}
for comb in mutations:
mut_dict[comb] = 0
with IOTools.open_file(infile, "r") as f:
for line in f.readlines():
if line.startswith('#'):
continue
values = line.split("\t")
key = lookup(values[3], values[4])
if key in mut_dict:
mut_dict[key] += 1
else:
comp_key = lookup(
comp(values[3]), comp(values[4]))
mut_dict[comp_key] += 1
patient_freq[patient_id] = mut_dict
for mutation in mutations:
base1, base2 = breakKey(mutation)
for infile in infiles:
patient_id = getID(infile)
outfile1.write("%s\t%s\t%s\t%s\t%s\n" % (patient_id, mutation,
base1, base2,
patient_freq[patient_id]
[mutation]))
outfile1.close()
outfile2 = IOTools.open_file(outfiles[1], "w")
outfile2.write("%s\t%s\n" % ("patient_id",
"\t".join(mutations)))
for infile in infiles:
patient_id = getID(infile)
frequencies = "\t".join(map(str, [patient_freq[patient_id][x]
for x in mutations]))
outfile2.write("%s\t%s\n" % (patient_id, frequencies))
outfile2.close()
##############################################################################
# utility functions for pipeline_exome_cancer
##############################################################################
@cluster_runnable
def parseMutectCallStats(infile, outfile):
'''take the call stats outfile from mutect and summarise the
reasons for variant rejection'''
single_dict = collections.defaultdict(int)
combinations_dict = collections.defaultdict(int)
with IOTools.open_file(infile, "rb") as infile:
lines = infile.readlines()
for i, line in enumerate(lines):
if i < 2:
continue
values = line.strip().split("\t")
judgement, justification = (values[-1], values[-2])
if judgement == "REJECT":
reasons = justification.split(",")
if len(reasons) == 1:
single_dict[reasons[0]] += 1
else:
for reason in reasons:
combinations_dict[reasons[0]] += 1
df = pd.DataFrame([single_dict, combinations_dict])
df = df.transpose()
df.columns = ["single", "combination"]
df = df.sort("single", ascending=False)
df.index.name = "justification"
df.to_csv(outfile, header=True, index=True, sep="\t")
@cluster_runnable
def defineEBioStudies(cancer_types, outfile):
''' For the cancer types specified in pipeline.yml, identify the
relevent studies in eBio '''
cancer_types = cancer_types.split(",")
cancer_studies_url = "http://www.cbioportal.org/webservice.do?cmd=getCancerStudies"
genetic_profiles_url = "http://www.cbioportal.org/webservice.do?cmd=getGeneticProfiles"
type2study_dict = collections.defaultdict(list)
study2table_dict = collections.defaultdict(list)
soup = makeSoup(cancer_studies_url)
for lines in soup.body:
if isinstance(lines, NavigableString):
for line in lines.split("\n"):
if "cancer_study_id" not in line:
values = str(line).strip().split("\t")
if len(values) > 1:
cancer_type = values[1].split(" (")[0]
if cancer_type in cancer_types:
study = re.sub(".\n", "", values[0])
type2study_dict[cancer_type].append(study)
for study_list in list(type2study_dict.values()):
for study in study_list:
soup = makeSoup(genetic_profiles_url + "&cancer_study_id=" + study)
lines = str(soup.body).split('\n')
for line in lines:
values = line.strip().split("\t")
if len(values) > 1:
if values[1] == "Mutations":
genetic_profile = values[0]
study2table_dict[study] = genetic_profile
outf = IOTools.open_file(outfile, "w")
for cancer_type, study_id in type2study_dict.items():
for study in study_id:
table_id = study2table_dict[study]
outf.write("%s\t%s\t%s\n" % (cancer_type, study, table_id))
outf.close()
@cluster_runnable
def extractEBioinfo(eBio_ids, vcfs, outfile):
'''find the number of mutations identitified in previous studies (eBio_ids)
for the mutated genes in the vcfs'''
genes = set()
for vcf in vcfs:
infile = VCF.VCFFile(IOTools.open_file(vcf))
for vcf_entry in infile:
# assumes all vcf entries without "REJECT" are "PASS"
if vcf_entry.filter != "REJECT":
info_entries = vcf_entry.info.split(";")
for entry in info_entries:
if "SNPEFF_GENE_NAME" in entry:
genes.update((entry.split("=")[1],))
eBio_ids = IOTools.open_file(eBio_ids, "r")
tissue_counts = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(int)))
def chunks(l, n):
''' Yield successive n-sized chunks from l '''
for i in range(0, len(l), n):
yield l[i:i + n]
# delete me
E.info("number of genes: %i" % len(list(genes)))
for line in eBio_ids:
tissue, study, table = line.strip().split("\t")
n = 0
for i in range(0, len(list(genes)), 250):
genes_chunk = list(genes)[i:i + 250]
# TS sporadic error when querying with a single gene at a time
# "urllib2.URLError: <urlopen error [Errno 110] Connection timed out>"
# max URL length appears to be 8200 characters,
# try doing 250 genes at a time?
gene_list = "+".join(list(genes_chunk))
n += len(genes_chunk)
E.info("number of genes processed: %i" % n)
url = ("http://www.cbioportal.org/webservice.do?cmd=getProfileData&"
"case_set_id=%(study)s_all&genetic_profile_id=%(table)s&"
"gene_list=%(gene_list)s" % locals())
df = pd.io.parsers.read_csv(
url, comment="#", sep="\t", index_col=0)
for gene in genes_chunk:
tmp_df = df[df['COMMON'] == gene]
# check dataframe contains data!
if tmp_df.shape[0] != 0:
# seem to be having issues with gene set containing duplicates!
# --> dataframe with repeated instances of gene after selection
# so splice to first row and recreate dataframe from series
if tmp_df.shape[0] > 1:
tmp_df = pd.DataFrame(tmp_df.iloc[0]).T
tissue_counts[tissue][gene]["total"] += tmp_df.shape[1] - 2
tissue_counts[tissue][gene][
"mutations"] += int(tmp_df.count(1)) - 1
out = IOTools.open_file(outfile, "w")
tissues = list(tissue_counts.keys())
out.write("gene\t%s\n" % "\t".join([
"%s_frequency" % x.replace(" ", "_") for x in tissues]))
for gene in genes:
freq_values = []
for tissue in tissues:
total = tissue_counts[tissue][gene]["total"]
mutations = tissue_counts[tissue][gene]["mutations"]
freq_values.append(round(np.divide(float(mutations), total), 4))
out.write("%s\t%s\n" % (gene, "\t".join(map(str, freq_values))))
out.close()
def intersectionHeatmap(infiles, outfile):
''' calculate the intersection between the infiles and plot'''
pandas2ri.activate()
name2genes = {}
df = pd.DataFrame(columns=["id_1", "id_2", "intersection", "perc"])
ix = 0
for inf in infiles:
name = P.snip(os.path.basename(inf)).split(".")[0]
name = name.replace(".", "_")
with IOTools.open_file(inf, "r") as f:
genes = set()
for line in f:
if line[0] == "#":
continue
values = line.strip().split("\t")
info = values[7].split(";")
for x in info:
if x.split("=")[0] == "SNPEFF_GENE_NAME":
gene_name = x.split("=")[1]
break
# if no gene name found, line is skipped
if gene_name:
genes.update((gene_name,))
name2genes[name] = genes
df.loc[ix] = [name, name, len(genes), 1.0]
ix += 1
for pair in itertools.permutations(list(name2genes.keys()), 2):
id_1, id_2 = pair
intersection = len(name2genes[id_1].intersection(name2genes[id_2]))
not_intersecting = len(
name2genes[id_1].symmetric_difference(name2genes[id_2]))
intersection_perc = float(intersection) / (intersection +
not_intersecting)
df.loc[ix] = [id_1, id_2, intersection, intersection_perc]
ix += 1
variant = os.path.basename(outfile).replace(
"overlap_", "").replace("_heatmap.png", "")
plotIntersectionHeatmap = R('''
function(df){
library(ggplot2)
m_txt = element_text(size=15)
m_txt_90 = element_text(size=15, angle=90, vjust=0.5, hjust=1)
l_txt = element_text(size=20)
p = ggplot(df, aes(id_1, id_2, fill=100*perc)) +
geom_tile() +
geom_text(aes(label=intersection), size=3) +
scale_fill_gradient(name="Intersection (%%)", limits=c(0,100),
low="yellow", high="dodgerblue4") +
theme(axis.text.x = m_txt_90, axis.text.y = m_txt,
legend.text = m_txt, legend.title = m_txt,
aspect.ratio=1) +
xlab("") + ylab("") +
ggtitle("%(variant)s")
ggsave("%(outfile)s", width=10, height=10)
}''' % locals())
plotIntersectionHeatmap(df)
@cluster_runnable
def filterQuality(infile, qualstr, qualfilter, outfiles):
'''
Filter variants based on quality. Columns to filter on and
how they should be filtered can be specified in the pipeline.yml.
Currently only implemented to filter numeric columns. "." is assumed
to mean pass.
'''
columns = IOTools.open_file(infile).readline()
columns = columns.split("\t")
qualparams = qualstr.split(",")
qualdict = dict()
fdict = dict()
for param in qualparams:
param = param.split("'")
# column to filter on
col = param[0]
# string of >, <, >= or <= depending how the column should
# be filtered
lessmore = param[1]
# score to filter by
score = float(param[2])
assert col in columns, "column %s not in variant table" % col
ind = columns.index(col)
i = 0
iset = set([0, 1])
with IOTools.open_file(infile) as input:
for line in input:
# rows one and two are headers
if i > 1:
line = line.strip().split("\t")
if line[ind] == ".":
iset.add(i)
elif lessmore == ">":
if float(line[ind]) > score:
iset.add(i)
elif lessmore == ">=":
if float(line[ind]) > score:
iset.add(i)
elif lessmore == "<":
if float(line[ind]) < score:
iset.add(i)
elif lessmore == "<=":
if float(line[ind]) <= score:
iset.add(i)
if i not in iset:
fdict.setdefault(i, [])
fdict[i].append("%s=%s" % (col, line[ind]))
i += 1
qualdict[col] = iset
if qualfilter == "all":
allqual = set.intersection(*list(qualdict.values()))
elif qualfilter == "any":
allqual = set.union(*list(qualdict.values()))
i = 0
out = IOTools.open_file(outfiles[0], "w")
out2 = IOTools.open_file(outfiles[1], "w")
with IOTools.open_file(infile) as input:
for line in input:
if i in allqual:
out.write(line)
else:
line = line.strip()
out2.write("%s\t%s\n" % (line, ",".join(fdict[i])))
i += 1
out.close()
out2.close()
@cluster_runnable
def FilterExacCols(infile, exac_suffs, exac_thresh):
'''
Returns a set of line indices indicating lines where either of the alleles
called have a frequency of greater that exac_thresh in any of the
populations specified as exac_suffs.
Where no data is available an allele frequency of -1 is used.
Exac provide data as AC_xxx and AN_xxx where AC is the allele count
- the number of times the allele has been called
- and AN is chromosome count - the number of
samples in which the allele could have been called - in population xxx.
AC / AN = allele frequecy.
exac_suffs are any columns where an AC_xxx and AN_xxx column is provided
in the VCF, e.g. Adj will calculate allele frequency from the AC_Adj
and AN_Adj columns
'''
# read columns from the input VCF
exac_suffs = exac_suffs.split(",")
cols = IOTools.open_file(infile).readline().strip().split("\t")
nD = dict()
afdict = dict()
for e in exac_suffs:
# find the columns with the appropriate information
# Allele count
AC_i = cols.index("AC_%s" % (e))
# Allele Number
AN_i = cols.index("AN_%s" % (e))
# Genotype
GT_i = cols.index('GT')
nlist = set()
n = 0
AFS = []
with IOTools.open_file(infile) as input:
for line in input:
if n > 1:
line = line.strip().split("\t")
# At multi-allelic sites, comma delimited AC and AN values
# are provided
# "." and "NA" indicate no data here - this is represented
# as an AF of -1
AC = line[AC_i].replace(".", "-1").replace(
"NA", "-1").split(",")
AN = line[AN_i].replace(".", "1").replace(
"NA", "1").split(",")
AC = np.array([float(a) for a in AC])
AN = np.array([float(a) for a in AN])
AF = AC / AN
AF2 = [af if af > 0 else 0 for af in AF]
AF = np.insert(AF, 0, (1 - sum(AF2)))
# Chromosome count is usually the same for all minor
# alleles (but not always)
# If it is not the same the AC and AN lists should be the
# same length
# Otherwise AN will have length 1
if len(AC) != len(AN):
AN = [AN] * len(AC)
# Record the genotype called in this sample for this SNP
GT = line[GT_i]
GT = GT.replace(".", '0')
GT = GT.split("/")
GT[0], GT[1] = int(GT[0]), int(GT[1])
# If the variant is not in ExAC the ExAC columns show "."
# but the site
# may still have been called as multi allelic
# - use -1 for all frequencies
# in this case
if max(GT) > (len(AF) - 1):
AF = np.array([-1] * (max(GT) + 1))
AF1 = AF[GT[0]]
AF2 = AF[GT[1]]
AFS.append((AF1, AF2))
# Remember where both allele frequencies are
# greater than exac_thresh
if AF1 >= exac_thresh and AF2 >= exac_thresh:
nlist.add(n)
else:
AFS.append(('NA', 'NA'))
n += 1
afdict[e] = AFS
nD[e] = nlist
ns = set.union(*list(nD.values()))
return afdict, ns
@cluster_runnable
def FilterFreqCols(infile, thresh, fcols):
'''
Returns a set of line indices indicating lines where either of the alleles
called have a frequency of less than thresh in all of the columns specified
in fcols.
No information - assigned allele frequency of -1.
'''
fcols = fcols.split(",")
# read the column headings from the variant table
cols = IOTools.open_file(infile).readline().strip().split("\t")
# store allele frequency columns
AFdict = dict()
# store low frequency indices
nD = dict()
for col in fcols:
ind = cols.index(col)
GT_i = cols.index('GT')
n = 0
nlist = set()
AFS = []
with IOTools.open_file(infile) as input:
for line in input:
if n > 1:
line = line.strip().split("\t")
GT = line[GT_i].replace(".", "0").split("/")
af = line[ind].split(",")
AF = []
# where the allele frequency is not numeric
# "." or "NA" use -1 to indicate no data
for a in af:
try:
AF.append(float(a))
except:
AF.append(float(-1))
AF2 = [l if l > 0 else 0 for l in AF]
AF = np.array(AF)
AF = np.insert(AF, 0, 1 - sum(AF2))
GT[0] = int(GT[0])
GT[1] = int(GT[1])
# If the variant is not in database the column shows "."
# but the site
# may still have been called as multi allelic
# - use -1 for all frequencies
# in this case
if max(GT[0], GT[1]) > (len(AF) - 1):
AF = [float(-1)] * (max(GT[0], GT[1]) + 1)
AF1 = AF[GT[0]]
AF2 = AF[GT[1]]
if AF1 >= thresh and AF2 >= thresh:
nlist.add(n)
AFS.append((AF1, AF2))
else:
AFS.append(('NA', 'NA'))
n += 1
AFdict[col] = AFS
nD[col] = nlist
ns = set.union(*list(nD.values()))
return AFdict, ns
def WriteFreqFiltered(infile, exacdict, exacinds, otherdict, otherinds,
outfiles):
'''
Writes the output of the frequency filtering steps to file, including
the new columns showing calculated allele frequency for the allele
in this specific sample.
'''
x = 0
out = IOTools.open_file(outfiles[0], "w")
out2 = IOTools.open_file(outfiles[1], "w")
exaccols = list(exacdict.keys())
othercols = list(otherdict.keys())
# column names for the new columns
exacnewcols = ["%s_calc" % c for c in exaccols]
othernewcols = ["%s_calc" % c for c in othercols]
with IOTools.open_file(infile) as infile:
for line in infile:
line = line.strip()
if x <= 1:
# write the column names
out.write("%s\t%s\t%s\n" % (line, "\t".join(exacnewcols),
"\t".join(othernewcols)))
else:
freqs = []
for key in exaccols:
col = exacdict[key]
freqs.append(col[x])
for key in othercols:
col = otherdict[key]
freqs.append(col[x])
freqs = [str(freq) for freq in freqs]
if x not in exacinds and x not in otherinds:
out.write("%s\t%s\n" % (line, "\t".join(freqs)))
else:
out2.write("%s\t%s\n" % (line, "\t".join(freqs)))
x += 1
out.close()
out2.close()
@cluster_runnable
def filterRarity(infile, exac, freqs, thresh, outfiles):
'''
Filter out variants which are common in any of the exac or other
population datasets as specified in the pipeline.yml.
'''
exacdict, exacinds = FilterExacCols(infile, exac, thresh)
otherdict, otherinds = FilterFreqCols(infile, thresh, freqs)
WriteFreqFiltered(infile, exacdict, exacinds, otherdict,
otherinds, outfiles)
@cluster_runnable
def filterDamage(infile, damagestr, outfiles):
'''
Filter variants which have not been assessed as damaging by any
of the specified tools.
Tools and thresholds can be specified in the pipeline.yml.
Does not account for multiple alt alleles - if any ALT allele has
been assessed as damaging with any tool the variant is kept,
regardless of if this is the allele called in the sample.
'''
damaging = damagestr.split(",")
cols = IOTools.open_file(infile).readline().strip().split("\t")
D = dict()
# parses the "damage string" from the pipeline.yml
# this should be formatted as COLUMN|result1-result2-...,COLUMN|result1...
# where variants with any of these results in this column will
# be retained
for d in damaging:
d = d.split("|")
col = d[0]
res = d[1].split("-")
i = cols.index(col)
D[col] = ((res, i))
x = 0
out = IOTools.open_file(outfiles[0], "w")
out2 = IOTools.open_file(outfiles[1], "w")
with IOTools.open_file(infile) as input:
for line in input:
if x > 1:
# grep for specific strings within this column of this
# line of the input file
line = line.strip().split("\t")
isdamaging = 0
for key in D:
res, i = D[key]
current = line[i]
for r in res:
if re.search(r, current):
isdamaging = 1
if isdamaging == 1:
out.write("%s\n" % "\t".join(line))
else:
out2.write("%s\n" % "\t".join(line))
else:
out.write(line)
x += 1
out.close()
out2.close()
@cluster_runnable
def filterFamily(infile, infile2, outfiles):
'''
Filter variants according to the output of calculateFamily -
only variants shared by both members of a family will be kept.
'''
cps1 = set()
cps2 = set()
# make a list of variants in infile1
with IOTools.open_file(infile) as input:
for line in input:
line = line.strip().split("\t")
chrom = line[0]
pos = line[1]
cp = "%s_%s" % (chrom, pos)
cps1.add(cp)
# make a list of variants in infile2
with IOTools.open_file(infile2) as input:
for line in input:
line = line.strip().split("\t")
chrom = line[0]
pos = line[1]
cp = "%s_%s" % (chrom, pos)
cps2.add(cp)
# only variants in both are of interest
cps = cps1 & cps2
out = IOTools.open_file(outfiles[0], "w")
out2 = IOTools.open_file(outfiles[1], "w")
with IOTools.open_file(infile) as input:
for line in input:
line = line.strip().split("\t")
if "%s_%s" % (line[0], line[1]) in cps:
out.write("%s\n" % "\t".join(line))
else:
out2.write("%s\n" % "\t".join(line))
out.close()
out2.close()
@cluster_runnable
def CleanVariantTables(genes, variants, cols, outfile):
variants = pd.read_csv(variants, sep="\t")
variants = variants.drop(0)
vp1 = copy.copy(variants[['CHROM',
'POS', 'QUAL', 'ID', 'REF1', 'ALT', 'GT']])
alleles = vp1['REF1'].str.cat(
vp1['ALT'].str.strip(), sep=",").str.split(",")
vp1['GT'] = vp1['GT'].str.replace(".", "0")
inds1 = vp1['GT'].str.get(0).astype(int).values
inds2 = vp1['GT'].str.get(-1).astype(int).values
x = 0
a1s = []
a2s = []
gts = []
homhet = []
for allele in alleles:
i1 = int(inds1[x])
i2 = int(inds2[x])
a1 = allele[i1]
a2 = allele[i2]
a1s.append(a1)
a2s.append(a2)
if a1 == a2:
homhet.append("HOM")
else:
homhet.append("HET")
gts.append("%s%s" % (a1, a2))
x += 1
vp1['HOMHET'] = homhet
vp1['Allele1'] = a1s
vp1['Allele2'] = a2s
vp1['Genotype'] = gts
vp1 = vp1.drop(['REF1', 'ALT', 'GT'], 1)
vp1[cols] = copy.copy(variants[cols])
Ls = []
for gene in [line.strip()
for line in IOTools.open_file(genes[0]).readlines()]:
cp = []
with IOTools.open_file(genes[1]) as infile:
for line in infile:
r = re.search(gene, line)
if r:
line = line.strip().split("\t")
chrom = line[0]
pos = line[1]
cp.append("%s_%s" % (chrom, pos))
cp = set(cp)
for c in cp:
Ls.append((gene, c.split("_")))
df = pd.DataFrame(Ls)
df['CHROM'] = df[1].str.get(0)
df['POS'] = df[1].str.get(1)
df = df.drop(1, 1)
df.columns = ['gene', 'CHROM', 'POS']
variants = vp1.merge(df, 'left')
variants.to_csv(outfile, sep="\t")
| [
"pandas.read_csv",
"collections.defaultdict",
"pandas.DataFrame",
"CGATCore.Pipeline.get_temp_dir",
"CGATCore.Pipeline.run",
"urllib.request.urlopen",
"CGATCore.IOTools.open_file",
"CGATCore.Experiment.info",
"collections.Counter",
"re.search",
"re.sub",
"numpy.divide",
"os.path.basename",
... | [((728, 744), 'urllib.request.urlopen', 'urlopen', (['address'], {}), '(address)\n', (735, 744), False, 'from urllib.request import urlopen\n'), ((785, 810), 'bs4.BeautifulSoup', 'BeautifulSoup', (['htmlSource'], {}), '(htmlSource)\n', (798, 810), False, 'from bs4 import BeautifulSoup, NavigableString\n'), ((1244, 1263), 'CGATCore.Pipeline.get_temp_dir', 'P.get_temp_dir', (['"""."""'], {}), "('.')\n", (1258, 1263), True, 'from CGATCore import Pipeline as P\n'), ((2256, 2272), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (2261, 2272), True, 'from CGATCore import Pipeline as P\n'), ((3173, 3189), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (3178, 3189), True, 'from CGATCore import Pipeline as P\n'), ((3505, 3524), 'CGATCore.Pipeline.get_temp_dir', 'P.get_temp_dir', (['"""."""'], {}), "('.')\n", (3519, 3524), True, 'from CGATCore import Pipeline as P\n'), ((4276, 4292), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (4281, 4292), True, 'from CGATCore import Pipeline as P\n'), ((5099, 5115), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (5104, 5115), True, 'from CGATCore import Pipeline as P\n'), ((5568, 5584), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (5573, 5584), True, 'from CGATCore import Pipeline as P\n'), ((7568, 7584), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (7573, 7584), True, 'from CGATCore import Pipeline as P\n'), ((8134, 8150), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (8139, 8150), True, 'from CGATCore import Pipeline as P\n'), ((9049, 9065), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (9054, 9065), True, 'from CGATCore import Pipeline as P\n'), ((9403, 9428), 'CGATCore.Pipeline.snip', 'P.snip', (['outfile', '""".recal"""'], {}), "(outfile, '.recal')\n", (9409, 9428), True, 'from CGATCore import Pipeline as P\n'), ((11210, 11226), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (11215, 11226), True, 'from CGATCore import Pipeline as P\n'), ((11736, 11752), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (11741, 11752), True, 'from CGATCore import Pipeline as P\n'), ((12220, 12236), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (12225, 12236), True, 'from CGATCore import Pipeline as P\n'), ((15380, 15396), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (15385, 15396), True, 'from CGATCore import Pipeline as P\n'), ((15730, 15751), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (15749, 15751), False, 'import collections\n'), ((19177, 19212), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[0]', '"""w"""'], {}), "(outfiles[0], 'w')\n", (19194, 19212), True, 'import CGATCore.IOTools as IOTools\n'), ((20592, 20627), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[1]', '"""w"""'], {}), "(outfiles[1], 'w')\n", (20609, 20627), True, 'import CGATCore.IOTools as IOTools\n'), ((21400, 21428), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (21423, 21428), False, 'import collections\n'), ((21453, 21481), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (21476, 21481), False, 'import collections\n'), ((22078, 22124), 'pandas.DataFrame', 'pd.DataFrame', (['[single_dict, combinations_dict]'], {}), '([single_dict, combinations_dict])\n', (22090, 22124), True, 'import pandas as pd\n'), ((22747, 22776), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (22770, 22776), False, 'import collections\n'), ((22800, 22829), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (22823, 22829), False, 'import collections\n'), ((23904, 23935), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (23921, 23935), True, 'import CGATCore.IOTools as IOTools\n'), ((24817, 24849), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['eBio_ids', '"""r"""'], {}), "(eBio_ids, 'r')\n", (24834, 24849), True, 'import CGATCore.IOTools as IOTools\n'), ((26868, 26899), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (26885, 26899), True, 'import CGATCore.IOTools as IOTools\n'), ((27536, 27556), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (27554, 27556), False, 'from rpy2.robjects import pandas2ri\n'), ((27587, 27649), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['id_1', 'id_2', 'intersection', 'perc']"}), "(columns=['id_1', 'id_2', 'intersection', 'perc'])\n", (27599, 27649), True, 'import pandas as pd\n'), ((31946, 31981), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[0]', '"""w"""'], {}), "(outfiles[0], 'w')\n", (31963, 31981), True, 'import CGATCore.IOTools as IOTools\n'), ((31993, 32028), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[1]', '"""w"""'], {}), "(outfiles[1], 'w')\n", (32010, 32028), True, 'import CGATCore.IOTools as IOTools\n'), ((38707, 38742), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[0]', '"""w"""'], {}), "(outfiles[0], 'w')\n", (38724, 38742), True, 'import CGATCore.IOTools as IOTools\n'), ((38754, 38789), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[1]', '"""w"""'], {}), "(outfiles[1], 'w')\n", (38771, 38789), True, 'import CGATCore.IOTools as IOTools\n'), ((41345, 41380), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[0]', '"""w"""'], {}), "(outfiles[0], 'w')\n", (41362, 41380), True, 'import CGATCore.IOTools as IOTools\n'), ((41392, 41427), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[1]', '"""w"""'], {}), "(outfiles[1], 'w')\n", (41409, 41427), True, 'import CGATCore.IOTools as IOTools\n'), ((43097, 43132), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[0]', '"""w"""'], {}), "(outfiles[0], 'w')\n", (43114, 43132), True, 'import CGATCore.IOTools as IOTools\n'), ((43144, 43179), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfiles[1]', '"""w"""'], {}), "(outfiles[1], 'w')\n", (43161, 43179), True, 'import CGATCore.IOTools as IOTools\n'), ((43595, 43626), 'pandas.read_csv', 'pd.read_csv', (['variants'], {'sep': '"""\t"""'}), "(variants, sep='\\t')\n", (43606, 43626), True, 'import pandas as pd\n'), ((43670, 43742), 'copy.copy', 'copy.copy', (["variants[['CHROM', 'POS', 'QUAL', 'ID', 'REF1', 'ALT', 'GT']]"], {}), "(variants[['CHROM', 'POS', 'QUAL', 'ID', 'REF1', 'ALT', 'GT']])\n", (43679, 43742), False, 'import copy\n'), ((44576, 44601), 'copy.copy', 'copy.copy', (['variants[cols]'], {}), '(variants[cols])\n', (44585, 44601), False, 'import copy\n'), ((45151, 45167), 'pandas.DataFrame', 'pd.DataFrame', (['Ls'], {}), '(Ls)\n', (45163, 45167), True, 'import pandas as pd\n'), ((3453, 3477), 'os.path.basename', 'os.path.basename', (['infile'], {}), '(infile)\n', (3469, 3477), False, 'import os\n'), ((10154, 10170), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (10159, 10170), True, 'from CGATCore import Pipeline as P\n'), ((12494, 12520), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['pedfile'], {}), '(pedfile)\n', (12511, 12520), True, 'import CGATCore.IOTools as IOTools\n'), ((15915, 15946), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (15932, 15946), True, 'import CGATCore.IOTools as IOTools\n'), ((18197, 18228), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['logfile', '"""w"""'], {}), "(logfile, 'w')\n", (18214, 18228), True, 'import CGATCore.IOTools as IOTools\n'), ((21492, 21523), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile', '"""rb"""'], {}), "(infile, 'rb')\n", (21509, 21523), True, 'import CGATCore.IOTools as IOTools\n'), ((32038, 32063), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (32055, 32063), True, 'import CGATCore.IOTools as IOTools\n'), ((39023, 39048), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (39040, 39048), True, 'import CGATCore.IOTools as IOTools\n'), ((41437, 41462), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (41454, 41462), True, 'import CGATCore.IOTools as IOTools\n'), ((42515, 42540), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (42532, 42540), True, 'import CGATCore.IOTools as IOTools\n'), ((42792, 42818), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile2'], {}), '(infile2)\n', (42809, 42818), True, 'import CGATCore.IOTools as IOTools\n'), ((43189, 43214), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (43206, 43214), True, 'import CGATCore.IOTools as IOTools\n'), ((1192, 1216), 'os.path.basename', 'os.path.basename', (['infile'], {}), '(infile)\n', (1208, 1216), False, 'import os\n'), ((10674, 10690), 'CGATCore.Pipeline.run', 'P.run', (['statement'], {}), '(statement)\n', (10679, 10690), True, 'from CGATCore import Pipeline as P\n'), ((15969, 15999), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile', '"""r"""'], {}), "(infile, 'r')\n", (15986, 15999), True, 'import CGATCore.IOTools as IOTools\n'), ((19075, 19099), 'os.path.basename', 'os.path.basename', (['infile'], {}), '(infile)\n', (19091, 19099), False, 'import os\n'), ((19603, 19633), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile', '"""r"""'], {}), "(infile, 'r')\n", (19620, 19633), True, 'import CGATCore.IOTools as IOTools\n'), ((24420, 24442), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['vcf'], {}), '(vcf)\n', (24437, 24442), True, 'import CGATCore.IOTools as IOTools\n'), ((25767, 25810), 'CGATCore.Experiment.info', 'E.info', (["('number of genes processed: %i' % n)"], {}), "('number of genes processed: %i' % n)\n", (25773, 25810), True, 'import CGATCore.Experiment as E\n'), ((26045, 26108), 'pandas.io.parsers.read_csv', 'pd.io.parsers.read_csv', (['url'], {'comment': '"""#"""', 'sep': '"""\t"""', 'index_col': '(0)'}), "(url, comment='#', sep='\\t', index_col=0)\n", (26067, 26108), True, 'import pandas as pd\n'), ((27798, 27825), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['inf', '"""r"""'], {}), "(inf, 'r')\n", (27815, 27825), True, 'import CGATCore.IOTools as IOTools\n'), ((30133, 30158), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (30150, 30158), True, 'import CGATCore.IOTools as IOTools\n'), ((30735, 30760), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (30752, 30760), True, 'import CGATCore.IOTools as IOTools\n'), ((33650, 33675), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (33667, 33675), True, 'import CGATCore.IOTools as IOTools\n'), ((36761, 36786), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (36778, 36786), True, 'import CGATCore.IOTools as IOTools\n'), ((44745, 44772), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['genes[1]'], {}), '(genes[1])\n', (44762, 44772), True, 'import CGATCore.IOTools as IOTools\n'), ((44836, 44857), 're.search', 're.search', (['gene', 'line'], {}), '(gene, line)\n', (44845, 44857), False, 'import re\n'), ((24957, 24985), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (24980, 24985), False, 'import collections\n'), ((28963, 28988), 'os.path.basename', 'os.path.basename', (['outfile'], {}), '(outfile)\n', (28979, 28988), False, 'import os\n'), ((37444, 37456), 'numpy.array', 'np.array', (['AF'], {}), '(AF)\n', (37452, 37456), True, 'import numpy as np\n'), ((44674, 44701), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['genes[0]'], {}), '(genes[0])\n', (44691, 44701), True, 'import CGATCore.IOTools as IOTools\n'), ((17172, 17198), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (17181, 17198), True, 'import numpy as np\n'), ((17233, 17258), 'numpy.divide', 'np.divide', (['t_alt', 't_depth'], {}), '(t_alt, t_depth)\n', (17242, 17258), True, 'import numpy as np\n'), ((17292, 17317), 'numpy.divide', 'np.divide', (['n_alt', 'n_depth'], {}), '(n_alt, n_depth)\n', (17301, 17317), True, 'import numpy as np\n'), ((27709, 27730), 'os.path.basename', 'os.path.basename', (['inf'], {}), '(inf)\n', (27725, 27730), False, 'import os\n'), ((41878, 41899), 're.search', 're.search', (['r', 'current'], {}), '(r, current)\n', (41887, 41899), False, 'import re\n'), ((23293, 23321), 're.sub', 're.sub', (['""".\n"""', '""""""', 'values[0]'], {}), "('.\\n', '', values[0])\n", (23299, 23321), False, 'import re\n'), ((26631, 26659), 'pandas.DataFrame', 'pd.DataFrame', (['tmp_df.iloc[0]'], {}), '(tmp_df.iloc[0])\n', (26643, 26659), True, 'import pandas as pd\n'), ((33226, 33251), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (33243, 33251), True, 'import CGATCore.IOTools as IOTools\n'), ((36447, 36472), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (36464, 36472), True, 'import CGATCore.IOTools as IOTools\n'), ((40879, 40904), 'CGATCore.IOTools.open_file', 'IOTools.open_file', (['infile'], {}), '(infile)\n', (40896, 40904), True, 'import CGATCore.IOTools as IOTools\n'), ((18006, 18031), 'numpy.divide', 'np.divide', (['t_freq', 'n_freq'], {}), '(t_freq, n_freq)\n', (18015, 18031), True, 'import numpy as np\n')] |
import os
import numpy as np
import mindspore.dataset as de
class npyDataset(object):
def __init__(self, data_dir, data_type, h, w):
super(npyDataset, self).__init__()
self.data = np.load(os.path.join(data_dir, '{}_data.npy'.format(data_type)))
self.data = np.reshape(self.data, (-1, 1, h, w))
self.label = np.load(os.path.join(data_dir, '{}_label.npy'.format(data_type)))
def __len__(self):
return self.data.shape[0]
def __getitem__(self, item):
data = self.data[item]
label = self.label[item]
# return data, label
return data.astype(np.float32), label.astype(np.int32)
def audio_dataset(data_dir, data_type, h, w, batch_size):
if 'testing' in data_dir:
shuffle = False
else:
shuffle = True
dataset = npyDataset(data_dir, data_type, h, w)
de_dataset = de.GeneratorDataset(dataset, ["feats", "labels"], shuffle=shuffle)
de_dataset = de_dataset.batch(batch_size, drop_remainder=False)
return de_dataset
| [
"numpy.reshape",
"mindspore.dataset.GeneratorDataset"
] | [((875, 941), 'mindspore.dataset.GeneratorDataset', 'de.GeneratorDataset', (['dataset', "['feats', 'labels']"], {'shuffle': 'shuffle'}), "(dataset, ['feats', 'labels'], shuffle=shuffle)\n", (894, 941), True, 'import mindspore.dataset as de\n'), ((287, 323), 'numpy.reshape', 'np.reshape', (['self.data', '(-1, 1, h, w)'], {}), '(self.data, (-1, 1, h, w))\n', (297, 323), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
DeepAnchor was a CNN-based method to distinguish loop-associated CTCF binding sites from others.
It has two different mode: train, predict
When mode is train, it train a classifier and save it to file_model, while if mode is predict,
it uses the classifier to predict the score of all motifs.
usage: python DeepAnchor.py work_dir mode
"""
import os
import sys
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models, layers
def ROC_AUC(y_raw, y_pred):
fig, (ax1, ax2) = plt.subplots(1,2,figsize=(9,4), sharex=True, sharey=True)
FPR, TPR, _ = metrics.roc_curve(y_raw, y_pred)
auc = metrics.roc_auc_score(y_raw, y_pred)
ax1.plot(FPR, TPR, lw=2, label='ROC AUC = %0.2f' % auc)
precision, recall, _ = metrics.precision_recall_curve(y_raw, y_pred)
aupr = metrics.average_precision_score(y_raw, y_pred)
ax2.plot(recall, precision, lw=2, label='AUPR = %0.2f' % aupr)
ax1.legend()
ax2.legend()
ax1.set_xlabel('1-Specificity')
ax1.set_ylabel('Sensitivity')
ax2.set_xlabel('Recall')
ax2.set_ylabel('Precision')
ax1.set_box_aspect(1)
ax2.set_box_aspect(1)
plt.tight_layout()
plt.show()
def plot_history(histories, key='binary_crossentropy'):
plt.figure(figsize=(8,6))
for name, history in histories:
val = plt.plot(history.epoch, history.history['val_'+key],
'--', label=name.title()+' Val')
plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
label=name.title()+' Train')
plt.xlabel('Epochs')
plt.ylabel(key.replace('_',' ').title())
plt.legend()
plt.xlim([0,max(history.epoch)])
plt.show()
def DeepAnchor(file_model, data):
### construct model
model = models.Sequential()
model.add(layers.Conv1D(32, 10, activation='relu', input_shape=(1000, 48)))
model.add(layers.MaxPooling1D(10))
model.add(layers.Dropout(0.5))
model.add(layers.Conv1D(64, 10, activation='relu'))
model.add(layers.MaxPooling1D(2))
model.add(layers.Dropout(0.5))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(2, activation='sigmoid'))
model.summary()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy','binary_crossentropy', tf.keras.metrics.AUC()])
earlystop_callback = keras.callbacks.EarlyStopping(
monitor='val_binary_crossentropy', min_delta=0.0001,
patience=3)
### loading data
train_X, train_y = data['train_Features'], data['train_Label']
valid_X, valid_y = data['valid_Features'], data['valid_Label']
test_X, test_y = data['test_Features'], data['test_Label']
### training
history_model = model.fit(train_X,
train_y,
epochs=20,
batch_size=50,
validation_data=(valid_X, valid_y),
callbacks=[earlystop_callback]
)
plot_history([('DeepAnchor', history_model)])
model.save(file_model)
### testing
pred_y = model.predict(test_X)[:, 1]
ROC_AUC(test_y, pred_y)
return model
def main(argv=sys.argv):
work_dir = argv[1]
mode = argv[2]
# input and output
os.chdir(os.path.expanduser(work_dir))
file_motif = './raw/CTCF_motif.tsv'
file_scored_motif = './scored_motif.tsv'
file_model = './DeepAnchor.model'
# train
enc = OneHotEncoder(categories='auto')
if mode == 'train':
### load data
train_data = np.load('./DeepAnchor/train.npz')
train_X, train_y = train_data['Features'], train_data['label']
train_y = enc.fit(train_y.reshape(-1,1)).transform(train_y.reshape(-1,1)).toarray()
valid_data = np.load('./DeepAnchor/valid.npz')
valid_X, valid_y = valid_data['Features'], valid_data['label']
valid_y = enc.fit(valid_y.reshape(-1,1)).transform(valid_y.reshape(-1,1)).toarray()
test_data = np.load('./DeepAnchor/test.npz')
test_X, test_y = test_data['Features'], test_data['label']
### training
data = {'train_Features': train_X, 'train_Label': train_y,
'valid_Features': valid_X, 'valid_Label': valid_y,
'test_Features': test_X, 'test_Label': test_y}
model = DeepAnchor(file_model, data)
pred_y = model.predict(test_X)[:, 1]
df_test = pd.DataFrame({'test_label': test_y,
'LoopAnchor': pred_y})
df_test.to_csv('./DeepAnchor/test_result.tsv', sep='\t', index=False)
elif mode == 'predict':
df_motif = pd.read_csv(file_motif, sep='\t', names=['chrom','start','end','strand','score'])
predict_X = np.load('./DeepAnchor/total.npz')['Features']
model = keras.models.load_model(file_model)
pred_y = model.predict(predict_X)[:,1]
df_motif['anchor_score'] = pred_y
df_motif.to_csv(file_scored_motif, sep='\t', index=False, header=False)
else:
print('{} mode is not currently supported'.format(mode))
if __name__ == '__main__':
main()
| [
"numpy.load",
"tensorflow.keras.layers.Dense",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.tight_layout",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.keras.layers.Flatten",
"pandas.DataFrame",
"sklearn.metrics.average_precisio... | [((711, 771), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(9, 4)', 'sharex': '(True)', 'sharey': '(True)'}), '(1, 2, figsize=(9, 4), sharex=True, sharey=True)\n', (723, 771), True, 'import matplotlib.pyplot as plt\n'), ((788, 820), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['y_raw', 'y_pred'], {}), '(y_raw, y_pred)\n', (805, 820), False, 'from sklearn import metrics\n'), ((831, 867), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['y_raw', 'y_pred'], {}), '(y_raw, y_pred)\n', (852, 867), False, 'from sklearn import metrics\n'), ((955, 1000), 'sklearn.metrics.precision_recall_curve', 'metrics.precision_recall_curve', (['y_raw', 'y_pred'], {}), '(y_raw, y_pred)\n', (985, 1000), False, 'from sklearn import metrics\n'), ((1012, 1058), 'sklearn.metrics.average_precision_score', 'metrics.average_precision_score', (['y_raw', 'y_pred'], {}), '(y_raw, y_pred)\n', (1043, 1058), False, 'from sklearn import metrics\n'), ((1347, 1365), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1363, 1365), True, 'import matplotlib.pyplot as plt\n'), ((1370, 1380), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1378, 1380), True, 'import matplotlib.pyplot as plt\n'), ((1447, 1473), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (1457, 1473), True, 'import matplotlib.pyplot as plt\n'), ((1764, 1784), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (1774, 1784), True, 'import matplotlib.pyplot as plt\n'), ((1834, 1846), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1844, 1846), True, 'import matplotlib.pyplot as plt\n'), ((1891, 1901), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1899, 1901), True, 'import matplotlib.pyplot as plt\n'), ((1974, 1993), 'tensorflow.keras.models.Sequential', 'models.Sequential', ([], {}), '()\n', (1991, 1993), False, 'from tensorflow.keras import models, layers\n'), ((2613, 2712), 'tensorflow.keras.callbacks.EarlyStopping', 'keras.callbacks.EarlyStopping', ([], {'monitor': '"""val_binary_crossentropy"""', 'min_delta': '(0.0001)', 'patience': '(3)'}), "(monitor='val_binary_crossentropy', min_delta=\n 0.0001, patience=3)\n", (2642, 2712), False, 'from tensorflow import keras\n'), ((3625, 3657), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'categories': '"""auto"""'}), "(categories='auto')\n", (3638, 3657), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((2008, 2072), 'tensorflow.keras.layers.Conv1D', 'layers.Conv1D', (['(32)', '(10)'], {'activation': '"""relu"""', 'input_shape': '(1000, 48)'}), "(32, 10, activation='relu', input_shape=(1000, 48))\n", (2021, 2072), False, 'from tensorflow.keras import models, layers\n'), ((2088, 2111), 'tensorflow.keras.layers.MaxPooling1D', 'layers.MaxPooling1D', (['(10)'], {}), '(10)\n', (2107, 2111), False, 'from tensorflow.keras import models, layers\n'), ((2127, 2146), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['(0.5)'], {}), '(0.5)\n', (2141, 2146), False, 'from tensorflow.keras import models, layers\n'), ((2162, 2202), 'tensorflow.keras.layers.Conv1D', 'layers.Conv1D', (['(64)', '(10)'], {'activation': '"""relu"""'}), "(64, 10, activation='relu')\n", (2175, 2202), False, 'from tensorflow.keras import models, layers\n'), ((2218, 2240), 'tensorflow.keras.layers.MaxPooling1D', 'layers.MaxPooling1D', (['(2)'], {}), '(2)\n', (2237, 2240), False, 'from tensorflow.keras import models, layers\n'), ((2256, 2275), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['(0.5)'], {}), '(0.5)\n', (2270, 2275), False, 'from tensorflow.keras import models, layers\n'), ((2291, 2307), 'tensorflow.keras.layers.Flatten', 'layers.Flatten', ([], {}), '()\n', (2305, 2307), False, 'from tensorflow.keras import models, layers\n'), ((2323, 2359), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(512)'], {'activation': '"""relu"""'}), "(512, activation='relu')\n", (2335, 2359), False, 'from tensorflow.keras import models, layers\n'), ((2375, 2412), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(2)'], {'activation': '"""sigmoid"""'}), "(2, activation='sigmoid')\n", (2387, 2412), False, 'from tensorflow.keras import models, layers\n'), ((3449, 3477), 'os.path.expanduser', 'os.path.expanduser', (['work_dir'], {}), '(work_dir)\n', (3467, 3477), False, 'import os\n'), ((3725, 3758), 'numpy.load', 'np.load', (['"""./DeepAnchor/train.npz"""'], {}), "('./DeepAnchor/train.npz')\n", (3732, 3758), True, 'import numpy as np\n'), ((3944, 3977), 'numpy.load', 'np.load', (['"""./DeepAnchor/valid.npz"""'], {}), "('./DeepAnchor/valid.npz')\n", (3951, 3977), True, 'import numpy as np\n'), ((4170, 4202), 'numpy.load', 'np.load', (['"""./DeepAnchor/test.npz"""'], {}), "('./DeepAnchor/test.npz')\n", (4177, 4202), True, 'import numpy as np\n'), ((4606, 4664), 'pandas.DataFrame', 'pd.DataFrame', (["{'test_label': test_y, 'LoopAnchor': pred_y}"], {}), "({'test_label': test_y, 'LoopAnchor': pred_y})\n", (4618, 4664), True, 'import pandas as pd\n'), ((4857, 4946), 'pandas.read_csv', 'pd.read_csv', (['file_motif'], {'sep': '"""\t"""', 'names': "['chrom', 'start', 'end', 'strand', 'score']"}), "(file_motif, sep='\\t', names=['chrom', 'start', 'end', 'strand',\n 'score'])\n", (4868, 4946), True, 'import pandas as pd\n'), ((5022, 5057), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['file_model'], {}), '(file_model)\n', (5045, 5057), False, 'from tensorflow import keras\n'), ((2558, 2580), 'tensorflow.keras.metrics.AUC', 'tf.keras.metrics.AUC', ([], {}), '()\n', (2578, 2580), True, 'import tensorflow as tf\n'), ((4959, 4992), 'numpy.load', 'np.load', (['"""./DeepAnchor/total.npz"""'], {}), "('./DeepAnchor/total.npz')\n", (4966, 4992), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# %reset -f
"""
@author: <NAME>
"""
import random
import numpy as np
import pandas as pd
from deap import base
from deap import creator
from deap import tools
from sklearn import model_selection
from sklearn import svm
# 設定 ここから
number_of_areas = 5 # 選択する領域の数
max_width_of_areas = 20 # 選択する領域の幅の最大値
number_of_population = 100 # GA の個体数
number_of_generation = 150 # GA の世代数
fold_number = 5 # クロスバリデーションの fold 数
svr_c_2_range = (-5, 10) # SVR の C の範囲 (2 の何乗か)
svr_epsilon_2_range = (-10, 0) # SVR の epsilon の範囲 (2 の何乗か)
svr_gamma_2_range = (-20, 10) # SVR の gamma の範囲 (2 の何乗か)
# 設定 ここまで
probability_of_crossover = 0.5
probability_of_mutation = 0.2
# load dataset
dataset = pd.read_csv('sample_spectra_dataset_with_y.csv', index_col=0)
x_train = dataset.iloc[:, 1:]
y_train = dataset.iloc[:, 0]
# autoscaling
autoscaled_x_train = (x_train - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1)
autoscaled_y_train = (y_train - y_train.mean()) / y_train.std(ddof=1)
# GAWLSSVR
creator.create('FitnessMax', base.Fitness, weights=(1.0,)) # for minimization, set weights as (-1.0,)
creator.create('Individual', list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
min_boundary = np.zeros(number_of_areas * 2 + 3)
max_boundary = np.ones(number_of_areas * 2 + 3) * x_train.shape[1]
max_boundary[np.arange(1, number_of_areas * 2, 2)] = max_width_of_areas
min_boundary[-3] = svr_c_2_range[0]
min_boundary[-2] = svr_epsilon_2_range[0]
min_boundary[-1] = svr_gamma_2_range[0]
max_boundary[-3] = svr_c_2_range[1]
max_boundary[-2] = svr_epsilon_2_range[1]
max_boundary[-1] = svr_gamma_2_range[1]
def create_ind_uniform(min_boundary, max_boundary):
index = []
for min, max in zip(min_boundary, max_boundary):
index.append(random.uniform(min, max))
return index
toolbox.register('create_ind', create_ind_uniform, min_boundary, max_boundary)
toolbox.register('individual', tools.initIterate, creator.Individual, toolbox.create_ind)
toolbox.register('population', tools.initRepeat, list, toolbox.individual)
def evalOneMax(individual):
individual_array = np.array(individual)
individual_array_wavelength = np.array(np.floor(individual_array[0:number_of_areas * 2]), dtype=int)
selected_x_variable_numbers = np.zeros(0, dtype=int)
for area_number in range(number_of_areas):
if individual_array_wavelength[2 * area_number] + individual_array_wavelength[2 * area_number + 1] <= \
autoscaled_x_train.shape[1]:
selected_x_variable_numbers = np.r_[
selected_x_variable_numbers, np.arange(individual_array_wavelength[2 * area_number],
individual_array_wavelength[2 * area_number] +
individual_array_wavelength[2 * area_number + 1])]
else:
selected_x_variable_numbers = np.r_[
selected_x_variable_numbers, np.arange(individual_array_wavelength[2 * area_number],
autoscaled_x_train.shape[1])]
selected_autoscaled_x_train = autoscaled_x_train.iloc[:, selected_x_variable_numbers]
if len(selected_x_variable_numbers):
# cross-validation
model_in_cv = svm.SVR(kernel='rbf', C=2 ** round(individual_array[-3]),
epsilon=2 ** round(individual_array[-2]), gamma=2 ** round(individual_array[-1]))
estimated_y_train_in_cv = model_selection.cross_val_predict(model_in_cv, selected_autoscaled_x_train,
autoscaled_y_train, cv=fold_number)
estimated_y_train_in_cv = estimated_y_train_in_cv * y_train.std(ddof=1) + y_train.mean()
value = 1 - sum((y_train - estimated_y_train_in_cv) ** 2) / sum((y_train - y_train.mean()) ** 2)
else:
value = -999
return value,
toolbox.register('evaluate', evalOneMax)
toolbox.register('mate', tools.cxTwoPoint)
toolbox.register('mutate', tools.mutFlipBit, indpb=0.05)
toolbox.register('select', tools.selTournament, tournsize=3)
# random.seed(100)
random.seed()
pop = toolbox.population(n=number_of_population)
print('Start of evolution')
fitnesses = list(map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
print(' Evaluated %i individuals' % len(pop))
for generation in range(number_of_generation):
print('-- Generation {0} --'.format(generation + 1))
offspring = toolbox.select(pop, len(pop))
offspring = list(map(toolbox.clone, offspring))
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < probability_of_crossover:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if random.random() < probability_of_mutation:
toolbox.mutate(mutant)
del mutant.fitness.values
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
print(' Evaluated %i individuals' % len(invalid_ind))
pop[:] = offspring
fits = [ind.fitness.values[0] for ind in pop]
length = len(pop)
mean = sum(fits) / length
sum2 = sum(x * x for x in fits)
std = abs(sum2 / length - mean ** 2) ** 0.5
print(' Min %s' % min(fits))
print(' Max %s' % max(fits))
print(' Avg %s' % mean)
print(' Std %s' % std)
print('-- End of (successful) evolution --')
best_individual = tools.selBest(pop, 1)[0]
best_individual_array = np.array(best_individual)
best_individual_array_wavelength = np.array(np.floor(best_individual_array[0:number_of_areas * 2]), dtype=int)
selected_x_variable_numbers = np.zeros(0, dtype=int)
for area_number in range(number_of_areas):
if best_individual_array_wavelength[2 * area_number] + best_individual_array_wavelength[2 * area_number + 1] <= \
autoscaled_x_train.shape[1]:
selected_x_variable_numbers = np.r_[
selected_x_variable_numbers, np.arange(best_individual_array_wavelength[2 * area_number],
best_individual_array_wavelength[2 * area_number] +
best_individual_array_wavelength[2 * area_number + 1])]
else:
selected_x_variable_numbers = np.r_[
selected_x_variable_numbers, np.arange(best_individual_array_wavelength[2 * area_number],
autoscaled_x_train.shape[1])]
selected_descriptors = x_train.iloc[:, selected_x_variable_numbers]
selected_descriptors.to_csv('gawlssvr_selected_x.csv') # 保存
selected_hyperparameters = pd.DataFrame(np.round(best_individual_array[-3:]), index=['C', 'epsilon', 'gamma'], columns=['hyperparameters of SVR (log2)'])
selected_hyperparameters.to_csv('gawlssvr_selected_hyperparameters.csv') # 保存
| [
"deap.base.Toolbox",
"random.uniform",
"pandas.read_csv",
"numpy.floor",
"numpy.zeros",
"numpy.ones",
"sklearn.model_selection.cross_val_predict",
"random.random",
"deap.creator.create",
"deap.tools.selBest",
"random.seed",
"numpy.array",
"numpy.arange",
"numpy.round"
] | [((738, 799), 'pandas.read_csv', 'pd.read_csv', (['"""sample_spectra_dataset_with_y.csv"""'], {'index_col': '(0)'}), "('sample_spectra_dataset_with_y.csv', index_col=0)\n", (749, 799), True, 'import pandas as pd\n'), ((1049, 1107), 'deap.creator.create', 'creator.create', (['"""FitnessMax"""', 'base.Fitness'], {'weights': '(1.0,)'}), "('FitnessMax', base.Fitness, weights=(1.0,))\n", (1063, 1107), False, 'from deap import creator\n'), ((1153, 1215), 'deap.creator.create', 'creator.create', (['"""Individual"""', 'list'], {'fitness': 'creator.FitnessMax'}), "('Individual', list, fitness=creator.FitnessMax)\n", (1167, 1215), False, 'from deap import creator\n'), ((1229, 1243), 'deap.base.Toolbox', 'base.Toolbox', ([], {}), '()\n', (1241, 1243), False, 'from deap import base\n'), ((1260, 1293), 'numpy.zeros', 'np.zeros', (['(number_of_areas * 2 + 3)'], {}), '(number_of_areas * 2 + 3)\n', (1268, 1293), True, 'import numpy as np\n'), ((4253, 4266), 'random.seed', 'random.seed', ([], {}), '()\n', (4264, 4266), False, 'import random\n'), ((5869, 5894), 'numpy.array', 'np.array', (['best_individual'], {}), '(best_individual)\n', (5877, 5894), True, 'import numpy as np\n'), ((6038, 6060), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'int'}), '(0, dtype=int)\n', (6046, 6060), True, 'import numpy as np\n'), ((1310, 1342), 'numpy.ones', 'np.ones', (['(number_of_areas * 2 + 3)'], {}), '(number_of_areas * 2 + 3)\n', (1317, 1342), True, 'import numpy as np\n'), ((1376, 1412), 'numpy.arange', 'np.arange', (['(1)', '(number_of_areas * 2)', '(2)'], {}), '(1, number_of_areas * 2, 2)\n', (1385, 1412), True, 'import numpy as np\n'), ((2178, 2198), 'numpy.array', 'np.array', (['individual'], {}), '(individual)\n', (2186, 2198), True, 'import numpy as np\n'), ((2340, 2362), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': 'int'}), '(0, dtype=int)\n', (2348, 2362), True, 'import numpy as np\n'), ((5819, 5840), 'deap.tools.selBest', 'tools.selBest', (['pop', '(1)'], {}), '(pop, 1)\n', (5832, 5840), False, 'from deap import tools\n'), ((5940, 5994), 'numpy.floor', 'np.floor', (['best_individual_array[0:number_of_areas * 2]'], {}), '(best_individual_array[0:number_of_areas * 2])\n', (5948, 5994), True, 'import numpy as np\n'), ((7043, 7079), 'numpy.round', 'np.round', (['best_individual_array[-3:]'], {}), '(best_individual_array[-3:])\n', (7051, 7079), True, 'import numpy as np\n'), ((2243, 2292), 'numpy.floor', 'np.floor', (['individual_array[0:number_of_areas * 2]'], {}), '(individual_array[0:number_of_areas * 2])\n', (2251, 2292), True, 'import numpy as np\n'), ((3581, 3696), 'sklearn.model_selection.cross_val_predict', 'model_selection.cross_val_predict', (['model_in_cv', 'selected_autoscaled_x_train', 'autoscaled_y_train'], {'cv': 'fold_number'}), '(model_in_cv, selected_autoscaled_x_train,\n autoscaled_y_train, cv=fold_number)\n', (3614, 3696), False, 'from sklearn import model_selection\n'), ((1826, 1850), 'random.uniform', 'random.uniform', (['min', 'max'], {}), '(min, max)\n', (1840, 1850), False, 'import random\n'), ((4803, 4818), 'random.random', 'random.random', ([], {}), '()\n', (4816, 4818), False, 'import random\n'), ((5011, 5026), 'random.random', 'random.random', ([], {}), '()\n', (5024, 5026), False, 'import random\n'), ((6354, 6530), 'numpy.arange', 'np.arange', (['best_individual_array_wavelength[2 * area_number]', '(best_individual_array_wavelength[2 * area_number] +\n best_individual_array_wavelength[2 * area_number + 1])'], {}), '(best_individual_array_wavelength[2 * area_number], \n best_individual_array_wavelength[2 * area_number] +\n best_individual_array_wavelength[2 * area_number + 1])\n', (6363, 6530), True, 'import numpy as np\n'), ((6726, 6819), 'numpy.arange', 'np.arange', (['best_individual_array_wavelength[2 * area_number]', 'autoscaled_x_train.shape[1]'], {}), '(best_individual_array_wavelength[2 * area_number],\n autoscaled_x_train.shape[1])\n', (6735, 6819), True, 'import numpy as np\n'), ((2666, 2827), 'numpy.arange', 'np.arange', (['individual_array_wavelength[2 * area_number]', '(individual_array_wavelength[2 * area_number] + individual_array_wavelength\n [2 * area_number + 1])'], {}), '(individual_array_wavelength[2 * area_number], \n individual_array_wavelength[2 * area_number] +\n individual_array_wavelength[2 * area_number + 1])\n', (2675, 2827), True, 'import numpy as np\n'), ((3043, 3132), 'numpy.arange', 'np.arange', (['individual_array_wavelength[2 * area_number]', 'autoscaled_x_train.shape[1]'], {}), '(individual_array_wavelength[2 * area_number], autoscaled_x_train.\n shape[1])\n', (3052, 3132), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 14:31:18 2020
@author: vatsal
"""
import numpy as np
import pandas as pd
df=pd.read_csv('Social_Network_Ads.csv')
print("\n")
print(df.columns)
print("\n")
print(df.shape)
print("\n")
print(df.isnull().sum())
print("\n")
print(df.corr())
import seaborn as sns
import matplotlib.pyplot as plt
corr=df.corr()
plt.figure(figsize=(20,10))
sns.heatmap(corr[(corr>=0.5)|(corr<=-0.4)],annot=True,cmap='Blues')
"""Segregate data into X and y"""
X=df.iloc[:,:-1].values
y=df.iloc[:,-1].values
"""Splitting the dataset"""
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)
print(X_train)
print("\n")
print(X_test)
print("\n")
print(y_train)
print("\n")
print(y_test)
print("\n")
"""Feature Scaling"""
from sklearn.preprocessing import StandardScaler
ss=StandardScaler()
X_train=ss.fit_transform(X_train)
X_test=ss.transform(X_test)
print(X_train)
print("\n")
print(X_test)
print("\n")
from sklearn.linear_model import LogisticRegression
clf=LogisticRegression()
clf.fit(X_train,y_train)
y_pred=clf.predict(X_test)
print(y_pred)
print("\n")
print("Predicted Values Actual Values ")
for i in range(0,len(y_pred)):
print(y_pred[i]," ",y_test[i])
print("\n")
#Confusion Matrix
from sklearn.metrics import confusion_matrix,accuracy_score
print("Confusion Matrix")
cm=confusion_matrix(y_test, y_pred)
print(cm)
print("\n")
# Predicting a new result
print(clf.predict(sc.transform([[30,87000]])))
"""Accuracy"""
print("The Accuracy of our model is ",accuracy_score(y_test,y_pred)*100)
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = sc.inverse_transform(X_train), y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 0.25),
np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 0.25))
plt.contourf(X1, X2, clf.predict(sc.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = sc.inverse_transform(X_test), y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 10, stop = X_set[:, 0].max() + 10, step = 0.25),
np.arange(start = X_set[:, 1].min() - 1000, stop = X_set[:, 1].max() + 1000, step = 0.25))
plt.contourf(X1, X2, clf.predict(sc.transform(np.array([X1.ravel(), X2.ravel()]).T)).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Logistic Regression (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
| [
"matplotlib.pyplot.title",
"seaborn.heatmap",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.legend",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.figure",
"sk... | [((128, 165), 'pandas.read_csv', 'pd.read_csv', (['"""Social_Network_Ads.csv"""'], {}), "('Social_Network_Ads.csv')\n", (139, 165), True, 'import pandas as pd\n'), ((369, 397), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (379, 397), True, 'import matplotlib.pyplot as plt\n'), ((397, 472), 'seaborn.heatmap', 'sns.heatmap', (['corr[(corr >= 0.5) | (corr <= -0.4)]'], {'annot': '(True)', 'cmap': '"""Blues"""'}), "(corr[(corr >= 0.5) | (corr <= -0.4)], annot=True, cmap='Blues')\n", (408, 472), True, 'import seaborn as sns\n'), ((661, 714), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(0)'}), '(X, y, test_size=0.3, random_state=0)\n', (677, 714), False, 'from sklearn.model_selection import train_test_split\n'), ((900, 916), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (914, 916), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1094, 1114), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (1112, 1114), False, 'from sklearn.linear_model import LogisticRegression\n'), ((1449, 1481), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (1465, 1481), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((2409, 2456), 'matplotlib.pyplot.title', 'plt.title', (['"""Logistic Regression (Training set)"""'], {}), "('Logistic Regression (Training set)')\n", (2418, 2456), True, 'import matplotlib.pyplot as plt\n'), ((2457, 2474), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (2467, 2474), True, 'import matplotlib.pyplot as plt\n'), ((2475, 2505), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimated Salary"""'], {}), "('Estimated Salary')\n", (2485, 2505), True, 'import matplotlib.pyplot as plt\n'), ((2506, 2518), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2516, 2518), True, 'import matplotlib.pyplot as plt\n'), ((2519, 2529), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2527, 2529), True, 'import matplotlib.pyplot as plt\n'), ((3266, 3309), 'matplotlib.pyplot.title', 'plt.title', (['"""Logistic Regression (Test set)"""'], {}), "('Logistic Regression (Test set)')\n", (3275, 3309), True, 'import matplotlib.pyplot as plt\n'), ((3310, 3327), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age"""'], {}), "('Age')\n", (3320, 3327), True, 'import matplotlib.pyplot as plt\n'), ((3328, 3358), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Estimated Salary"""'], {}), "('Estimated Salary')\n", (3338, 3358), True, 'import matplotlib.pyplot as plt\n'), ((3359, 3371), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3369, 3371), True, 'import matplotlib.pyplot as plt\n'), ((3372, 3382), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3380, 3382), True, 'import matplotlib.pyplot as plt\n'), ((2278, 2294), 'numpy.unique', 'np.unique', (['y_set'], {}), '(y_set)\n', (2287, 2294), True, 'import numpy as np\n'), ((3135, 3151), 'numpy.unique', 'np.unique', (['y_set'], {}), '(y_set)\n', (3144, 3151), True, 'import numpy as np\n'), ((1632, 1662), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (1646, 1662), False, 'from sklearn.metrics import confusion_matrix, accuracy_score\n'), ((2164, 2196), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (2178, 2196), False, 'from matplotlib.colors import ListedColormap\n'), ((3021, 3053), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (3035, 3053), False, 'from matplotlib.colors import ListedColormap\n'), ((2361, 2393), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (2375, 2393), False, 'from matplotlib.colors import ListedColormap\n'), ((3218, 3250), 'matplotlib.colors.ListedColormap', 'ListedColormap', (["('red', 'green')"], {}), "(('red', 'green'))\n", (3232, 3250), False, 'from matplotlib.colors import ListedColormap\n')] |
import time
from config import parse_args, parse_class_weights
from seg_helper import *
from tfsolver import TFSolver, DELIMITER
from network_factory import seg_network
from dataset_iterator import *
from dataset_preloader import *
from data_augmentation import *
from libs import points_property, octree_property,check_octree
import numpy as np
from tqdm import trange
import os
from ocnn import *
from learning_rate import LRFactory
from tensorflow.python.client import timeline
import psutil
from memory_profiler import profile
# tf.compat.v1.enable_eager_execution()
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
# Add config
best_metric_dict = {"accu": 0.0, "total_loss": 10e100, "iou": 0.0} # TODO store last values in ckpt & restore them
DO_NOT_AVG = ["intsc_", "union_", "iou"]
TRAIN_DATA = DataLoader()
TEST_DATA = DataLoader()
# @profile
def read_datasets(flags):
global TRAIN_DATA, TEST_DATA
if flags.SOLVER.run != 'test':
TRAIN_DATA = TRAIN_DATA(flags.DATA.train, flags.MODEL.nout, flags.MODEL.channel, True,True)
if flags.SOLVER.run != "timeline":
TEST_DATA = TEST_DATA(flags.DATA.test, flags.MODEL.nout, flags.MODEL.channel, True,
True if flags.SOLVER.run == "test" else False)
# get the label and pts
def get_point_info(points, mask_ratio=0, mask=-1):
debug_checks = {}
with tf.name_scope('points_info'):
pts = points_property(points, property_name='xyz', channel=4) # can run with channel=3 too, 4th channel is
# point id (to which octree in the batch it belongs to)
label = points_property(points, property_name='label', channel=1)
debug_checks['{}/pts(xyz)'.format(tf.get_variable_scope().name)] = pts
debug_checks['{}/label'.format(tf.get_variable_scope().name)] = label
label = tf.reshape(label, [-1])
label_mask = tf.not_equal(label, mask) # mask out invalid points, -1
if mask_ratio > 0: # random drop some points to speed up training
rnd_mask = tf.random.uniform(tf.shape(label_mask)) > mask_ratio
label_mask = tf.logical_and(label_mask, rnd_mask)
label = tf.boolean_mask(label, label_mask)
pts = tf.boolean_mask(pts, label_mask)
debug_checks['{}/masked_and_dropped/pts(xyz)'.format(tf.get_variable_scope().name)] = pts
debug_checks['{}/masked_and_dropped/label'.format(tf.get_variable_scope().name)] = label
return pts, label, debug_checks
def tf_IoU_per_shape(logits, label, class_num, mask=-1, ignore=666):
# -1 CAN EXIST IF LABELS COME FROM OCTREE_PROPERTY('LABEL')
with tf.name_scope('IoU'):
# mask out unwanted labels (empty and undetermined)
label_mask = tf.logical_and(tf.not_equal(label, mask), tf.not_equal(label, ignore))
masked_label = tf.boolean_mask(label, label_mask)
prediction = tf.argmax(tf.boolean_mask(logits, label_mask), axis=1, output_type=tf.int32)
intsc, union = [0] * class_num, [0] * class_num
for k in range(0, class_num):
pk = tf.equal(prediction, k)
lk = tf.equal(masked_label, k)
intsc[k] = tf.reduce_sum(tf.cast(pk & lk, dtype=tf.float32))
union[k] = tf.reduce_sum(tf.cast(pk | lk, dtype=tf.float32))
return intsc, union
# define the graph
class ComputeGraphSeg:
def __init__(self, flags):
self.flags = flags
self.weights = ComputeGraphSeg.set_weights(parse_class_weights(flags))
self.points = tf.placeholder(dtype=tf.float32, name="batch_points")
self.normals = tf.placeholder(dtype=tf.float32, name="point_nrms")
self.features = tf.placeholder(dtype=tf.float32, name="point_fts")
self.labels = tf.placeholder(dtype=tf.float32, name="point_labels")
self.rot = tf.placeholder(dtype=tf.float32, name="point_rotation")
@staticmethod
def set_weights(w_list):
weights = tf.constant(w_list)
return weights
def __call__(self, dataset='train', training=True, reuse=False, gpu_num=1):
if gpu_num != 1:
raise Exception('Since I made a dict there is no implementation for multi gpu support')
debug_checks = {}
tensors_dict = {}
FLAGS = self.flags
with tf.device('/cpu:0'):
flags_data = FLAGS.DATA.train if dataset == 'train' else FLAGS.DATA.test
data_aug = DataAugmentor(flags_data)
with tf.device('/gpu:0'):
with tf.name_scope('device_0'):
octree, points = data_aug(self.points, self.normals, self.features, self.labels, self.rot)
debug_checks["octree"] = octree
print("mask ratio for {} is {}".format(dataset, flags_data.mask_ratio))
pts, label, dc = get_point_info(points, flags_data.mask_ratio)
debug_checks.update(dc)
if not FLAGS.LOSS.point_wise: # octree-wise loss
pts, label = None, get_seg_label(octree, FLAGS.MODEL.depth)
debug_checks["{}/seg_label/label(pts=None)".format(tf.get_variable_scope().name)] = label
logit, dc = seg_network(octree, FLAGS.MODEL, training, reuse, pts=pts)
debug_checks.update(dc)
debug_checks["{}/probabilities".format(tf.get_variable_scope().name)] = get_probabilities(logit)
metrics_dict = loss_functions_seg(logit=logit, label_gt=label, num_class=FLAGS.LOSS.num_class,
weight_decay=FLAGS.LOSS.weight_decay, var_name='ocnn',
weights=self.weights, mask=-1, ignore=FLAGS.MODEL.nout)
tensors_dict.update(metrics_dict)
tensors_dict['total_loss'] = metrics_dict['loss'] + metrics_dict['regularizer']
if flags_data.batch_size == 1: # TODO make it work for different batch sizes
num_class = FLAGS.LOSS.num_class
intsc, union = tf_IoU_per_shape(logit, label, num_class, mask=-1, ignore=FLAGS.MODEL.nout)
tensors_dict['iou'] = tf.constant(0.0) # placeholder, calc its value later
for i in range(0, num_class):
tensors_dict['intsc_%d' % i] = intsc[i]
tensors_dict['union_%d' % i] = union[i]
return tensors_dict, debug_checks
def result_callback(avg_results_dict, num_class):
# calc part-IoU, update `iou`, this is in correspondence with Line 77
ious = {}
for i in range(0, num_class): # !!! First label is wall, undetermined is num_class+1
instc_i = avg_results_dict['intsc_%d' % i]
union_i = avg_results_dict['union_%d' % i] # max value of union is the # of determined points
if union_i > 0.0:
ious[i] = instc_i / union_i
try:
avg_results_dict['iou'] = sum(ious.values()) / len(ious)
except ZeroDivisionError:
avg_results_dict['iou'] = 0.0
return avg_results_dict
def get_probabilities(logits):
return tf.nn.softmax(logits)
# define the solver
class PartNetSolver(TFSolver):
def __init__(self, flags, compute_graph, build_solver):
self.flags = flags
super(PartNetSolver, self).__init__(flags.SOLVER, compute_graph, build_solver)
self.num_class = flags.LOSS.num_class # used to calculate the IoU
def result_callback(self, avg_results_dict):
return result_callback(avg_results_dict, self.num_class)
def build_train_graph(self):
gpu_num = len(self.flags.gpu)
train_params = {'dataset': 'train', 'training': True, 'reuse': False}
test_params = {'dataset': 'test', 'training': False, 'reuse': True}
if gpu_num > 1: # TODO: check / remove / clean
train_params['gpu_num'] = gpu_num
test_params['gpu_num'] = gpu_num
self.train_tensors_dict, self.train_debug_checks = self.graph(**train_params)
self.test_tensors_dict, self.test_debug_checks = self.graph(**test_params)
self.total_loss = self.train_tensors_dict['total_loss']
solver_param = [self.total_loss]
if self.val_depended_lr:
with tf.name_scope('lr'):
self.lr = tf.Variable(initial_value=self.flags.learning_rate, name='learning_rate', trainable=False)
solver_param.append(self.lr)
else:
solver_param.append(LRFactory(self.flags))
if gpu_num > 1:
solver_param.append(gpu_num)
if self.val_depended_lr:
self.train_op = self.build_solver(*solver_param)
else:
self.train_op, self.lr = self.build_solver(*solver_param)
if gpu_num > 1: # average the tensors from different gpus for summaries
with tf.device('/cpu:0'):
self.train_tensors_dict = average_tensors(self.train_tensors_dict)
self.test_tensors_dict = average_tensors(self.test_tensors_dict)
tensor_dict_for_test_summary = {}
tensor_dict_for_test_summary.update(self.test_tensors_dict)
if self.val_depended_lr:
tensor_dict_for_test_summary.update({'lr': self.lr})
else:
self.train_tensors_dict['lr'] = self.lr
self.summaries_dict(self.train_tensors_dict, tensor_dict_for_test_summary)
def summaries_dict(self, train_tensor_dict, test_tensor_dict):
self.summ_train = summary_train_dict(train_tensor_dict)
self.summ_test, self.summ_holder_dict = summary_test_dict(test_tensor_dict)
self.csv_summ_test_keys = [key for key in self.summ_holder_dict.keys()]
self.summ2txt(self.csv_summ_test_keys, 'iter', 'w')
def build_test_graph(self):
gpu_num = len(self.flags.gpu)
test_params = {'dataset': 'test', 'training': False, 'reuse': False}
if gpu_num > 1: test_params['gpu_num'] = gpu_num
self.verbose = self.flags.verbose
self.test_tensors_dict, self.test_debug_checks = self.graph(**test_params)
if gpu_num > 1: # average the tensors from different gpus
with tf.device('/cpu:0'):
self.test_tensors_dict = average_tensors(self.test_tensors_dict)
# @profile
def run_k_test_iterations(self, sess, test_batch):
# print("Running validation...")
global TEST_DATA
avg_results_dict = {key: np.zeros(value.get_shape()) for key, value in self.test_tensors_dict.items()}
for _ in trange(self.flags.test_iter, leave=False, desc="Validation", file=sys.stdout):
idxs, rots = sess.run(test_batch)
pts, nrms, fts, labels = TEST_DATA.points[idxs], \
TEST_DATA.normals[idxs], \
TEST_DATA.features[idxs], \
TEST_DATA.point_labels[idxs]
iter_results_dict = sess.run(self.test_tensors_dict,
feed_dict={self.graph.points: pts,
self.graph.normals: nrms,
self.graph.features: fts,
self.graph.labels: labels,
self.graph.rot: rots
})
for key, value in iter_results_dict.items():
avg_results_dict[key] += value
for key in avg_results_dict.keys():
if not any(k in key for k in DO_NOT_AVG):
avg_results_dict[key] /= self.flags.test_iter
# calculate iou
avg_results = self.result_callback(avg_results_dict)
# plateau lr updates based on validation loss vs step/cos lr
if self.val_depended_lr:
curr_lr = sess.run(self.lr, feed_dict={self.lr: self.lr_metric(avg_results_dict['total_loss'])})
sess.run(self.lr.assign(curr_lr))
avg_results['lr'] = curr_lr
return avg_results
def save_ckpt(self, dc, sess, iter):
with open(os.path.join(self.best_ckpt_path, "evaluation_report.txt"), 'a') as f:
f.write('---- EPOCH %04d EVALUATION ----\n' % (iter))
for key in best_metric_dict.keys():
if not "loss" in key:
if dc[key] > best_metric_dict[key]:
best_metric_dict[key] = dc[key]
self.tf_saver.save(sess, save_path=os.path.join(self.best_ckpt_path, 'best_' + key + '.ckpt'),
write_meta_graph=False)
else:
if dc[key] < best_metric_dict[key]:
best_metric_dict[key] = dc[key]
self.tf_saver.save(sess, save_path=os.path.join(self.best_ckpt_path, 'best_' + key + '.ckpt'),
write_meta_graph=False)
f.write('eval ' + key + ': %f\n' % (dc[key]))
# @profile
def train(self):
global TRAIN_DATA, TEST_DATA
train_iter = DataIterator(TRAIN_DATA.flags, TRAIN_DATA.tfrecord_num)
test_iter = DataIterator(TEST_DATA.flags, TEST_DATA.tfrecord_num)
# build the computation graph
self.build_train_graph()
# checkpoint
start_iter = 1
self.tf_saver = tf.train.Saver(max_to_keep=self.flags.ckpt_num)
ckpt_path = os.path.join(self.flags.logdir, 'model')
self.best_ckpt_path = os.path.join(self.flags.logdir, 'best_ckpts')
os.makedirs(self.best_ckpt_path, exist_ok=True)
if self.flags.ckpt: # restore from the provided checkpoint
ckpt = self.flags.ckpt
else: # restore from the breaking pointer
ckpt = tf.train.latest_checkpoint(ckpt_path)
if ckpt: start_iter = int(ckpt[ckpt.find("iter") + 5:-5]) + 1
# session
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = self.flags.gpu # '0'
with tf.Session(config=config) as sess:
summary_writer = tf.summary.FileWriter(self.flags.logdir, sess.graph)
print('Initialize ...')
self.initialize(sess)
if ckpt:
self.restore(sess, ckpt)
py = psutil.Process(os.getpid())
memory_usage = py.memory_info()[0] / 1024 ** 3
print("init memory: ", memory_usage)
print('Start training ...')
# option 1: use feed dict to pass the calculated learning rate
# option 2: use model.compile and pass the optimizer and the callbacks
if ckpt and self.val_depended_lr:
self.flags.defrost()
print(self.flags.learning_rate)
self.flags.learning_rate = float(sess.run(self.lr))
print(self.flags.learning_rate)
self.flags.freeze()
if self.val_depended_lr:
self.lr_metric = LRFactory(self.flags)
batch = train_iter()
test_batch = test_iter()
log_freq = self.flags.test_every_iter
for i in range(start_iter, self.flags.max_iter + 1):
if (i - 1) % log_freq == 0: print("Training iters: {}/{}".format(i - 1, self.flags.max_iter))
idxs, rots = sess.run(batch)
# print(TRAIN_DATA.filenames[idxs])
pts, nrms, fts, labels = TRAIN_DATA.points[idxs], \
TRAIN_DATA.normals[idxs], \
TRAIN_DATA.features[idxs], \
TRAIN_DATA.point_labels[idxs]
# training
if self.val_depended_lr:
summary_train, _, curr_loss, curr_lr = sess.run(
[self.summ_train, self.train_op, self.total_loss, self.lr],
feed_dict={self.graph.points: pts,
self.graph.normals: nrms,
self.graph.features: fts,
self.graph.labels: labels,
self.graph.rot: rots
})
else:
summary_train, _, curr_loss = sess.run([self.summ_train, self.train_op, self.total_loss],
feed_dict={self.graph.points: pts,
self.graph.normals: nrms,
self.graph.features: fts,
self.graph.labels: labels,
self.graph.rot: rots
}) #check_octree(self.train_debug_checks['octree'])
# py = psutil.Process(os.getpid())
# memory_usage = py.memory_info()[0] / 1024 ** 3
# print("iter memory: ", memory_usage)
summary_writer.add_summary(summary_train, i)
# testing
if i % self.flags.test_every_iter == 0:
# run testing average
avg_test_dict = self.run_k_test_iterations(sess, test_batch)
# save best acc,loss and iou network snapshots
self.save_ckpt(avg_test_dict, sess, i / self.flags.test_every_iter)
# run testing summary
summary = sess.run(self.summ_test,
feed_dict={pl: avg_test_dict[m]
for m, pl in self.summ_holder_dict.items()})
summary_writer.add_summary(summary, i)
csv_avg_tests = [avg_test_dict[key] for key in self.csv_summ_test_keys]
self.summ2txt(csv_avg_tests, i)
# save session
ckpt_name = os.path.join(ckpt_path, 'iter_%06d.ckpt' % i)
self.tf_saver.save(sess, ckpt_name, write_meta_graph=False)
print('Training done!')
def timeline(self):
global TRAIN_DATA
train_iter = DataIterator(TRAIN_DATA.flags, TRAIN_DATA.tfrecord_num)
# build the computation graph
self.build_train_graph()
# session
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = self.flags.gpu
options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
timeline_skip, timeline_iter = 100, 2
with tf.Session(config=config) as sess:
summary_writer = tf.summary.FileWriter(self.flags.logdir, sess.graph)
print('Initialize ...')
self.initialize(sess)
batch = train_iter()
print('Start profiling ...')
for i in trange(0, timeline_skip + timeline_iter, ncols=80, desc="Timeline"):
idxs, rots = sess.run(batch)
pts, nrms, fts, labels = TRAIN_DATA.points[idxs], \
TRAIN_DATA.normals[idxs], \
TRAIN_DATA.features[idxs], \
TRAIN_DATA.point_labels[idxs]
summary, _ = sess.run([self.summ_train, self.train_op],
options=options, run_metadata=run_metadata,
feed_dict={self.graph.points: pts,
self.graph.normals: nrms,
self.graph.features: fts,
self.graph.labels: labels,
self.graph.rot: rots
})
if i == timeline_skip + timeline_iter - 1:
# summary_writer.add_run_metadata(run_metadata, 'step_%d'%i, i)
# write timeline to a json file
fetched_timeline = timeline.Timeline(run_metadata.step_stats)
chrome_trace = fetched_timeline.generate_chrome_trace_format()
with open(os.path.join(self.flags.logdir, 'timeline.json'), 'w') as f:
f.write(chrome_trace)
summary_writer.add_summary(summary, i)
print('Profiling done!')
def test(self):
# CATEGORIES = ANNFASS_LABELS
COLOURS = ANNFASS_COLORS
global TEST_DATA
test_iter = DataIterator(TEST_DATA.flags, TEST_DATA.tfrecord_num)
# build graph
self.build_test_graph()
# checkpoint
assert self.flags.ckpt, "Checkpoint was not provided!!!" # the self.flags.ckpt should be provided
assert self.flags.test_iter == len(
TEST_DATA.filenames), "Test iterations does not match number of files provided ({} vs {})".format(
self.flags.test_iter, len(TEST_DATA.filenames))
tf_saver = tf.train.Saver(max_to_keep=10)
logdir = os.path.join(self.flags.logdir, os.path.basename(self.flags.ckpt).split(".")[0])
# start
test_metrics_dict = {key: np.zeros(value.get_shape()) for key, value in self.test_tensors_dict.items()}
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = self.flags.gpu
with tf.Session(config=config) as sess:
self.summ2txt_line(self.flags.ckpt)
self.summ2txt_line(DELIMITER.join(['iteration'] + [key for key in self.test_tensors_dict.keys()]))
# restore and initialize
self.initialize(sess)
print('Restore from checkpoint: %s' % self.flags.ckpt)
tf_saver.restore(sess, self.flags.ckpt)
predicted_ply_dir = os.path.join(logdir, "predicted_ply")
if not os.path.exists(predicted_ply_dir):
os.makedirs(predicted_ply_dir)
probabilities_dir = os.path.join(logdir, "probabilities")
if not os.path.exists(probabilities_dir):
os.makedirs(probabilities_dir)
batch = test_iter()
print('Start testing ...')
for i in range(0, self.flags.test_iter):
idxs, rots = sess.run(batch)
pts, nrms, fts, labels = TEST_DATA.points[idxs], \
TEST_DATA.normals[idxs], \
TEST_DATA.features[idxs], \
TEST_DATA.point_labels[idxs]
iter_test_result_dict, iter_tdc = sess.run([self.test_tensors_dict, self.test_debug_checks],
feed_dict={self.graph.points: pts,
self.graph.normals: nrms,
self.graph.features: fts,
self.graph.labels: labels,
self.graph.rot: rots
})
iter_test_result_dict = self.result_callback(iter_test_result_dict)
probabilities = iter_tdc['/probabilities']
filename = os.path.basename(TEST_DATA.filenames[i])
predictions = np.argmax(probabilities, axis=1).astype(np.int32) + 1 # remap labels to initial values
prediction_colors = np.array([to_rgb(COLOURS[int(p)]) for p in predictions])
if self.verbose:
reports = str(i) + "-" + filename + ": "
for key, value in iter_test_result_dict.items():
test_metrics_dict[key] += value
reports += '%s: %0.4f; ' % (key, value)
print(reports)
else:
for key, value in iter_test_result_dict.items():
test_metrics_dict[key] += value
current_ply_o_f = os.path.join(predicted_ply_dir, "{}.ply".format(filename))
save_ply(current_ply_o_f, pts[0], prediction_colors)
np.save(file=os.path.join(probabilities_dir, filename), arr=np.array(probabilities))
self.summ2txt([value for key, value in iter_test_result_dict.items()], str(i) + "-" + filename)
# Average test results
for key, value in test_metrics_dict.items():
test_metrics_dict[key] /= self.flags.test_iter
test_metrics_dict = self.result_callback(test_metrics_dict)
print('Testing done!\n')
avg_test_sorted = []
part_iou = []
reports = 'ALL: %04d; ' % self.flags.test_iter
ious = "PART IoUs: "
intsc = 0.0
# write/print results
for key in iter_test_result_dict.keys():
avg_test_sorted.append(test_metrics_dict[key])
reports += '%s: %0.4f; ' % (key, test_metrics_dict[key])
if "intsc" in key:
ious += "%s: " % (key.split("_")[-1])
intsc = test_metrics_dict[key]
elif "union" in key:
p_iou = intsc / test_metrics_dict[key]
ious += "%0.4f; " % (p_iou)
intsc = 0.0
part_iou.append(p_iou)
part_iou.append("-")
else:
part_iou.append("-")
if self.verbose:
print(reports)
print(ious)
self.summ2txt(avg_test_sorted, 'ALL')
self.summ2txt(part_iou, "Part_IoUs")
# run the experiments
if __name__ == '__main__':
t = time.time()
FLAGS = parse_args()
print("\nReading data files. This may take a while...\n")
read_datasets(FLAGS)
compute_graph = ComputeGraphSeg(FLAGS)
builder_op = build_solver_given_lr if FLAGS.SOLVER.lr_type == 'plateau' else build_solver
solver = PartNetSolver(FLAGS, compute_graph, builder_op)
solver.run()
print("Minutes passed {}".format((time.time() - t) / 60))
| [
"os.getpid",
"os.makedirs",
"tqdm.trange",
"os.path.basename",
"numpy.argmax",
"os.path.exists",
"time.time",
"learning_rate.LRFactory",
"libs.points_property",
"tensorflow.python.client.timeline.Timeline",
"network_factory.seg_network",
"numpy.array",
"config.parse_args",
"config.parse_cl... | [((26129, 26140), 'time.time', 'time.time', ([], {}), '()\n', (26138, 26140), False, 'import time\n'), ((26153, 26165), 'config.parse_args', 'parse_args', ([], {}), '()\n', (26163, 26165), False, 'from config import parse_args, parse_class_weights\n'), ((1426, 1481), 'libs.points_property', 'points_property', (['points'], {'property_name': '"""xyz"""', 'channel': '(4)'}), "(points, property_name='xyz', channel=4)\n", (1441, 1481), False, 'from libs import points_property, octree_property, check_octree\n'), ((1608, 1665), 'libs.points_property', 'points_property', (['points'], {'property_name': '"""label"""', 'channel': '(1)'}), "(points, property_name='label', channel=1)\n", (1623, 1665), False, 'from libs import points_property, octree_property, check_octree\n'), ((10495, 10572), 'tqdm.trange', 'trange', (['self.flags.test_iter'], {'leave': '(False)', 'desc': '"""Validation"""', 'file': 'sys.stdout'}), "(self.flags.test_iter, leave=False, desc='Validation', file=sys.stdout)\n", (10501, 10572), False, 'from tqdm import trange\n'), ((13460, 13500), 'os.path.join', 'os.path.join', (['self.flags.logdir', '"""model"""'], {}), "(self.flags.logdir, 'model')\n", (13472, 13500), False, 'import os\n'), ((13531, 13576), 'os.path.join', 'os.path.join', (['self.flags.logdir', '"""best_ckpts"""'], {}), "(self.flags.logdir, 'best_ckpts')\n", (13543, 13576), False, 'import os\n'), ((13585, 13632), 'os.makedirs', 'os.makedirs', (['self.best_ckpt_path'], {'exist_ok': '(True)'}), '(self.best_ckpt_path, exist_ok=True)\n', (13596, 13632), False, 'import os\n'), ((3463, 3489), 'config.parse_class_weights', 'parse_class_weights', (['flags'], {}), '(flags)\n', (3482, 3489), False, 'from config import parse_args, parse_class_weights\n'), ((19171, 19238), 'tqdm.trange', 'trange', (['(0)', '(timeline_skip + timeline_iter)'], {'ncols': '(80)', 'desc': '"""Timeline"""'}), "(0, timeline_skip + timeline_iter, ncols=80, desc='Timeline')\n", (19177, 19238), False, 'from tqdm import trange\n'), ((22195, 22232), 'os.path.join', 'os.path.join', (['logdir', '"""predicted_ply"""'], {}), "(logdir, 'predicted_ply')\n", (22207, 22232), False, 'import os\n'), ((22366, 22403), 'os.path.join', 'os.path.join', (['logdir', '"""probabilities"""'], {}), "(logdir, 'probabilities')\n", (22378, 22403), False, 'import os\n'), ((5159, 5217), 'network_factory.seg_network', 'seg_network', (['octree', 'FLAGS.MODEL', 'training', 'reuse'], {'pts': 'pts'}), '(octree, FLAGS.MODEL, training, reuse, pts=pts)\n', (5170, 5217), False, 'from network_factory import seg_network\n'), ((8448, 8469), 'learning_rate.LRFactory', 'LRFactory', (['self.flags'], {}), '(self.flags)\n', (8457, 8469), False, 'from learning_rate import LRFactory\n'), ((12120, 12178), 'os.path.join', 'os.path.join', (['self.best_ckpt_path', '"""evaluation_report.txt"""'], {}), "(self.best_ckpt_path, 'evaluation_report.txt')\n", (12132, 12178), False, 'import os\n'), ((14410, 14421), 'os.getpid', 'os.getpid', ([], {}), '()\n', (14419, 14421), False, 'import os\n'), ((15083, 15104), 'learning_rate.LRFactory', 'LRFactory', (['self.flags'], {}), '(self.flags)\n', (15092, 15104), False, 'from learning_rate import LRFactory\n'), ((22252, 22285), 'os.path.exists', 'os.path.exists', (['predicted_ply_dir'], {}), '(predicted_ply_dir)\n', (22266, 22285), False, 'import os\n'), ((22303, 22333), 'os.makedirs', 'os.makedirs', (['predicted_ply_dir'], {}), '(predicted_ply_dir)\n', (22314, 22333), False, 'import os\n'), ((22423, 22456), 'os.path.exists', 'os.path.exists', (['probabilities_dir'], {}), '(probabilities_dir)\n', (22437, 22456), False, 'import os\n'), ((22474, 22504), 'os.makedirs', 'os.makedirs', (['probabilities_dir'], {}), '(probabilities_dir)\n', (22485, 22504), False, 'import os\n'), ((23777, 23817), 'os.path.basename', 'os.path.basename', (['TEST_DATA.filenames[i]'], {}), '(TEST_DATA.filenames[i])\n', (23793, 23817), False, 'import os\n'), ((18169, 18214), 'os.path.join', 'os.path.join', (['ckpt_path', "('iter_%06d.ckpt' % i)"], {}), "(ckpt_path, 'iter_%06d.ckpt' % i)\n", (18181, 18214), False, 'import os\n'), ((20373, 20415), 'tensorflow.python.client.timeline.Timeline', 'timeline.Timeline', (['run_metadata.step_stats'], {}), '(run_metadata.step_stats)\n', (20390, 20415), False, 'from tensorflow.python.client import timeline\n'), ((26506, 26517), 'time.time', 'time.time', ([], {}), '()\n', (26515, 26517), False, 'import time\n'), ((21416, 21449), 'os.path.basename', 'os.path.basename', (['self.flags.ckpt'], {}), '(self.flags.ckpt)\n', (21432, 21449), False, 'import os\n'), ((24688, 24729), 'os.path.join', 'os.path.join', (['probabilities_dir', 'filename'], {}), '(probabilities_dir, filename)\n', (24700, 24729), False, 'import os\n'), ((24735, 24758), 'numpy.array', 'np.array', (['probabilities'], {}), '(probabilities)\n', (24743, 24758), True, 'import numpy as np\n'), ((20529, 20577), 'os.path.join', 'os.path.join', (['self.flags.logdir', '"""timeline.json"""'], {}), "(self.flags.logdir, 'timeline.json')\n", (20541, 20577), False, 'import os\n'), ((23848, 23880), 'numpy.argmax', 'np.argmax', (['probabilities'], {'axis': '(1)'}), '(probabilities, axis=1)\n', (23857, 23880), True, 'import numpy as np\n'), ((12515, 12573), 'os.path.join', 'os.path.join', (['self.best_ckpt_path', "('best_' + key + '.ckpt')"], {}), "(self.best_ckpt_path, 'best_' + key + '.ckpt')\n", (12527, 12573), False, 'import os\n'), ((12835, 12893), 'os.path.join', 'os.path.join', (['self.best_ckpt_path', "('best_' + key + '.ckpt')"], {}), "(self.best_ckpt_path, 'best_' + key + '.ckpt')\n", (12847, 12893), False, 'import os\n')] |
from typing import (
Callable,
Dict,
List,
Tuple,
Iterator,
Any,
TypeVar,
Optional,
TYPE_CHECKING,
)
import collections
import numpy as np
from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U
from ray.data.row import TableRow
from ray.data.impl.table_block import TableBlockAccessor, TableBlockBuilder
from ray.data.impl.arrow_block import ArrowBlockAccessor
from ray.data.aggregate import AggregateFn
if TYPE_CHECKING:
import pyarrow
import pandas
from ray.data.impl.sort import SortKeyT
T = TypeVar("T")
_pandas = None
def lazy_import_pandas():
global _pandas
if _pandas is None:
import pandas
_pandas = pandas
return _pandas
class PandasRow(TableRow):
"""
Row of a tabular Dataset backed by a Pandas DataFrame block.
"""
def __getitem__(self, key: str) -> Any:
col = self._row[key]
if len(col) == 0:
return None
item = col.iloc[0]
try:
# Try to interpret this as a numpy-type value.
# See https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types. # noqa: E501
return item.item()
except AttributeError:
# Fallback to the original form.
return item
def __iter__(self) -> Iterator:
for k in self._row.columns:
yield k
def __len__(self):
return self._row.shape[1]
class PandasBlockBuilder(TableBlockBuilder[T]):
def __init__(self):
pandas = lazy_import_pandas()
super().__init__(pandas.DataFrame)
def _table_from_pydict(self, columns: Dict[str, List[Any]]) -> "pandas.DataFrame":
pandas = lazy_import_pandas()
return pandas.DataFrame(columns)
def _concat_tables(self, tables: List["pandas.DataFrame"]) -> "pandas.DataFrame":
pandas = lazy_import_pandas()
return pandas.concat(tables, ignore_index=True)
@staticmethod
def _empty_table() -> "pandas.DataFrame":
pandas = lazy_import_pandas()
return pandas.DataFrame()
# This is to be compatible with pyarrow.lib.schema
# TODO (kfstorm): We need a format-independent way to represent schema.
PandasBlockSchema = collections.namedtuple("PandasBlockSchema", ["names", "types"])
class PandasBlockAccessor(TableBlockAccessor):
def __init__(self, table: "pandas.DataFrame"):
super().__init__(table)
def _create_table_row(self, row: "pandas.DataFrame") -> PandasRow:
return PandasRow(row)
def slice(self, start: int, end: int, copy: bool) -> "pandas.DataFrame":
view = self._table[start:end]
if copy:
view = view.copy(deep=True)
return view
def random_shuffle(self, random_seed: Optional[int]) -> "pandas.DataFrame":
return self._table.sample(frac=1, random_state=random_seed)
def schema(self) -> PandasBlockSchema:
dtypes = self._table.dtypes
schema = PandasBlockSchema(
names=dtypes.index.tolist(), types=dtypes.values.tolist()
)
# Column names with non-str types of a pandas DataFrame is not
# supported by Ray Dataset.
if any(not isinstance(name, str) for name in schema.names):
raise ValueError(
"A Pandas DataFrame with column names of non-str types"
" is not supported by Ray Dataset. Column names of this"
f" DataFrame: {schema.names!r}."
)
return schema
def to_pandas(self) -> "pandas.DataFrame":
return self._table
def to_numpy(self, column: str = None) -> np.ndarray:
if not column:
raise ValueError(
"`column` must be specified when calling .to_numpy() "
"on Pandas blocks."
)
if column not in self._table.columns:
raise ValueError(
"Cannot find column {}, available columns: {}".format(
column, self._table.columns.tolist()
)
)
return self._table[column].to_numpy()
def to_arrow(self) -> "pyarrow.Table":
import pyarrow
return pyarrow.table(self._table)
def num_rows(self) -> int:
return self._table.shape[0]
def size_bytes(self) -> int:
return self._table.memory_usage(index=True, deep=True).sum()
def _zip(self, acc: BlockAccessor) -> "pandas.DataFrame":
r = self.to_pandas().copy(deep=False)
s = acc.to_pandas()
for col_name in s.columns:
col = s[col_name]
column_names = list(r.columns)
# Ensure the column names are unique after zip.
if col_name in column_names:
i = 1
new_name = col_name
while new_name in column_names:
new_name = "{}_{}".format(col_name, i)
i += 1
col_name = new_name
r[col_name] = col
return r
@staticmethod
def builder() -> PandasBlockBuilder[T]:
return PandasBlockBuilder()
@staticmethod
def _empty_table() -> "pandas.DataFrame":
return PandasBlockBuilder._empty_table()
def _sample(self, n_samples: int, key: "SortKeyT") -> "pandas.DataFrame":
return self._table[[k[0] for k in key]].sample(n_samples, ignore_index=True)
def _apply_agg(
self, agg_fn: Callable[["pandas.Series", bool], U], on: KeyFn
) -> Optional[U]:
"""Helper providing null handling around applying an aggregation to a column."""
if on is not None and not isinstance(on, str):
raise ValueError(
"on must be a string or None when aggregating on Pandas blocks, but "
f"got: {type(on)}."
)
col = self._table[on]
try:
return agg_fn(col)
except TypeError as e:
# Converting an all-null column in an Arrow Table to a Pandas DataFrame
# column will result in an all-None column of object type, which will raise
# a type error when attempting to do most binary operations. We explicitly
# check for this type failure here so we can properly propagate a null.
if np.issubdtype(col.dtype, np.object_) and col.isnull().all():
return None
raise e from None
def count(self, on: KeyFn) -> Optional[U]:
return self._apply_agg(lambda col: col.count(), on)
def sum(self, on: KeyFn, ignore_nulls: bool) -> Optional[U]:
if on is not None and not isinstance(on, str):
raise ValueError(
"on must be a string or None when aggregating on Pandas blocks, but "
f"got: {type(on)}."
)
col = self._table[on]
if col.isnull().all():
# Short-circuit on an all-null column, returning None. This is required for
# sum() since it will otherwise return 0 when summing on an all-null column,
# which is not what we want.
return None
return col.sum(skipna=ignore_nulls)
def min(self, on: KeyFn, ignore_nulls: bool) -> Optional[U]:
return self._apply_agg(lambda col: col.min(skipna=ignore_nulls), on)
def max(self, on: KeyFn, ignore_nulls: bool) -> Optional[U]:
return self._apply_agg(lambda col: col.max(skipna=ignore_nulls), on)
def mean(self, on: KeyFn, ignore_nulls: bool) -> Optional[U]:
return self._apply_agg(lambda col: col.mean(skipna=ignore_nulls), on)
def sum_of_squared_diffs_from_mean(
self,
on: KeyFn,
ignore_nulls: bool,
mean: Optional[U] = None,
) -> Optional[U]:
if mean is None:
mean = self.mean(on, ignore_nulls)
return self._apply_agg(
lambda col: ((col - mean) ** 2).sum(skipna=ignore_nulls),
on,
)
def sort_and_partition(
self, boundaries: List[T], key: "SortKeyT", descending: bool
) -> List["pandas.DataFrame"]:
# TODO (kfstorm): A workaround to pass tests. Not efficient.
delegated_result = BlockAccessor.for_block(self.to_arrow()).sort_and_partition(
boundaries, key, descending
)
return [BlockAccessor.for_block(_).to_pandas() for _ in delegated_result]
def combine(self, key: KeyFn, aggs: Tuple[AggregateFn]) -> "pandas.DataFrame":
# TODO (kfstorm): A workaround to pass tests. Not efficient.
return BlockAccessor.for_block(self.to_arrow()).combine(key, aggs).to_pandas()
@staticmethod
def merge_sorted_blocks(
blocks: List["pandas.DataFrame"], key: "SortKeyT", _descending: bool
) -> Tuple["pandas.DataFrame", BlockMetadata]:
# TODO (kfstorm): A workaround to pass tests. Not efficient.
block, metadata = ArrowBlockAccessor.merge_sorted_blocks(
[BlockAccessor.for_block(block).to_arrow() for block in blocks],
key,
_descending,
)
return BlockAccessor.for_block(block).to_pandas(), metadata
@staticmethod
def aggregate_combined_blocks(
blocks: List["pandas.DataFrame"], key: KeyFn, aggs: Tuple[AggregateFn]
) -> Tuple["pandas.DataFrame", BlockMetadata]:
# TODO (kfstorm): A workaround to pass tests. Not efficient.
block, metadata = ArrowBlockAccessor.aggregate_combined_blocks(
[BlockAccessor.for_block(block).to_arrow() for block in blocks], key, aggs
)
return BlockAccessor.for_block(block).to_pandas(), metadata
| [
"pandas.DataFrame",
"pyarrow.table",
"ray.data.block.BlockAccessor.for_block",
"collections.namedtuple",
"typing.TypeVar",
"pandas.concat",
"numpy.issubdtype"
] | [((558, 570), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (565, 570), False, 'from typing import Callable, Dict, List, Tuple, Iterator, Any, TypeVar, Optional, TYPE_CHECKING\n'), ((2249, 2312), 'collections.namedtuple', 'collections.namedtuple', (['"""PandasBlockSchema"""', "['names', 'types']"], {}), "('PandasBlockSchema', ['names', 'types'])\n", (2271, 2312), False, 'import collections\n'), ((1760, 1785), 'pandas.DataFrame', 'pandas.DataFrame', (['columns'], {}), '(columns)\n', (1776, 1785), False, 'import pandas\n'), ((1926, 1966), 'pandas.concat', 'pandas.concat', (['tables'], {'ignore_index': '(True)'}), '(tables, ignore_index=True)\n', (1939, 1966), False, 'import pandas\n'), ((2085, 2103), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (2101, 2103), False, 'import pandas\n'), ((4193, 4219), 'pyarrow.table', 'pyarrow.table', (['self._table'], {}), '(self._table)\n', (4206, 4219), False, 'import pyarrow\n'), ((6276, 6312), 'numpy.issubdtype', 'np.issubdtype', (['col.dtype', 'np.object_'], {}), '(col.dtype, np.object_)\n', (6289, 6312), True, 'import numpy as np\n'), ((8283, 8309), 'ray.data.block.BlockAccessor.for_block', 'BlockAccessor.for_block', (['_'], {}), '(_)\n', (8306, 8309), False, 'from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U\n'), ((9044, 9074), 'ray.data.block.BlockAccessor.for_block', 'BlockAccessor.for_block', (['block'], {}), '(block)\n', (9067, 9074), False, 'from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U\n'), ((9534, 9564), 'ray.data.block.BlockAccessor.for_block', 'BlockAccessor.for_block', (['block'], {}), '(block)\n', (9557, 9564), False, 'from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U\n'), ((8913, 8943), 'ray.data.block.BlockAccessor.for_block', 'BlockAccessor.for_block', (['block'], {}), '(block)\n', (8936, 8943), False, 'from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U\n'), ((9435, 9465), 'ray.data.block.BlockAccessor.for_block', 'BlockAccessor.for_block', (['block'], {}), '(block)\n', (9458, 9465), False, 'from ray.data.block import BlockAccessor, BlockMetadata, KeyFn, U\n')] |
import unittest
import numpy as np
from mutils.water_vapor import *
#freezing point
fp = 273.15
class wv_round_trip(unittest.TestCase):
# def setUp(self):
# pass
# def tearDown(self):
# pass
def runTest(self):
# integer
T = 273.15 + 20
e = 611.
p = 1.0132 * 10**5
assert np.allclose(rho_v_2_e(e_2_rho_v(e, T), T), e)
assert np.allclose(q_v_2_e(e_2_q_v(e, p), p), e)
assert np.allclose(w_v_2_e(e_2_w_v(e, p), p), e)
assert np.allclose(rel_hum_2_e(e_2_rel_hum(e, T, fp), T, fp), e)
# numpy array
T = np.linspace(-10, 30) + 273.15
e = np.linspace(125, 4000)
p = np.linspace(0.85, 1.1) * 10**5
assert np.allclose(rho_v_2_e(e_2_rho_v(e, T), T), e)
assert np.allclose(q_v_2_e(e_2_q_v(e, p), p), e)
assert np.allclose(w_v_2_e(e_2_w_v(e, p), p), e)
assert np.allclose(rel_hum_2_e(e_2_rel_hum(e, T, fp), T, fp), e)
class wv_RH(unittest.TestCase):
def runTest(self):
T = np.linspace(-10, 30) + 273.15
es = saturation_vapor_pressure(T, freezing_point=273.15)
res = np.ones_like(T)
assert np.allclose(e_2_rel_hum(es, T, fp), res)
res = np.zeros_like(T)
assert np.allclose(e_2_rel_hum(res, T, fp), res)
class wv_saturation_vapor_pressure(unittest.TestCase):
def runTest(self):
# error on T < 0
self.assertRaises(ValueError, saturation_vapor_pressure, -5)
T = np.arange(-70, 50, 10) + 273.15
# values from the script
res = np.asarray([0.48, 1.87, 6.32, 18.9, 51.0, 125.6, 286.7, 611.7,
1228.1, 2339.4, 4246.8, 7384.3])
e_s_w = saturation_vapor_pressure(T, freezing_point=273.15 - 80)
e_s_w = np.round(e_s_w, 2)
assert np.allclose(e_s_w, res, atol=0.5)
T = np.arange(-70, 10, 10) + 273.15
res = np.asarray([0.26, 1.08, 3.94, 12.9, 38.1, 103.4, 260.1, 611.7])
e_s_i = np.round(saturation_vapor_pressure(T), 2)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"numpy.zeros_like",
"numpy.ones_like",
"numpy.asarray",
"numpy.allclose",
"numpy.arange",
"numpy.linspace",
"numpy.round"
] | [((2109, 2124), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2122, 2124), False, 'import unittest\n'), ((656, 678), 'numpy.linspace', 'np.linspace', (['(125)', '(4000)'], {}), '(125, 4000)\n', (667, 678), True, 'import numpy as np\n'), ((1159, 1174), 'numpy.ones_like', 'np.ones_like', (['T'], {}), '(T)\n', (1171, 1174), True, 'import numpy as np\n'), ((1247, 1263), 'numpy.zeros_like', 'np.zeros_like', (['T'], {}), '(T)\n', (1260, 1263), True, 'import numpy as np\n'), ((1588, 1688), 'numpy.asarray', 'np.asarray', (['[0.48, 1.87, 6.32, 18.9, 51.0, 125.6, 286.7, 611.7, 1228.1, 2339.4, 4246.8,\n 7384.3]'], {}), '([0.48, 1.87, 6.32, 18.9, 51.0, 125.6, 286.7, 611.7, 1228.1, \n 2339.4, 4246.8, 7384.3])\n', (1598, 1688), True, 'import numpy as np\n'), ((1803, 1821), 'numpy.round', 'np.round', (['e_s_w', '(2)'], {}), '(e_s_w, 2)\n', (1811, 1821), True, 'import numpy as np\n'), ((1838, 1871), 'numpy.allclose', 'np.allclose', (['e_s_w', 'res'], {'atol': '(0.5)'}), '(e_s_w, res, atol=0.5)\n', (1849, 1871), True, 'import numpy as np\n'), ((1932, 1995), 'numpy.asarray', 'np.asarray', (['[0.26, 1.08, 3.94, 12.9, 38.1, 103.4, 260.1, 611.7]'], {}), '([0.26, 1.08, 3.94, 12.9, 38.1, 103.4, 260.1, 611.7])\n', (1942, 1995), True, 'import numpy as np\n'), ((614, 634), 'numpy.linspace', 'np.linspace', (['(-10)', '(30)'], {}), '(-10, 30)\n', (625, 634), True, 'import numpy as np\n'), ((691, 713), 'numpy.linspace', 'np.linspace', (['(0.85)', '(1.1)'], {}), '(0.85, 1.1)\n', (702, 713), True, 'import numpy as np\n'), ((1040, 1060), 'numpy.linspace', 'np.linspace', (['(-10)', '(30)'], {}), '(-10, 30)\n', (1051, 1060), True, 'import numpy as np\n'), ((1508, 1530), 'numpy.arange', 'np.arange', (['(-70)', '(50)', '(10)'], {}), '(-70, 50, 10)\n', (1517, 1530), True, 'import numpy as np\n'), ((1886, 1908), 'numpy.arange', 'np.arange', (['(-70)', '(10)', '(10)'], {}), '(-70, 10, 10)\n', (1895, 1908), True, 'import numpy as np\n')] |
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import torch
import numpy as np
from mmcv.utils.registry import build_from_cfg
from mmcls.datasets.builder import DATASETS, PIPELINES
from mmcls.datasets.pipelines import Compose
from mmcls.datasets.base_dataset import BaseDataset
from mpa.utils.logger import get_logger
logger = get_logger()
@DATASETS.register_module()
class MPAClsDataset(BaseDataset):
def __init__(self, old_new_indices=None, ote_dataset=None, labels=None, **kwargs):
self.ote_dataset = ote_dataset
self.labels = labels
self.CLASSES = list(label.name for label in labels)
self.gt_labels = []
pipeline = kwargs['pipeline']
self.img_indices = dict(old=[], new=[])
self.num_classes = len(self.CLASSES)
if old_new_indices is not None:
self.img_indices['old'] = old_new_indices['old']
self.img_indices['new'] = old_new_indices['new']
if isinstance(pipeline, dict):
self.pipeline = {}
for k, v in pipeline.items():
_pipeline = [dict(type='LoadImageFromOTEDataset'), *v]
_pipeline = [build_from_cfg(p, PIPELINES) for p in _pipeline]
self.pipeline[k] = Compose(_pipeline)
self.num_pipes = len(pipeline)
elif isinstance(pipeline, list):
self.num_pipes = 1
_pipeline = [dict(type='LoadImageFromOTEDataset'), *pipeline]
self.pipeline = Compose([build_from_cfg(p, PIPELINES) for p in _pipeline])
self.load_annotations()
def load_annotations(self):
for dataset_item in self.ote_dataset:
if dataset_item.get_annotations() == []:
label = None
else:
label = int(dataset_item.get_annotations()[0].get_labels()[0].id_)
self.gt_labels.append(label)
self.gt_labels = np.array(self.gt_labels)
def __getitem__(self, index):
dataset_item = self.ote_dataset[index]
if self.pipeline is None:
return dataset_item
results = {}
results['index'] = index
results['dataset_item'] = dataset_item
results['height'], results['width'], _ = dataset_item.numpy.shape
results['gt_label'] = None if self.gt_labels[index] is None else torch.tensor(self.gt_labels[index])
results = self.pipeline(results)
return results
def get_gt_labels(self):
"""Get all ground-truth labels (categories).
Returns:
list[int]: categories for all images.
"""
return self.gt_labels
def __len__(self):
return len(self.ote_dataset)
def evaluate(self,
results,
metric='accuracy',
metric_options=None,
logger=None):
"""Evaluate the dataset with new metric 'class_accuracy'
Args:
results (list): Testing results of the dataset.
metric (str | list[str]): Metrics to be evaluated.
Default value is `accuracy`.
'accuracy', 'precision', 'recall', 'f1_score', 'support', 'class_accuracy'
metric_options (dict, optional): Options for calculating metrics.
Allowed keys are 'topk', 'thrs' and 'average_mode'.
Defaults to None.
logger (logging.Logger | str, optional): Logger used for printing
related information during evaluation. Defaults to None.
Returns:
dict: evaluation results
"""
if metric_options is None:
metric_options = {'topk': (1, 5) if self.num_classes >= 5 else (1, )}
if isinstance(metric, str):
metrics = [metric]
else:
metrics = metric
if 'class_accuracy' in metrics:
metrics.remove('class_accuracy')
self.class_acc = True
eval_results = super().evaluate(results, metrics, metric_options, logger)
# Add Evaluation Accuracy score per Class
if self.class_acc:
results = np.vstack(results)
gt_labels = self.get_gt_labels()
accuracies = self.class_accuracy(results, gt_labels)
eval_results.update({f'{c} accuracy': a for c, a in zip(self.CLASSES, accuracies)})
eval_results.update({'mean accuracy': np.mean(accuracies)})
return eval_results
def class_accuracy(self, results, gt_labels):
accracies = []
pred_label = results.argsort(axis=1)[:, -1:][:, ::-1]
for i in range(self.num_classes):
cls_pred = pred_label == i
cls_pred = cls_pred[gt_labels == i]
cls_acc = np.sum(cls_pred) / len(cls_pred)
accracies.append(cls_acc)
return accracies
| [
"mpa.utils.logger.get_logger",
"numpy.sum",
"mmcls.datasets.pipelines.Compose",
"numpy.mean",
"numpy.array",
"mmcls.datasets.builder.DATASETS.register_module",
"torch.tensor",
"mmcv.utils.registry.build_from_cfg",
"numpy.vstack"
] | [((362, 374), 'mpa.utils.logger.get_logger', 'get_logger', ([], {}), '()\n', (372, 374), False, 'from mpa.utils.logger import get_logger\n'), ((378, 404), 'mmcls.datasets.builder.DATASETS.register_module', 'DATASETS.register_module', ([], {}), '()\n', (402, 404), False, 'from mmcls.datasets.builder import DATASETS, PIPELINES\n'), ((1930, 1954), 'numpy.array', 'np.array', (['self.gt_labels'], {}), '(self.gt_labels)\n', (1938, 1954), True, 'import numpy as np\n'), ((2353, 2388), 'torch.tensor', 'torch.tensor', (['self.gt_labels[index]'], {}), '(self.gt_labels[index])\n', (2365, 2388), False, 'import torch\n'), ((4131, 4149), 'numpy.vstack', 'np.vstack', (['results'], {}), '(results)\n', (4140, 4149), True, 'import numpy as np\n'), ((1274, 1292), 'mmcls.datasets.pipelines.Compose', 'Compose', (['_pipeline'], {}), '(_pipeline)\n', (1281, 1292), False, 'from mmcls.datasets.pipelines import Compose\n'), ((4744, 4760), 'numpy.sum', 'np.sum', (['cls_pred'], {}), '(cls_pred)\n', (4750, 4760), True, 'import numpy as np\n'), ((1190, 1218), 'mmcv.utils.registry.build_from_cfg', 'build_from_cfg', (['p', 'PIPELINES'], {}), '(p, PIPELINES)\n', (1204, 1218), False, 'from mmcv.utils.registry import build_from_cfg\n'), ((4406, 4425), 'numpy.mean', 'np.mean', (['accuracies'], {}), '(accuracies)\n', (4413, 4425), True, 'import numpy as np\n'), ((1519, 1547), 'mmcv.utils.registry.build_from_cfg', 'build_from_cfg', (['p', 'PIPELINES'], {}), '(p, PIPELINES)\n', (1533, 1547), False, 'from mmcv.utils.registry import build_from_cfg\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Make statistics on the noise of benchmark FITS files.
"""
import common_functions as common
import argparse
from matplotlib import pyplot as plt
import os
import math
import numpy as np
from datapipe.io import images
def parse_fits_files(fits_file_name):
# Read the input file #########
fits_images_dict, fits_metadata_dict = images.load_benchmark_images(fits_file_name)
# Get images ##################
input_img = fits_images_dict["input_image"]
reference_img = fits_images_dict["reference_image"]
pure_noise_image = input_img - reference_img
return pure_noise_image, fits_metadata_dict
if __name__ == '__main__':
# PARSE OPTIONS ###########################################################
parser = argparse.ArgumentParser(description="Make statistics on the noise of benchmark FITS files.")
parser.add_argument("--output", "-o", default=None,
metavar="FILE",
help="The output file path")
parser.add_argument("--title", default=None,
metavar="STRING",
help="The title of the plot")
parser.add_argument("--logy", "-L", action="store_true", default=False,
help="Use a logaritmic scale on the Y axis")
parser.add_argument("--quiet", "-q", action="store_true",
help="Don't show the plot, just save it")
parser.add_argument("fileargs", nargs=1, metavar="FILE",
help="The input image (FITS file) used to make statistics on the noise.")
args = parser.parse_args()
title = args.title
logy = args.logy
quiet = args.quiet
input_file_path = args.fileargs[0]
# FETCH NOISE #############################################################
# Parse FITS file
data_list, metadata_dict = parse_fits_files(input_file_path)
if title is None:
title = "Noise histogram for event {} on telescope {}".format(metadata_dict["event_id"], metadata_dict["tel_id"])
if args.output is None:
output_file_path = "noise_histogram_ev{}_tel{}.png".format(metadata_dict["event_id"], metadata_dict["tel_id"])
else:
output_file_path = args.output
# PLOT STATISTICS #########################################################
print("Plotting...")
fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(16, 9))
common.plot_hist1d(axis=ax1,
data_list=[np.array(data_list).flatten(),
np.random.poisson(lam=2, size=40*40),
np.random.poisson(lam=3, size=40*40)],
label_list=["Noise",
r"Poisson dist. ($\lambda$=2)",
r"Poisson dist. ($\lambda$=3)"],
logy=logy,
xlabel="Photoelectrons",
xylabel_fontsize=16,
title=title,
linear_xlabel_style=None,
linear_ylabel_style=None,
num_bins=None,
info_box_num_samples=False,
info_box_rms=False,
info_box_std=True)
# Save file and plot ########
plt.tight_layout()
plt.savefig(output_file_path, bbox_inches='tight')
if not quiet:
plt.show()
| [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.subplots",
"numpy.array",
"datapipe.io.images.load_benchmark_images",
"numpy.random.poisson",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] | [((392, 436), 'datapipe.io.images.load_benchmark_images', 'images.load_benchmark_images', (['fits_file_name'], {}), '(fits_file_name)\n', (420, 436), False, 'from datapipe.io import images\n'), ((801, 898), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Make statistics on the noise of benchmark FITS files."""'}), "(description=\n 'Make statistics on the noise of benchmark FITS files.')\n", (824, 898), False, 'import argparse\n'), ((2399, 2446), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(16, 9)'}), '(nrows=1, ncols=1, figsize=(16, 9))\n', (2411, 2446), True, 'from matplotlib import pyplot as plt\n'), ((3344, 3362), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3360, 3362), True, 'from matplotlib import pyplot as plt\n'), ((3368, 3418), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output_file_path'], {'bbox_inches': '"""tight"""'}), "(output_file_path, bbox_inches='tight')\n", (3379, 3418), True, 'from matplotlib import pyplot as plt\n'), ((3446, 3456), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3454, 3456), True, 'from matplotlib import pyplot as plt\n'), ((2580, 2618), 'numpy.random.poisson', 'np.random.poisson', ([], {'lam': '(2)', 'size': '(40 * 40)'}), '(lam=2, size=40 * 40)\n', (2597, 2618), True, 'import numpy as np\n'), ((2652, 2690), 'numpy.random.poisson', 'np.random.poisson', ([], {'lam': '(3)', 'size': '(40 * 40)'}), '(lam=3, size=40 * 40)\n', (2669, 2690), True, 'import numpy as np\n'), ((2515, 2534), 'numpy.array', 'np.array', (['data_list'], {}), '(data_list)\n', (2523, 2534), True, 'import numpy as np\n')] |
import numpy as np
import pinocchio
from classic_framework import GotoCartPosImpedanceController
from classic_framework import GotoCartPosQuatImpedanceController
from classic_framework.controllers.TrajectoryTracking import GotoJointController
from classic_framework.controllers.TrajectoryTracking import JointTrajectoryTracker
from classic_framework.interface.Robots import RobotBase
from classic_framework.utils.sim_path import sim_framework_path
class FictiveRobot(RobotBase):
def __init__(self, init_j_pos, dt, offset=0, config_path=None):
if config_path is None:
config_path = sim_framework_path('./classic_framework/controllers/Config/PyBullet/FictiveRobot')
super().__init__(config_path, dt=dt)
obj_urdf = sim_framework_path("./envs/panda_arm_hand_pinocchio.urdf")
self.model = pinocchio.buildModelFromUrdf(obj_urdf)
self.data = self.model.createData()
# The offset is [0, 0, 0.88] for pybullet (with the table)
# The offset is [0, 0, 0] for mujoco (with current scene)
# NOTE: adjust the offset (z-direction), if you re-place the robot! (Use check offset function of fictive robot)
self.offset = offset
self.init_j_pos = init_j_pos
self.end_effector_frame_id = self.model.getFrameId('panda_grasptarget')
self.des_joint_traj = []
self.gotoJointController = GotoJointController(self.dt)
self.gotoCartPosController = GotoCartPosImpedanceController(self.dt)
self.gotoCartPosQuatController = GotoCartPosQuatImpedanceController(self.dt)
self.jointTrajectoryTracker = JointTrajectoryTracker(self.dt)
def set_joints(self, new_joints):
# implement here setting the new joints in the simulation
# Note: After calling this function, we always have to call the fwd_kinematics
return new_joints
def getForwardKinematics(self, q=None):
if q is None:
q = self.current_j_pos
if q.shape[0] == 7:
q_tmp = q.copy()
q = np.zeros(9)
q[:7] = q_tmp
pinocchio.framesForwardKinematics(self.model, self.data, q)
def getJacobian(self, q=None):
if q is None:
q = self.current_j_pos
if q.shape[0] == 7:
q_tmp = q.copy()
q = np.zeros(9)
q[:7] = q_tmp
pinocchio.computeJointJacobians(self.model, self.data, q)
pinocchio.framesForwardKinematics(self.model, self.data, q)
return pinocchio.getFrameJacobian(self.model, self.data,
self.end_effector_frame_id,
pinocchio.LOCAL_WORLD_ALIGNED)[:, :7]
def extract_new_positions(self):
# This function needs to return:
# 1: end_effector position
# 2: end_effector velocity
# 3: end_effector orientation
current_c_pos = np.array(
self.data.oMf[self.end_effector_frame_id].translation)
current_c_pos += self.offset
# should return 0 always as we do not give torques
# current_c_vel = np.array(pinocchio.getFrameVelocity(self.model, self.data,
# self.model.getFrameId('panda_grasptarget')))
current_c_vel = np.zeros(3)
# current_c_vel = (current_c_pos - self.c_pos_old)*self.dt
rotation_matrix = np.array(
self.data.oMf[self.end_effector_frame_id].rotation)
quat_pin = pinocchio.Quaternion(self.data.oMf[
self.end_effector_frame_id].rotation).coeffs() # [ x, y, z, w]
current_c_quat = np.zeros(4)
current_c_quat[1:] = quat_pin[:3]
current_c_quat[0] = quat_pin[-1]
return current_c_pos, current_c_vel, current_c_quat
def receiveState(self):
if self.time_stamp == 0:
self.current_j_pos = self.init_j_pos
self.current_j_vel = np.zeros(7)
self.set_joints(self.current_j_pos)
self.getForwardKinematics()
infos = self.extract_new_positions()
self.current_c_pos = infos[0]
self.current_c_vel = infos[1]
self.current_c_quat = infos[2]
self.current_c_quat_vel = np.zeros(4)
self.last_cmd = self.uff
# self.des_joint_pos = np.zeros((self.num_DoF,)) * np.nan
# self.des_joint_vel = np.zeros((self.num_DoF,)) * np.nan
# self.des_joint_acc = np.zeros((self.num_DoF,)) * np.nan
def nextStep(self):
if self.time_stamp == 0:
self.receiveState()
else:
"""use this function to get your offset: only when changing the robots cartesian position. Adjust only once"""
# self.check_offset_to_pinocchio_model_in_cart_space(self.current_j_pos)
# self.check_orientation_offset(self.current_j_pos)
self.num_calls += 1
if self.logger.isLogging:
self.logger.logData()
self.receiveState()
self.current_j_pos += self.dt * self.command.copy()
self.current_j_vel = self.command.copy()
self.set_joints(self.current_j_pos)
self.getForwardKinematics()
state_info = self.extract_new_positions()
self.current_c_pos = state_info[0]
self.current_c_vel = state_info[1]
self.current_c_quat = state_info[2]
self.current_c_quat_vel = np.zeros(4)
self.initCounter = self.initCounter + 1
self.des_joint_traj.append(self.current_j_pos.copy())
self.counter += 1
self.time_stamp += self.dt
# Reset all the joint positions, velocities etc. for next time stamp
# self.des_joint_pos = np.zeros((self.num_DoF,)) * np.nan
# self.des_joint_vel = np.zeros((self.num_DoF,)) * np.nan
# self.des_joint_acc = np.zeros((self.num_DoF,)) * np.nan
#
# self.des_c_pos = np.zeros((3,)) * np.nan
# self.des_c_vel = np.zeros((3,)) * np.nan
#
# self.des_quat = np.zeros((4,)) * np.nan
# self.des_quat_vel = np.zeros((4,)) * np.nan
| [
"pinocchio.framesForwardKinematics",
"classic_framework.controllers.TrajectoryTracking.JointTrajectoryTracker",
"classic_framework.GotoCartPosImpedanceController",
"numpy.zeros",
"pinocchio.Quaternion",
"pinocchio.getFrameJacobian",
"numpy.array",
"classic_framework.utils.sim_path.sim_framework_path",... | [((757, 815), 'classic_framework.utils.sim_path.sim_framework_path', 'sim_framework_path', (['"""./envs/panda_arm_hand_pinocchio.urdf"""'], {}), "('./envs/panda_arm_hand_pinocchio.urdf')\n", (775, 815), False, 'from classic_framework.utils.sim_path import sim_framework_path\n'), ((837, 875), 'pinocchio.buildModelFromUrdf', 'pinocchio.buildModelFromUrdf', (['obj_urdf'], {}), '(obj_urdf)\n', (865, 875), False, 'import pinocchio\n'), ((1389, 1417), 'classic_framework.controllers.TrajectoryTracking.GotoJointController', 'GotoJointController', (['self.dt'], {}), '(self.dt)\n', (1408, 1417), False, 'from classic_framework.controllers.TrajectoryTracking import GotoJointController\n'), ((1455, 1494), 'classic_framework.GotoCartPosImpedanceController', 'GotoCartPosImpedanceController', (['self.dt'], {}), '(self.dt)\n', (1485, 1494), False, 'from classic_framework import GotoCartPosImpedanceController\n'), ((1536, 1579), 'classic_framework.GotoCartPosQuatImpedanceController', 'GotoCartPosQuatImpedanceController', (['self.dt'], {}), '(self.dt)\n', (1570, 1579), False, 'from classic_framework import GotoCartPosQuatImpedanceController\n'), ((1618, 1649), 'classic_framework.controllers.TrajectoryTracking.JointTrajectoryTracker', 'JointTrajectoryTracker', (['self.dt'], {}), '(self.dt)\n', (1640, 1649), False, 'from classic_framework.controllers.TrajectoryTracking import JointTrajectoryTracker\n'), ((2089, 2148), 'pinocchio.framesForwardKinematics', 'pinocchio.framesForwardKinematics', (['self.model', 'self.data', 'q'], {}), '(self.model, self.data, q)\n', (2122, 2148), False, 'import pinocchio\n'), ((2361, 2418), 'pinocchio.computeJointJacobians', 'pinocchio.computeJointJacobians', (['self.model', 'self.data', 'q'], {}), '(self.model, self.data, q)\n', (2392, 2418), False, 'import pinocchio\n'), ((2427, 2486), 'pinocchio.framesForwardKinematics', 'pinocchio.framesForwardKinematics', (['self.model', 'self.data', 'q'], {}), '(self.model, self.data, q)\n', (2460, 2486), False, 'import pinocchio\n'), ((2913, 2976), 'numpy.array', 'np.array', (['self.data.oMf[self.end_effector_frame_id].translation'], {}), '(self.data.oMf[self.end_effector_frame_id].translation)\n', (2921, 2976), True, 'import numpy as np\n'), ((3303, 3314), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (3311, 3314), True, 'import numpy as np\n'), ((3409, 3469), 'numpy.array', 'np.array', (['self.data.oMf[self.end_effector_frame_id].rotation'], {}), '(self.data.oMf[self.end_effector_frame_id].rotation)\n', (3417, 3469), True, 'import numpy as np\n'), ((3671, 3682), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (3679, 3682), True, 'import numpy as np\n'), ((609, 696), 'classic_framework.utils.sim_path.sim_framework_path', 'sim_framework_path', (['"""./classic_framework/controllers/Config/PyBullet/FictiveRobot"""'], {}), "(\n './classic_framework/controllers/Config/PyBullet/FictiveRobot')\n", (627, 696), False, 'from classic_framework.utils.sim_path import sim_framework_path\n'), ((2043, 2054), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (2051, 2054), True, 'import numpy as np\n'), ((2315, 2326), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (2323, 2326), True, 'import numpy as np\n'), ((2502, 2615), 'pinocchio.getFrameJacobian', 'pinocchio.getFrameJacobian', (['self.model', 'self.data', 'self.end_effector_frame_id', 'pinocchio.LOCAL_WORLD_ALIGNED'], {}), '(self.model, self.data, self.\n end_effector_frame_id, pinocchio.LOCAL_WORLD_ALIGNED)\n', (2528, 2615), False, 'import pinocchio\n'), ((3971, 3982), 'numpy.zeros', 'np.zeros', (['(7)'], {}), '(7)\n', (3979, 3982), True, 'import numpy as np\n'), ((4285, 4296), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (4293, 4296), True, 'import numpy as np\n'), ((5486, 5497), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (5494, 5497), True, 'import numpy as np\n'), ((3502, 3574), 'pinocchio.Quaternion', 'pinocchio.Quaternion', (['self.data.oMf[self.end_effector_frame_id].rotation'], {}), '(self.data.oMf[self.end_effector_frame_id].rotation)\n', (3522, 3574), False, 'import pinocchio\n')] |
"""Tests for ribs.factory."""
import numpy as np
import pytest
import toml
import ribs.factory
from ribs.archives import GridArchive
from ribs.emitters import GaussianEmitter
from ribs.optimizers import Optimizer
@pytest.mark.parametrize(
"registration_func",
[
ribs.factory.register_archive,
ribs.factory.register_emitter,
ribs.factory.register_optimizer,
],
ids=[
"archive",
"emitter",
"optimizer",
],
)
def test_registering_again_fails(registration_func):
class NewClass:
"""Arbitrary class for registration."""
with pytest.raises(ribs.factory.RegistrationError):
registration_func("NewClass", NewClass)
# The second registration should fail.
registration_func("NewClass", NewClass)
@pytest.mark.parametrize("use_toml", [False, True], ids=["dict", "toml"])
def test_from_config_with_valid_input(use_toml, tmp_path):
seed = 42
batch_size = 4
archive = GridArchive([64, 64], [(-1, 1), (-1, 1)], seed=seed)
emitters = [
GaussianEmitter(archive, [0.0, 0.0],
0.1,
batch_size=batch_size,
seed=seed)
]
optimizer = Optimizer(archive, emitters)
config_dict = {
"archive": {
"type": "GridArchive",
"dims": [64, 64],
"ranges": [(-1, 1), (-1, 1)],
"seed": seed,
},
"emitters": [{
"type": "GaussianEmitter",
"x0": [0.0, 0.0],
"sigma0": 0.1,
"batch_size": batch_size,
"seed": seed,
}],
"optimizer": {
"type": "Optimizer",
},
}
if use_toml:
config_path = tmp_path / "config.toml"
with config_path.open("w") as file:
toml.dump(config_dict, file)
created_optimizer = ribs.factory.from_config(config_path)
else:
created_optimizer = ribs.factory.from_config(config_dict)
# Check types.
assert isinstance(created_optimizer, Optimizer)
assert isinstance(created_optimizer.archive, GridArchive)
assert len(created_optimizer.emitters) == 1
assert isinstance(created_optimizer.emitters[0], GaussianEmitter)
# Check results from ask() and tell() -- since seeds are the same, all
# results should be the same.
optimizer_sols = optimizer.ask()
created_optimizer_sols = created_optimizer.ask()
assert len(optimizer_sols) == batch_size
assert (optimizer_sols == created_optimizer_sols).all()
objective_values = [0.0] * batch_size
behavior_values = np.array([[1, 1], [-1, 1], [-1, -1], [1, -1]])
optimizer.tell(objective_values, behavior_values)
created_optimizer.tell(objective_values, behavior_values)
assert (optimizer.archive.as_pandas() ==
created_optimizer.archive.as_pandas()).all(None)
@pytest.mark.parametrize("entity_type", ["archive", "emitter", "optimizer"])
def test_from_config_fails_on_unknown_entity(entity_type):
config_dict = {
"archive": {
"type": "GridArchive",
"dims": [64, 64],
"ranges": [(-1, 1), (-1, 1)],
"seed": 42,
},
"emitters": [{
"type": "GaussianEmitter",
"x0": [0.0, 0.0],
"sigma0": 0.1,
"batch_size": 32,
"seed": 42,
}],
"optimizer": {
"type": "Optimizer",
},
}
if entity_type == "archive":
config_dict["archive"]["type"] = "NonexistentArchive"
elif entity_type == "emitter":
config_dict["emitters"][0]["type"] = "NonexistentEmitter"
elif entity_type == "optimizer":
config_dict["optimizer"]["type"] = "NonexistentOptimizer"
with pytest.raises(KeyError):
ribs.factory.from_config(config_dict)
| [
"ribs.emitters.GaussianEmitter",
"pytest.raises",
"ribs.optimizers.Optimizer",
"numpy.array",
"ribs.archives.GridArchive",
"pytest.mark.parametrize",
"toml.dump"
] | [((217, 408), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""registration_func"""', '[ribs.factory.register_archive, ribs.factory.register_emitter, ribs.factory\n .register_optimizer]'], {'ids': "['archive', 'emitter', 'optimizer']"}), "('registration_func', [ribs.factory.register_archive,\n ribs.factory.register_emitter, ribs.factory.register_optimizer], ids=[\n 'archive', 'emitter', 'optimizer'])\n", (240, 408), False, 'import pytest\n'), ((802, 874), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""use_toml"""', '[False, True]'], {'ids': "['dict', 'toml']"}), "('use_toml', [False, True], ids=['dict', 'toml'])\n", (825, 874), False, 'import pytest\n'), ((2898, 2973), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""entity_type"""', "['archive', 'emitter', 'optimizer']"], {}), "('entity_type', ['archive', 'emitter', 'optimizer'])\n", (2921, 2973), False, 'import pytest\n'), ((982, 1034), 'ribs.archives.GridArchive', 'GridArchive', (['[64, 64]', '[(-1, 1), (-1, 1)]'], {'seed': 'seed'}), '([64, 64], [(-1, 1), (-1, 1)], seed=seed)\n', (993, 1034), False, 'from ribs.archives import GridArchive\n'), ((1230, 1258), 'ribs.optimizers.Optimizer', 'Optimizer', (['archive', 'emitters'], {}), '(archive, emitters)\n', (1239, 1258), False, 'from ribs.optimizers import Optimizer\n'), ((2626, 2672), 'numpy.array', 'np.array', (['[[1, 1], [-1, 1], [-1, -1], [1, -1]]'], {}), '([[1, 1], [-1, 1], [-1, -1], [1, -1]])\n', (2634, 2672), True, 'import numpy as np\n'), ((609, 654), 'pytest.raises', 'pytest.raises', (['ribs.factory.RegistrationError'], {}), '(ribs.factory.RegistrationError)\n', (622, 654), False, 'import pytest\n'), ((1060, 1135), 'ribs.emitters.GaussianEmitter', 'GaussianEmitter', (['archive', '[0.0, 0.0]', '(0.1)'], {'batch_size': 'batch_size', 'seed': 'seed'}), '(archive, [0.0, 0.0], 0.1, batch_size=batch_size, seed=seed)\n', (1075, 1135), False, 'from ribs.emitters import GaussianEmitter\n'), ((3784, 3807), 'pytest.raises', 'pytest.raises', (['KeyError'], {}), '(KeyError)\n', (3797, 3807), False, 'import pytest\n'), ((1833, 1861), 'toml.dump', 'toml.dump', (['config_dict', 'file'], {}), '(config_dict, file)\n', (1842, 1861), False, 'import toml\n')] |
# Copyright (c) 2018 <NAME>
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# Code ported from java to python based on the mallet implementation:
#
# http://mallet.cs.umass.edu/index.php
import numpy as np
from numpy.random import randint
from scipy.io import loadmat
import sys
def learnParameters(alpha,
locTopicDocCounts,
locDocLengthCounts,
shape=1.001, scale=1.0,
numIterations=1):
i = 0
k = 0
parametersSum = np.sum(alpha)
oldParametersK = 0.0
currentDigamma = 0.0
denominator = 1e-10
nonZeroLimit = 0
nonZeroLimits = np.zeros(locTopicDocCounts.shape[0])
nonZeroLimits[:] = -1
histogram = np.zeros(locTopicDocCounts.shape[1])
for i in range(locTopicDocCounts.shape[0]):
histogram[:] = locTopicDocCounts[i, :]
for k in range(histogram.shape[0]):
if histogram[k] > 0:
nonZeroLimits[i] = k
for itr in range(numIterations):
denominator = 1e-10
currentDigamma = 0.0
for i in range(locDocLengthCounts.shape[0]):
currentDigamma += 1.0 / ((
parametersSum + np.float64(i) - 1.0) + 1e-100
)
denominator += locDocLengthCounts[i] * currentDigamma
denominator -= 1.0 / scale
parametersSum = 0.0
for k in range(alpha.shape[0]):
nonZeroLimit = nonZeroLimits[k]
oldParametersK = alpha[k]
currentDigamma = 0.0
histogram[:] = locTopicDocCounts[k, :]
for i in range(np.int64(np.round(nonZeroLimit))):
currentDigamma += 1.0 / (oldParametersK + np.float64(i) - 1.0)
alpha[k] += histogram[i] * currentDigamma
alpha[k] = (oldParametersK * alpha[k] + shape) / denominator
parametersSum += alpha[k]
return parametersSum
def digamma(z):
EULER_MASCHERONI = -0.5772156649015328606065121
DIGAMMA_COEF_1 = 1.0 / 12.0
DIGAMMA_COEF_2 = 1.0 / 120.0
DIGAMMA_COEF_3 = 1.0 / 252.0
DIGAMMA_COEF_4 = 1.0 / 240.0
DIGAMMA_COEF_5 = 1.0 / 132.0
DIGAMMA_COEF_6 = 691.0 / 32760.0
DIGAMMA_COEF_7 = 1.0 / 12.0
# DIGAMMA_COEF_8 = 3617.0/8160.0
# DIGAMMA_COEF_9 = 43867.0/14364.0
# DIGAMMA_COEF_10 = 174611.0/6600.0
DIGAMMA_LARGE = 9.5
DIGAMMA_SMALL = 0.000001
invZ = (1.0 / np.float64(z))
if z < DIGAMMA_SMALL:
return EULER_MASCHERONI - invZ
psi = 0.0
while z < DIGAMMA_LARGE:
psi -= invZ
z += 1.0
invZSquared = invZ * invZ
psi += np.log(z) - 0.5 * invZ
- (invZSquared * (DIGAMMA_COEF_1 - invZSquared * (
DIGAMMA_COEF_2 - invZSquared * (
DIGAMMA_COEF_3 - invZSquared * (
DIGAMMA_COEF_4 - invZSquared * (
DIGAMMA_COEF_5 - invZSquared * (
DIGAMMA_COEF_6 - invZSquared * (DIGAMMA_COEF_7)
)
)
)
)
)))
return psi
def learnSymmetricConcentration(countHistogram, topicSizeHistogram,
numTypes, betaSum, optitr=200):
currentDigamma = 0.0
largestNonZeroCount = 0
nonZeroLengthIndex = np.zeros(topicSizeHistogram.shape[0])
largestNonZeroCount = np.argmax(countHistogram)
idxs = np.where(topicSizeHistogram > 0)[0]
denseIdx = len(idxs)
nonZeroLengthIndex[idxs] = idxs
denseIdxSize = denseIdx
fnumTypes = np.float64(numTypes)
for i in range(optitr):
currentParameter = betaSum / fnumTypes
currentDigamma = 0.0
numerator = 0
for idx in range(largestNonZeroCount):
currentDigamma += 1.0 / (currentParameter + idx - 1.0)
numerator += countHistogram[idx] * currentDigamma
currentDigamma = 0.0
denominator = 1e-10
previousLength = 0
cachedDigamma = digamma(betaSum)
for denseIdx in range(denseIdxSize):
length = nonZeroLengthIndex[denseIdx]
if length - previousLength > 20:
currentDigamma = digamma(betaSum + np.float64(length))
- cachedDigamma
else:
for idx in range(np.int64(previousLength), np.int64(length)):
currentDigamma += 1.0 / (betaSum + np.float64(length))
denominator += currentDigamma * topicSizeHistogram[
np.int64(length)
]
betaSum = currentParameter * numerator / denominator
return betaSum
def optimizeAlpha(topicDocCounts, docLengthCounts, maxTokens,
numTopics, alphaSum, usingSymmetricAlpha=False):
locDocLengthCounts = np.zeros(maxTokens + 1)
locTopicDocCounts = np.zeros((numTopics, maxTokens + 1))
alpha = np.zeros(numTopics)
alpha[:] = alphaSum / np.float64(numTopics)
locDocLengthCounts[:] = docLengthCounts[:]
if usingSymmetricAlpha:
locTopicDocCounts[0, :] = np.sum(topicDocCounts, axis=0)
alphaSum = learnSymmetricConcentration(locTopicDocCounts[0, :],
locDocLengthCounts, numTopics,
alphaSum)
else:
locTopicDocCounts[:, :] = topicDocCounts[:, :]
alphaSum = learnParameters(alpha, locTopicDocCounts,
locDocLengthCounts, 1.001, 1.0, 1)
return alphaSum
def optimizeBeta(typeTopicCounts, tokensPerTopic,
numTypes, betaSum, maxTypeCount):
countHistogram = np.zeros(np.int64(np.round(
maxTypeCount
)) + 1, dtype=np.int64)
for t in range(numTypes):
x = np.where(typeTopicCounts[t] > 0)
for xidx in x:
countHistogram[np.int64(np.round(typeTopicCounts[xidx]))] += 1
maxTopicSize = tokensPerTopic[np.argmax(tokensPerTopic)]
topicSizeHistogram = np.zeros(np.int64(
np.round(maxTopicSize)
) + 1, dtype=np.int64)
for t in range(tokensPerTopic.shape[0]):
topicSizeHistogram[np.int64(np.round(tokensPerTopic[t]))] += 1
betaSum = learnSymmetricConcentration(
countHistogram, topicSizeHistogram, numTypes, betaSum
)
beta = betaSum / np.float64(numTypes)
return beta
def estimate(training, numTopics, alpha_, beta_,
numIterations=2000, burnInPeriod=200, optimizeInterval=50):
# alphabet = range(training.shape[1])
numTypes = training.shape[1] # types means 'words'
alphaSum = alpha_
alpha = np.zeros(numTopics)
alpha[:] = alphaSum / np.float(numTopics)
beta = beta_
betaSum = beta * np.float(numTypes)
typeTopicCounts = np.zeros((numTypes, numTopics))
# typeTotals = np.zeros(numTypes)
tokensPerTopic = np.zeros(numTopics)
docLength = np.sum(training, axis=1)
maxTermFreq = np.max(docLength)
# totalTokens = np.sum(training)
initBeta = beta
initBetaSum = betaSum
training_indices = np.ma.masked_where(training > 0, training)
topicSeq = list([randint(0, numTopics, np.sum(
training[i, training_indices[i, :].mask]
)) for i in range(training_indices.shape[0])])
for i in range(training_indices.shape[0]):
typ_idx = np.where(training_indices[i, :].mask)[0]
count_idx = training[i, training_indices[i, :].mask]
j = 0
for typ, count in zip(typ_idx, count_idx):
for topc in topicSeq[i][j:j + count]:
typeTopicCounts[typ, topc] += 1
tokensPerTopic[topc] += 1
j += count
docLengthCounts = np.zeros(maxTermFreq + 1)
topicDocCounts = np.zeros((numTopics, maxTermFreq + 1))
cachedCoefficients = np.zeros(numTopics)
shouldSaveState = False
UNASSIGNED_TOPIC = -1
i = 0
for itr in range(numIterations):
if itr % 10 == 0:
print(itr)
denom = tokensPerTopic + betaSum
smoothingOnlyMass = np.sum(alpha * beta / denom)
cachedCoefficients = alpha / denom
for j in range(training.shape[0]):
localTopicCounts, localTopicIndex = \
(np.zeros(numTopics), np.zeros(numTopics, dtype=np.int))
# (old_topic, new_topic, topicWeightSum) = (-1, -1, 0.)
(old_topic, new_topic) = (-1, -1)
docLen = docLength[j]
oneDocTopics = topicSeq[j]
oneDocTypes = np.where(training_indices[i, :].mask)[0]
oneDocTypesFreq = training[i, training_indices[i, :].mask]
for t in oneDocTopics[
np.where(oneDocTopics != UNASSIGNED_TOPIC)[0]
]:
localTopicCounts[t] += 1
msk = np.where(localTopicCounts > 0)[0]
localTopicIndex[msk] = msk
# nonZeroTopics = len(localTopicIndex)-1
nonZeroTopics = msk.shape[0]
topicBetaMass = 0.0
denom = tokensPerTopic[localTopicIndex] + betaSum
topicBetaMass += np.sum(
(beta * localTopicCounts[localTopicIndex]) / denom
)
cachedCoefficients[localTopicIndex] = (alpha[
localTopicIndex
] + localTopicCounts[localTopicIndex]) / denom
topicTermMass = 0.0
topicTermScores = np.zeros(numTopics)
denseIdx = 0
score = 0.0
oneDocIndices = np.zeros(
oneDocTypesFreq.shape[0] + 1, dtype=np.uint64
)
oneDocIndices[1:] = np.cumsum(oneDocTypesFreq)
for pos in range(oneDocIndices.shape[0] - 1):
pos_rng = oneDocIndices[pos:pos + 2]
if pos_rng[1] >= oneDocTopics.shape[0]:
break
topics = oneDocTopics[pos_rng]
odtf = oneDocTypesFreq[pos]
types_freq = [odtf] * odtf
types = [oneDocTypes[pos]] * odtf
for pos_range, old_topic, type_, type_freq in zip(
pos_rng, topics, types, types_freq
):
currentTypeTopicCounts = typeTopicCounts[type_, :]
if old_topic != UNASSIGNED_TOPIC:
denom = (tokensPerTopic[old_topic] + betaSum)
smoothingOnlyMass -= alpha[old_topic] * beta / denom
topicBetaMass -= \
beta * localTopicCounts[old_topic] / denom
localTopicCounts[old_topic] -= 1
if localTopicCounts[old_topic] == 0:
denseIdx = 0
denseIdx = len(list(zip(*np.where(
localTopicIndex != old_topic
))))
while denseIdx < nonZeroTopics:
if denseIdx < len(localTopicIndex) - 1:
localTopicIndex[
denseIdx
] = localTopicIndex[denseIdx + 1]
denseIdx += 1
nonZeroTopics -= 1
tokensPerTopic[old_topic] -= 1
denom = tokensPerTopic[old_topic] + betaSum
smoothingOnlyMass += alpha[old_topic] * beta / denom
topicBetaMass += beta * localTopicCounts[
old_topic
] / denom
cachedCoefficients[old_topic] = (alpha[
old_topic
] + localTopicCounts[old_topic]) / denom
alreadyDecremented = (old_topic == UNASSIGNED_TOPIC)
topicTermMass = 0.0
idx_ = 0
while (idx_ < currentTypeTopicCounts.shape[0]) and \
(currentTypeTopicCounts[idx_] > 0):
currentTopic = idx_
currentValue = currentTypeTopicCounts[idx_]
if (not alreadyDecremented) and \
(currentTopic == old_topic):
currentValue -= 1
if currentValue == 0:
currentTypeTopicCounts[idx_] = 0
else:
currentTypeTopicCounts[
old_topic
] = currentValue
subidx = idx_
tmp = 0
while (
subidx < len(currentTypeTopicCounts) - 1) and \
(currentTypeTopicCounts[subidx] < \
currentTypeTopicCounts[subidx + 1]):
tmp = currentTypeTopicCounts[subidx]
currentTypeTopicCounts[subidx] = \
currentTypeTopicCounts[subidx + 1]
currentTypeTopicCounts[subidx + 1] = tmp
subidx += 1
alreadyDecremented = True
else:
score = cachedCoefficients[
currentTopic
] * currentValue
topicTermMass += score
topicTermScores[idx_] = score
idx_ += 1
sample = np.random.rand() * \
(smoothingOnlyMass + topicBetaMass + topicTermMass)
# origSample = sample
new_topic = -1
if sample < topicTermMass:
i = -1
while sample > 0:
i += 1
sample -= topicTermScores[i]
new_topic = i
currentValue = currentTypeTopicCounts[i]
currentTypeTopicCounts[:] = currentTypeTopicCounts[
np.argsort(currentTypeTopicCounts)
]
else:
sample -= topicTermMass
if sample < topicBetaMass:
sample /= beta
denseIdx = 0
while denseIdx < nonZeroTopics:
tpc = localTopicIndex[denseIdx]
sample -= localTopicCounts[tpc] / \
(tokensPerTopic[tpc] + betaSum)
if sample <= 0.0:
new_topic = tpc
break
denseIdx += 1
else:
sample -= topicBetaMass
sample /= beta
new_topic = 0
sample -= alpha[new_topic] / \
(tokensPerTopic[new_topic] + betaSum)
while sample > 0.0 and new_topic + 1 < numTopics:
new_topic += 1
sample -= alpha[new_topic] / \
(tokensPerTopic[new_topic] + betaSum)
idx_ = 0
while (idx_ < len(currentTypeTopicCounts) - 1) and \
(currentTypeTopicCounts[idx_] > 0) and \
(currentTypeTopicCounts[idx_] != new_topic):
idx_ += 1
if currentTypeTopicCounts[idx_] == 0:
currentTypeTopicCounts[idx_] = new_topic
else:
currentValue = idx_
currentTypeTopicCounts[idx_] = new_topic
if new_topic < 0:
new_topic = numTopics - 1
oneDocTopics[pos_range] = new_topic
denom = tokensPerTopic[new_topic] + betaSum
topicBetaMass -= beta * localTopicCounts[new_topic] / denom
localTopicCounts[new_topic] += 1
if localTopicCounts[new_topic] == 1:
denseIdx = nonZeroTopics
while (denseIdx > 0) and \
(localTopicIndex[denseIdx - 1] > new_topic):
localTopicIndex[denseIdx] = \
localTopicIndex[denseIdx - 1]
denseIdx -= 1
localTopicIndex[denseIdx] = new_topic
nonZeroTopics += 1
tokensPerTopic[new_topic] += 1
denom = (tokensPerTopic[new_topic] + betaSum)
cachedCoefficients[new_topic] = \
(alpha[new_topic] + localTopicCounts[new_topic]) \
/ denom
smoothingOnlyMass += (alpha[new_topic] + beta) / denom
topicBetaMass += beta * localTopicCounts[new_topic] / denom
if shouldSaveState:
docLengthCounts[docLen] += 1
for denseIdx in range(nonZeroTopics):
topic = localTopicIndex[denseIdx]
topicDocCounts[topic, localTopicCounts[topic]] += 1
for denseIdx in range(nonZeroTopics):
topic = localTopicIndex[denseIdx]
cachedCoefficients[topic] = alpha[topic] / \
(tokensPerTopic[topic] + betaSum)
if itr > burnInPeriod and optimizeInterval != 0 and \
itr % optimizeInterval == 0:
alpha_ = optimizeAlpha(topicDocCounts, docLengthCounts,
maxTermFreq, numTopics, np.sum(alpha))
ttc_mx = np.max(typeTopicCounts)
optimizeBeta(typeTopicCounts, tokensPerTopic, numTypes, betaSum,
ttc_mx)
beta = initBeta
betaSum = initBetaSum
return (docLengthCounts, topicDocCounts)
if __name__ == "__main__":
matlab_vars = dict()
if len(sys.argv) > 1 and sys.argv[1] == 0:
loadmat('docword.nips.train.mat', matlab_vars)
else:
loadmat('docword.kos.train.mat', matlab_vars)
D = int(matlab_vars['D'][0][0])
W = int(matlab_vars['W'][0][0])
N = int(matlab_vars['N'][0][0])
T = int(4)
w = matlab_vars['w']
d = matlab_vars['d']
w.reshape(w.shape[0])
d.reshape(d.shape[0])
w -= 1
d -= 1
z = np.random.randint(0, T, size=T * N)
beta = 0.01
alpha = 0.5
iters = 1000
word_doc_mat = np.zeros((D, W), dtype=np.int)
for j in range(N):
word_doc_mat[d[j], w[j]] += 1
doclenhist, topicdochist = \
estimate(word_doc_mat, T, alpha, beta, iters)
| [
"numpy.sum",
"numpy.log",
"numpy.ma.masked_where",
"numpy.argmax",
"scipy.io.loadmat",
"numpy.zeros",
"numpy.float",
"numpy.argsort",
"numpy.cumsum",
"numpy.max",
"numpy.random.randint",
"numpy.where",
"numpy.int64",
"numpy.random.rand",
"numpy.float64",
"numpy.round"
] | [((623, 636), 'numpy.sum', 'np.sum', (['alpha'], {}), '(alpha)\n', (629, 636), True, 'import numpy as np\n'), ((753, 789), 'numpy.zeros', 'np.zeros', (['locTopicDocCounts.shape[0]'], {}), '(locTopicDocCounts.shape[0])\n', (761, 789), True, 'import numpy as np\n'), ((833, 869), 'numpy.zeros', 'np.zeros', (['locTopicDocCounts.shape[1]'], {}), '(locTopicDocCounts.shape[1])\n', (841, 869), True, 'import numpy as np\n'), ((3350, 3387), 'numpy.zeros', 'np.zeros', (['topicSizeHistogram.shape[0]'], {}), '(topicSizeHistogram.shape[0])\n', (3358, 3387), True, 'import numpy as np\n'), ((3414, 3439), 'numpy.argmax', 'np.argmax', (['countHistogram'], {}), '(countHistogram)\n', (3423, 3439), True, 'import numpy as np\n'), ((3592, 3612), 'numpy.float64', 'np.float64', (['numTypes'], {}), '(numTypes)\n', (3602, 3612), True, 'import numpy as np\n'), ((4807, 4830), 'numpy.zeros', 'np.zeros', (['(maxTokens + 1)'], {}), '(maxTokens + 1)\n', (4815, 4830), True, 'import numpy as np\n'), ((4855, 4891), 'numpy.zeros', 'np.zeros', (['(numTopics, maxTokens + 1)'], {}), '((numTopics, maxTokens + 1))\n', (4863, 4891), True, 'import numpy as np\n'), ((4904, 4923), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (4912, 4923), True, 'import numpy as np\n'), ((6621, 6640), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (6629, 6640), True, 'import numpy as np\n'), ((6766, 6797), 'numpy.zeros', 'np.zeros', (['(numTypes, numTopics)'], {}), '((numTypes, numTopics))\n', (6774, 6797), True, 'import numpy as np\n'), ((6857, 6876), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (6865, 6876), True, 'import numpy as np\n'), ((6894, 6918), 'numpy.sum', 'np.sum', (['training'], {'axis': '(1)'}), '(training, axis=1)\n', (6900, 6918), True, 'import numpy as np\n'), ((6937, 6954), 'numpy.max', 'np.max', (['docLength'], {}), '(docLength)\n', (6943, 6954), True, 'import numpy as np\n'), ((7063, 7105), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(training > 0)', 'training'], {}), '(training > 0, training)\n', (7081, 7105), True, 'import numpy as np\n'), ((7677, 7702), 'numpy.zeros', 'np.zeros', (['(maxTermFreq + 1)'], {}), '(maxTermFreq + 1)\n', (7685, 7702), True, 'import numpy as np\n'), ((7724, 7762), 'numpy.zeros', 'np.zeros', (['(numTopics, maxTermFreq + 1)'], {}), '((numTopics, maxTermFreq + 1))\n', (7732, 7762), True, 'import numpy as np\n'), ((7788, 7807), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (7796, 7807), True, 'import numpy as np\n'), ((18842, 18877), 'numpy.random.randint', 'np.random.randint', (['(0)', 'T'], {'size': '(T * N)'}), '(0, T, size=T * N)\n', (18859, 18877), True, 'import numpy as np\n'), ((18946, 18976), 'numpy.zeros', 'np.zeros', (['(D, W)'], {'dtype': 'np.int'}), '((D, W), dtype=np.int)\n', (18954, 18976), True, 'import numpy as np\n'), ((2508, 2521), 'numpy.float64', 'np.float64', (['z'], {}), '(z)\n', (2518, 2521), True, 'import numpy as np\n'), ((2712, 2721), 'numpy.log', 'np.log', (['z'], {}), '(z)\n', (2718, 2721), True, 'import numpy as np\n'), ((3451, 3483), 'numpy.where', 'np.where', (['(topicSizeHistogram > 0)'], {}), '(topicSizeHistogram > 0)\n', (3459, 3483), True, 'import numpy as np\n'), ((4950, 4971), 'numpy.float64', 'np.float64', (['numTopics'], {}), '(numTopics)\n', (4960, 4971), True, 'import numpy as np\n'), ((5082, 5112), 'numpy.sum', 'np.sum', (['topicDocCounts'], {'axis': '(0)'}), '(topicDocCounts, axis=0)\n', (5088, 5112), True, 'import numpy as np\n'), ((5781, 5813), 'numpy.where', 'np.where', (['(typeTopicCounts[t] > 0)'], {}), '(typeTopicCounts[t] > 0)\n', (5789, 5813), True, 'import numpy as np\n'), ((5947, 5972), 'numpy.argmax', 'np.argmax', (['tokensPerTopic'], {}), '(tokensPerTopic)\n', (5956, 5972), True, 'import numpy as np\n'), ((6327, 6347), 'numpy.float64', 'np.float64', (['numTypes'], {}), '(numTypes)\n', (6337, 6347), True, 'import numpy as np\n'), ((6667, 6686), 'numpy.float', 'np.float', (['numTopics'], {}), '(numTopics)\n', (6675, 6686), True, 'import numpy as np\n'), ((6725, 6743), 'numpy.float', 'np.float', (['numTypes'], {}), '(numTypes)\n', (6733, 6743), True, 'import numpy as np\n'), ((8029, 8057), 'numpy.sum', 'np.sum', (['(alpha * beta / denom)'], {}), '(alpha * beta / denom)\n', (8035, 8057), True, 'import numpy as np\n'), ((18471, 18517), 'scipy.io.loadmat', 'loadmat', (['"""docword.nips.train.mat"""', 'matlab_vars'], {}), "('docword.nips.train.mat', matlab_vars)\n", (18478, 18517), False, 'from scipy.io import loadmat\n'), ((18536, 18581), 'scipy.io.loadmat', 'loadmat', (['"""docword.kos.train.mat"""', 'matlab_vars'], {}), "('docword.kos.train.mat', matlab_vars)\n", (18543, 18581), False, 'from scipy.io import loadmat\n'), ((7324, 7361), 'numpy.where', 'np.where', (['training_indices[i, :].mask'], {}), '(training_indices[i, :].mask)\n', (7332, 7361), True, 'import numpy as np\n'), ((9057, 9113), 'numpy.sum', 'np.sum', (['(beta * localTopicCounts[localTopicIndex] / denom)'], {}), '(beta * localTopicCounts[localTopicIndex] / denom)\n', (9063, 9113), True, 'import numpy as np\n'), ((9359, 9378), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (9367, 9378), True, 'import numpy as np\n'), ((9456, 9511), 'numpy.zeros', 'np.zeros', (['(oneDocTypesFreq.shape[0] + 1)'], {'dtype': 'np.uint64'}), '(oneDocTypesFreq.shape[0] + 1, dtype=np.uint64)\n', (9464, 9511), True, 'import numpy as np\n'), ((9574, 9600), 'numpy.cumsum', 'np.cumsum', (['oneDocTypesFreq'], {}), '(oneDocTypesFreq)\n', (9583, 9600), True, 'import numpy as np\n'), ((18117, 18140), 'numpy.max', 'np.max', (['typeTopicCounts'], {}), '(typeTopicCounts)\n', (18123, 18140), True, 'import numpy as np\n'), ((5679, 5701), 'numpy.round', 'np.round', (['maxTypeCount'], {}), '(maxTypeCount)\n', (5687, 5701), True, 'import numpy as np\n'), ((6026, 6048), 'numpy.round', 'np.round', (['maxTopicSize'], {}), '(maxTopicSize)\n', (6034, 6048), True, 'import numpy as np\n'), ((6158, 6185), 'numpy.round', 'np.round', (['tokensPerTopic[t]'], {}), '(tokensPerTopic[t])\n', (6166, 6185), True, 'import numpy as np\n'), ((7150, 7198), 'numpy.sum', 'np.sum', (['training[i, training_indices[i, :].mask]'], {}), '(training[i, training_indices[i, :].mask])\n', (7156, 7198), True, 'import numpy as np\n'), ((8212, 8231), 'numpy.zeros', 'np.zeros', (['numTopics'], {}), '(numTopics)\n', (8220, 8231), True, 'import numpy as np\n'), ((8233, 8266), 'numpy.zeros', 'np.zeros', (['numTopics'], {'dtype': 'np.int'}), '(numTopics, dtype=np.int)\n', (8241, 8266), True, 'import numpy as np\n'), ((8482, 8519), 'numpy.where', 'np.where', (['training_indices[i, :].mask'], {}), '(training_indices[i, :].mask)\n', (8490, 8519), True, 'import numpy as np\n'), ((8766, 8796), 'numpy.where', 'np.where', (['(localTopicCounts > 0)'], {}), '(localTopicCounts > 0)\n', (8774, 8796), True, 'import numpy as np\n'), ((18080, 18093), 'numpy.sum', 'np.sum', (['alpha'], {}), '(alpha)\n', (18086, 18093), True, 'import numpy as np\n'), ((1715, 1737), 'numpy.round', 'np.round', (['nonZeroLimit'], {}), '(nonZeroLimit)\n', (1723, 1737), True, 'import numpy as np\n'), ((4336, 4360), 'numpy.int64', 'np.int64', (['previousLength'], {}), '(previousLength)\n', (4344, 4360), True, 'import numpy as np\n'), ((4362, 4378), 'numpy.int64', 'np.int64', (['length'], {}), '(length)\n', (4370, 4378), True, 'import numpy as np\n'), ((4537, 4553), 'numpy.int64', 'np.int64', (['length'], {}), '(length)\n', (4545, 4553), True, 'import numpy as np\n'), ((5873, 5904), 'numpy.round', 'np.round', (['typeTopicCounts[xidx]'], {}), '(typeTopicCounts[xidx])\n', (5881, 5904), True, 'import numpy as np\n'), ((8645, 8687), 'numpy.where', 'np.where', (['(oneDocTopics != UNASSIGNED_TOPIC)'], {}), '(oneDocTopics != UNASSIGNED_TOPIC)\n', (8653, 8687), True, 'import numpy as np\n'), ((4233, 4251), 'numpy.float64', 'np.float64', (['length'], {}), '(length)\n', (4243, 4251), True, 'import numpy as np\n'), ((13646, 13662), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (13660, 13662), True, 'import numpy as np\n'), ((1299, 1312), 'numpy.float64', 'np.float64', (['i'], {}), '(i)\n', (1309, 1312), True, 'import numpy as np\n'), ((1799, 1812), 'numpy.float64', 'np.float64', (['i'], {}), '(i)\n', (1809, 1812), True, 'import numpy as np\n'), ((4436, 4454), 'numpy.float64', 'np.float64', (['length'], {}), '(length)\n', (4446, 4454), True, 'import numpy as np\n'), ((14240, 14274), 'numpy.argsort', 'np.argsort', (['currentTypeTopicCounts'], {}), '(currentTypeTopicCounts)\n', (14250, 14274), True, 'import numpy as np\n'), ((10717, 10755), 'numpy.where', 'np.where', (['(localTopicIndex != old_topic)'], {}), '(localTopicIndex != old_topic)\n', (10725, 10755), True, 'import numpy as np\n')] |
import numpy as np
from pathlib import Path
import json
import random
import torch
import os
def save_json(data, file_path):
'''
save json
:param data:
:param json_path:
:param file_name:
:return:
'''
if not isinstance(file_path, Path):
file_path = Path(file_path)
# if isinstance(data,dict):
# data = json.dumps(data)
with open(str(file_path), 'w') as f:
json.dump(data, f)
def load_json(file_path):
'''
load json
:param json_path:
:param file_name:
:return:
'''
if not isinstance(file_path, Path):
file_path = Path(file_path)
with open(str(file_path), 'r') as f:
data = json.load(f)
return data
class AverageMeter(object):
'''
# computes and stores the average and current value
# Example:
# >>> loss = AverageMeter()
# >>> for step,batch in enumerate(train_data):
# >>> pred = self.model(batch)
# >>> raw_loss = self.metrics(pred,target)
# >>> loss.update(raw_loss.item(),n = 1)
# >>> cur_loss = loss.avg
# '''
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def seed_everything(seed=1029):
'''
:param seed:
:param device:
:return:
'''
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# some cudnn methods can be random even after fixing the seed
# unless you tell it to be deterministic
torch.backends.cudnn.deterministic = True | [
"json.dump",
"json.load",
"numpy.random.seed",
"torch.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.manual_seed_all",
"pathlib.Path",
"random.seed"
] | [((1588, 1605), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1599, 1605), False, 'import random\n'), ((1657, 1677), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1671, 1677), True, 'import numpy as np\n'), ((1683, 1706), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1700, 1706), False, 'import torch\n'), ((1712, 1740), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (1734, 1740), False, 'import torch\n'), ((1746, 1778), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (1772, 1778), False, 'import torch\n'), ((308, 323), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (312, 323), False, 'from pathlib import Path\n'), ((443, 461), 'json.dump', 'json.dump', (['data', 'f'], {}), '(data, f)\n', (452, 461), False, 'import json\n'), ((648, 663), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (652, 663), False, 'from pathlib import Path\n'), ((722, 734), 'json.load', 'json.load', (['f'], {}), '(f)\n', (731, 734), False, 'import json\n')] |
import itertools
import operator
import numpy as np
from sklearn import cross_validation
from sklearn import feature_selection
from sklearn import ensemble
from sklearn import neighbors
from sklearn import svm
train = np.load('train.npy')
# Remove the labels
test = np.load('test_distribute.npy')[:,1:]
data = train[:,1:]
target = train[:,0]
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
groups = itertools.groupby(SL, key=operator.itemgetter(0))
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
# Now I rock out some ensemble-ception, because hopefully these are all
# wrong in different ways, and I choose the most common answer. If they're all
# different let's go with the first, and I'll order my classifiers based on
# which one is my favorite
def predictificate(data, target, test, clfs):
res = []
for clf in clfs:
clf.fit(data, target)
res.append(clf.predict(test))
pred = [most_common(x) for x in zip(*res)]
f = open('final-predictions.csv', 'w')
f.write("ID,Category\n")
for i, res in enumerate(pred):
f.write("%d,%d\n" % (i+1,res))
f.close()
clfs = []
# Through cv testing, I found the optimal number of estimators to be 15
clfs.append(ensemble.RandomForestClassifier(n_estimators=150))
clfs.append(ensemble.GradientBoostingClassifier(n_estimators=200))
clfs.append(ensemble.AdaBoostClassifier(n_estimators=135))
#clfs.append(neighbors.KNeighborsClassifier(n_neighbors=10))
#clfs.append(svm.SVC())
predictificate(data, target, test, clfs)
# I use the following code to find good hyperparameter values
#scores = cross_validation.cross_val_score(
#clf, data, target, cv=5)
#print("Accuracy: %0.2f (+/- %0.2f) %f" % (scores.mean(), scores.std() * 2, x))
| [
"sklearn.ensemble.RandomForestClassifier",
"numpy.load",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.ensemble.GradientBoostingClassifier",
"operator.itemgetter"
] | [((220, 240), 'numpy.load', 'np.load', (['"""train.npy"""'], {}), "('train.npy')\n", (227, 240), True, 'import numpy as np\n'), ((268, 298), 'numpy.load', 'np.load', (['"""test_distribute.npy"""'], {}), "('test_distribute.npy')\n", (275, 298), True, 'import numpy as np\n'), ((1501, 1550), 'sklearn.ensemble.RandomForestClassifier', 'ensemble.RandomForestClassifier', ([], {'n_estimators': '(150)'}), '(n_estimators=150)\n', (1532, 1550), False, 'from sklearn import ensemble\n'), ((1564, 1617), 'sklearn.ensemble.GradientBoostingClassifier', 'ensemble.GradientBoostingClassifier', ([], {'n_estimators': '(200)'}), '(n_estimators=200)\n', (1599, 1617), False, 'from sklearn import ensemble\n'), ((1631, 1676), 'sklearn.ensemble.AdaBoostClassifier', 'ensemble.AdaBoostClassifier', ([], {'n_estimators': '(135)'}), '(n_estimators=135)\n', (1658, 1676), False, 'from sklearn import ensemble\n'), ((496, 518), 'operator.itemgetter', 'operator.itemgetter', (['(0)'], {}), '(0)\n', (515, 518), False, 'import operator\n')] |
#
# GADANN - GPU Accelerated Deep Artificial Neural Network
#
# Copyright (C) 2014 <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import pycuda
import pycuda.curandom
import pycuda.compiler
import pycuda.autoinit
import numpy
import operator
import math
import os
from . import tensor
def seed_getter_func(count):
return pycuda.gpuarray.arange(0, count, 1, dtype=numpy.int32)
#rand_gen = pycuda.curandom.XORWOWRandomNumberGenerator()
rand_gen = pycuda.curandom.XORWOWRandomNumberGenerator(seed_getter=seed_getter_func)
def mult(a,b):
output = tensor.Tensor(a.shape)
mult_kernel(a.gpuarray, b.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(a.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def div(a,b):
output = tensor.Tensor(a.shape)
div_kernel(a.gpuarray, b.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(a.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def sample(input):
rand = tensor.Tensor(input.shape)
rand_gen.fill_uniform(rand.gpuarray)
output = tensor.Tensor(input.shape)
sample_kernel(input.gpuarray, rand.gpuarray, output.gpuarray, block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def sqrt(input):
output = tensor.Tensor(input.shape)
sqrt_kernel(input.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def broadcast(input):
result = tensor.Tensor(input.shape)
sample_kernel(input.gpuarray, result.gpuarray, block=(shape[1],1,1), grid=(shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
return output
def logistic(input):
output = tensor.Tensor(input.shape)
logistic_kernel(input.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def dlogistic(input, activation):
output = tensor.Tensor(input.shape)
dlogistic_kernel(input.gpuarray, activation.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
# channelwise softmax
def softmax(input):
output = tensor.Tensor(input.shape)
if True:
if len(input.shape) == 4:
grid = (input.shape[2],input.shape[3],1)
block = (input.shape[0],1,1)
channel_sum = tensor.Tensor((input.shape[0],input.shape[2],input.shape[3]))
channel_max = tensor.Tensor((input.shape[0],input.shape[2],input.shape[3]))
elif len(input.shape) == 2:
grid = (1,1,1)
block = (input.shape[0],1,1)
channel_sum = tensor.Tensor((input.shape[0],1,1))
channel_max = tensor.Tensor((input.shape[0],1,1))
assert( not numpy.isnan(input.get()).any())
channel_max_kernel(input.gpuarray, channel_max.gpuarray, numpy.uint32(input.shape[1]), block=block, grid=grid)
if len(input.shape) == 2:
grid = (1,1,input.shape[0])
block = (input.shape[1],1,1)
elif len(input.shape) == 4:
grid = (input.shape[2],input.shape[3],input.shape[0])
block = (input.shape[1],1,1)
channel_subtract_kernel(input.gpuarray, channel_max.gpuarray, output.gpuarray, numpy.uint32(input.shape[1]), block=block, grid=grid)
if len(input.shape) == 4:
grid = (input.shape[2],input.shape[3],1)
block = (input.shape[0],1,1)
elif len(input.shape) == 2:
grid = (1,1,1)
block = (input.shape[0],1,1)
channel_sum_kernel(output.gpuarray, channel_sum.gpuarray, numpy.uint32(input.shape[1]), block=block, grid=grid)
if len(input.shape) == 2:
grid = (1,1,input.shape[0])
block = (input.shape[1],1,1)
elif len(input.shape) == 4:
grid = (input.shape[2],input.shape[3],input.shape[0])
block = (input.shape[1],1,1)
softmax_divide_kernel(output.gpuarray, channel_sum.gpuarray, block=block, grid=grid)
else:
if len(input.shape) == 2:
softmax_naive_kernel(input.gpuarray, output.gpuarray, block=(input.shape[1],1,1), grid=(input.shape[0],1,1))
else:
softmax_naive_kernel(input.gpuarray, output.gpuarray, block=(input.shape[1],1,1), grid=(input.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
return output
def naive_softmax(input):
output = tensor.Tensor(input.shape)
#shape = (input.shape[0], reduce(operator.__mul__, input.shape[1:], 1))
#channel_stride = reduce(operator.__mul__, input.shape[2:], 1)
assert( not numpy.isnan(input.get()).any())
softmax_naive_kernel(input.gpuarray, output.gpuarray, block=(input.shape[1],1,1), grid=(input.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
return output
def dsoftmax(input, activation):
output = tensor.Tensor(input.shape)
#shape = (input.shape[0], reduce(operator.__mul__, input.shape[1:], 1))
dsoftmax_kernel(input.gpuarray, activation.gpuarray, output.gpuarray, block=(input.shape[1],1,1), grid=(input.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
return output
def tanh(input, output):
tanh_kernel(input, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def dtanh(input, activation, output):
dtanh_kernel(input, activation, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def relu(input):
output = tensor.Tensor(input.shape)
relu_kernel(input.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def drelu(input, activation):
output = tensor.Tensor(input.shape)
drelu_kernel(input.gpuarray, activation.gpuarray, output.gpuarray, numpy.uint32(output.gpuarray.size), block=(128,1,1), grid=(int(math.ceil(input.gpuarray.size/128.0)),1,1))
assert( not numpy.isnan(output.get()).any())
return output
def softplus(input, output):
softplus_kernel(input, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def dsoftplus(input, activation, output):
dsoftplus_kernel(input, activation, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def gaussian(input, output):
gaussian_kernel(input, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def dgaussian(input, activation, output):
dgaussian_kernel(input, activation, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def identity(input, output):
identity_kernel(input, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def didentity(input, activation, output):
didentity_kernel(input, activation, output, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(output.get()).any())
def diff(output, target, result):
diff_kernel(output, target, result, block=(output.shape[1],1,1), grid=(output.shape[0],1,1))
assert( not numpy.isnan(result.get()).any())
def mosaic(input, border_size=1):
block_shape = input.shape[-2:] + (1,)
if input.shape[1] in (1,3):
grid_size = input.shape[0]
grid_shape = (int(math.ceil(math.sqrt(grid_size))), int(math.sqrt(grid_size)), input.shape[1])
output = tensor.Tensor(((block_shape[1]+border_size)*grid_shape[1], (block_shape[0]+border_size)*grid_shape[0], input.shape[1]))
else:
grid_size = input.shape[0]*input.shape[1]
grid_shape = (int(math.ceil(math.sqrt(grid_size))), int(math.sqrt(grid_size)), 1)
output = tensor.Tensor(((block_shape[1]+border_size)*grid_shape[1], (block_shape[0]+border_size)*grid_shape[0], 1))
output.gpuarray.fill(.2)
mosaic_kernel(input.gpuarray, output.gpuarray, numpy.uint32(grid_size), numpy.uint32(border_size), block=block_shape, grid=grid_shape)
return output
def image_2_design(image):
output = tensor.Tensor((256,256))
output.gpuarray.fill(0)
image_2_design_kernel(image.gpuarray, output.gpuarray, block=(16,16,1), grid=(1,1,1))
assert( not numpy.isnan(output.get()).any())
return output
module_dir = os.path.dirname(os.path.abspath(__file__))
cuda_src = open(os.path.join(module_dir,"kernels.cu"), 'r').read()
sm = pycuda.compiler.SourceModule(cuda_src)
import re
p = re.compile('\w*_kernel')
kernels = p.findall(cuda_src)
for kernel in kernels:
globals()[kernel] = sm.get_function(kernel)
| [
"numpy.uint32",
"os.path.abspath",
"pycuda.compiler.SourceModule",
"re.compile",
"math.sqrt",
"math.ceil",
"pycuda.curandom.XORWOWRandomNumberGenerator",
"os.path.join",
"pycuda.gpuarray.arange"
] | [((1529, 1602), 'pycuda.curandom.XORWOWRandomNumberGenerator', 'pycuda.curandom.XORWOWRandomNumberGenerator', ([], {'seed_getter': 'seed_getter_func'}), '(seed_getter=seed_getter_func)\n', (1572, 1602), False, 'import pycuda\n'), ((10303, 10341), 'pycuda.compiler.SourceModule', 'pycuda.compiler.SourceModule', (['cuda_src'], {}), '(cuda_src)\n', (10331, 10341), False, 'import pycuda\n'), ((10360, 10385), 're.compile', 're.compile', (['"""\\\\w*_kernel"""'], {}), "('\\\\w*_kernel')\n", (10370, 10385), False, 'import re\n'), ((1401, 1455), 'pycuda.gpuarray.arange', 'pycuda.gpuarray.arange', (['(0)', 'count', '(1)'], {'dtype': 'numpy.int32'}), '(0, count, 1, dtype=numpy.int32)\n', (1423, 1455), False, 'import pycuda\n'), ((10202, 10227), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (10217, 10227), False, 'import os\n'), ((1716, 1750), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (1728, 1750), False, 'import numpy\n'), ((1999, 2033), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (2011, 2033), False, 'import numpy\n'), ((2635, 2669), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (2647, 2669), False, 'import numpy\n'), ((3160, 3194), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (3172, 3194), False, 'import numpy\n'), ((3490, 3524), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (3502, 3524), False, 'import numpy\n'), ((7237, 7271), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (7249, 7271), False, 'import numpy\n'), ((7559, 7593), 'numpy.uint32', 'numpy.uint32', (['output.gpuarray.size'], {}), '(output.gpuarray.size)\n', (7571, 7593), False, 'import numpy\n'), ((9803, 9826), 'numpy.uint32', 'numpy.uint32', (['grid_size'], {}), '(grid_size)\n', (9815, 9826), False, 'import numpy\n'), ((9828, 9853), 'numpy.uint32', 'numpy.uint32', (['border_size'], {}), '(border_size)\n', (9840, 9853), False, 'import numpy\n'), ((4428, 4456), 'numpy.uint32', 'numpy.uint32', (['input.shape[1]'], {}), '(input.shape[1])\n', (4440, 4456), False, 'import numpy\n'), ((4836, 4864), 'numpy.uint32', 'numpy.uint32', (['input.shape[1]'], {}), '(input.shape[1])\n', (4848, 4864), False, 'import numpy\n'), ((5197, 5225), 'numpy.uint32', 'numpy.uint32', (['input.shape[1]'], {}), '(input.shape[1])\n', (5209, 5225), False, 'import numpy\n'), ((10246, 10284), 'os.path.join', 'os.path.join', (['module_dir', '"""kernels.cu"""'], {}), "(module_dir, 'kernels.cu')\n", (10258, 10284), False, 'import os\n'), ((9264, 9284), 'math.sqrt', 'math.sqrt', (['grid_size'], {}), '(grid_size)\n', (9273, 9284), False, 'import math\n'), ((9568, 9588), 'math.sqrt', 'math.sqrt', (['grid_size'], {}), '(grid_size)\n', (9577, 9588), False, 'import math\n'), ((1779, 1813), 'math.ceil', 'math.ceil', (['(a.gpuarray.size / 128.0)'], {}), '(a.gpuarray.size / 128.0)\n', (1788, 1813), False, 'import math\n'), ((2062, 2096), 'math.ceil', 'math.ceil', (['(a.gpuarray.size / 128.0)'], {}), '(a.gpuarray.size / 128.0)\n', (2071, 2096), False, 'import math\n'), ((2409, 2447), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (2418, 2447), False, 'import math\n'), ((2698, 2736), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (2707, 2736), False, 'import math\n'), ((3223, 3261), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (3232, 3261), False, 'import math\n'), ((3553, 3591), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (3562, 3591), False, 'import math\n'), ((7300, 7338), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (7309, 7338), False, 'import math\n'), ((7622, 7660), 'math.ceil', 'math.ceil', (['(input.gpuarray.size / 128.0)'], {}), '(input.gpuarray.size / 128.0)\n', (7631, 7660), False, 'import math\n'), ((9236, 9256), 'math.sqrt', 'math.sqrt', (['grid_size'], {}), '(grid_size)\n', (9245, 9256), False, 'import math\n'), ((9540, 9560), 'math.sqrt', 'math.sqrt', (['grid_size'], {}), '(grid_size)\n', (9549, 9560), False, 'import math\n')] |
#!/usr/bin/env python3
# coding: utf-8
import json
import numpy as np
import pandas as pd
from visdom import Visdom
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
# import seaborn
# seaborn.set()
# import pylab import mpl
import os, time, sys, pickle
from datetime import datetime
from dateutil.parser import parse
font = {'family': 'SimHei'}
xlabel_dict = {'social_average': u'社会平均', 'state_owned': u'国有单位'}
ylabel_dict = {'salary': u'年收入(RMB)'}
def show_salary_chart(ylabel=''):
global ylabel_dict
plt.style.use('seaborn-whitegrid')
plt.xlabel(u'时间轴', fontproperties='SimHei')
plt.xticks(rotation=-90)
plt.title(ylabel, fontproperties='SimHei')
# plt.xlim(2000, 2020)
# plt.ylim(-1, max_pe+10)
plt.legend(loc=0, prop=font)
plt.grid(True)
viz = Visdom(env='main')
viz.matplot(plt)
if __name__=='__main__':
if len(sys.argv) < 2:
print("please enter the csv path")
raise SystemExit(1)
csv_data_file = sys.argv[1]
data_frame = pd.read_csv(csv_data_file)
date_list = data_frame['year'].apply(str).apply(parse)
print(date_list)
col = data_frame.columns
for i in range(1, len(col)):
print(i, ':', col[i])
# 社会平均
data_array = np.array(data_frame[xlabel_dict['social_average']])
salary_data_series = pd.Series(data_array, index=date_list.values).sort_index(ascending=False)
plt.plot(salary_data_series.index, salary_data_series.values, label=xlabel_dict['social_average'])
# 国有单位
data_array = np.array(data_frame[xlabel_dict['state_owned']])
salary_data_series = pd.Series(data_array, index=date_list.values).sort_index(ascending=False)
plt.plot(salary_data_series.index, salary_data_series.values, label=xlabel_dict['state_owned'])
plt.xticks(salary_data_series.index)
show_salary_chart(ylabel=ylabel_dict['salary'])
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"visdom.Visdom",
"matplotlib.pyplot.style.use",
"numpy.array",
"matplotlib.pyplot.xticks",
"pandas.Series",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] | [((555, 589), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (568, 589), True, 'import matplotlib.pyplot as plt\n'), ((594, 637), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['u"""时间轴"""'], {'fontproperties': '"""SimHei"""'}), "(u'时间轴', fontproperties='SimHei')\n", (604, 637), True, 'import matplotlib.pyplot as plt\n'), ((642, 666), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(-90)'}), '(rotation=-90)\n', (652, 666), True, 'import matplotlib.pyplot as plt\n'), ((671, 713), 'matplotlib.pyplot.title', 'plt.title', (['ylabel'], {'fontproperties': '"""SimHei"""'}), "(ylabel, fontproperties='SimHei')\n", (680, 713), True, 'import matplotlib.pyplot as plt\n'), ((775, 803), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(0)', 'prop': 'font'}), '(loc=0, prop=font)\n', (785, 803), True, 'import matplotlib.pyplot as plt\n'), ((808, 822), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (816, 822), True, 'import matplotlib.pyplot as plt\n'), ((833, 851), 'visdom.Visdom', 'Visdom', ([], {'env': '"""main"""'}), "(env='main')\n", (839, 851), False, 'from visdom import Visdom\n'), ((1046, 1072), 'pandas.read_csv', 'pd.read_csv', (['csv_data_file'], {}), '(csv_data_file)\n', (1057, 1072), True, 'import pandas as pd\n'), ((1275, 1326), 'numpy.array', 'np.array', (["data_frame[xlabel_dict['social_average']]"], {}), "(data_frame[xlabel_dict['social_average']])\n", (1283, 1326), True, 'import numpy as np\n'), ((1430, 1533), 'matplotlib.pyplot.plot', 'plt.plot', (['salary_data_series.index', 'salary_data_series.values'], {'label': "xlabel_dict['social_average']"}), "(salary_data_series.index, salary_data_series.values, label=\n xlabel_dict['social_average'])\n", (1438, 1533), True, 'import matplotlib.pyplot as plt\n'), ((1558, 1606), 'numpy.array', 'np.array', (["data_frame[xlabel_dict['state_owned']]"], {}), "(data_frame[xlabel_dict['state_owned']])\n", (1566, 1606), True, 'import numpy as np\n'), ((1710, 1810), 'matplotlib.pyplot.plot', 'plt.plot', (['salary_data_series.index', 'salary_data_series.values'], {'label': "xlabel_dict['state_owned']"}), "(salary_data_series.index, salary_data_series.values, label=\n xlabel_dict['state_owned'])\n", (1718, 1810), True, 'import matplotlib.pyplot as plt\n'), ((1810, 1846), 'matplotlib.pyplot.xticks', 'plt.xticks', (['salary_data_series.index'], {}), '(salary_data_series.index)\n', (1820, 1846), True, 'import matplotlib.pyplot as plt\n'), ((1352, 1397), 'pandas.Series', 'pd.Series', (['data_array'], {'index': 'date_list.values'}), '(data_array, index=date_list.values)\n', (1361, 1397), True, 'import pandas as pd\n'), ((1632, 1677), 'pandas.Series', 'pd.Series', (['data_array'], {'index': 'date_list.values'}), '(data_array, index=date_list.values)\n', (1641, 1677), True, 'import pandas as pd\n')] |
import argparse
import time
import cv2
import numpy as np
import tensorflow as tf
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from models import vnect_model as vnect_model
import utils.utils as utils
parser = argparse.ArgumentParser()
parser.add_argument('--device', default='gpu')
parser.add_argument('--demo_type', default='image')
parser.add_argument('--model_file', default='models/weights/vnect_tf')
parser.add_argument('--test_img', default='test_imgs/yuniko.jpg')
parser.add_argument('--input_size', default=368)
parser.add_argument('--num_of_joints', default=21)
parser.add_argument('--pool_scale', default=8)
parser.add_argument('--plot_2d', default=True)
parser.add_argument('--plot_3d', default=True)
args = parser.parse_args()
joint_color_code = [[139, 53, 255],
[0, 56, 255],
[43, 140, 237],
[37, 168, 36],
[147, 147, 0],
[70, 17, 145]]
# Limb parents of each joint
limb_parents = [1, 15, 1, 2, 3, 1, 5, 6, 14, 8, 9, 14, 11, 12, 14, 14, 1, 4, 7, 10, 13]
# input scales
scales = [1.0, 0.7]
# Use gpu or cpu
gpu_count = {'GPU':1} if args.device == 'gpu' else {'GPU':0}
def demo_single_image():
# Create model
model_tf = vnect_model.VNect(args.input_size)
# Create session
sess_config = tf.ConfigProto(device_count=gpu_count)
sess = tf.Session(config=sess_config)
# Restore weights
saver = tf.train.Saver()
saver.restore(sess, args.model_file)
# Joints placeholder
joints_2d = np.zeros(shape=(args.num_of_joints, 2), dtype=np.int32)
joints_3d = np.zeros(shape=(args.num_of_joints, 3), dtype=np.float32)
img_path = args.test_img
t1 = time.time()
input_batch = []
cam_img = utils.read_square_image(img_path, '', args.input_size, 'IMAGE')
orig_size_input = cam_img.astype(np.float32)
# Create multi-scale inputs
for scale in scales:
resized_img = utils.resize_pad_img(orig_size_input, scale, args.input_size)
input_batch.append(resized_img)
input_batch = np.asarray(input_batch, dtype=np.float32)
input_batch /= 255.0
input_batch -= 0.4
# Inference
[hm, x_hm, y_hm, z_hm] = sess.run(
[model_tf.heapmap, model_tf.x_heatmap, model_tf.y_heatmap, model_tf.z_heatmap],
feed_dict={model_tf.input_holder: input_batch})
# Average scale outputs
hm_size = args.input_size // args.pool_scale
hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
x_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
y_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
z_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
for i in range(len(scales)):
rescale = 1.0 / scales[i]
scaled_hm = cv2.resize(hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_x_hm = cv2.resize(x_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_y_hm = cv2.resize(y_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_z_hm = cv2.resize(z_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
mid = [scaled_hm.shape[0] // 2, scaled_hm.shape[1] // 2]
hm_avg += scaled_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
x_hm_avg += scaled_x_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
y_hm_avg += scaled_y_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
z_hm_avg += scaled_z_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
hm_avg /= len(scales)
x_hm_avg /= len(scales)
y_hm_avg /= len(scales)
z_hm_avg /= len(scales)
# Get 2d joints
utils.extract_2d_joint_from_heatmap(hm_avg, args.input_size, joints_2d)
# Get 3d joints
utils.extract_3d_joints_from_heatmap(joints_2d, x_hm_avg, y_hm_avg, z_hm_avg, args.input_size, joints_3d)
if args.plot_2d:
# Plot 2d joint location
joint_map = np.zeros(shape=(args.input_size, args.input_size, 3))
for joint_num in range(joints_2d.shape[0]):
cv2.circle(joint_map, center=(joints_2d[joint_num][1], joints_2d[joint_num][0]), radius=3,
color=(255, 0, 0), thickness=-1)
# Draw 2d limbs
utils.draw_limbs_2d(cam_img, joints_2d, limb_parents)
print('FPS: {:>2.2f}'.format(1 / (time.time() - t1)))
if args.plot_3d:
# Draw 3d limbs
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
utils.draw_limbs_3d_gl(joints_3d, limb_parents)
pygame.display.flip()
pygame.time.wait(1)
if args.plot_2d:
# Display 2d results
concat_img = np.concatenate((cam_img, joint_map), axis=1)
cv2.imshow('2D', concat_img.astype(np.uint8))
cv2.waitKey(0)
def demo_webcam():
# Create model
model_tf = vnect_model.VNect(args.input_size)
# Create session
sess_config = tf.ConfigProto(device_count=gpu_count)
sess = tf.Session(config=sess_config)
# Restore weights
saver = tf.train.Saver()
saver.restore(sess, args.model_file)
# Joints placeholder
joints_2d = np.zeros(shape=(args.num_of_joints, 2), dtype=np.int32)
joints_3d = np.zeros(shape=(args.num_of_joints, 3), dtype=np.float32)
cam = cv2.VideoCapture(0)
while True:
t1 = time.time()
input_batch = []
cam_img = utils.read_square_image('', cam, args.input_size, 'WEBCAM')
orig_size_input = cam_img.astype(np.float32)
# Create multi-scale inputs
for scale in scales:
resized_img = utils.resize_pad_img(orig_size_input, scale, args.input_size)
input_batch.append(resized_img)
input_batch = np.asarray(input_batch, dtype=np.float32)
input_batch /= 255.0
input_batch -= 0.4
# Inference
[hm, x_hm, y_hm, z_hm] = sess.run(
[model_tf.heapmap, model_tf.x_heatmap, model_tf.y_heatmap, model_tf.z_heatmap],
feed_dict={model_tf.input_holder: input_batch})
# Average scale outputs
hm_size = args.input_size // args.pool_scale
hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
x_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
y_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
z_hm_avg = np.zeros(shape=(hm_size, hm_size, args.num_of_joints))
for i in range(len(scales)):
rescale = 1.0 / scales[i]
scaled_hm = cv2.resize(hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_x_hm = cv2.resize(x_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_y_hm = cv2.resize(y_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
scaled_z_hm = cv2.resize(z_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=cv2.INTER_LINEAR)
mid = [scaled_hm.shape[0] // 2, scaled_hm.shape[1] // 2]
hm_avg += scaled_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
x_hm_avg += scaled_x_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
y_hm_avg += scaled_y_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
z_hm_avg += scaled_z_hm[mid[0] - hm_size // 2: mid[0] + hm_size // 2,
mid[1] - hm_size // 2: mid[1] + hm_size // 2, :]
hm_avg /= len(scales)
x_hm_avg /= len(scales)
y_hm_avg /= len(scales)
z_hm_avg /= len(scales)
# Get 2d joints
utils.extract_2d_joint_from_heatmap(hm_avg, args.input_size, joints_2d)
# Get 3d joints
utils.extract_3d_joints_from_heatmap(joints_2d, x_hm_avg, y_hm_avg, z_hm_avg, args.input_size, joints_3d)
if args.plot_2d:
# Plot 2d joint location
joint_map = np.zeros(shape=(args.input_size, args.input_size, 3))
for joint_num in range(joints_2d.shape[0]):
cv2.circle(joint_map, center=(joints_2d[joint_num][1], joints_2d[joint_num][0]), radius=3,
color=(255, 0, 0), thickness=-1)
# Draw 2d limbs
utils.draw_limbs_2d(cam_img, joints_2d, limb_parents)
print('FPS: {:>2.2f}'.format(1 / (time.time() - t1)))
if args.plot_3d:
# Draw 3d limbs
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
utils.draw_limbs_3d_gl(joints_3d, limb_parents)
pygame.display.flip()
pygame.time.wait(1)
if args.plot_2d:
# Display 2d results
concat_img = np.concatenate((cam_img, joint_map), axis=1)
cv2.imshow('2D', concat_img.astype(np.uint8))
if cv2.waitKey(1) == ord('q'): break
if __name__ == '__main__':
# GL initiation
pygame.init()
display = (800, 600)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
gluPerspective(70, (display[0] / display[1]), 0.1, 800.0)
glMatrixMode(GL_MODELVIEW)
gluLookAt(-.0, 0.0, -200.0,
5.0, 0.0, 0.0,
-5.0, -1.0, -10.0)
if args.demo_type == 'image':
demo_single_image()
elif args.demo_type == 'webcam':
demo_webcam()
| [
"utils.utils.resize_pad_img",
"argparse.ArgumentParser",
"tensorflow.ConfigProto",
"utils.utils.draw_limbs_2d",
"pygame.display.set_mode",
"models.vnect_model.VNect",
"utils.utils.extract_2d_joint_from_heatmap",
"cv2.resize",
"cv2.circle",
"utils.utils.extract_3d_joints_from_heatmap",
"tensorflo... | [((259, 284), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (282, 284), False, 'import argparse\n'), ((1295, 1329), 'models.vnect_model.VNect', 'vnect_model.VNect', (['args.input_size'], {}), '(args.input_size)\n', (1312, 1329), True, 'from models import vnect_model as vnect_model\n'), ((1370, 1408), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': 'gpu_count'}), '(device_count=gpu_count)\n', (1384, 1408), True, 'import tensorflow as tf\n'), ((1420, 1450), 'tensorflow.Session', 'tf.Session', ([], {'config': 'sess_config'}), '(config=sess_config)\n', (1430, 1450), True, 'import tensorflow as tf\n'), ((1486, 1502), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1500, 1502), True, 'import tensorflow as tf\n'), ((1586, 1641), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.num_of_joints, 2)', 'dtype': 'np.int32'}), '(shape=(args.num_of_joints, 2), dtype=np.int32)\n', (1594, 1641), True, 'import numpy as np\n'), ((1658, 1715), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.num_of_joints, 3)', 'dtype': 'np.float32'}), '(shape=(args.num_of_joints, 3), dtype=np.float32)\n', (1666, 1715), True, 'import numpy as np\n'), ((1756, 1767), 'time.time', 'time.time', ([], {}), '()\n', (1765, 1767), False, 'import time\n'), ((1804, 1867), 'utils.utils.read_square_image', 'utils.read_square_image', (['img_path', '""""""', 'args.input_size', '"""IMAGE"""'], {}), "(img_path, '', args.input_size, 'IMAGE')\n", (1827, 1867), True, 'import utils.utils as utils\n'), ((2118, 2159), 'numpy.asarray', 'np.asarray', (['input_batch'], {'dtype': 'np.float32'}), '(input_batch, dtype=np.float32)\n', (2128, 2159), True, 'import numpy as np\n'), ((2499, 2553), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (2507, 2553), True, 'import numpy as np\n'), ((2569, 2623), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (2577, 2623), True, 'import numpy as np\n'), ((2639, 2693), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (2647, 2693), True, 'import numpy as np\n'), ((2709, 2763), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (2717, 2763), True, 'import numpy as np\n'), ((4069, 4140), 'utils.utils.extract_2d_joint_from_heatmap', 'utils.extract_2d_joint_from_heatmap', (['hm_avg', 'args.input_size', 'joints_2d'], {}), '(hm_avg, args.input_size, joints_2d)\n', (4104, 4140), True, 'import utils.utils as utils\n'), ((4166, 4275), 'utils.utils.extract_3d_joints_from_heatmap', 'utils.extract_3d_joints_from_heatmap', (['joints_2d', 'x_hm_avg', 'y_hm_avg', 'z_hm_avg', 'args.input_size', 'joints_3d'], {}), '(joints_2d, x_hm_avg, y_hm_avg,\n z_hm_avg, args.input_size, joints_3d)\n', (4202, 4275), True, 'import utils.utils as utils\n'), ((5228, 5262), 'models.vnect_model.VNect', 'vnect_model.VNect', (['args.input_size'], {}), '(args.input_size)\n', (5245, 5262), True, 'from models import vnect_model as vnect_model\n'), ((5303, 5341), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': 'gpu_count'}), '(device_count=gpu_count)\n', (5317, 5341), True, 'import tensorflow as tf\n'), ((5353, 5383), 'tensorflow.Session', 'tf.Session', ([], {'config': 'sess_config'}), '(config=sess_config)\n', (5363, 5383), True, 'import tensorflow as tf\n'), ((5419, 5435), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (5433, 5435), True, 'import tensorflow as tf\n'), ((5519, 5574), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.num_of_joints, 2)', 'dtype': 'np.int32'}), '(shape=(args.num_of_joints, 2), dtype=np.int32)\n', (5527, 5574), True, 'import numpy as np\n'), ((5591, 5648), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.num_of_joints, 3)', 'dtype': 'np.float32'}), '(shape=(args.num_of_joints, 3), dtype=np.float32)\n', (5599, 5648), True, 'import numpy as np\n'), ((5660, 5679), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (5676, 5679), False, 'import cv2\n'), ((9448, 9461), 'pygame.init', 'pygame.init', ([], {}), '()\n', (9459, 9461), False, 'import pygame\n'), ((9545, 9597), 'pygame.display.set_mode', 'pygame.display.set_mode', (['display', '(DOUBLEBUF | OPENGL)'], {}), '(display, DOUBLEBUF | OPENGL)\n', (9568, 9597), False, 'import pygame\n'), ((1997, 2058), 'utils.utils.resize_pad_img', 'utils.resize_pad_img', (['orig_size_input', 'scale', 'args.input_size'], {}), '(orig_size_input, scale, args.input_size)\n', (2017, 2058), True, 'import utils.utils as utils\n'), ((2851, 2946), 'cv2.resize', 'cv2.resize', (['hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (2861, 2946), False, 'import cv2\n'), ((2964, 3061), 'cv2.resize', 'cv2.resize', (['x_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(x_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (2974, 3061), False, 'import cv2\n'), ((3079, 3176), 'cv2.resize', 'cv2.resize', (['y_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(y_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (3089, 3176), False, 'import cv2\n'), ((3194, 3291), 'cv2.resize', 'cv2.resize', (['z_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(z_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (3204, 3291), False, 'import cv2\n'), ((4347, 4400), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.input_size, args.input_size, 3)'}), '(shape=(args.input_size, args.input_size, 3))\n', (4355, 4400), True, 'import numpy as np\n'), ((4644, 4697), 'utils.utils.draw_limbs_2d', 'utils.draw_limbs_2d', (['cam_img', 'joints_2d', 'limb_parents'], {}), '(cam_img, joints_2d, limb_parents)\n', (4663, 4697), True, 'import utils.utils as utils\n'), ((4871, 4918), 'utils.utils.draw_limbs_3d_gl', 'utils.draw_limbs_3d_gl', (['joints_3d', 'limb_parents'], {}), '(joints_3d, limb_parents)\n', (4893, 4918), True, 'import utils.utils as utils\n'), ((4927, 4948), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (4946, 4948), False, 'import pygame\n'), ((4957, 4976), 'pygame.time.wait', 'pygame.time.wait', (['(1)'], {}), '(1)\n', (4973, 4976), False, 'import pygame\n'), ((5049, 5093), 'numpy.concatenate', 'np.concatenate', (['(cam_img, joint_map)'], {'axis': '(1)'}), '((cam_img, joint_map), axis=1)\n', (5063, 5093), True, 'import numpy as np\n'), ((5156, 5170), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (5167, 5170), False, 'import cv2\n'), ((5710, 5721), 'time.time', 'time.time', ([], {}), '()\n', (5719, 5721), False, 'import time\n'), ((5766, 5825), 'utils.utils.read_square_image', 'utils.read_square_image', (['""""""', 'cam', 'args.input_size', '"""WEBCAM"""'], {}), "('', cam, args.input_size, 'WEBCAM')\n", (5789, 5825), True, 'import utils.utils as utils\n'), ((6100, 6141), 'numpy.asarray', 'np.asarray', (['input_batch'], {'dtype': 'np.float32'}), '(input_batch, dtype=np.float32)\n', (6110, 6141), True, 'import numpy as np\n'), ((6517, 6571), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (6525, 6571), True, 'import numpy as np\n'), ((6591, 6645), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (6599, 6645), True, 'import numpy as np\n'), ((6665, 6719), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (6673, 6719), True, 'import numpy as np\n'), ((6739, 6793), 'numpy.zeros', 'np.zeros', ([], {'shape': '(hm_size, hm_size, args.num_of_joints)'}), '(shape=(hm_size, hm_size, args.num_of_joints))\n', (6747, 6793), True, 'import numpy as np\n'), ((8183, 8254), 'utils.utils.extract_2d_joint_from_heatmap', 'utils.extract_2d_joint_from_heatmap', (['hm_avg', 'args.input_size', 'joints_2d'], {}), '(hm_avg, args.input_size, joints_2d)\n', (8218, 8254), True, 'import utils.utils as utils\n'), ((8288, 8397), 'utils.utils.extract_3d_joints_from_heatmap', 'utils.extract_3d_joints_from_heatmap', (['joints_2d', 'x_hm_avg', 'y_hm_avg', 'z_hm_avg', 'args.input_size', 'joints_3d'], {}), '(joints_2d, x_hm_avg, y_hm_avg,\n z_hm_avg, args.input_size, joints_3d)\n', (8324, 8397), True, 'import utils.utils as utils\n'), ((4465, 4593), 'cv2.circle', 'cv2.circle', (['joint_map'], {'center': '(joints_2d[joint_num][1], joints_2d[joint_num][0])', 'radius': '(3)', 'color': '(255, 0, 0)', 'thickness': '(-1)'}), '(joint_map, center=(joints_2d[joint_num][1], joints_2d[joint_num]\n [0]), radius=3, color=(255, 0, 0), thickness=-1)\n', (4475, 4593), False, 'import cv2\n'), ((5971, 6032), 'utils.utils.resize_pad_img', 'utils.resize_pad_img', (['orig_size_input', 'scale', 'args.input_size'], {}), '(orig_size_input, scale, args.input_size)\n', (5991, 6032), True, 'import utils.utils as utils\n'), ((6893, 6988), 'cv2.resize', 'cv2.resize', (['hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (6903, 6988), False, 'import cv2\n'), ((7010, 7107), 'cv2.resize', 'cv2.resize', (['x_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(x_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (7020, 7107), False, 'import cv2\n'), ((7129, 7226), 'cv2.resize', 'cv2.resize', (['y_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(y_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (7139, 7226), False, 'import cv2\n'), ((7248, 7345), 'cv2.resize', 'cv2.resize', (['z_hm[i, :, :, :]', '(0, 0)'], {'fx': 'rescale', 'fy': 'rescale', 'interpolation': 'cv2.INTER_LINEAR'}), '(z_hm[i, :, :, :], (0, 0), fx=rescale, fy=rescale, interpolation=\n cv2.INTER_LINEAR)\n', (7258, 7345), False, 'import cv2\n'), ((8481, 8534), 'numpy.zeros', 'np.zeros', ([], {'shape': '(args.input_size, args.input_size, 3)'}), '(shape=(args.input_size, args.input_size, 3))\n', (8489, 8534), True, 'import numpy as np\n'), ((8798, 8851), 'utils.utils.draw_limbs_2d', 'utils.draw_limbs_2d', (['cam_img', 'joints_2d', 'limb_parents'], {}), '(cam_img, joints_2d, limb_parents)\n', (8817, 8851), True, 'import utils.utils as utils\n'), ((9044, 9091), 'utils.utils.draw_limbs_3d_gl', 'utils.draw_limbs_3d_gl', (['joints_3d', 'limb_parents'], {}), '(joints_3d, limb_parents)\n', (9066, 9091), True, 'import utils.utils as utils\n'), ((9104, 9125), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (9123, 9125), False, 'import pygame\n'), ((9138, 9157), 'pygame.time.wait', 'pygame.time.wait', (['(1)'], {}), '(1)\n', (9154, 9157), False, 'import pygame\n'), ((9242, 9286), 'numpy.concatenate', 'np.concatenate', (['(cam_img, joint_map)'], {'axis': '(1)'}), '((cam_img, joint_map), axis=1)\n', (9256, 9286), True, 'import numpy as np\n'), ((8607, 8735), 'cv2.circle', 'cv2.circle', (['joint_map'], {'center': '(joints_2d[joint_num][1], joints_2d[joint_num][0])', 'radius': '(3)', 'color': '(255, 0, 0)', 'thickness': '(-1)'}), '(joint_map, center=(joints_2d[joint_num][1], joints_2d[joint_num]\n [0]), radius=3, color=(255, 0, 0), thickness=-1)\n', (8617, 8735), False, 'import cv2\n'), ((9360, 9374), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (9371, 9374), False, 'import cv2\n'), ((4738, 4749), 'time.time', 'time.time', ([], {}), '()\n', (4747, 4749), False, 'import time\n'), ((8895, 8906), 'time.time', 'time.time', ([], {}), '()\n', (8904, 8906), False, 'import time\n')] |
# encoding: utf-8
"""
Interactive Data Visualization classes for Scene, Camera and BlockCollection
"""
# ----------------------------------------------------------------------------
# Copyright (c) 2016, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
# This is a part of the experimental Interactive Data Visualization
import OpenGL.GL as GL
from collections import OrderedDict
import matplotlib.cm as cm
import numpy as np
import ctypes
from yt.config import \
ytcfg
from yt.utilities.math_utils import \
get_translate_matrix, \
get_scale_matrix, \
get_lookat_matrix, \
get_perspective_matrix, \
quaternion_mult, \
quaternion_to_rotation_matrix, \
rotation_matrix_to_quaternion
from yt.utilities.lib.mesh_triangulation import triangulate_mesh
from .shader_objects import known_shaders, ShaderProgram
bbox_vertices = np.array(
[[ 0., 0., 0., 1.],
[ 0., 0., 1., 1.],
[ 0., 1., 1., 1.],
[ 1., 1., 0., 1.],
[ 0., 0., 0., 1.],
[ 0., 1., 0., 1.],
[ 1., 0., 1., 1.],
[ 0., 0., 0., 1.],
[ 1., 0., 0., 1.],
[ 1., 1., 0., 1.],
[ 1., 0., 0., 1.],
[ 0., 0., 0., 1.],
[ 0., 0., 0., 1.],
[ 0., 1., 1., 1.],
[ 0., 1., 0., 1.],
[ 1., 0., 1., 1.],
[ 0., 0., 1., 1.],
[ 0., 0., 0., 1.],
[ 0., 1., 1., 1.],
[ 0., 0., 1., 1.],
[ 1., 0., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 0., 0., 1.],
[ 1., 1., 0., 1.],
[ 1., 0., 0., 1.],
[ 1., 1., 1., 1.],
[ 1., 0., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 0., 1.],
[ 0., 1., 0., 1.],
[ 1., 1., 1., 1.],
[ 0., 1., 0., 1.],
[ 0., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 0., 1., 1., 1.],
[ 1., 0., 1., 1.]], dtype=np.float32)
FULLSCREEN_QUAD = np.array(
[-1.0, -1.0, 0.0,
+1.0, -1.0, 0.0,
-1.0, +1.0, 0.0,
-1.0, +1.0, 0.0,
+1.0, -1.0, 0.0,
+1.0, +1.0, 0.0], dtype=np.float32
)
class IDVCamera(object):
'''Camera object used in the Interactive Data Visualization
Parameters
----------
position : :obj:`!iterable`, or 3 element array in code_length
The initial position of the camera.
focus : :obj:`!iterable`, or 3 element array in code_length
A point in space that the camera is looking at.
up : :obj:`!iterable`, or 3 element array in code_length
The 'up' direction for the camera.
fov : float, optional
An angle defining field of view in degrees.
near_plane : float, optional
The distance to the near plane of the perspective camera.
far_plane : float, optional
The distance to the far plane of the perspective camera.
aspect_ratio: float, optional
The ratio between the height and the width of the camera's fov.
'''
def __init__(self,
position=(0.0, 0.0, 1.0),
focus=(0.0, 0.0, 0.0),
up=(0.0, 1.0, 0.0),
fov=45.0, near_plane=0.01, far_plane=20.0,
aspect_ratio=8.0/6.0):
self.position = np.array(position)
self.focus = np.array(focus)
self.up = np.array(up)
self.fov = fov
self.near_plane = near_plane
self.far_plane = far_plane
self.aspect_ratio = aspect_ratio
# set cmap
cmap = cm.get_cmap(ytcfg.get("yt", "default_colormap"))
self.cmap = np.array(cmap(np.linspace(0, 1, 256)), dtype=np.float32)
self.cmap_min = 1e55
self.cmap_max = -1e55
self.cmap_log = True
self.cmap_new = True
self.view_matrix = np.zeros((4, 4), dtype=np.float32)
self.projection_matrix = np.zeros((4, 4), dtype=np.float32)
self.orientation = np.zeros((4, 4), dtype=np.float32)
self.proj_func = get_perspective_matrix
def compute_matrices(self):
'''Regenerate all position, view and projection matrices of the camera.'''
pass
def update_orientation(self, start_x, start_y, end_x, end_y):
'''Change camera orientation matrix using delta of mouse's cursor position
Parameters
----------
start_x : float
initial cursor position in x direction
start_y : float
initial cursor position in y direction
end_x : float
final cursor position in x direction
end_y : float
final cursor position in y direction
'''
pass
def get_viewpoint(self):
return self.position
def get_view_matrix(self):
return self.view_matrix
def get_projection_matrix(self):
return self.projection_matrix
def update_cmap_minmax(self, minval, maxval, iflog):
'''Update camera's colormap bounds
Parameters
----------
minval: float
min color limit used for image scaling
maxval: float
max color limit used for image scaling
iflog: boolean
Set to True if colormap is using log scale, False for linear scale.
'''
self.cmap_log = iflog
self.cmap_min = minval
self.cmap_max = maxval
class TrackballCamera(IDVCamera):
"""
This class implements a basic "Trackball" or "Arcball" camera control system
that allows for unconstrained 3D rotations without suffering from Gimbal lock.
Following Ken Shoemake's orginal C implementation (Graphics Gems IV, III.1)
we project mouse movements onto the unit sphere and use quaternions to
represent the corresponding rotation.
See also:
https://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_Arcball
"""
def __init__(self, position=(0.0, 0.0, 1.0), focus=(0.0, 0.0, 0.0),
up=(0.0, 1.0, 0.0), fov=45.0, near_plane=0.01, far_plane=20.0,
aspect_ratio=8.0/6.0):
super(TrackballCamera, self).__init__(position=position, focus=focus,
up=up, fov=fov,
near_plane=near_plane,
far_plane=far_plane,
aspect_ratio=aspect_ratio)
self.view_matrix = get_lookat_matrix(self.position,
self.focus,
self.up)
rotation_matrix = self.view_matrix[0:3,0:3]
self.orientation = rotation_matrix_to_quaternion(rotation_matrix)
def _map_to_surface(self, mouse_x, mouse_y):
# right now this just maps to the surface of the unit sphere
x, y = mouse_x, mouse_y
mag = np.sqrt(x*x + y*y)
if (mag > 1.0):
x /= mag
y /= mag
z = 0.0
else:
z = np.sqrt(1.0 - mag**2)
return np.array([x, -y, z])
def update_orientation(self, start_x, start_y, end_x, end_y):
old = self._map_to_surface(start_x, start_y)
new = self._map_to_surface(end_x, end_y)
# dot product controls the angle of the rotation
w = old[0]*new[0] + old[1]*new[1] + old[2]*new[2]
# cross product gives the rotation axis
x = old[1]*new[2] - old[2]*new[1]
y = old[2]*new[0] - old[0]*new[2]
z = old[0]*new[1] - old[1]*new[0]
q = np.array([w, x, y, z])
#renormalize to prevent floating point issues
mag = np.sqrt(w**2 + x**2 + y**2 + z**2)
q /= mag
self.orientation = quaternion_mult(self.orientation, q)
def compute_matrices(self):
rotation_matrix = quaternion_to_rotation_matrix(self.orientation)
dp = np.linalg.norm(self.position - self.focus)*rotation_matrix[2]
self.position = dp + self.focus
self.up = rotation_matrix[1]
self.view_matrix = get_lookat_matrix(self.position,
self.focus,
self.up)
self.projection_matrix = self.proj_func(self.fov,
self.aspect_ratio,
self.near_plane,
self.far_plane)
class SceneComponent(object):
"""A class that defines basic OpenGL object
This class contains the largest common set of features that every object in
the OpenGL rendering uses: a set of vertices, a set of vertex attributes and
a shader program to operate on them.
"""
name = None
_program = None
_program_invalid = True
fragment_shader = None
vertex_shader = None
def __init__(self):
self.vert_attrib = OrderedDict()
self.vert_arrays = OrderedDict()
@property
def program(self):
if self._program_invalid:
if self._program is not None:
self._program.delete_program()
self._program = ShaderProgram(self.vertex_shader,
self.fragment_shader)
self._program_invalid = False
return self._program
def _initialize_vertex_array(self, name):
if name in self.vert_arrays:
GL.glDeleteVertexArrays(1, [self.vert_arrays[name]])
self.vert_arrays[name] = GL.glGenVertexArrays(1)
def run_program(self):
with self.program.enable():
if len(self.vert_arrays) != 1:
raise NotImplementedError
for vert_name in self.vert_arrays:
GL.glBindVertexArray(self.vert_arrays[vert_name])
for an in self.vert_attrib:
bind_loc, size = self.vert_attrib[an]
self.program.bind_vert_attrib(an, bind_loc, size)
self._set_uniforms(self.program)
self.draw()
for an in self.vert_attrib:
self.program.disable_vert_attrib(an)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def add_vert_attrib(self, name, arr, each):
self.vert_attrib[name] = (GL.glGenBuffers(1), each)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vert_attrib[name][0])
GL.glBufferData(GL.GL_ARRAY_BUFFER, arr.nbytes, arr, GL.GL_STATIC_DRAW)
def set_shader(self, name):
r""" Compiles and links a fragment shader from a set of known shaders.
Parameters
----------
name : String
The name of the fragment shader to use.
"""
shader = known_shaders[name]()
if shader.shader_type == "vertex":
self.vertex_shader = shader
elif shader.shader_type == "fragment":
self.fragment_shader = shader
else:
raise KeyError(shader.shader_type)
self._program_invalid = True
class BlockCollection(SceneComponent):
name = "block_collection"
def __init__(self, scale=False):
'''Class responsible for converting yt data objects into a set of 3D textures
Parameters
----------
scale : boolean, optional
Rescale the data passed to the texture from 0 to 1
'''
self.scale = scale
super(BlockCollection, self).__init__()
self.set_shader("default.v")
self.set_shader("max_intensity.f")
self.data_source = None
self.blocks = {} # A collection of PartionedGrid objects
self.block_order = []
self.gl_texture_names = []
self.redraw = True
self.geometry_loaded = False
self.camera = None
GL.glEnable(GL.GL_CULL_FACE)
GL.glCullFace(GL.GL_BACK)
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glDepthFunc(GL.GL_LESS)
self._init_blending()
def _init_blending(self):
GL.glEnable(GL.GL_BLEND)
GL.glBlendColor(1.0, 1.0, 1.0, 1.0)
GL.glBlendFunc(GL.GL_ONE, GL.GL_ONE)
GL.glBlendEquation(GL.GL_MAX)
def set_fields_log(self, log_field):
"""Switch between a logarithmic and a linear scale for the data.
Parameters
----------
log_field : boolean
If set to True log10 will be applied to data before passing it to GPU.
"""
self.add_data(self.data_source, self.data_source.tiles.fields[0], log_field)
def add_data(self, data_source, field, log_field=True):
r"""Adds a source of data for the block collection.
Given a `data_source` and a `field` to populate from, adds the data
to the block collection so that is able to be rendered.
Parameters
----------
data_source : YTRegion
A YTRegion object to use as a data source.
field : string
A field to populate from.
log_field : boolean, optional
If set to True log10 will be applied to data before passing it to GPU.
"""
self.data_source = data_source
self.data_source.tiles.set_fields([field], [log_field], no_ghost=False)
self.data_logged = log_field
self.blocks = {}
self.block_order = []
# Every time we change our data source, we wipe all existing ones.
# We now set up our vertices into our current data source.
vert, dx, le, re = [], [], [], []
self.min_val = 1e60
self.max_val = -1e60
if self.scale:
left_min = np.ones(3, "f8") * np.inf
right_max = np.ones(3, "f8") * -np.inf
for block in self.data_source.tiles.traverse():
np.minimum(left_min, block.LeftEdge, left_min)
np.maximum(right_max, block.LeftEdge, right_max)
scale = right_max.max() - left_min.min()
for block in self.data_source.tiles.traverse():
block.LeftEdge -= left_min
block.LeftEdge /= scale
block.RightEdge -= left_min
block.RightEdge /= scale
for i, block in enumerate(self.data_source.tiles.traverse()):
self.min_val = min(self.min_val, np.nanmin(block.my_data[0].min()))
self.max_val = max(self.max_val, np.nanmax(block.my_data[0].max()))
self.blocks[id(block)] = (i, block)
vert.append(self._compute_geometry(block, bbox_vertices))
dds = (block.RightEdge - block.LeftEdge)/block.my_data[0].shape
n = int(vert[-1].size) // 4
dx.append([dds.astype('f4') for _ in range(n)])
le.append([block.LeftEdge.astype('f4') for _ in range(n)])
re.append([block.RightEdge.astype('f4') for _ in range(n)])
self.block_order.append(id(block))
LE = np.array([b.LeftEdge
for i, b in self.blocks.values()]).min(axis=0)
RE = np.array([b.RightEdge
for i, b in self.blocks.values()]).max(axis=0)
self.diagonal = np.sqrt(((RE - LE) ** 2).sum())
# Now we set up our buffer
vert = np.concatenate(vert)
dx = np.concatenate(dx)
le = np.concatenate(le)
re = np.concatenate(re)
self._initialize_vertex_array("block_info")
self.add_vert_attrib("model_vertex", vert, 4)
self.add_vert_attrib("in_dx", dx, 3)
self.add_vert_attrib("in_left_edge", le, 3)
self.add_vert_attrib("in_right_edge", re, 3)
# Now we set up our textures
self._load_textures()
def set_camera(self, camera):
r"""Sets the camera for the block collection.
Parameters
----------
camera : :class:`~yt.visualization.volume_rendering.interactive_vr.IDVCamera`
A simple camera object.
"""
self.block_order = []
for block in self.data_source.tiles.traverse(viewpoint = camera.position):
self.block_order.append(id(block))
self.camera = camera
self.redraw = True
def draw(self):
r"""Runs a given shader program on the block collection. It is assumed
that the GL Context has been set up, which is typically handled by the
run_program method.
"""
# clear the color and depth buffer
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
GL.glActiveTexture(GL.GL_TEXTURE0)
for bi in self.block_order:
tex_i, block = self.blocks[bi]
ti = self.gl_texture_names[tex_i]
GL.glBindTexture(GL.GL_TEXTURE_3D, ti)
GL.glDrawArrays(GL.GL_TRIANGLES, tex_i*36, 36)
def _set_uniforms(self, shader_program):
shader_program._set_uniform("projection",
self.camera.get_projection_matrix())
shader_program._set_uniform("lookat",
self.camera.get_view_matrix())
shader_program._set_uniform("viewport",
np.array(GL.glGetIntegerv(GL.GL_VIEWPORT), dtype = 'f4'))
shader_program._set_uniform("camera_pos",
self.camera.position)
def _compute_geometry(self, block, bbox_vertices):
move = get_translate_matrix(*block.LeftEdge)
dds = (block.RightEdge - block.LeftEdge)
scale = get_scale_matrix(*dds)
transformed_box = bbox_vertices.dot(scale.T).dot(move.T).astype("float32")
return transformed_box
def _load_textures(self):
print("Loading textures.")
if len(self.gl_texture_names) == 0:
self.gl_texture_names = GL.glGenTextures(len(self.blocks))
if len(self.blocks) == 1:
self.gl_texture_names = [self.gl_texture_names]
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
GL.glTexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
GL.glTexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MIN_FILTER,
GL.GL_LINEAR)
else:
for texture in self.gl_texture_names:
GL.glDeleteTextures([texture])
self.gl_texture_names = GL.glGenTextures(len(self.blocks))
if len(self.blocks) == 1:
self.gl_texture_names = [self.gl_texture_names]
for block_id in sorted(self.blocks):
tex_i, block = self.blocks[block_id]
texture_name = self.gl_texture_names[tex_i]
dx, dy, dz = block.my_data[0].shape
n_data = block.my_data[0].copy(order="F").astype("float32")
n_data = (n_data - self.min_val) / ((self.max_val - self.min_val) * self.diagonal)
GL.glBindTexture(GL.GL_TEXTURE_3D, texture_name)
GL.glTexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE)
GL.glTexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)
GL.glTexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_R, GL.GL_CLAMP_TO_EDGE)
GL.glTexStorage3D(GL.GL_TEXTURE_3D, 1, GL.GL_R32F,
*block.my_data[0].shape)
GL.glTexSubImage3D(GL.GL_TEXTURE_3D, 0, 0, 0, 0, dx, dy, dz,
GL.GL_RED, GL.GL_FLOAT, n_data.T)
GL.glGenerateMipmap(GL.GL_TEXTURE_3D)
class ColorBarSceneComponent(SceneComponent):
'''
A class for scene components that apply colorbars using a 1D texture.
'''
def __init__(self):
super(ColorBarSceneComponent, self).__init__()
self.camera = None
self.cmap_texture = None
def set_camera(self, camera):
pass
def update_minmax(self):
pass
def setup_cmap_tex(self):
'''Creates 1D texture that will hold colormap in framebuffer'''
self.cmap_texture = GL.glGenTextures(1) # create target texture
GL.glBindTexture(GL.GL_TEXTURE_1D, self.cmap_texture)
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
GL.glTexParameterf(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE)
GL.glTexParameteri(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
GL.glTexImage1D(GL.GL_TEXTURE_1D, 0, GL.GL_RGBA, 256,
0, GL.GL_RGBA, GL.GL_FLOAT, self.camera.cmap)
GL.glBindTexture(GL.GL_TEXTURE_1D, 0)
def update_cmap_tex(self):
'''Updates 1D texture with colormap that's used in framebuffer'''
if self.camera is None or not self.camera.cmap_new:
return
if self.cmap_texture is None:
self.setup_cmap_tex()
GL.glBindTexture(GL.GL_TEXTURE_1D, self.cmap_texture)
GL.glTexSubImage1D(GL.GL_TEXTURE_1D, 0, 0, 256,
GL.GL_RGBA, GL.GL_FLOAT, self.camera.cmap)
self.camera.cmap_new = False
class MeshSceneComponent(ColorBarSceneComponent):
'''
A scene component for representing unstructured mesh data.
'''
def __init__(self, data_source, field):
super(MeshSceneComponent, self).__init__()
self.set_shader("mesh.v")
self.set_shader("mesh.f")
self.data_source = None
self.redraw = True
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glDepthFunc(GL.GL_LESS)
GL.glEnable(GL.GL_CULL_FACE)
GL.glCullFace(GL.GL_BACK)
vertices, data, indices = self.get_mesh_data(data_source, field)
self._initialize_vertex_array("mesh_info")
GL.glBindVertexArray(self.vert_arrays["mesh_info"])
self.add_vert_attrib("vertex_buffer", vertices, vertices.size)
self.add_vert_attrib("data_buffer", data, data.size)
self.vert_attrib["element_buffer"] = (GL.glGenBuffers(1), indices.size)
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.vert_attrib["element_buffer"][0])
GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL.GL_STATIC_DRAW)
self.transform_matrix = GL.glGetUniformLocation(self.program.program,
"model_to_clip")
self.cmin = data.min()
self.cmax = data.max()
def set_camera(self, camera):
r""" Sets the camera orientation for the entire scene.
Parameters
----------
camera : :class:`~yt.visualization.volume_rendering.interactive_vr.IDVCamera`
"""
self.camera = camera
self.camera.cmap_min = float(self.cmin)
self.camera.cmap_max = float(self.cmax)
self.redraw = True
def get_mesh_data(self, data_source, field):
"""
This reads the mesh data into a form that can be fed in to OpenGL.
"""
# get mesh information
try:
ftype, fname = field
mesh_id = int(ftype[-1])
except ValueError:
mesh_id = 0
mesh = data_source.ds.index.meshes[mesh_id-1]
offset = mesh._index_offset
vertices = mesh.connectivity_coords
indices = mesh.connectivity_indices - offset
data = data_source[field]
return triangulate_mesh(vertices, data, indices)
def run_program(self):
""" Renders one frame of the scene. """
with self.program.enable():
# Handle colormap
self.update_cmap_tex()
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
projection_matrix = self.camera.projection_matrix
view_matrix = self.camera.view_matrix
model_to_clip = np.dot(projection_matrix, view_matrix)
GL.glUniformMatrix4fv(self.transform_matrix, 1, True, model_to_clip)
GL.glActiveTexture(GL.GL_TEXTURE1)
GL.glBindTexture(GL.GL_TEXTURE_1D, self.cmap_texture)
self.program._set_uniform("cmap", 0)
self.program._set_uniform("cmap_min", self.camera.cmap_min)
self.program._set_uniform("cmap_max", self.camera.cmap_max)
GL.glEnableVertexAttribArray(0)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vert_attrib["vertex_buffer"][0])
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glEnableVertexAttribArray(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.vert_attrib["data_buffer"][0])
GL.glVertexAttribPointer(1, 1, GL.GL_FLOAT, False, 0, ctypes.c_void_p(0))
GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, self.vert_attrib["element_buffer"][0])
GL.glDrawElements(GL.GL_TRIANGLES, self.vert_attrib["element_buffer"][1],
GL.GL_UNSIGNED_INT, ctypes.c_void_p(0))
GL.glDisableVertexAttribArray(0)
GL.glDisableVertexAttribArray(1)
render = run_program
class SceneGraph(ColorBarSceneComponent):
"""A basic OpenGL render for IDV.
The SceneGraph class is the primary driver behind creating a IDV rendering.
It is responsible for performing two pass volume rendering: firstly ray
casting through the BlockCollection into 2D Texture that is stored into a
framebuffer, secondly performing a fragment shader based modification of
the 2D texture from the first pass before showing it in the interactive
window.
Parameters
----------
None
"""
def __init__(self):
super(SceneGraph, self).__init__()
self.collections = []
self.fbo = None
self.fb_texture = None
self.shader_program = None
self.fb_shader_program = None
self.min_val, self.max_val = 1e60, -1e60
self.diagonal = 0.0
self.data_logged = True
ox, oy, width, height = GL.glGetIntegerv(GL.GL_VIEWPORT)
self.width = width
self.height = height
self.set_shader("passthrough.v")
self.set_shader("apply_colormap.f")
self._init_framebuffer()
def _init_framebuffer(self):
self._initialize_vertex_array("fb_vbo")
GL.glBindVertexArray(self.vert_arrays["fb_vbo"])
quad_attrib = GL.glGenBuffers(1)
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, quad_attrib)
GL.glBufferData(GL.GL_ARRAY_BUFFER, FULLSCREEN_QUAD.nbytes,
FULLSCREEN_QUAD, GL.GL_STATIC_DRAW)
GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None)
# unbind
GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
GL.glBindVertexArray(0)
self.setup_fb(self.width, self.height)
def setup_fb(self, width, height):
'''Sets up FrameBuffer that will be used as container
for 1 pass of rendering'''
# Clean up old FB and Texture
if self.fb_texture is not None and \
GL.glIsTexture(self.fb_texture):
GL.glDeleteTextures([self.fb_texture])
if self.fbo is not None and GL.glIsFramebuffer(self.fbo):
GL.glDeleteFramebuffers(1, [self.fbo])
# initialize FrameBuffer
self.fbo = GL.glGenFramebuffers(1)
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.fbo)
depthbuffer = GL.glGenRenderbuffers(1)
GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, depthbuffer)
GL.glRenderbufferStorage(GL.GL_RENDERBUFFER, GL.GL_DEPTH_COMPONENT32F,
width, height)
GL.glFramebufferRenderbuffer(
GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.GL_RENDERBUFFER,
depthbuffer
)
# end of FrameBuffer initialization
# generate the texture we render to, and set parameters
self.fb_texture = GL.glGenTextures(1) # create target texture
# bind to new texture, all future texture functions will modify this
# particular one
GL.glBindTexture(GL.GL_TEXTURE_2D, self.fb_texture)
# set how our texture behaves on x,y boundaries
GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT)
GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT)
# set how our texture is filtered
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)
GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)
# occupy width x height texture memory, (None at the end == empty
# image)
GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F, width,
height, 0, GL.GL_RGBA, GL.GL_FLOAT, None)
# --- end texture init
# Set "fb_texture" as our colour attachement #0
GL.glFramebufferTexture2D(
GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D,
self.fb_texture,
0 # mipmap level, normally 0
)
# verify that everything went well
status = GL.glCheckFramebufferStatus(GL.GL_FRAMEBUFFER)
assert status == GL.GL_FRAMEBUFFER_COMPLETE, status
def add_collection(self, collection):
r"""Adds a block collection to the scene. Collections must not overlap.
Although it hasn't been tested, this should allow one to add multiple
datasets to a single scene.
Parameters
----------
collection : BlockCollection
A block collection object representing a data-set. Behavior is
undefined if any collection overlaps with another.
"""
self.collections.append(collection)
self.update_minmax()
def update_minmax(self):
self.min_val, self.max_val, self.diagonal = 1e60, -1e60, -1e60
self.data_logged = False
for collection in self.collections:
self.min_val = min(self.min_val, collection.min_val)
self.max_val = max(self.max_val, collection.max_val)
# doesn't make sense for multiple collections
self.diagonal = max(self.diagonal, collection.diagonal)
self.data_logged = self.data_logged or collection.data_logged
if self.camera is not None:
self.camera.update_cmap_minmax(self.min_val, self.max_val,
self.data_logged)
def set_camera(self, camera):
r""" Sets the camera orientation for the entire scene.
Upon calling this function a kd-tree is constructed for each collection.
This function simply calls the BlockCollection set_camera function on
each collection in the scene.
Parameters
----------
camera : :class:`~yt.visualization.volume_rendering.interactive_vr.IDVCamera`
"""
self.camera = camera
for collection in self.collections:
collection.set_camera(camera)
def _retrieve_framebuffer(self):
ox, oy, width, height = GL.glGetIntegerv(GL.GL_VIEWPORT)
debug_buffer = GL.glReadPixels(0, 0, width, height, GL.GL_RGB,
GL.GL_UNSIGNED_BYTE)
arr = np.fromstring(debug_buffer, "uint8", count = width*height*3)
return arr.reshape((width, height, 3))
def run_program(self):
""" Renders one frame of the scene.
Renders the scene using the current collection and camera set by calls
to add_collection and set_camera respectively. Also uses the last shader
provided to the add_shader_from_file function.
"""
# get size of current viewport
ox, oy, width, height = GL.glGetIntegerv(GL.GL_VIEWPORT)
if (width, height) != (self.width, self.height):
# size of viewport changed => fb needs to be recreated
self.setup_fb(width, height)
self.width = width
self.width = height
# Handle colormap
self.update_cmap_tex()
# bind to fb
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, self.fbo)
# clear the color and depth buffer
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
# render collections to fb
for collection in self.collections:
collection.run_program()
# unbind FB
GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0)
# 2 pass of rendering
GL.glUseProgram(self.program.program)
GL.glActiveTexture(GL.GL_TEXTURE0)
# bind to the result of 1 pass
GL.glBindTexture(GL.GL_TEXTURE_2D, self.fb_texture)
# Set our "fb_texture" sampler to user Texture Unit 0
self.program._set_uniform("fb_texture", 0)
GL.glActiveTexture(GL.GL_TEXTURE1)
GL.glBindTexture(GL.GL_TEXTURE_1D, self.cmap_texture)
self.program._set_uniform("cmap", 1)
scale = (self.max_val - self.min_val) * self.diagonal
self.program._set_uniform("min_val", self.min_val)
self.program._set_uniform("scale", scale)
self.program._set_uniform("cmap_min", self.camera.cmap_min)
self.program._set_uniform("cmap_max", self.camera.cmap_max)
if self.data_logged:
self.program._set_uniform("cmap_log", float(False))
else:
self.program._set_uniform("cmap_log", float(self.camera.cmap_log))
# clear the color and depth buffer
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
# Bind to Vertex array that contains simple quad filling fullscreen,
# that was defined in __init__()
GL.glBindVertexArray(self.vert_arrays["fb_vbo"])
GL.glEnableVertexAttribArray(0)
# Draw our 2 triangles
GL.glDrawArrays(GL.GL_TRIANGLES, 0, 6)
# Clean up
GL.glDisableVertexAttribArray(0)
GL.glBindVertexArray(0)
GL.glBindTexture(GL.GL_TEXTURE_1D, 0)
GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
render = run_program
| [
"OpenGL.GL.glBindFramebuffer",
"numpy.maximum",
"OpenGL.GL.glBlendEquation",
"OpenGL.GL.glBindTexture",
"OpenGL.GL.glGetIntegerv",
"OpenGL.GL.glGenBuffers",
"OpenGL.GL.glBlendColor",
"OpenGL.GL.glFramebufferRenderbuffer",
"OpenGL.GL.glVertexAttribPointer",
"numpy.ones",
"OpenGL.GL.glBindVertexAr... | [((1050, 1919), 'numpy.array', 'np.array', (['[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [1.0, \n 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, \n 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 0.0, \n 1.0], [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0],\n [0.0, 1.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0], [0.0,\n 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 1.0], [0.0, 0.0, \n 1.0, 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 0.0, 0.0, \n 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0],\n [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0], [0.0,\n 1.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 1.0, \n 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0]\n ]'], {'dtype': 'np.float32'}), '([[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0],\n [1.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0,\n 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, \n 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, \n 1.0], [0.0, 1.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 1.0], [0.0,\n 0.0, 1.0, 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 0.0, \n 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, \n 1.0], [1.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0],\n [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0,\n 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0], [1.0, 0.0, \n 1.0, 1.0]], dtype=np.float32)\n', (1058, 1919), True, 'import numpy as np\n'), ((2142, 2277), 'numpy.array', 'np.array', (['[-1.0, -1.0, 0.0, +1.0, -1.0, 0.0, -1.0, +1.0, 0.0, -1.0, +1.0, 0.0, +1.0, \n -1.0, 0.0, +1.0, +1.0, 0.0]'], {'dtype': 'np.float32'}), '([-1.0, -1.0, 0.0, +1.0, -1.0, 0.0, -1.0, +1.0, 0.0, -1.0, +1.0, \n 0.0, +1.0, -1.0, 0.0, +1.0, +1.0, 0.0], dtype=np.float32)\n', (2150, 2277), True, 'import numpy as np\n'), ((3417, 3435), 'numpy.array', 'np.array', (['position'], {}), '(position)\n', (3425, 3435), True, 'import numpy as np\n'), ((3457, 3472), 'numpy.array', 'np.array', (['focus'], {}), '(focus)\n', (3465, 3472), True, 'import numpy as np\n'), ((3491, 3503), 'numpy.array', 'np.array', (['up'], {}), '(up)\n', (3499, 3503), True, 'import numpy as np\n'), ((3954, 3988), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {'dtype': 'np.float32'}), '((4, 4), dtype=np.float32)\n', (3962, 3988), True, 'import numpy as np\n'), ((4022, 4056), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {'dtype': 'np.float32'}), '((4, 4), dtype=np.float32)\n', (4030, 4056), True, 'import numpy as np\n'), ((4084, 4118), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {'dtype': 'np.float32'}), '((4, 4), dtype=np.float32)\n', (4092, 4118), True, 'import numpy as np\n'), ((6603, 6656), 'yt.utilities.math_utils.get_lookat_matrix', 'get_lookat_matrix', (['self.position', 'self.focus', 'self.up'], {}), '(self.position, self.focus, self.up)\n', (6620, 6656), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((6827, 6873), 'yt.utilities.math_utils.rotation_matrix_to_quaternion', 'rotation_matrix_to_quaternion', (['rotation_matrix'], {}), '(rotation_matrix)\n', (6856, 6873), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((7039, 7061), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y)'], {}), '(x * x + y * y)\n', (7046, 7061), True, 'import numpy as np\n'), ((7211, 7231), 'numpy.array', 'np.array', (['[x, -y, z]'], {}), '([x, -y, z])\n', (7219, 7231), True, 'import numpy as np\n'), ((7705, 7727), 'numpy.array', 'np.array', (['[w, x, y, z]'], {}), '([w, x, y, z])\n', (7713, 7727), True, 'import numpy as np\n'), ((7797, 7839), 'numpy.sqrt', 'np.sqrt', (['(w ** 2 + x ** 2 + y ** 2 + z ** 2)'], {}), '(w ** 2 + x ** 2 + y ** 2 + z ** 2)\n', (7804, 7839), True, 'import numpy as np\n'), ((7877, 7913), 'yt.utilities.math_utils.quaternion_mult', 'quaternion_mult', (['self.orientation', 'q'], {}), '(self.orientation, q)\n', (7892, 7913), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((7973, 8020), 'yt.utilities.math_utils.quaternion_to_rotation_matrix', 'quaternion_to_rotation_matrix', (['self.orientation'], {}), '(self.orientation)\n', (8002, 8020), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((8201, 8254), 'yt.utilities.math_utils.get_lookat_matrix', 'get_lookat_matrix', (['self.position', 'self.focus', 'self.up'], {}), '(self.position, self.focus, self.up)\n', (8218, 8254), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((9059, 9072), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9070, 9072), False, 'from collections import OrderedDict\n'), ((9100, 9113), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9111, 9113), False, 'from collections import OrderedDict\n'), ((9628, 9651), 'OpenGL.GL.glGenVertexArrays', 'GL.glGenVertexArrays', (['(1)'], {}), '(1)\n', (9648, 9651), True, 'import OpenGL.GL as GL\n'), ((10404, 10466), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', 'self.vert_attrib[name][0]'], {}), '(GL.GL_ARRAY_BUFFER, self.vert_attrib[name][0])\n', (10419, 10466), True, 'import OpenGL.GL as GL\n'), ((10475, 10546), 'OpenGL.GL.glBufferData', 'GL.glBufferData', (['GL.GL_ARRAY_BUFFER', 'arr.nbytes', 'arr', 'GL.GL_STATIC_DRAW'], {}), '(GL.GL_ARRAY_BUFFER, arr.nbytes, arr, GL.GL_STATIC_DRAW)\n', (10490, 10546), True, 'import OpenGL.GL as GL\n'), ((11867, 11895), 'OpenGL.GL.glEnable', 'GL.glEnable', (['GL.GL_CULL_FACE'], {}), '(GL.GL_CULL_FACE)\n', (11878, 11895), True, 'import OpenGL.GL as GL\n'), ((11904, 11929), 'OpenGL.GL.glCullFace', 'GL.glCullFace', (['GL.GL_BACK'], {}), '(GL.GL_BACK)\n', (11917, 11929), True, 'import OpenGL.GL as GL\n'), ((11938, 11967), 'OpenGL.GL.glEnable', 'GL.glEnable', (['GL.GL_DEPTH_TEST'], {}), '(GL.GL_DEPTH_TEST)\n', (11949, 11967), True, 'import OpenGL.GL as GL\n'), ((11976, 12002), 'OpenGL.GL.glDepthFunc', 'GL.glDepthFunc', (['GL.GL_LESS'], {}), '(GL.GL_LESS)\n', (11990, 12002), True, 'import OpenGL.GL as GL\n'), ((12073, 12097), 'OpenGL.GL.glEnable', 'GL.glEnable', (['GL.GL_BLEND'], {}), '(GL.GL_BLEND)\n', (12084, 12097), True, 'import OpenGL.GL as GL\n'), ((12106, 12141), 'OpenGL.GL.glBlendColor', 'GL.glBlendColor', (['(1.0)', '(1.0)', '(1.0)', '(1.0)'], {}), '(1.0, 1.0, 1.0, 1.0)\n', (12121, 12141), True, 'import OpenGL.GL as GL\n'), ((12150, 12186), 'OpenGL.GL.glBlendFunc', 'GL.glBlendFunc', (['GL.GL_ONE', 'GL.GL_ONE'], {}), '(GL.GL_ONE, GL.GL_ONE)\n', (12164, 12186), True, 'import OpenGL.GL as GL\n'), ((12195, 12224), 'OpenGL.GL.glBlendEquation', 'GL.glBlendEquation', (['GL.GL_MAX'], {}), '(GL.GL_MAX)\n', (12213, 12224), True, 'import OpenGL.GL as GL\n'), ((15244, 15264), 'numpy.concatenate', 'np.concatenate', (['vert'], {}), '(vert)\n', (15258, 15264), True, 'import numpy as np\n'), ((15278, 15296), 'numpy.concatenate', 'np.concatenate', (['dx'], {}), '(dx)\n', (15292, 15296), True, 'import numpy as np\n'), ((15310, 15328), 'numpy.concatenate', 'np.concatenate', (['le'], {}), '(le)\n', (15324, 15328), True, 'import numpy as np\n'), ((15342, 15360), 'numpy.concatenate', 'np.concatenate', (['re'], {}), '(re)\n', (15356, 15360), True, 'import numpy as np\n'), ((16437, 16496), 'OpenGL.GL.glClear', 'GL.glClear', (['(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)'], {}), '(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n', (16447, 16496), True, 'import OpenGL.GL as GL\n'), ((16505, 16539), 'OpenGL.GL.glActiveTexture', 'GL.glActiveTexture', (['GL.GL_TEXTURE0'], {}), '(GL.GL_TEXTURE0)\n', (16523, 16539), True, 'import OpenGL.GL as GL\n'), ((17299, 17336), 'yt.utilities.math_utils.get_translate_matrix', 'get_translate_matrix', (['*block.LeftEdge'], {}), '(*block.LeftEdge)\n', (17319, 17336), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((17402, 17424), 'yt.utilities.math_utils.get_scale_matrix', 'get_scale_matrix', (['*dds'], {}), '(*dds)\n', (17418, 17424), False, 'from yt.utilities.math_utils import get_translate_matrix, get_scale_matrix, get_lookat_matrix, get_perspective_matrix, quaternion_mult, quaternion_to_rotation_matrix, rotation_matrix_to_quaternion\n'), ((19854, 19873), 'OpenGL.GL.glGenTextures', 'GL.glGenTextures', (['(1)'], {}), '(1)\n', (19870, 19873), True, 'import OpenGL.GL as GL\n'), ((19908, 19961), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', 'self.cmap_texture'], {}), '(GL.GL_TEXTURE_1D, self.cmap_texture)\n', (19924, 19961), True, 'import OpenGL.GL as GL\n'), ((19970, 20013), 'OpenGL.GL.glPixelStorei', 'GL.glPixelStorei', (['GL.GL_UNPACK_ALIGNMENT', '(1)'], {}), '(GL.GL_UNPACK_ALIGNMENT, 1)\n', (19986, 20013), True, 'import OpenGL.GL as GL\n'), ((20022, 20101), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_1D', 'GL.GL_TEXTURE_WRAP_S', 'GL.GL_CLAMP_TO_EDGE'], {}), '(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE)\n', (20040, 20101), True, 'import OpenGL.GL as GL\n'), ((20110, 20186), 'OpenGL.GL.glTexParameteri', 'GL.glTexParameteri', (['GL.GL_TEXTURE_1D', 'GL.GL_TEXTURE_MAG_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)\n', (20128, 20186), True, 'import OpenGL.GL as GL\n'), ((20195, 20271), 'OpenGL.GL.glTexParameteri', 'GL.glTexParameteri', (['GL.GL_TEXTURE_1D', 'GL.GL_TEXTURE_MIN_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_1D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)\n', (20213, 20271), True, 'import OpenGL.GL as GL\n'), ((20280, 20384), 'OpenGL.GL.glTexImage1D', 'GL.glTexImage1D', (['GL.GL_TEXTURE_1D', '(0)', 'GL.GL_RGBA', '(256)', '(0)', 'GL.GL_RGBA', 'GL.GL_FLOAT', 'self.camera.cmap'], {}), '(GL.GL_TEXTURE_1D, 0, GL.GL_RGBA, 256, 0, GL.GL_RGBA, GL.\n GL_FLOAT, self.camera.cmap)\n', (20295, 20384), True, 'import OpenGL.GL as GL\n'), ((20412, 20449), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', '(0)'], {}), '(GL.GL_TEXTURE_1D, 0)\n', (20428, 20449), True, 'import OpenGL.GL as GL\n'), ((20717, 20770), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', 'self.cmap_texture'], {}), '(GL.GL_TEXTURE_1D, self.cmap_texture)\n', (20733, 20770), True, 'import OpenGL.GL as GL\n'), ((20779, 20873), 'OpenGL.GL.glTexSubImage1D', 'GL.glTexSubImage1D', (['GL.GL_TEXTURE_1D', '(0)', '(0)', '(256)', 'GL.GL_RGBA', 'GL.GL_FLOAT', 'self.camera.cmap'], {}), '(GL.GL_TEXTURE_1D, 0, 0, 256, GL.GL_RGBA, GL.GL_FLOAT,\n self.camera.cmap)\n', (20797, 20873), True, 'import OpenGL.GL as GL\n'), ((21303, 21332), 'OpenGL.GL.glEnable', 'GL.glEnable', (['GL.GL_DEPTH_TEST'], {}), '(GL.GL_DEPTH_TEST)\n', (21314, 21332), True, 'import OpenGL.GL as GL\n'), ((21341, 21367), 'OpenGL.GL.glDepthFunc', 'GL.glDepthFunc', (['GL.GL_LESS'], {}), '(GL.GL_LESS)\n', (21355, 21367), True, 'import OpenGL.GL as GL\n'), ((21376, 21404), 'OpenGL.GL.glEnable', 'GL.glEnable', (['GL.GL_CULL_FACE'], {}), '(GL.GL_CULL_FACE)\n', (21387, 21404), True, 'import OpenGL.GL as GL\n'), ((21413, 21438), 'OpenGL.GL.glCullFace', 'GL.glCullFace', (['GL.GL_BACK'], {}), '(GL.GL_BACK)\n', (21426, 21438), True, 'import OpenGL.GL as GL\n'), ((21573, 21624), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (["self.vert_arrays['mesh_info']"], {}), "(self.vert_arrays['mesh_info'])\n", (21593, 21624), True, 'import OpenGL.GL as GL\n'), ((21847, 21934), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ELEMENT_ARRAY_BUFFER', "self.vert_attrib['element_buffer'][0]"], {}), "(GL.GL_ELEMENT_ARRAY_BUFFER, self.vert_attrib[\n 'element_buffer'][0])\n", (21862, 21934), True, 'import OpenGL.GL as GL\n'), ((21938, 22030), 'OpenGL.GL.glBufferData', 'GL.glBufferData', (['GL.GL_ELEMENT_ARRAY_BUFFER', 'indices.nbytes', 'indices', 'GL.GL_STATIC_DRAW'], {}), '(GL.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL.\n GL_STATIC_DRAW)\n', (21953, 22030), True, 'import OpenGL.GL as GL\n'), ((22059, 22121), 'OpenGL.GL.glGetUniformLocation', 'GL.glGetUniformLocation', (['self.program.program', '"""model_to_clip"""'], {}), "(self.program.program, 'model_to_clip')\n", (22082, 22121), True, 'import OpenGL.GL as GL\n'), ((23202, 23243), 'yt.utilities.lib.mesh_triangulation.triangulate_mesh', 'triangulate_mesh', (['vertices', 'data', 'indices'], {}), '(vertices, data, indices)\n', (23218, 23243), False, 'from yt.utilities.lib.mesh_triangulation import triangulate_mesh\n'), ((25763, 25795), 'OpenGL.GL.glGetIntegerv', 'GL.glGetIntegerv', (['GL.GL_VIEWPORT'], {}), '(GL.GL_VIEWPORT)\n', (25779, 25795), True, 'import OpenGL.GL as GL\n'), ((26062, 26110), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (["self.vert_arrays['fb_vbo']"], {}), "(self.vert_arrays['fb_vbo'])\n", (26082, 26110), True, 'import OpenGL.GL as GL\n'), ((26134, 26152), 'OpenGL.GL.glGenBuffers', 'GL.glGenBuffers', (['(1)'], {}), '(1)\n', (26149, 26152), True, 'import OpenGL.GL as GL\n'), ((26161, 26209), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', 'quad_attrib'], {}), '(GL.GL_ARRAY_BUFFER, quad_attrib)\n', (26176, 26209), True, 'import OpenGL.GL as GL\n'), ((26218, 26317), 'OpenGL.GL.glBufferData', 'GL.glBufferData', (['GL.GL_ARRAY_BUFFER', 'FULLSCREEN_QUAD.nbytes', 'FULLSCREEN_QUAD', 'GL.GL_STATIC_DRAW'], {}), '(GL.GL_ARRAY_BUFFER, FULLSCREEN_QUAD.nbytes, FULLSCREEN_QUAD,\n GL.GL_STATIC_DRAW)\n', (26233, 26317), True, 'import OpenGL.GL as GL\n'), ((26346, 26411), 'OpenGL.GL.glVertexAttribPointer', 'GL.glVertexAttribPointer', (['(0)', '(3)', 'GL.GL_FLOAT', 'GL.GL_FALSE', '(0)', 'None'], {}), '(0, 3, GL.GL_FLOAT, GL.GL_FALSE, 0, None)\n', (26370, 26411), True, 'import OpenGL.GL as GL\n'), ((26438, 26476), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', '(0)'], {}), '(GL.GL_ARRAY_BUFFER, 0)\n', (26453, 26476), True, 'import OpenGL.GL as GL\n'), ((26485, 26508), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (['(0)'], {}), '(0)\n', (26505, 26508), True, 'import OpenGL.GL as GL\n'), ((27051, 27074), 'OpenGL.GL.glGenFramebuffers', 'GL.glGenFramebuffers', (['(1)'], {}), '(1)\n', (27071, 27074), True, 'import OpenGL.GL as GL\n'), ((27083, 27132), 'OpenGL.GL.glBindFramebuffer', 'GL.glBindFramebuffer', (['GL.GL_FRAMEBUFFER', 'self.fbo'], {}), '(GL.GL_FRAMEBUFFER, self.fbo)\n', (27103, 27132), True, 'import OpenGL.GL as GL\n'), ((27156, 27180), 'OpenGL.GL.glGenRenderbuffers', 'GL.glGenRenderbuffers', (['(1)'], {}), '(1)\n', (27177, 27180), True, 'import OpenGL.GL as GL\n'), ((27189, 27243), 'OpenGL.GL.glBindRenderbuffer', 'GL.glBindRenderbuffer', (['GL.GL_RENDERBUFFER', 'depthbuffer'], {}), '(GL.GL_RENDERBUFFER, depthbuffer)\n', (27210, 27243), True, 'import OpenGL.GL as GL\n'), ((27252, 27341), 'OpenGL.GL.glRenderbufferStorage', 'GL.glRenderbufferStorage', (['GL.GL_RENDERBUFFER', 'GL.GL_DEPTH_COMPONENT32F', 'width', 'height'], {}), '(GL.GL_RENDERBUFFER, GL.GL_DEPTH_COMPONENT32F,\n width, height)\n', (27276, 27341), True, 'import OpenGL.GL as GL\n'), ((27379, 27488), 'OpenGL.GL.glFramebufferRenderbuffer', 'GL.glFramebufferRenderbuffer', (['GL.GL_FRAMEBUFFER', 'GL.GL_DEPTH_ATTACHMENT', 'GL.GL_RENDERBUFFER', 'depthbuffer'], {}), '(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT, GL.\n GL_RENDERBUFFER, depthbuffer)\n', (27407, 27488), True, 'import OpenGL.GL as GL\n'), ((27653, 27672), 'OpenGL.GL.glGenTextures', 'GL.glGenTextures', (['(1)'], {}), '(1)\n', (27669, 27672), True, 'import OpenGL.GL as GL\n'), ((27809, 27860), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_2D', 'self.fb_texture'], {}), '(GL.GL_TEXTURE_2D, self.fb_texture)\n', (27825, 27860), True, 'import OpenGL.GL as GL\n'), ((27925, 27997), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_2D', 'GL.GL_TEXTURE_WRAP_S', 'GL.GL_REPEAT'], {}), '(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT)\n', (27943, 27997), True, 'import OpenGL.GL as GL\n'), ((28006, 28078), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_2D', 'GL.GL_TEXTURE_WRAP_T', 'GL.GL_REPEAT'], {}), '(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT)\n', (28024, 28078), True, 'import OpenGL.GL as GL\n'), ((28129, 28205), 'OpenGL.GL.glTexParameteri', 'GL.glTexParameteri', (['GL.GL_TEXTURE_2D', 'GL.GL_TEXTURE_MAG_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)\n', (28147, 28205), True, 'import OpenGL.GL as GL\n'), ((28214, 28290), 'OpenGL.GL.glTexParameteri', 'GL.glTexParameteri', (['GL.GL_TEXTURE_2D', 'GL.GL_TEXTURE_MIN_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)\n', (28232, 28290), True, 'import OpenGL.GL as GL\n'), ((28391, 28496), 'OpenGL.GL.glTexImage2D', 'GL.glTexImage2D', (['GL.GL_TEXTURE_2D', '(0)', 'GL.GL_RGBA32F', 'width', 'height', '(0)', 'GL.GL_RGBA', 'GL.GL_FLOAT', 'None'], {}), '(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA32F, width, height, 0, GL.\n GL_RGBA, GL.GL_FLOAT, None)\n', (28406, 28496), True, 'import OpenGL.GL as GL\n'), ((28613, 28725), 'OpenGL.GL.glFramebufferTexture2D', 'GL.glFramebufferTexture2D', (['GL.GL_FRAMEBUFFER', 'GL.GL_COLOR_ATTACHMENT0', 'GL.GL_TEXTURE_2D', 'self.fb_texture', '(0)'], {}), '(GL.GL_FRAMEBUFFER, GL.GL_COLOR_ATTACHMENT0, GL.\n GL_TEXTURE_2D, self.fb_texture, 0)\n', (28638, 28725), True, 'import OpenGL.GL as GL\n'), ((28855, 28901), 'OpenGL.GL.glCheckFramebufferStatus', 'GL.glCheckFramebufferStatus', (['GL.GL_FRAMEBUFFER'], {}), '(GL.GL_FRAMEBUFFER)\n', (28882, 28901), True, 'import OpenGL.GL as GL\n'), ((30797, 30829), 'OpenGL.GL.glGetIntegerv', 'GL.glGetIntegerv', (['GL.GL_VIEWPORT'], {}), '(GL.GL_VIEWPORT)\n', (30813, 30829), True, 'import OpenGL.GL as GL\n'), ((30853, 30921), 'OpenGL.GL.glReadPixels', 'GL.glReadPixels', (['(0)', '(0)', 'width', 'height', 'GL.GL_RGB', 'GL.GL_UNSIGNED_BYTE'], {}), '(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE)\n', (30868, 30921), True, 'import OpenGL.GL as GL\n'), ((30975, 31037), 'numpy.fromstring', 'np.fromstring', (['debug_buffer', '"""uint8"""'], {'count': '(width * height * 3)'}), "(debug_buffer, 'uint8', count=width * height * 3)\n", (30988, 31037), True, 'import numpy as np\n'), ((31456, 31488), 'OpenGL.GL.glGetIntegerv', 'GL.glGetIntegerv', (['GL.GL_VIEWPORT'], {}), '(GL.GL_VIEWPORT)\n', (31472, 31488), True, 'import OpenGL.GL as GL\n'), ((31805, 31854), 'OpenGL.GL.glBindFramebuffer', 'GL.glBindFramebuffer', (['GL.GL_FRAMEBUFFER', 'self.fbo'], {}), '(GL.GL_FRAMEBUFFER, self.fbo)\n', (31825, 31854), True, 'import OpenGL.GL as GL\n'), ((31906, 31965), 'OpenGL.GL.glClear', 'GL.glClear', (['(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)'], {}), '(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n', (31916, 31965), True, 'import OpenGL.GL as GL\n'), ((32111, 32153), 'OpenGL.GL.glBindFramebuffer', 'GL.glBindFramebuffer', (['GL.GL_FRAMEBUFFER', '(0)'], {}), '(GL.GL_FRAMEBUFFER, 0)\n', (32131, 32153), True, 'import OpenGL.GL as GL\n'), ((32193, 32230), 'OpenGL.GL.glUseProgram', 'GL.glUseProgram', (['self.program.program'], {}), '(self.program.program)\n', (32208, 32230), True, 'import OpenGL.GL as GL\n'), ((32239, 32273), 'OpenGL.GL.glActiveTexture', 'GL.glActiveTexture', (['GL.GL_TEXTURE0'], {}), '(GL.GL_TEXTURE0)\n', (32257, 32273), True, 'import OpenGL.GL as GL\n'), ((32321, 32372), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_2D', 'self.fb_texture'], {}), '(GL.GL_TEXTURE_2D, self.fb_texture)\n', (32337, 32372), True, 'import OpenGL.GL as GL\n'), ((32495, 32529), 'OpenGL.GL.glActiveTexture', 'GL.glActiveTexture', (['GL.GL_TEXTURE1'], {}), '(GL.GL_TEXTURE1)\n', (32513, 32529), True, 'import OpenGL.GL as GL\n'), ((32538, 32591), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', 'self.cmap_texture'], {}), '(GL.GL_TEXTURE_1D, self.cmap_texture)\n', (32554, 32591), True, 'import OpenGL.GL as GL\n'), ((33182, 33241), 'OpenGL.GL.glClear', 'GL.glClear', (['(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)'], {}), '(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n', (33192, 33241), True, 'import OpenGL.GL as GL\n'), ((33368, 33416), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (["self.vert_arrays['fb_vbo']"], {}), "(self.vert_arrays['fb_vbo'])\n", (33388, 33416), True, 'import OpenGL.GL as GL\n'), ((33425, 33456), 'OpenGL.GL.glEnableVertexAttribArray', 'GL.glEnableVertexAttribArray', (['(0)'], {}), '(0)\n', (33453, 33456), True, 'import OpenGL.GL as GL\n'), ((33496, 33534), 'OpenGL.GL.glDrawArrays', 'GL.glDrawArrays', (['GL.GL_TRIANGLES', '(0)', '(6)'], {}), '(GL.GL_TRIANGLES, 0, 6)\n', (33511, 33534), True, 'import OpenGL.GL as GL\n'), ((33562, 33594), 'OpenGL.GL.glDisableVertexAttribArray', 'GL.glDisableVertexAttribArray', (['(0)'], {}), '(0)\n', (33591, 33594), True, 'import OpenGL.GL as GL\n'), ((33603, 33626), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (['(0)'], {}), '(0)\n', (33623, 33626), True, 'import OpenGL.GL as GL\n'), ((33635, 33672), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', '(0)'], {}), '(GL.GL_TEXTURE_1D, 0)\n', (33651, 33672), True, 'import OpenGL.GL as GL\n'), ((33681, 33718), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_2D', '(0)'], {}), '(GL.GL_TEXTURE_2D, 0)\n', (33697, 33718), True, 'import OpenGL.GL as GL\n'), ((3695, 3730), 'yt.config.ytcfg.get', 'ytcfg.get', (['"""yt"""', '"""default_colormap"""'], {}), "('yt', 'default_colormap')\n", (3704, 3730), False, 'from yt.config import ytcfg\n'), ((7174, 7197), 'numpy.sqrt', 'np.sqrt', (['(1.0 - mag ** 2)'], {}), '(1.0 - mag ** 2)\n', (7181, 7197), True, 'import numpy as np\n'), ((8034, 8076), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.position - self.focus)'], {}), '(self.position - self.focus)\n', (8048, 8076), True, 'import numpy as np\n'), ((9542, 9594), 'OpenGL.GL.glDeleteVertexArrays', 'GL.glDeleteVertexArrays', (['(1)', '[self.vert_arrays[name]]'], {}), '(1, [self.vert_arrays[name]])\n', (9565, 9594), True, 'import OpenGL.GL as GL\n'), ((10248, 10286), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', '(0)'], {}), '(GL.GL_ARRAY_BUFFER, 0)\n', (10263, 10286), True, 'import OpenGL.GL as GL\n'), ((10370, 10388), 'OpenGL.GL.glGenBuffers', 'GL.glGenBuffers', (['(1)'], {}), '(1)\n', (10385, 10388), True, 'import OpenGL.GL as GL\n'), ((16678, 16716), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_3D', 'ti'], {}), '(GL.GL_TEXTURE_3D, ti)\n', (16694, 16716), True, 'import OpenGL.GL as GL\n'), ((16729, 16777), 'OpenGL.GL.glDrawArrays', 'GL.glDrawArrays', (['GL.GL_TRIANGLES', '(tex_i * 36)', '(36)'], {}), '(GL.GL_TRIANGLES, tex_i * 36, 36)\n', (16744, 16777), True, 'import OpenGL.GL as GL\n'), ((17835, 17878), 'OpenGL.GL.glPixelStorei', 'GL.glPixelStorei', (['GL.GL_UNPACK_ALIGNMENT', '(1)'], {}), '(GL.GL_UNPACK_ALIGNMENT, 1)\n', (17851, 17878), True, 'import OpenGL.GL as GL\n'), ((17891, 17967), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_3D', 'GL.GL_TEXTURE_MAG_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR)\n', (17909, 17967), True, 'import OpenGL.GL as GL\n'), ((17980, 18056), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_3D', 'GL.GL_TEXTURE_MIN_FILTER', 'GL.GL_LINEAR'], {}), '(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR)\n', (17998, 18056), True, 'import OpenGL.GL as GL\n'), ((18741, 18789), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_3D', 'texture_name'], {}), '(GL.GL_TEXTURE_3D, texture_name)\n', (18757, 18789), True, 'import OpenGL.GL as GL\n'), ((18802, 18881), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_3D', 'GL.GL_TEXTURE_WRAP_S', 'GL.GL_CLAMP_TO_EDGE'], {}), '(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE)\n', (18820, 18881), True, 'import OpenGL.GL as GL\n'), ((18894, 18973), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_3D', 'GL.GL_TEXTURE_WRAP_T', 'GL.GL_CLAMP_TO_EDGE'], {}), '(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE)\n', (18912, 18973), True, 'import OpenGL.GL as GL\n'), ((18986, 19065), 'OpenGL.GL.glTexParameterf', 'GL.glTexParameterf', (['GL.GL_TEXTURE_3D', 'GL.GL_TEXTURE_WRAP_R', 'GL.GL_CLAMP_TO_EDGE'], {}), '(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_R, GL.GL_CLAMP_TO_EDGE)\n', (19004, 19065), True, 'import OpenGL.GL as GL\n'), ((19078, 19153), 'OpenGL.GL.glTexStorage3D', 'GL.glTexStorage3D', (['GL.GL_TEXTURE_3D', '(1)', 'GL.GL_R32F', '*block.my_data[0].shape'], {}), '(GL.GL_TEXTURE_3D, 1, GL.GL_R32F, *block.my_data[0].shape)\n', (19095, 19153), True, 'import OpenGL.GL as GL\n'), ((19182, 19281), 'OpenGL.GL.glTexSubImage3D', 'GL.glTexSubImage3D', (['GL.GL_TEXTURE_3D', '(0)', '(0)', '(0)', '(0)', 'dx', 'dy', 'dz', 'GL.GL_RED', 'GL.GL_FLOAT', 'n_data.T'], {}), '(GL.GL_TEXTURE_3D, 0, 0, 0, 0, dx, dy, dz, GL.GL_RED, GL.\n GL_FLOAT, n_data.T)\n', (19200, 19281), True, 'import OpenGL.GL as GL\n'), ((19313, 19350), 'OpenGL.GL.glGenerateMipmap', 'GL.glGenerateMipmap', (['GL.GL_TEXTURE_3D'], {}), '(GL.GL_TEXTURE_3D)\n', (19332, 19350), True, 'import OpenGL.GL as GL\n'), ((21805, 21823), 'OpenGL.GL.glGenBuffers', 'GL.glGenBuffers', (['(1)'], {}), '(1)\n', (21820, 21823), True, 'import OpenGL.GL as GL\n'), ((23435, 23494), 'OpenGL.GL.glClear', 'GL.glClear', (['(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)'], {}), '(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n', (23445, 23494), True, 'import OpenGL.GL as GL\n'), ((23635, 23673), 'numpy.dot', 'np.dot', (['projection_matrix', 'view_matrix'], {}), '(projection_matrix, view_matrix)\n', (23641, 23673), True, 'import numpy as np\n'), ((23686, 23754), 'OpenGL.GL.glUniformMatrix4fv', 'GL.glUniformMatrix4fv', (['self.transform_matrix', '(1)', '(True)', 'model_to_clip'], {}), '(self.transform_matrix, 1, True, model_to_clip)\n', (23707, 23754), True, 'import OpenGL.GL as GL\n'), ((23768, 23802), 'OpenGL.GL.glActiveTexture', 'GL.glActiveTexture', (['GL.GL_TEXTURE1'], {}), '(GL.GL_TEXTURE1)\n', (23786, 23802), True, 'import OpenGL.GL as GL\n'), ((23815, 23868), 'OpenGL.GL.glBindTexture', 'GL.glBindTexture', (['GL.GL_TEXTURE_1D', 'self.cmap_texture'], {}), '(GL.GL_TEXTURE_1D, self.cmap_texture)\n', (23831, 23868), True, 'import OpenGL.GL as GL\n'), ((24076, 24107), 'OpenGL.GL.glEnableVertexAttribArray', 'GL.glEnableVertexAttribArray', (['(0)'], {}), '(0)\n', (24104, 24107), True, 'import OpenGL.GL as GL\n'), ((24120, 24193), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', "self.vert_attrib['vertex_buffer'][0]"], {}), "(GL.GL_ARRAY_BUFFER, self.vert_attrib['vertex_buffer'][0])\n", (24135, 24193), True, 'import OpenGL.GL as GL\n'), ((24293, 24324), 'OpenGL.GL.glEnableVertexAttribArray', 'GL.glEnableVertexAttribArray', (['(1)'], {}), '(1)\n', (24321, 24324), True, 'import OpenGL.GL as GL\n'), ((24337, 24408), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ARRAY_BUFFER', "self.vert_attrib['data_buffer'][0]"], {}), "(GL.GL_ARRAY_BUFFER, self.vert_attrib['data_buffer'][0])\n", (24352, 24408), True, 'import OpenGL.GL as GL\n'), ((24508, 24595), 'OpenGL.GL.glBindBuffer', 'GL.glBindBuffer', (['GL.GL_ELEMENT_ARRAY_BUFFER', "self.vert_attrib['element_buffer'][0]"], {}), "(GL.GL_ELEMENT_ARRAY_BUFFER, self.vert_attrib[\n 'element_buffer'][0])\n", (24523, 24595), True, 'import OpenGL.GL as GL\n'), ((24760, 24792), 'OpenGL.GL.glDisableVertexAttribArray', 'GL.glDisableVertexAttribArray', (['(0)'], {}), '(0)\n', (24789, 24792), True, 'import OpenGL.GL as GL\n'), ((24805, 24837), 'OpenGL.GL.glDisableVertexAttribArray', 'GL.glDisableVertexAttribArray', (['(1)'], {}), '(1)\n', (24834, 24837), True, 'import OpenGL.GL as GL\n'), ((26792, 26823), 'OpenGL.GL.glIsTexture', 'GL.glIsTexture', (['self.fb_texture'], {}), '(self.fb_texture)\n', (26806, 26823), True, 'import OpenGL.GL as GL\n'), ((26841, 26879), 'OpenGL.GL.glDeleteTextures', 'GL.glDeleteTextures', (['[self.fb_texture]'], {}), '([self.fb_texture])\n', (26860, 26879), True, 'import OpenGL.GL as GL\n'), ((26916, 26944), 'OpenGL.GL.glIsFramebuffer', 'GL.glIsFramebuffer', (['self.fbo'], {}), '(self.fbo)\n', (26934, 26944), True, 'import OpenGL.GL as GL\n'), ((26958, 26996), 'OpenGL.GL.glDeleteFramebuffers', 'GL.glDeleteFramebuffers', (['(1)', '[self.fbo]'], {}), '(1, [self.fbo])\n', (26981, 26996), True, 'import OpenGL.GL as GL\n'), ((3766, 3788), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(256)'], {}), '(0, 1, 256)\n', (3777, 3788), True, 'import numpy as np\n'), ((9864, 9913), 'OpenGL.GL.glBindVertexArray', 'GL.glBindVertexArray', (['self.vert_arrays[vert_name]'], {}), '(self.vert_arrays[vert_name])\n', (9884, 9913), True, 'import OpenGL.GL as GL\n'), ((13668, 13684), 'numpy.ones', 'np.ones', (['(3)', '"""f8"""'], {}), "(3, 'f8')\n", (13675, 13684), True, 'import numpy as np\n'), ((13718, 13734), 'numpy.ones', 'np.ones', (['(3)', '"""f8"""'], {}), "(3, 'f8')\n", (13725, 13734), True, 'import numpy as np\n'), ((13821, 13867), 'numpy.minimum', 'np.minimum', (['left_min', 'block.LeftEdge', 'left_min'], {}), '(left_min, block.LeftEdge, left_min)\n', (13831, 13867), True, 'import numpy as np\n'), ((13884, 13932), 'numpy.maximum', 'np.maximum', (['right_max', 'block.LeftEdge', 'right_max'], {}), '(right_max, block.LeftEdge, right_max)\n', (13894, 13932), True, 'import numpy as np\n'), ((17091, 17123), 'OpenGL.GL.glGetIntegerv', 'GL.glGetIntegerv', (['GL.GL_VIEWPORT'], {}), '(GL.GL_VIEWPORT)\n', (17107, 17123), True, 'import OpenGL.GL as GL\n'), ((18158, 18188), 'OpenGL.GL.glDeleteTextures', 'GL.glDeleteTextures', (['[texture]'], {}), '([texture])\n', (18177, 18188), True, 'import OpenGL.GL as GL\n'), ((24260, 24278), 'ctypes.c_void_p', 'ctypes.c_void_p', (['(0)'], {}), '(0)\n', (24275, 24278), False, 'import ctypes\n'), ((24475, 24493), 'ctypes.c_void_p', 'ctypes.c_void_p', (['(0)'], {}), '(0)\n', (24490, 24493), False, 'import ctypes\n'), ((24727, 24745), 'ctypes.c_void_p', 'ctypes.c_void_p', (['(0)'], {}), '(0)\n', (24742, 24745), False, 'import ctypes\n')] |
import collections
from sklearn.manifold import MDS
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
from MDSimsEval.rmsf_analysis import reset_rmsf_calculations
from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue
from MDSimsEval.rmsf_bootstrapped_analysis import find_rmsf_of_residues
from MDSimsEval.utils import complement_residues
from scipy import stats
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
import random
class BaselineClassifier(ABC):
"""
An abstract class that the baseline classifiers models extend from. The subclasses must implement the abstract
methods ``fit`` and ``predict``.
The class provides some helper methods in order to stack the RMSF of the selected residues for training and
getting the RMSF of the unknown ligand we want to predict its class.
If you want to extend the method we suggest reading the other classes in this model. This will help in order
to better understand how ``fit`` and ``predict`` are implemented and how we use the helper methods in this class.
"""
def __init__(self, start, stop, rmsf_cache, method):
self.start = start
self.stop = stop
self.method = method
self.rmsf_cache = rmsf_cache
self.selected_residues = None
def read_list_stack_rmsfs(self, train_analysis_actors, residues):
reset_rmsf_calculations(train_analysis_actors, self.start, self.stop, self.rmsf_cache)
# Create a mask of the residues selected
self.selected_residues = [which_res in residues for which_res in np.arange(290)]
# Calculating baseline agonist RMSF value
stacked_agonists = get_avg_rmsf_per_residue(train_analysis_actors['Agonists'][0])[self.selected_residues]
for which_ligand in train_analysis_actors['Agonists'][1:]:
stacked_agonists = np.vstack(
(stacked_agonists, get_avg_rmsf_per_residue(which_ligand)[self.selected_residues]))
# Calculating baseline antagonist RMSF value
stacked_antagonists = get_avg_rmsf_per_residue(train_analysis_actors['Antagonists'][0])[
self.selected_residues]
for which_ligand in train_analysis_actors['Antagonists'][1:]:
stacked_antagonists = np.vstack(
(stacked_antagonists, get_avg_rmsf_per_residue(which_ligand)[self.selected_residues]))
return stacked_agonists, stacked_antagonists
def read_dict_stack_rmsfs(self, train_analysis_actors, residues):
# Case that we are given a dictionary of residue_ids: [[start1, stop1], [start2, stop2]]
self.selected_residues = residues
rmsf_array = []
for res, windows in residues.items():
for window in windows:
rmsf_array.append(
find_rmsf_of_residues(train_analysis_actors, [res], window[0], window[1], self.rmsf_cache))
rmsf_array = np.array(rmsf_array).reshape(len(rmsf_array), len(rmsf_array[0])).T
stacked_agonists = rmsf_array[:len(train_analysis_actors['Agonists']), :]
stacked_antagonists = rmsf_array[len(train_analysis_actors['Agonists']):, :]
return stacked_agonists, stacked_antagonists
def read_unknown_list_residues(self, ligand):
reset_rmsf_calculations({'Agonists': [ligand], 'Antagonists': []}, self.start, self.stop, self.rmsf_cache)
return get_avg_rmsf_per_residue(ligand)[self.selected_residues]
def read_unknown_dict_residues(self, ligand):
rmsf_array = []
for res, windows in self.selected_residues.items():
for window in windows:
rmsf_array.append(
find_rmsf_of_residues({'Agonists': [ligand], 'Antagonists': [ligand]},
[res], window[0], window[1], self.rmsf_cache))
rmsf_array = np.array(rmsf_array).reshape(len(rmsf_array), len(rmsf_array[0])).T[0]
return rmsf_array
@abstractmethod
def fit(self, train_analysis_actors, residues):
pass
@abstractmethod
def predict(self, ligand):
pass
class AggregatedResidues(BaselineClassifier):
"""
This simple model fits on the training data by calculating the average RMSF value of the agonist and the
antagonist sets. The RMSF is calculated on the residues given and aggregated to one value. This means that for
the agonists we calculate the average/median value for each residue and then we aggregate again ending with a
scalar value.
Attributes:
start (int): The starting frame of the window
stop (int): The last frame of the window
method (func): Function that we will use for summarizing each residue, eg `np.mean`, `np.median`
agonist_baseline (float): The aggregated RMSF value of the agonist class
antagonist_baseline (float): The aggregated RMSF value of the antagonist class
selected_residues (List[boolean]): A list of size total_residues, where True on the indexes of the residue ids
selected
"""
def __init__(self, start, stop, rmsf_cache, method=np.mean):
super().__init__(start, stop, rmsf_cache, method)
self.agonist_baseline = None
self.antagonist_baseline = None
def fit(self, train_analysis_actors, residues):
"""
The function that initializes the aggregated RMSF value for each class.
Args:
train_analysis_actors: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
residues: A list of residue ids that the model will use. For all the residues give ``np.arange(290)`` . Can
also be a dictionary with residue ids as keys and values a list of ``[start, stop]``. This
argument allows us to use a residue in more than one window. This is used in the residue cherry
picking part of the thesis.
Example:
::
# This will use the window saved as an attribute when we created the model object
residues = [10, 11, 27, 52, 83]
or
residues = {
115: [[0, 500], [2000, 2500]],
117: [[2000, 2500]],
81: [[2000, 2500]],
78: [[1000, 1500], [1500, 2000]],
254: [[0, 500], [1500, 2000]],
}
"""
if isinstance(residues, list):
stacked_agonists, stacked_antagonists = self.read_list_stack_rmsfs(train_analysis_actors, residues)
elif isinstance(residues, collections.Mapping):
stacked_agonists, stacked_antagonists = self.read_dict_stack_rmsfs(train_analysis_actors, residues)
else:
raise ValueError('residues argument expecting a list or a mapping (dictionary)')
self.agonist_baseline = self.method(stacked_agonists)
self.antagonist_baseline = self.method(stacked_antagonists)
def predict(self, ligand):
"""
Checks the distance of the unknown ligand from the agonist and antagonist averages and returns
as a label the class that is closest.
Args:
ligand (AnalysisActorClass): The ligand we want to predict its class
Returns:
The class label, 1 for Agonist, 0 for Antagonist.
"""
if isinstance(self.selected_residues, list):
rmsf_value = self.method(self.read_unknown_list_residues(ligand))
elif isinstance(self.selected_residues, collections.Mapping):
rmsf_value = self.method(self.read_unknown_dict_residues(ligand))
else:
raise ValueError('UNEXPECTED: selected residues is missing or is not of type list or mapping (dictionary)')
agon_distance = np.abs(self.agonist_baseline - rmsf_value)
antagon_distance = np.abs(self.antagonist_baseline - rmsf_value)
if agon_distance < antagon_distance:
return 1 # Case agonist
else:
return 0 # Case antagonist
class ResidueMajority(BaselineClassifier):
"""
Used for evaluating residue selections based on their RMSF.
This is a simple baseline model able to quantify how good our residue selection is.
Given a k - k training set of agonists - antagonists,for an unknown ligand
we iterate through the residues. If the residue is closer to the median/average of the
training agonists (of the RMSF values of the specific residue) then the residue votes that
the ligand is an agonist. Else it votes that the ligand is an antagonist.
|
| At then end we see which class had the most votes.
Attributes:
start (int): The starting frame of the window
stop (int): The last frame of the window
method (func): Function that we will use for summarizing each residue, eg ``np.mean``, ``np.median``
agonist_residue_baseline (List[float]): A list of the aggregated RMSF value of the agonists of each residue
antagonist_residue_baseline (List[float]): A list of the aggregated RMSF value of the antagonists of each
residue
selected_residues (List[boolean]): A list of size total_residues, where True on the indexes of the residue ids
selected
"""
def __init__(self, start, stop, rmsf_cache, method=np.mean):
super().__init__(start, stop, rmsf_cache, method)
self.agonist_residue_baseline = None
self.antagonist_residue_baseline = None
def fit(self, train_analysis_actors, residues):
"""
The function that initializes the aggregated RMSF value for each residue for each class.
Args:
train_analysis_actors: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
residues: A list of residue ids that the model will use. For all the residues give
``np.arange(290)`` . Can also be a dictionary with residue ids as keys and values a
list of ``[start, stop]``. This argument allows us to use a residue in more than
one window. This is used in the residue cherry picking part of the thesis.
Example:
::
# This will use the window saved as an attribute when we created the model object
residues = [10, 11, 27, 52, 83]
or
residues = {
115: [[0, 500], [2000, 2500]],
117: [[2000, 2500]],
81: [[2000, 2500]],
78: [[1000, 1500], [1500, 2000]],
254: [[0, 500], [1500, 2000]],
}
"""
if isinstance(residues, list):
stacked_agonists, stacked_antagonists = self.read_list_stack_rmsfs(train_analysis_actors, residues)
elif isinstance(residues, collections.Mapping):
stacked_agonists, stacked_antagonists = self.read_dict_stack_rmsfs(train_analysis_actors, residues)
else:
raise ValueError('residues argument expecting a list or a mapping (dictionary)')
self.agonist_residue_baseline = self.method(stacked_agonists, axis=0)
self.antagonist_residue_baseline = self.method(stacked_antagonists, axis=0)
def predict(self, ligand):
"""
Performs the majority voting and returns the predicted class.
Args:
ligand (AnalysisActorClass): The ligand we want to predict its class
Returns:
The class label, 1 for Agonist, 0 for Antagonist.
"""
if isinstance(self.selected_residues, list):
rmsf_values = self.read_unknown_list_residues(ligand)
elif isinstance(self.selected_residues, collections.Mapping):
rmsf_values = self.read_unknown_dict_residues(ligand)
else:
raise ValueError('UNEXPECTED: selected residues is missing or is not of type list or mapping (dictionary)')
agon_distances = np.abs(self.agonist_residue_baseline - rmsf_values)
antagon_distances = np.abs(self.antagonist_residue_baseline - rmsf_values)
# Perform the majority voting
if np.sum(agon_distances < antagon_distances) > len(rmsf_values) / 2:
return 1 # Case agonist
else:
return 0 # Case antagonist
class KSDistance(BaselineClassifier):
"""
Used for evaluating residue selections based on their RMSF.
We calculate for each class the average/median RMSF of each residue. Then when we receive an unknown ligand
we use the `k-s test <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ks_2samp.html>`_
which returns the "distance" of the distributions of the unknown ligand and the class. We calculate the distance
for the other class too and classify on the class with the smallest distance.
Attributes:
start (int): The starting frame of the window
stop (int): The last frame of the window
method (func): Function that we will use for summarizing each residue, eg ``np.mean``, ``np.median``
agonist_residue_baseline (List[float]): A list of the aggregated RMSF value of the agonists of each residue
antagonist_residue_baseline (List[float]): A list of the aggregated RMSF value of the antagonists of each
residue
selected_residues (List[boolean]): A list of size total_residues, where True on the indexes of the residue ids
selected
"""
def __init__(self, start, stop, rmsf_cache, method=np.mean):
super().__init__(start, stop, rmsf_cache, method)
self.agonist_residue_baseline = None
self.antagonist_residue_baseline = None
def fit(self, train_analysis_actors, residues):
"""
The function that initializes the aggregated RMSF value for each residue for each class.
Args:
train_analysis_actors: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
residues: A list of residue ids that the model will use. For all the residues give
``np.arange(290)`` . Can also be a dictionary with residue ids as keys and values a
list of ``[start, stop]``. This argument allows us to use a residue in more than
one window. This is used in the residue cherry picking part of the thesis.
Example:
::
# This will use the window saved as an attribute when we created the model object
residues = [10, 11, 27, 52, 83]
or
residues = {
115: [[0, 500], [2000, 2500]],
117: [[2000, 2500]],
81: [[2000, 2500]],
78: [[1000, 1500], [1500, 2000]],
254: [[0, 500], [1500, 2000]],
}
"""
if isinstance(residues, list):
stacked_agonists, stacked_antagonists = self.read_list_stack_rmsfs(train_analysis_actors, residues)
elif isinstance(residues, collections.Mapping):
stacked_agonists, stacked_antagonists = self.read_dict_stack_rmsfs(train_analysis_actors, residues)
else:
raise ValueError('residues argument expecting a list or a mapping (dictionary)')
self.agonist_residue_baseline = self.method(stacked_agonists, axis=0)
self.antagonist_residue_baseline = self.method(stacked_antagonists, axis=0)
def predict(self, ligand):
"""
Performs the K-S test. If we have a mismatch of outcomes (one class accepts it, the other one rejects it) then
we classify as the one that accepted. Else, we classify using the distance of K-S.
Args:
ligand (AnalysisActorClass): The ligand we want to predict its class
Returns:
The class label, 1 for Agonist, 0 for Antagonist
"""
if isinstance(self.selected_residues, list):
rmsf_values = self.read_unknown_list_residues(ligand)
elif isinstance(self.selected_residues, collections.Mapping):
rmsf_values = self.read_unknown_dict_residues(ligand)
else:
raise ValueError('UNEXPECTED: selected residues is missing or is not of type list or mapping (dictionary)')
# We perform the K-S test which returns (distance, p_value) and keep the distance only
agon_distance, agon_p_value = stats.ks_2samp(self.agonist_residue_baseline, rmsf_values)
antagon_distances, antagon_p_value = stats.ks_2samp(self.antagonist_residue_baseline, rmsf_values)
# # See if the test rejects the null hypothesis for one class and rejects it for the other
# if antagon_p_value <= 0.05 < agon_p_value:
# return 1, "A-R" # Case agonist
# elif agon_p_value <= 0.05 < antagon_p_value:
# return 0, "A-R" # Case antagonist
#
# # Decide if we had a reject - reject or accept - accept
# if antagon_p_value < 0.05:
# ret_str = "R-R"
# else:
# ret_str = "A-A"
#
# # Return the class that has the lowest K-S distance
# if agon_distance < antagon_distances:
# return 1, ret_str # Case agonist
# else:
# return 0, ret_str # Case antagonist
# Return the class that has the lowest K-S distance
if agon_distance < antagon_distances:
return 1 # Case agonist
else:
return 0 # Case antagonist
def bootstrap_dataset(analysis_actors_dict, samples, sample_size):
"""
Creates a given number of bootstrapped samples of the Agonist - Antagonist dataset.
| Also the remaining ligands are returned as a validation set.
| Eg if sample_size = 20 and on each class we have 27 ligands, then we create
a dict of 20 - 20 unique ligands and the remaining 7 ligands are returned as a validation set.
Args:
analysis_actors_dict: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
samples (int): Number of bootstrapped samples generated
sample_size (int): How many ligands of each class the training set will have
Returns:
A tuple of (``train_dicts``, ``test_dicts``)
"""
train_agonists_samples = [random.sample(analysis_actors_dict['Agonists'], k=sample_size)
for i in np.arange(samples)]
test_agonists_samples = [complement_residues(analysis_actors_dict['Agonists'], selected_ligands)
for selected_ligands in train_agonists_samples]
train_antagonists_samples = [random.sample(analysis_actors_dict['Antagonists'], k=sample_size)
for i in np.arange(samples)]
test_antagonists_samples = [complement_residues(analysis_actors_dict['Antagonists'], selected_ligands)
for selected_ligands in train_antagonists_samples]
# Merge the agonists and the antagonists to a dictionary which is the expected input
# of classify_on_baseline method above
train_actor_dicts = [{'Agonists': agonist_sample, 'Antagonists': antagonist_sample}
for agonist_sample, antagonist_sample in
zip(train_agonists_samples, train_antagonists_samples)]
test_actor_dicts = [{'Agonists': agonist_sample, 'Antagonists': antagonist_sample}
for agonist_sample, antagonist_sample in zip(test_agonists_samples, test_antagonists_samples)]
return train_actor_dicts, test_actor_dicts
class MDStoKNN(BaselineClassifier):
"""
This is a model that classifies ligands based on the K nearest neighbors on a MDS 2D projection.
We first calculate the pairwise distances of **all** the ligands creating an ``agons_numb`` + ``antagons_numb`` *x*
``agons_numb`` + ``antagons_numb`` matrix. We perform a non-linear projection using MDS transforming the matrix to a
``agons_numb`` + ``antagons_numb`` *x* 2 shape.
We provide the indexes of the ligands that the labels are known. These will be considered our train set. We fit a
KNN model on them. We then provide the index of the ligand we want to predict. For example we may have 20 agonists,
20 antagonists and we want to predict an unknown ligand. The transformed shape of our 2D projection will be
20 + 20 + 1 *x* 2. The indexes [0, 1, ..., 39] will for the train set and will be passed on the fit of the KNN. We
then pass the index 40 in the ``predict`` method in order to predict the unknown ligand.
.. note::
This model is more complex than the others which have a straight forward approach, similar to the ``sklearn``
models. The main idea is that the model knows all the data points a priori in order to create the 2D mapping. We
then reveal to the model the labels of the known ligands in order to predict the unknown ligands.
Args:
start (int): The starting frame of the window
stop (int): The last frame of the window
metric: A method used to calculate the pairwise distance of the ligands. Possible metrics are K-S distance and
Spearman's r
neigh (KNeighborsClassifier): The KNN model used for predicting the unknown ligands
"""
def __init__(self, start, stop, rmsf_cache, metric, neighbors):
super().__init__(start, stop, rmsf_cache, None)
self.pairwise_distances = None
self.metric_method = metric
self.neigh = KNeighborsClassifier(n_neighbors=neighbors)
def create_pairwise_distances(self, analysis_actors_dict, residues):
"""
Creates the pairwise distance matrix of all the input ligands that will be projected on a 2D manifold using MDS
Args:
analysis_actors_dict: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
residues: A list of residue ids that the model will use. For all the residues give
``np.arange(290)``.
Returns:
A DataFrame of shape ``agons_numb`` + ``antagons_numb`` *x* ``agons_numb`` + ``antagons_numb``
"""
reset_rmsf_calculations(analysis_actors_dict, self.start, self.stop, self.rmsf_cache)
# Create a mask of the residues selected
selected_residues = [which_res in residues for which_res in np.arange(290)]
ligand_rmsf = collections.OrderedDict()
for which_ligand in analysis_actors_dict['Agonists'] + analysis_actors_dict['Antagonists']:
ligand_rmsf[which_ligand.drug_name] = get_avg_rmsf_per_residue(which_ligand)[selected_residues]
distances_df = pd.DataFrame(np.zeros((len(ligand_rmsf), len(ligand_rmsf))), columns=list(ligand_rmsf),
index=list(ligand_rmsf))
for ind_ligand, ind_rmsf in ligand_rmsf.items():
for col_ligand, col_rmsf in ligand_rmsf.items():
distances_df.at[ind_ligand, col_ligand] = self.metric_method(ind_rmsf, col_rmsf)
return distances_df
def fit(self, analysis_actors_dict, residues):
"""
Create the pairwise distance matrix and perform MDS to transform it to a 2D matrix.
Args:
analysis_actors_dict: ``{ "Agonists": List[AnalysisActor.class], "Antagonists": List[AnalysisActor.class] }``
residues: A list of residue ids that the model will use. For all the residues give
``np.arange(290)``.
"""
self.pairwise_distances = self.create_pairwise_distances(analysis_actors_dict, residues)
# Perform the MDS dimensionality reduction
# mds = MDS(n_components=2, dissimilarity='precomputed')
mds = PCA(n_components=2)
self.pairwise_distances = mds.fit_transform(self.pairwise_distances)
def choose_known_ligands(self, agonist_inds, antagonists_inds):
"""
Give the indexes of the agonists and antagonists ligands that will be form the train set and fits the KNN
model using the transformed pairwise distances.
Args:
agonist_inds: The indexes of the train agonists
antagonists_inds: The indexes of the train antagonists
"""
x_train = np.array(self.pairwise_distances)[agonist_inds + antagonists_inds]
y_train = np.concatenate([np.ones(len(agonist_inds)), np.zeros(len(antagonists_inds))])
self.neigh.fit(x_train, y_train)
def predict(self, ligand_ind):
"""
Given an index of the unknown ligand predict it using the KNN fitted KNN model
Args:
ligand_ind: The index of the unknown ligand
Returns:
The class label, 1 for Agonist, 0 for Antagonist
"""
pred_x = self.pairwise_distances[ligand_ind]
return self.neigh.predict([pred_x])
| [
"numpy.abs",
"numpy.sum",
"MDSimsEval.rmsf_analysis.reset_rmsf_calculations",
"random.sample",
"MDSimsEval.rmsf_bootstrapped_analysis.find_rmsf_of_residues",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.decomposition.PCA",
"MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue",
"MDSimsEval.utils.... | [((1414, 1505), 'MDSimsEval.rmsf_analysis.reset_rmsf_calculations', 'reset_rmsf_calculations', (['train_analysis_actors', 'self.start', 'self.stop', 'self.rmsf_cache'], {}), '(train_analysis_actors, self.start, self.stop, self.\n rmsf_cache)\n', (1437, 1505), False, 'from MDSimsEval.rmsf_analysis import reset_rmsf_calculations\n'), ((3306, 3417), 'MDSimsEval.rmsf_analysis.reset_rmsf_calculations', 'reset_rmsf_calculations', (["{'Agonists': [ligand], 'Antagonists': []}", 'self.start', 'self.stop', 'self.rmsf_cache'], {}), "({'Agonists': [ligand], 'Antagonists': []}, self.\n start, self.stop, self.rmsf_cache)\n", (3329, 3417), False, 'from MDSimsEval.rmsf_analysis import reset_rmsf_calculations\n'), ((8085, 8127), 'numpy.abs', 'np.abs', (['(self.agonist_baseline - rmsf_value)'], {}), '(self.agonist_baseline - rmsf_value)\n', (8091, 8127), True, 'import numpy as np\n'), ((8155, 8200), 'numpy.abs', 'np.abs', (['(self.antagonist_baseline - rmsf_value)'], {}), '(self.antagonist_baseline - rmsf_value)\n', (8161, 8200), True, 'import numpy as np\n'), ((12572, 12623), 'numpy.abs', 'np.abs', (['(self.agonist_residue_baseline - rmsf_values)'], {}), '(self.agonist_residue_baseline - rmsf_values)\n', (12578, 12623), True, 'import numpy as np\n'), ((12652, 12706), 'numpy.abs', 'np.abs', (['(self.antagonist_residue_baseline - rmsf_values)'], {}), '(self.antagonist_residue_baseline - rmsf_values)\n', (12658, 12706), True, 'import numpy as np\n'), ((17315, 17373), 'scipy.stats.ks_2samp', 'stats.ks_2samp', (['self.agonist_residue_baseline', 'rmsf_values'], {}), '(self.agonist_residue_baseline, rmsf_values)\n', (17329, 17373), False, 'from scipy import stats\n'), ((17419, 17480), 'scipy.stats.ks_2samp', 'stats.ks_2samp', (['self.antagonist_residue_baseline', 'rmsf_values'], {}), '(self.antagonist_residue_baseline, rmsf_values)\n', (17433, 17480), False, 'from scipy import stats\n'), ((19203, 19265), 'random.sample', 'random.sample', (["analysis_actors_dict['Agonists']"], {'k': 'sample_size'}), "(analysis_actors_dict['Agonists'], k=sample_size)\n", (19216, 19265), False, 'import random\n'), ((19354, 19425), 'MDSimsEval.utils.complement_residues', 'complement_residues', (["analysis_actors_dict['Agonists']", 'selected_ligands'], {}), "(analysis_actors_dict['Agonists'], selected_ligands)\n", (19373, 19425), False, 'from MDSimsEval.utils import complement_residues\n'), ((19537, 19602), 'random.sample', 'random.sample', (["analysis_actors_dict['Antagonists']"], {'k': 'sample_size'}), "(analysis_actors_dict['Antagonists'], k=sample_size)\n", (19550, 19602), False, 'import random\n'), ((19697, 19771), 'MDSimsEval.utils.complement_residues', 'complement_residues', (["analysis_actors_dict['Antagonists']", 'selected_ligands'], {}), "(analysis_actors_dict['Antagonists'], selected_ligands)\n", (19716, 19771), False, 'from MDSimsEval.utils import complement_residues\n'), ((22425, 22468), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': 'neighbors'}), '(n_neighbors=neighbors)\n', (22445, 22468), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((23095, 23185), 'MDSimsEval.rmsf_analysis.reset_rmsf_calculations', 'reset_rmsf_calculations', (['analysis_actors_dict', 'self.start', 'self.stop', 'self.rmsf_cache'], {}), '(analysis_actors_dict, self.start, self.stop, self.\n rmsf_cache)\n', (23118, 23185), False, 'from MDSimsEval.rmsf_analysis import reset_rmsf_calculations\n'), ((23338, 23363), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (23361, 23363), False, 'import collections\n'), ((24661, 24680), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (24664, 24680), False, 'from sklearn.decomposition import PCA\n'), ((1718, 1780), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (["train_analysis_actors['Agonists'][0]"], {}), "(train_analysis_actors['Agonists'][0])\n", (1742, 1780), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((2098, 2163), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (["train_analysis_actors['Antagonists'][0]"], {}), "(train_analysis_actors['Antagonists'][0])\n", (2122, 2163), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((3429, 3461), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (['ligand'], {}), '(ligand)\n', (3453, 3461), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((12757, 12799), 'numpy.sum', 'np.sum', (['(agon_distances < antagon_distances)'], {}), '(agon_distances < antagon_distances)\n', (12763, 12799), True, 'import numpy as np\n'), ((19305, 19323), 'numpy.arange', 'np.arange', (['samples'], {}), '(samples)\n', (19314, 19323), True, 'import numpy as np\n'), ((19645, 19663), 'numpy.arange', 'np.arange', (['samples'], {}), '(samples)\n', (19654, 19663), True, 'import numpy as np\n'), ((25182, 25215), 'numpy.array', 'np.array', (['self.pairwise_distances'], {}), '(self.pairwise_distances)\n', (25190, 25215), True, 'import numpy as np\n'), ((1624, 1638), 'numpy.arange', 'np.arange', (['(290)'], {}), '(290)\n', (1633, 1638), True, 'import numpy as np\n'), ((23299, 23313), 'numpy.arange', 'np.arange', (['(290)'], {}), '(290)\n', (23308, 23313), True, 'import numpy as np\n'), ((23514, 23552), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (['which_ligand'], {}), '(which_ligand)\n', (23538, 23552), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((2843, 2937), 'MDSimsEval.rmsf_bootstrapped_analysis.find_rmsf_of_residues', 'find_rmsf_of_residues', (['train_analysis_actors', '[res]', 'window[0]', 'window[1]', 'self.rmsf_cache'], {}), '(train_analysis_actors, [res], window[0], window[1],\n self.rmsf_cache)\n', (2864, 2937), False, 'from MDSimsEval.rmsf_bootstrapped_analysis import find_rmsf_of_residues\n'), ((2957, 2977), 'numpy.array', 'np.array', (['rmsf_array'], {}), '(rmsf_array)\n', (2965, 2977), True, 'import numpy as np\n'), ((3711, 3832), 'MDSimsEval.rmsf_bootstrapped_analysis.find_rmsf_of_residues', 'find_rmsf_of_residues', (["{'Agonists': [ligand], 'Antagonists': [ligand]}", '[res]', 'window[0]', 'window[1]', 'self.rmsf_cache'], {}), "({'Agonists': [ligand], 'Antagonists': [ligand]}, [res\n ], window[0], window[1], self.rmsf_cache)\n", (3732, 3832), False, 'from MDSimsEval.rmsf_bootstrapped_analysis import find_rmsf_of_residues\n'), ((1949, 1987), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (['which_ligand'], {}), '(which_ligand)\n', (1973, 1987), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((2354, 2392), 'MDSimsEval.rmsf_analysis.get_avg_rmsf_per_residue', 'get_avg_rmsf_per_residue', (['which_ligand'], {}), '(which_ligand)\n', (2378, 2392), False, 'from MDSimsEval.rmsf_analysis import get_avg_rmsf_per_residue\n'), ((3893, 3913), 'numpy.array', 'np.array', (['rmsf_array'], {}), '(rmsf_array)\n', (3901, 3913), True, 'import numpy as np\n')] |
########################################################################
## basic sample ##
########################################################################
# https://docs.pymc.io/notebooks/GLM-negative-binomial-regression.html
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom
numargs = nbinom.numargs
a, b = 0.2, 0.8
rv = nbinom(a, b)
quantile = np.arange(0.01, 1, 0.1)
# Random Variates
R = nbinom.rvs(a, b, size=10)
print("Random Variates : \n", R)
# datasets
x = np.linspace(nbinom.ppf(0.01, a, b), nbinom.ppf(0.99, a, b), 10)
R = nbinom.ppf(x, 1, 3)
print("\nProbability Distribution : \n", R)
distribution = np.linspace(0, np.minimum(rv.dist.b, 2))
print("\nDistribution : \n", distribution)
# # Graphical Representation.
# plt.plot(distribution, rv.ppf(distribution))
x = np.linspace(0, 5, 100)
y1 = nbinom.ppf(x, a, b)
y2 = nbinom.pmf(x, a, b)
# Varying positional arguments
plt.plot(x, y1, "*", x, y2, "r--")
plt.show()
# ########################################################################
# ## Bayesian negative binomial regression sample ##
# ########################################################################
# # https://kieranrcampbell.github.io/blog/2015/03/31/tutorial-bayesian-nb-regression.html
# import numpy as np
# import matplotlib.pyplot as plt
# from scipy.special import gammaln
# from scipy.stats import truncnorm
# import seaborn as sns
# import pylab
# n_iter = 10000
# burn_in = 4000
# sigma_beta_0 = 0.5
# sigma_beta_1 = 0.7
# sigma_r = 0.5
# def nb_acceptance_ratio(theta, theta_p, y, N):
# """ theta = (mu, r), y is data, N = len(x) """
# mu, r = theta
# mu_p, r_p = theta_p
# term1 = r_p * np.log(r_p / (r_p + mu_p))
# term2 = -r * np.log(r / (r + mu))
# term3 = y * np.log(mu_p / mu * (mu + r) / (mu_p + r_p))
# term4 = gammaln(r_p + y)
# term5 = - gammaln(r + y)
# term6 = N * (gammaln(r) - gammaln(r_p))
# return (term1 + term2 + term3 + term4 + term5).sum() + term6
# def truncnorm_prop(x, sigma): # proposal for r (non-negative)
# return truncnorm.rvs(-x / sigma, np.Inf, loc=x, scale=sigma)
# def calculate_mu(beta, x):
# return beta[0] + beta[1] * x
# def metropolis_hastings(n_iter, bunr_in, thin=5):
# trace = np.zeros((n_iter, 3))# ordered beta_0 beta_1 r
# trace[0, :] = np.array([5.0, 5.0, 1.0])
# acceptance_rate = np.zeros(n_iter)
# # store previous mu to avoid calculating each time
# mu = calculate_mu(trace[0, 0:2], y)
# for i in range(1, n_iter):
# theta = trace[i-1,:] # theta = (beta_0, beta_1, r)
# theta_p = np.array(
# [
# np.random.normal(theta[0], sigma_beta_0),
# np.random.normal(theta[1], sigma_beta_1),
# truncnorm_prop(theta[2], sigma_r)
# ]
# )
# mu_p = calculate_mu(theta_p[0:2], x)
# if np.any(mu <= 0):
# print("mu == 0 on iteration %d" % i)
# alpha = nb_acceptance_ratio(
# (mu, theta[2]),
# (mu_p, theta_p[2]),
# y, N
# )
# u = np.log(np.random.uniform(0.0, 1.0))
# if u < alpha:
# trace[i,:] = theta_p
# mu = mu_p
# acceptance_rate[i - 1] = 1
# else:
# trace[i, :] = theta
# print("Acceptance rate: %.2f" % acceptance_rate[burn_in:].mean())
# return trace[burn_in::thin,:]
# # generate data
# sns.set_palette("hls", desat=0.6)
# sns.set_context(rc={"figure.figsize" : (6, 4)})
# np.random.seed(123)
# beta_0 = 10
# beta_1 = 5
# N = 150
# x = np.random.randint(0, 50, N)
# true_mu = beta_0 + beta_1 * x
# true_r = 10
# p = 1 - true_mu / (float(true_r) + true_mu)
# y = np.random.negative_binomial(n=true_r, p=p, size=N)
# # Graphical Representation.
# plt.scatter(x, y, color="black")
# plt.xlabel("x")
# plt.ylabel("y")
# plt.title("150 points generated")
# trace = metropolis_hastings(n_iter, burn_in)
# # Display traces
# pylab.rcParams["figure.figsize"] = (12.0, 8.0)
# plt.subplot(3, 2, 1)
# plt.plot(trace[:, 0])
# plt.title("beta_0")
# plt.subplot(3, 2, 2)
# plt.hist(trace[:, 0])
# plt.subplot(3, 2, 3)
# plt.plot(trace[:, 1])
# plt.title("beta_1")
# plt.subplot(3, 2, 4)
# plt.hist(trace[:, 1])
# plt.subplot(3, 2, 5)
# plt.plot(trace[:, 2])
# plt.title("r")
# plt.subplot(3, 2, 6)
# plt.hist(trace[:, 2])
# plt.show() | [
"numpy.minimum",
"matplotlib.pyplot.show",
"scipy.stats.nbinom.rvs",
"matplotlib.pyplot.plot",
"scipy.stats.nbinom.pmf",
"numpy.arange",
"numpy.linspace",
"scipy.stats.nbinom.ppf",
"scipy.stats.nbinom"
] | [((420, 432), 'scipy.stats.nbinom', 'nbinom', (['a', 'b'], {}), '(a, b)\n', (426, 432), False, 'from scipy.stats import nbinom\n'), ((445, 468), 'numpy.arange', 'np.arange', (['(0.01)', '(1)', '(0.1)'], {}), '(0.01, 1, 0.1)\n', (454, 468), True, 'import numpy as np\n'), ((492, 517), 'scipy.stats.nbinom.rvs', 'nbinom.rvs', (['a', 'b'], {'size': '(10)'}), '(a, b, size=10)\n', (502, 517), False, 'from scipy.stats import nbinom\n'), ((636, 655), 'scipy.stats.nbinom.ppf', 'nbinom.ppf', (['x', '(1)', '(3)'], {}), '(x, 1, 3)\n', (646, 655), False, 'from scipy.stats import nbinom\n'), ((883, 905), 'numpy.linspace', 'np.linspace', (['(0)', '(5)', '(100)'], {}), '(0, 5, 100)\n', (894, 905), True, 'import numpy as np\n'), ((911, 930), 'scipy.stats.nbinom.ppf', 'nbinom.ppf', (['x', 'a', 'b'], {}), '(x, a, b)\n', (921, 930), False, 'from scipy.stats import nbinom\n'), ((936, 955), 'scipy.stats.nbinom.pmf', 'nbinom.pmf', (['x', 'a', 'b'], {}), '(x, a, b)\n', (946, 955), False, 'from scipy.stats import nbinom\n'), ((988, 1022), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y1', '"""*"""', 'x', 'y2', '"""r--"""'], {}), "(x, y1, '*', x, y2, 'r--')\n", (996, 1022), True, 'import matplotlib.pyplot as plt\n'), ((1023, 1033), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1031, 1033), True, 'import matplotlib.pyplot as plt\n'), ((579, 601), 'scipy.stats.nbinom.ppf', 'nbinom.ppf', (['(0.01)', 'a', 'b'], {}), '(0.01, a, b)\n', (589, 601), False, 'from scipy.stats import nbinom\n'), ((603, 625), 'scipy.stats.nbinom.ppf', 'nbinom.ppf', (['(0.99)', 'a', 'b'], {}), '(0.99, a, b)\n', (613, 625), False, 'from scipy.stats import nbinom\n'), ((731, 755), 'numpy.minimum', 'np.minimum', (['rv.dist.b', '(2)'], {}), '(rv.dist.b, 2)\n', (741, 755), True, 'import numpy as np\n')] |
"""
Projects anchors into bird's eye view and image space.
Returns the minimum and maximum box corners, and will only work
for anchors rotated at 0 or 90 degrees
"""
import numpy as np
from lib.dataset.kitti_util import compute_numpy_boxes_3d
# import tensorflow as tf
# from wavedata.tools.core import calib_utils
def project_to_bev(anchors, bev_extents):
"""
Projects an array of 3D anchors into bird's eye view
Args:
anchors: list of anchors in anchor format (N x 6):
N x [x, y, z, dim_x, dim_y, dim_z],
can be a numpy array or tensor
bev_extents: xz extents of the 3d area
[[min_x, max_x], [min_z, max_z]]
Returns:
box_corners_norm: corners as a percentage of the map size, in the
format N x [x1, y1, x2, y2]. Origin is the top left corner
"""
# tensor_format = isinstance(anchors, tf.Tensor)
#
# if not tensor_format:
anchors = np.asarray(anchors)
x = anchors[:, 0]
z = anchors[:, 2]
half_dim_x = anchors[:, 3] / 2.0
half_dim_z = anchors[:, 5] / 2.0
# Calculate extent ranges
bev_x_extents_min = bev_extents[0][0]
bev_z_extents_min = bev_extents[1][0]
bev_x_extents_max = bev_extents[0][1]
bev_z_extents_max = bev_extents[1][1]
bev_x_extents_range = bev_x_extents_max - bev_x_extents_min
bev_z_extents_range = bev_z_extents_max - bev_z_extents_min
# 2D corners (top left, bottom right)
x1 = x - half_dim_x
x2 = x + half_dim_x
# Flip z co-ordinates (origin changes from bottom left to top left)
z1 = bev_z_extents_max - (z + half_dim_z)
z2 = bev_z_extents_max - (z - half_dim_z)
# Stack into (N x 4)
# if tensor_format:
# bev_box_corners = tf.stack([x1, z1, x2, z2], axis=1)
# else:
bev_box_corners = np.stack([x1, z1, x2, z2], axis=1)
# Convert from original xz into bev xz, origin moves to top left
bev_extents_min_tiled = [bev_x_extents_min, bev_z_extents_min,
bev_x_extents_min, bev_z_extents_min]
bev_box_corners = bev_box_corners - bev_extents_min_tiled
# Calculate normalized box corners for ROI pooling
extents_tiled = [bev_x_extents_range, bev_z_extents_range,
bev_x_extents_range, bev_z_extents_range]
bev_box_corners_norm = bev_box_corners / extents_tiled
return bev_box_corners, bev_box_corners_norm
def project_to_image_space(anchor, P, image_shape):
"""
Projects 3D anchors into image space
Args:
anchors: list of anchors in anchor format 1 x [x, y, z,
l, w, h, ry]
stereo_calib_p2: stereo camera calibration p2 matrix
image_shape: dimensions of the image [h, w]
Returns:
img_box: corners in image space - 1 x [x1, y1, x2, y2]
box_norm: corners as a percentage of the image size -
1 x [x1, y1, x2, y2]
"""
# if anchors.shape[1] != 6:
# raise ValueError("Invalid shape for anchors {}, should be "
# "(N, 6)".format(anchors.shape[1]))
#
pts_2d, pts_3d = compute_numpy_boxes_3d(anchor, P)
if pts_2d is None:
return None, None
# Get the min and maxes of image coordinates
x1 = np.amin(pts_2d[:, 0])
y1 = np.amin(pts_2d[:, 1])
x2 = np.amax(pts_2d[:, 0])
y2 = np.amax(pts_2d[:, 1])
img_box = np.array([x1, y1, x2, y2])
# Normalize
image_shape_h = image_shape[0]
image_shape_w = image_shape[1]
# Truncate remaining boxes into image space
if img_box[0] < 0:
img_box[0] = 0
if img_box[1] < 0:
img_box[1] = 0
if img_box[2] > image_shape_w:
img_box[2] = image_shape_w
if img_box[3] > image_shape_h:
img_box[3] = image_shape_h
image_shape_tiled = [image_shape_w, image_shape_h,
image_shape_w, image_shape_h]
box_norm = img_box / image_shape_tiled
return np.array(img_box, dtype=np.float32), \
np.array(box_norm, dtype=np.float32)
| [
"numpy.stack",
"numpy.amin",
"numpy.asarray",
"numpy.amax",
"numpy.array",
"lib.dataset.kitti_util.compute_numpy_boxes_3d"
] | [((949, 968), 'numpy.asarray', 'np.asarray', (['anchors'], {}), '(anchors)\n', (959, 968), True, 'import numpy as np\n'), ((1817, 1851), 'numpy.stack', 'np.stack', (['[x1, z1, x2, z2]'], {'axis': '(1)'}), '([x1, z1, x2, z2], axis=1)\n', (1825, 1851), True, 'import numpy as np\n'), ((3097, 3130), 'lib.dataset.kitti_util.compute_numpy_boxes_3d', 'compute_numpy_boxes_3d', (['anchor', 'P'], {}), '(anchor, P)\n', (3119, 3130), False, 'from lib.dataset.kitti_util import compute_numpy_boxes_3d\n'), ((3240, 3261), 'numpy.amin', 'np.amin', (['pts_2d[:, 0]'], {}), '(pts_2d[:, 0])\n', (3247, 3261), True, 'import numpy as np\n'), ((3271, 3292), 'numpy.amin', 'np.amin', (['pts_2d[:, 1]'], {}), '(pts_2d[:, 1])\n', (3278, 3292), True, 'import numpy as np\n'), ((3303, 3324), 'numpy.amax', 'np.amax', (['pts_2d[:, 0]'], {}), '(pts_2d[:, 0])\n', (3310, 3324), True, 'import numpy as np\n'), ((3334, 3355), 'numpy.amax', 'np.amax', (['pts_2d[:, 1]'], {}), '(pts_2d[:, 1])\n', (3341, 3355), True, 'import numpy as np\n'), ((3371, 3397), 'numpy.array', 'np.array', (['[x1, y1, x2, y2]'], {}), '([x1, y1, x2, y2])\n', (3379, 3397), True, 'import numpy as np\n'), ((3933, 3968), 'numpy.array', 'np.array', (['img_box'], {'dtype': 'np.float32'}), '(img_box, dtype=np.float32)\n', (3941, 3968), True, 'import numpy as np\n'), ((3980, 4016), 'numpy.array', 'np.array', (['box_norm'], {'dtype': 'np.float32'}), '(box_norm, dtype=np.float32)\n', (3988, 4016), True, 'import numpy as np\n')] |
import unittest
from chainer import backend
from chainer.backends import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initializers.GlorotUniform,
],
'shape': [(2, 3), (2, 3, 4)],
'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
class TestUniform(unittest.TestCase):
scale = 0.1
def check_initializer(self, w):
initializer = self.target(scale=self.scale)
initializer(w)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype, self.dtype)
def test_initializer_cpu(self):
w = numpy.empty(self.shape, dtype=self.dtype)
self.check_initializer(w)
@attr.gpu
def test_initializer_gpu(self):
w = cuda.cupy.empty(self.shape, dtype=self.dtype)
self.check_initializer(w)
def check_shaped_initializer(self, xp):
initializer = self.target(scale=self.scale, dtype=self.dtype)
w = initializers.generate_array(initializer, self.shape, xp)
self.assertIs(backend.get_array_module(w), xp)
self.assertTupleEqual(w.shape, self.shape)
self.assertEqual(w.dtype, self.dtype)
def test_shaped_initializer_cpu(self):
self.check_shaped_initializer(numpy)
@attr.gpu
def test_shaped_initializer_gpu(self):
self.check_shaped_initializer(cuda.cupy)
testing.run_module(__name__, __file__)
| [
"chainer.testing.product",
"numpy.empty",
"chainer.backend.get_array_module",
"chainer.initializers.generate_array",
"chainer.testing.run_module",
"chainer.backends.cuda.cupy.empty"
] | [((1549, 1587), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (1567, 1587), False, 'from chainer import testing\n'), ((796, 837), 'numpy.empty', 'numpy.empty', (['self.shape'], {'dtype': 'self.dtype'}), '(self.shape, dtype=self.dtype)\n', (807, 837), False, 'import numpy\n'), ((935, 980), 'chainer.backends.cuda.cupy.empty', 'cuda.cupy.empty', (['self.shape'], {'dtype': 'self.dtype'}), '(self.shape, dtype=self.dtype)\n', (950, 980), False, 'from chainer.backends import cuda\n'), ((1142, 1198), 'chainer.initializers.generate_array', 'initializers.generate_array', (['initializer', 'self.shape', 'xp'], {}), '(initializer, self.shape, xp)\n', (1169, 1198), False, 'from chainer import initializers\n'), ((211, 435), 'chainer.testing.product', 'testing.product', (["{'target': [initializers.Uniform, initializers.LeCunUniform, initializers.\n HeUniform, initializers.GlorotUniform], 'shape': [(2, 3), (2, 3, 4)],\n 'dtype': [numpy.float16, numpy.float32, numpy.float64]}"], {}), "({'target': [initializers.Uniform, initializers.LeCunUniform,\n initializers.HeUniform, initializers.GlorotUniform], 'shape': [(2, 3),\n (2, 3, 4)], 'dtype': [numpy.float16, numpy.float32, numpy.float64]})\n", (226, 435), False, 'from chainer import testing\n'), ((1221, 1248), 'chainer.backend.get_array_module', 'backend.get_array_module', (['w'], {}), '(w)\n', (1245, 1248), False, 'from chainer import backend\n')] |
""" Version of slider example that uses a Python function as a callback,
which is transpiled to JavaScript using PyScript. Read more on PyScript
here:
http://flexx.readthedocs.org/en/stable/pyscript
"""
import numpy as np
from bokeh. layouts import row, widgetbox
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.models import CustomJS, Slider
x = np.linspace(0, 10, 500)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
def callback(source=source, window=None):
data = source.data
A, B = amp.value, offset.value
k, phi = freq.value, phase.value
x, y = data['x'], data['y']
for i in range(len(x)):
y[i] = B + A * window.Math.sin(k * x[i] + phi)
source.trigger('change')
# turn our function into a CustomJS object.
# print(callback.code) to see the generated JavaScript code
callback = CustomJS.from_py_func(callback)
amp_slider = Slider(start=0.1, end=10, value=1, step=.1,
title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider
freq_slider = Slider(start=0.1, end=10, value=1, step=.1,
title="Frequency", callback=callback)
callback.args["freq"] = freq_slider
phase_slider = Slider(start=0, end=6.4, value=0, step=.1,
title="Phase", callback=callback)
callback.args["phase"] = phase_slider
offset_slider = Slider(start=-5, end=5, value=0, step=.1,
title="Offset", callback=callback)
callback.args["offset"] = offset_slider
layout = row(
plot,
widgetbox(amp_slider, freq_slider, phase_slider, offset_slider),
)
output_file("python_callback.html", title="python_callback.py example")
show(layout)
| [
"bokeh.plotting.figure",
"bokeh.models.Slider",
"bokeh.layouts.widgetbox",
"bokeh.plotting.output_file",
"numpy.sin",
"bokeh.plotting.show",
"numpy.linspace",
"bokeh.models.CustomJS.from_py_func"
] | [((390, 413), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(500)'], {}), '(0, 10, 500)\n', (401, 413), True, 'import numpy as np\n'), ((418, 427), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (424, 427), True, 'import numpy as np\n'), ((484, 542), 'bokeh.plotting.figure', 'figure', ([], {'y_range': '(-10, 10)', 'plot_width': '(400)', 'plot_height': '(400)'}), '(y_range=(-10, 10), plot_width=400, plot_height=400)\n', (490, 542), False, 'from bokeh.plotting import figure, output_file, show, ColumnDataSource\n'), ((1007, 1038), 'bokeh.models.CustomJS.from_py_func', 'CustomJS.from_py_func', (['callback'], {}), '(callback)\n', (1028, 1038), False, 'from bokeh.models import CustomJS, Slider\n'), ((1053, 1140), 'bokeh.models.Slider', 'Slider', ([], {'start': '(0.1)', 'end': '(10)', 'value': '(1)', 'step': '(0.1)', 'title': '"""Amplitude"""', 'callback': 'callback'}), "(start=0.1, end=10, value=1, step=0.1, title='Amplitude', callback=\n callback)\n", (1059, 1140), False, 'from bokeh.models import CustomJS, Slider\n'), ((1204, 1291), 'bokeh.models.Slider', 'Slider', ([], {'start': '(0.1)', 'end': '(10)', 'value': '(1)', 'step': '(0.1)', 'title': '"""Frequency"""', 'callback': 'callback'}), "(start=0.1, end=10, value=1, step=0.1, title='Frequency', callback=\n callback)\n", (1210, 1291), False, 'from bokeh.models import CustomJS, Slider\n'), ((1359, 1436), 'bokeh.models.Slider', 'Slider', ([], {'start': '(0)', 'end': '(6.4)', 'value': '(0)', 'step': '(0.1)', 'title': '"""Phase"""', 'callback': 'callback'}), "(start=0, end=6.4, value=0, step=0.1, title='Phase', callback=callback)\n", (1365, 1436), False, 'from bokeh.models import CustomJS, Slider\n'), ((1513, 1590), 'bokeh.models.Slider', 'Slider', ([], {'start': '(-5)', 'end': '(5)', 'value': '(0)', 'step': '(0.1)', 'title': '"""Offset"""', 'callback': 'callback'}), "(start=-5, end=5, value=0, step=0.1, title='Offset', callback=callback)\n", (1519, 1590), False, 'from bokeh.models import CustomJS, Slider\n'), ((1750, 1821), 'bokeh.plotting.output_file', 'output_file', (['"""python_callback.html"""'], {'title': '"""python_callback.py example"""'}), "('python_callback.html', title='python_callback.py example')\n", (1761, 1821), False, 'from bokeh.plotting import figure, output_file, show, ColumnDataSource\n'), ((1823, 1835), 'bokeh.plotting.show', 'show', (['layout'], {}), '(layout)\n', (1827, 1835), False, 'from bokeh.plotting import figure, output_file, show, ColumnDataSource\n'), ((1682, 1745), 'bokeh.layouts.widgetbox', 'widgetbox', (['amp_slider', 'freq_slider', 'phase_slider', 'offset_slider'], {}), '(amp_slider, freq_slider, phase_slider, offset_slider)\n', (1691, 1745), False, 'from bokeh.layouts import row, widgetbox\n')] |
import os.path as op
import cooler
import cooltools
import cooltools.api
from numpy import testing
import numpy as np
def test_coverage_symmetric_upper(request):
# perform test:
clr = cooler.Cooler(op.join(request.fspath.dirname, "data/CN.mm9.1000kb.cool"))
cis_cov, tot_cov = cooltools.api.coverage.coverage(
clr, ignore_diags=2, chunksize=int(1e7)
)
# Test that minimal coverage is larger than 0.5
assert tot_cov[tot_cov > 0].min() >= 1
# Test that dense matrix marginal is the same:
mtx = clr.matrix(balance=False, as_pixels=False)[:]
np.fill_diagonal(mtx, 0)
np.fill_diagonal(mtx[1:, :], 0)
np.fill_diagonal(mtx[:, 1:], 0)
cov_dense = np.sum(mtx, axis=1)
testing.assert_allclose(
actual=tot_cov, desired=cov_dense, equal_nan=True,
)
| [
"numpy.fill_diagonal",
"numpy.testing.assert_allclose",
"numpy.sum",
"os.path.join"
] | [((587, 611), 'numpy.fill_diagonal', 'np.fill_diagonal', (['mtx', '(0)'], {}), '(mtx, 0)\n', (603, 611), True, 'import numpy as np\n'), ((616, 647), 'numpy.fill_diagonal', 'np.fill_diagonal', (['mtx[1:, :]', '(0)'], {}), '(mtx[1:, :], 0)\n', (632, 647), True, 'import numpy as np\n'), ((652, 683), 'numpy.fill_diagonal', 'np.fill_diagonal', (['mtx[:, 1:]', '(0)'], {}), '(mtx[:, 1:], 0)\n', (668, 683), True, 'import numpy as np\n'), ((700, 719), 'numpy.sum', 'np.sum', (['mtx'], {'axis': '(1)'}), '(mtx, axis=1)\n', (706, 719), True, 'import numpy as np\n'), ((724, 798), 'numpy.testing.assert_allclose', 'testing.assert_allclose', ([], {'actual': 'tot_cov', 'desired': 'cov_dense', 'equal_nan': '(True)'}), '(actual=tot_cov, desired=cov_dense, equal_nan=True)\n', (747, 798), False, 'from numpy import testing\n'), ((209, 267), 'os.path.join', 'op.join', (['request.fspath.dirname', '"""data/CN.mm9.1000kb.cool"""'], {}), "(request.fspath.dirname, 'data/CN.mm9.1000kb.cool')\n", (216, 267), True, 'import os.path as op\n')] |
'''
Basic numpy style mathematics operations on arrays.
These include --
*
'''
import sys
import __builtin__
import numpy as np
import scipy.sparse as sp
from .operator.map import map, map2
from .operator.map_with_location import map_with_location
from .operator.reduce import reduce
from .operator.ndarray import ndarray
from .operator.optimize import disable_parakeet, not_idempotent
from .. import util, blob_ctx
from ..array import extent
from ..array.extent import index_for_reduction, shapes_match
from ..util import Assert
def add(a, b):
return map((a, b), fn=np.add)
def reciprocal(a):
return map(a, fn=np.reciprocal)
def negative(a):
return map(a, fn=np.negative)
def sub(a, b):
return map((a, b), fn=np.subtract)
def _rsub(a, b):
return map((b, a), fn=np.sub)
def _multiply(a, b):
if sp.issparse(a):
return a.multiply(b)
else:
return np.multiply(a, b)
def multiply(a, b):
return map((a, b), fn=_multiply)
def _divide(a, b):
if sp.issparse(a):
return a.divide(b)
else:
return np.divide(a, b)
def divide(a, b):
return map((a, b), fn=_divide)
def _rdivide(a, b):
return divide(b, a)
def true_divide(a, b):
return map((a, b), fn=np.true_divide)
def floor_divide(a, b):
return map((a, b), fn=np.floor_divide)
def fmod(a, b):
return map((a, b), fn=np.fmod)
def mod(a, b):
return map((a, b), fn=np.mod)
def remainder(a, b):
return remainder((a, b), fn=np.remainder)
def power(a, b):
return map((a, b), fn=np.power)
def maximum(a, b):
return map((a, b), np.maximum)
def minimum(a, b):
return map((a, b), np.minimum)
def ln(v):
return map(v, fn=np.log)
def log(v):
return map(v, fn=np.log)
def exp(v):
return map(v, fn=np.exp)
def square(v):
return map(v, fn=np.square)
def sqrt(v):
return map(v, fn=np.sqrt)
def abs(v):
return map(v, fn=np.abs)
def _sum_local(ex, data, axis):
return data.sum(axis)
def sum(x, axis=None, tile_hint=None):
'''
Sum ``x`` over ``axis``.
:param x: The array to sum.
:param axis: Either an integer or ``None``.
'''
return reduce(x,
axis=axis,
dtype_fn=lambda input: input.dtype,
local_reduce_fn=_sum_local,
accumulate_fn=np.add,
tile_hint=tile_hint)
def _prod_local(ex, data, axis):
return data.prod(axis)
def _prod_dtype_fn(input):
if input.dtype == np.int32:
return np.dtype(np.int64)
else:
return input.dtype
def prod(x, axis=None, tile_hint=None):
'''
Prod ``x`` over ``axis``.
:param x: The array to product.
:param axis: Either an integer or ``None``.
'''
return reduce(x,
axis=axis,
dtype_fn=_prod_dtype_fn,
local_reduce_fn=_prod_local,
accumulate_fn=np.multiply,
tile_hint=tile_hint)
| [
"scipy.sparse.issparse",
"numpy.divide",
"numpy.dtype",
"numpy.multiply"
] | [((821, 835), 'scipy.sparse.issparse', 'sp.issparse', (['a'], {}), '(a)\n', (832, 835), True, 'import scipy.sparse as sp\n'), ((982, 996), 'scipy.sparse.issparse', 'sp.issparse', (['a'], {}), '(a)\n', (993, 996), True, 'import scipy.sparse as sp\n'), ((881, 898), 'numpy.multiply', 'np.multiply', (['a', 'b'], {}), '(a, b)\n', (892, 898), True, 'import numpy as np\n'), ((1040, 1055), 'numpy.divide', 'np.divide', (['a', 'b'], {}), '(a, b)\n', (1049, 1055), True, 'import numpy as np\n'), ((2429, 2447), 'numpy.dtype', 'np.dtype', (['np.int64'], {}), '(np.int64)\n', (2437, 2447), True, 'import numpy as np\n')] |
# MIT License
# Copyright 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# ==============================================================================
"""Tests the model functions"""
import collections
import pytest
import numpy as np
import tensorflow as tf
import morpheus.core.base_model as base_model
import morpheus.core.unet as unet
from morpheus.core.hparams import HParams
class TestAssistant:
"""Makes things that the tests want."""
@staticmethod
def mock_dataset() -> collections.namedtuple:
"""Makes a compatible mock dataset.
This snippet is adapted from morpheus.core.model.Morpheus
"""
MockDataset = collections.namedtuple("Dataset", ["num_labels", "train", "test"])
train_data = (TestAssistant.zero_array(), TestAssistant.zero_array())
return MockDataset(5, train=train_data, test=train_data)
@staticmethod
def mock_hparams(
inference: bool, batch_norm: bool, drop_out: bool, num_contractions: int
):
"""Makes a simple model config for testing.
Args:
inference (bool): boolean flag for inference
batch_norm (bool): boolean flag for batch normalization in graph
drop_out (bool): boolean flag for drop out in graph
num_contractions (int): number of down/up sample pairs
"""
num_filters = [1 for _ in range(num_contractions)]
hparams = HParams(
inference=inference,
num_epochs=1,
batch_norm=batch_norm,
drop_out=drop_out,
down_filters=num_filters,
up_filters=num_filters,
learning_rate=0.1,
dropout_rate=0.5,
num_down_convs=1,
num_up_convs=1,
num_intermediate_filters=1,
)
return hparams
@staticmethod
def zero_tensor() -> tf.Tensor:
"""Makes a zero filled tensor with shape [3, 3]"""
return tf.zeros([3, 3])
@staticmethod
def in_tensor(data_format: str) -> tf.Tensor:
"""Makes a sample tensor input tensor for shape testing.
Args:
data_format (str): 'channels_first' or 'channels_last'
Returns:
A tensor with shape [100, 80, 80, 5] if 'channels_last' or
[100, 5, 80, 80] if 'channels_first'
"""
shape = [100, 80, 80, 80]
if data_format == "channels_first":
shape[1] = 4
else:
shape[3] = 4
return tf.zeros(shape, dtype=tf.float32)
@staticmethod
def zero_array() -> np.ndarray:
"""Makes a zero filled tensor with shape [3, 3]"""
return np.zeros([3, 3])
@pytest.mark.unit
class TestBaseModel:
"""A class that tests the functions of morpheus.core.base_model.Model."""
@staticmethod
def test_model_fn_raises():
"""Tests that the non overridden model_fn raises NotImplemented."""
model = base_model.Model(TestAssistant.mock_dataset())
with pytest.raises(NotImplementedError):
model.model_fn(TestAssistant.zero_tensor(), True)
@staticmethod
def test_build_graph_raises():
"""Tests that the non overridden model_fn raises on a build_graph call."""
model = base_model.Model(TestAssistant.mock_dataset())
with pytest.raises(NotImplementedError):
model.build_graph(TestAssistant.zero_tensor(), True)
@staticmethod
def test_build_graph():
"""Tests the build_graph method."""
model = base_model.Model(TestAssistant.mock_dataset())
model.model_fn = lambda x, y: (x, y)
expected_x = TestAssistant.zero_array()
expected_is_training = True
x, is_training = model.build_graph(expected_x, expected_is_training)
np.testing.assert_array_equal(x, expected_x)
assert is_training == expected_is_training
@staticmethod
def test_build_graph_singleton():
"""Tests the build_graph method, two calls."""
model = base_model.Model(TestAssistant.mock_dataset())
model.model_fn = lambda x, y: (x, y)
expected_x = TestAssistant.zero_array()
expected_is_training = True
model.build_graph(expected_x, expected_is_training)
x, is_training = model.build_graph(expected_x, expected_is_training)
np.testing.assert_array_equal(x, expected_x)
assert is_training == expected_is_training
@staticmethod
def test_train():
"""Test the train() method, doesn't raise."""
model = base_model.Model(TestAssistant.mock_dataset())
model.model_fn = lambda x, y: x
model.train()
@staticmethod
def test_test():
"""Test the test() method, doesn't raise."""
model = base_model.Model(TestAssistant.mock_dataset())
model.model_fn = lambda x, y: x
model.test()
@pytest.mark.unit
class TestUNet:
"""A class that tests the functions of morpheus.core.unet.Model"""
@staticmethod
def test_upsample_shape_doubles():
inference, batch_norm, drop_out = True, True, True
num_contractions = 1
data_format = "channels_last"
dataset = TestAssistant.mock_dataset()
hparams = TestAssistant.mock_hparams(
inference, batch_norm, drop_out, num_contractions
)
x = TestAssistant.in_tensor(data_format)
expected_shape = x.shape.as_list()
expected_shape[1] *= 2
expected_shape[2] *= 2
model = unet.Model(hparams, dataset, data_format)
x = model.up_sample(x)
actual_shape = x.shape.as_list()
assert expected_shape == actual_shape
@staticmethod
def test_upsample_with_transpose_shape_doubles():
inference, batch_norm, drop_out = True, True, True
num_contractions = 1
data_format = "channels_first"
dataset = TestAssistant.mock_dataset()
hparams = TestAssistant.mock_hparams(
inference, batch_norm, drop_out, num_contractions
)
x = TestAssistant.in_tensor(data_format)
expected_shape = x.shape.as_list()
expected_shape[2] *= 2
expected_shape[3] *= 2
model = unet.Model(hparams, dataset, data_format)
x = model.up_sample(x)
actual_shape = x.shape.as_list()
assert expected_shape == actual_shape
@staticmethod
def test_downsample_shape_halves():
inference, batch_norm, drop_out = True, True, True
num_contractions = 1
data_format = "channels_last"
dataset = TestAssistant.mock_dataset()
hparams = TestAssistant.mock_hparams(
inference, batch_norm, drop_out, num_contractions
)
x = TestAssistant.in_tensor(data_format)
expected_shape = x.shape.as_list()
expected_shape[1] /= 2
expected_shape[2] /= 2
model = unet.Model(hparams, dataset, data_format)
x = model.down_sample(x)
actual_shape = x.shape.as_list()
assert expected_shape == actual_shape
| [
"morpheus.core.unet.Model",
"numpy.testing.assert_array_equal",
"numpy.zeros",
"pytest.raises",
"tensorflow.zeros",
"morpheus.core.hparams.HParams",
"collections.namedtuple"
] | [((1690, 1756), 'collections.namedtuple', 'collections.namedtuple', (['"""Dataset"""', "['num_labels', 'train', 'test']"], {}), "('Dataset', ['num_labels', 'train', 'test'])\n", (1712, 1756), False, 'import collections\n'), ((2453, 2699), 'morpheus.core.hparams.HParams', 'HParams', ([], {'inference': 'inference', 'num_epochs': '(1)', 'batch_norm': 'batch_norm', 'drop_out': 'drop_out', 'down_filters': 'num_filters', 'up_filters': 'num_filters', 'learning_rate': '(0.1)', 'dropout_rate': '(0.5)', 'num_down_convs': '(1)', 'num_up_convs': '(1)', 'num_intermediate_filters': '(1)'}), '(inference=inference, num_epochs=1, batch_norm=batch_norm, drop_out=\n drop_out, down_filters=num_filters, up_filters=num_filters,\n learning_rate=0.1, dropout_rate=0.5, num_down_convs=1, num_up_convs=1,\n num_intermediate_filters=1)\n', (2460, 2699), False, 'from morpheus.core.hparams import HParams\n'), ((2984, 3000), 'tensorflow.zeros', 'tf.zeros', (['[3, 3]'], {}), '([3, 3])\n', (2992, 3000), True, 'import tensorflow as tf\n'), ((3526, 3559), 'tensorflow.zeros', 'tf.zeros', (['shape'], {'dtype': 'tf.float32'}), '(shape, dtype=tf.float32)\n', (3534, 3559), True, 'import tensorflow as tf\n'), ((3690, 3706), 'numpy.zeros', 'np.zeros', (['[3, 3]'], {}), '([3, 3])\n', (3698, 3706), True, 'import numpy as np\n'), ((4814, 4858), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['x', 'expected_x'], {}), '(x, expected_x)\n', (4843, 4858), True, 'import numpy as np\n'), ((5362, 5406), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['x', 'expected_x'], {}), '(x, expected_x)\n', (5391, 5406), True, 'import numpy as np\n'), ((6525, 6566), 'morpheus.core.unet.Model', 'unet.Model', (['hparams', 'dataset', 'data_format'], {}), '(hparams, dataset, data_format)\n', (6535, 6566), True, 'import morpheus.core.unet as unet\n'), ((7227, 7268), 'morpheus.core.unet.Model', 'unet.Model', (['hparams', 'dataset', 'data_format'], {}), '(hparams, dataset, data_format)\n', (7237, 7268), True, 'import morpheus.core.unet as unet\n'), ((7914, 7955), 'morpheus.core.unet.Model', 'unet.Model', (['hparams', 'dataset', 'data_format'], {}), '(hparams, dataset, data_format)\n', (7924, 7955), True, 'import morpheus.core.unet as unet\n'), ((4030, 4064), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (4043, 4064), False, 'import pytest\n'), ((4342, 4376), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (4355, 4376), False, 'import pytest\n')] |
#!/usr/bin/env python
import os
import numpy as np
import cv2
import argparse
import chumpy as ch
from chumpy import Ch
from argparse import ArgumentParser
import os.path as path
import SHLoss as sh
def is_valid_file(parser, arg):
if not path.exists(arg):
parser.error("The file %s does not exist!" % arg)
else:
return path.abspath(arg) #open(arg, 'r') # return an open file handle
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="Normals From Shading: Environment Light Estimation.")
parser.add_argument("--image", dest="image", required=True,
help="Path to raw RGB Image", metavar="FILE",
type=lambda x: is_valid_file(parser, x))
parser.add_argument("--albedo", dest="albedo", required=True,
help="Path to albedo Image", metavar="FILE",
type=lambda x: is_valid_file(parser, x))
parser.add_argument("--normals", dest="normalMap", required=False,
help="Path to normal map", metavar="FILE",
type=lambda x: is_valid_file(parser, x))
parser.add_argument("--output", dest="output", default='./output-normals.bmp',
help="Path to output file", type=str)
return parser.parse_args()
def mkdir_s( dir ):
if not path.exists( dir ):
os.mkdir( dir )
# -----------------------------------------------------------------------------
def normalsFromShading(image, # input RGB image
albedo, # albedo image
illum, # Initial SH illumination Parameters
normals, # Initial normal map
weights, # weights for the objectives
opt_options, # options
mask, mask_reg, edge_list):
image_ch = ch.array(image)
albedo_ch = ch.array(albedo)
illum_ch = ch.array(illum)
normals_ref_ch = ch.array(normals)
normals_ch = ch.array(normals)
""" function: estimate Normals from Shading using Spherical Harmonics
input:
image: input RGB image
albedo: albedo image
illum_init: Initial SH illumination Parameters
normals_init: Initial normal map
weights: weights for the objectives
opt_options: optimization options
output:
illum: estimated SH illumination
normals: estimated Normals
"""
# options
if opt_options is None:
print("normalsFromShading(): 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'] = 100
sparse_solver = lambda A, x: sp.linalg.cg(A, x, maxiter=opt_options['maxiter'])[0]
opt_options['sparse_solver'] = sparse_solver
# weights
print("normalsFromShading(): use the following weights:")
for kk in weights.keys():
print("normalsFromShading(): weights['%s'] = %f" % (kk, weights[kk]))
# objectives
# Illumination Error
illum_err = sh.illum_error(image=image_ch,
albedo=albedo_ch,
illum=illum_ch,
normals=normals_ch,
mask=mask,
weight=weights['illum'])
# regularizer
#illum_reg = weights['illum_reg'] * illum_ch
# Difference Regularization
# normals_reg = Ch(weights['normals_reg']) * (normals_ch - normals_ref_ch)
illum_reg = sh.illum_reg(normals=normals_ch,
normals_ref=normals_ref_ch,
edge_list=edge_list,
mask=mask_reg,
weight=weights['normals_reg'])
objectives = {}
# objectives.update({'illum': illum_err})
objectives.update({'illum': illum_err, 'normals_reg': illum_reg})
# on_step callback
def on_step(_):
pass
# optimize
# step 1: rigid alignment
from time import time
timer_start = time()
print("\nstep 1: start Illumination Estimation...")
ch.minimize(fun=illum_err,
x0=[illum_ch],
method='dogleg',
callback=on_step,
options=opt_options)
timer_end = time()
print("step 1: Illumination Estimation done, in %f sec\n" % (timer_end - timer_start))
# step 2: non-rigid alignment
timer_start = time()
print("step 2: start Normal Refinement...")
ch.minimize(fun=objectives,
x0=[normals_ch],
method='dogleg',
callback=on_step,
options=opt_options)
timer_end = time()
print("step 2: Normal Refinement done, in %f sec\n" % (timer_end - timer_start))
R = sh.computeSHEnergy(illum_ch, normals_ch)
result = albedo.reshape(-1) * R
R_init = sh.computeSHEnergy(illum_ch, ch.array(normals))
initNormalSH = albedo.reshape(-1) * R_init
# return results
return illum_ch.r, normals_ch.r, result.r.reshape(albedo.shape), initNormalSH.r.reshape(albedo.shape), albedo_ch.r
# -----------------------------------------------------------------------------
def run_fitting(image, albedo, normals_init, mask, mask_reg, edge_list, outputPath=None):
# output
if outputPath is not None:
dir_path = path.dirname(path.realpath(outputPath))
mkdir_s(dir_path)
# weights
weights = {}
weights['illum'] = 1.0
weights['normals'] = 1.0
weights['illum_reg'] = 0.0
weights['normals_reg'] = 3e-3
# 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'] = 200
sparse_solver = lambda A, x: sp.linalg.cg(A, x, maxiter=opt_options['maxiter'])[0]
opt_options['sparse_solver'] = sparse_solver
illum_init = np.zeros(9)
# run fitting
illum, normals, result, result_init, albedo_r = \
normalsFromShading( image=image, # input RGB image
albedo=albedo, # albedo image
illum=illum_init, # albedo image
normals=normals_init, # Initial normal map
weights=weights, # weights for the objectives
opt_options=opt_options, # options
mask=mask,
mask_reg=mask_reg,
edge_list=edge_list)
# write result
print("Estimatied SH Lignting Params:\n{0}".format(illum))
if outputPath is not None:
np.savetxt("{}.csv".format(outputPath), illum, delimiter=",")
cv2.imwrite(outputPath, (normals+1)*128)
cv2.imwrite("before.png", result_init*255)
cv2.imwrite("result.png", result*255)
cv2.imwrite("albedo.png", albedo_r*255)
return illum, normals
# -----------------------------------------------------------------------------
def main():
args = get_arguments()
imagePath = args.image
albedoPath = args.albedo
normalsPath = args.normalMap
outputPath = args.output
# print(imagePath)
# print(albedoPath)
# print(normalsPath)
print("Output Path: {}".format(outputPath))
# Read Images into numpy arrays and normalize
# TODO: compute SH for each channel
image = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)/255
albedo = cv2.imread(albedoPath, cv2.IMREAD_GRAYSCALE)/255
normalMap = None
if args.normalMap is not None:
print("Loading Normal Map...")
# Recreate normal map from uchar
normalMap_raw = cv2.imread(normalsPath, cv2.IMREAD_COLOR)
#normalMap = ((normalMap_raw - 127) / 127)
# normalMap = normalMap_raw/255
normalMap = (normalMap_raw / 128) - 1
else:
print("Assuming solid surface perpendicular to camera...")
normalMap = np.zeros(np.hstack((image.shape,3)))
normalMap[:,:,0] = 1.
normalMap[:,:,1] = 0.
normalMap[:,:,2] = 0.
#print(image.shape)
#print(albedo.shape)
#print(normalMap.shape)
run_fitting(image, albedo, normalMap, outputPath)
# run_fitting()
# -----------------------------------------------------------------------------
if __name__ == '__main__':
main() | [
"os.mkdir",
"os.path.abspath",
"argparse.ArgumentParser",
"SHLoss.illum_error",
"cv2.imwrite",
"os.path.realpath",
"scipy.sparse.linalg.cg",
"SHLoss.computeSHEnergy",
"numpy.zeros",
"os.path.exists",
"time.time",
"SHLoss.illum_reg",
"cv2.imread",
"numpy.hstack",
"chumpy.array",
"chumpy... | [((557, 652), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Normals From Shading: Environment Light Estimation."""'}), "(description=\n 'Normals From Shading: Environment Light Estimation.')\n", (580, 652), False, 'import argparse\n'), ((1963, 1978), 'chumpy.array', 'ch.array', (['image'], {}), '(image)\n', (1971, 1978), True, 'import chumpy as ch\n'), ((1995, 2011), 'chumpy.array', 'ch.array', (['albedo'], {}), '(albedo)\n', (2003, 2011), True, 'import chumpy as ch\n'), ((2027, 2042), 'chumpy.array', 'ch.array', (['illum'], {}), '(illum)\n', (2035, 2042), True, 'import chumpy as ch\n'), ((2064, 2081), 'chumpy.array', 'ch.array', (['normals'], {}), '(normals)\n', (2072, 2081), True, 'import chumpy as ch\n'), ((2099, 2116), 'chumpy.array', 'ch.array', (['normals'], {}), '(normals)\n', (2107, 2116), True, 'import chumpy as ch\n'), ((3264, 3389), 'SHLoss.illum_error', 'sh.illum_error', ([], {'image': 'image_ch', 'albedo': 'albedo_ch', 'illum': 'illum_ch', 'normals': 'normals_ch', 'mask': 'mask', 'weight': "weights['illum']"}), "(image=image_ch, albedo=albedo_ch, illum=illum_ch, normals=\n normals_ch, mask=mask, weight=weights['illum'])\n", (3278, 3389), True, 'import SHLoss as sh\n'), ((3736, 3868), 'SHLoss.illum_reg', 'sh.illum_reg', ([], {'normals': 'normals_ch', 'normals_ref': 'normals_ref_ch', 'edge_list': 'edge_list', 'mask': 'mask_reg', 'weight': "weights['normals_reg']"}), "(normals=normals_ch, normals_ref=normals_ref_ch, edge_list=\n edge_list, mask=mask_reg, weight=weights['normals_reg'])\n", (3748, 3868), True, 'import SHLoss as sh\n'), ((4265, 4271), 'time.time', 'time', ([], {}), '()\n', (4269, 4271), False, 'from time import time\n'), ((4332, 4433), 'chumpy.minimize', 'ch.minimize', ([], {'fun': 'illum_err', 'x0': '[illum_ch]', 'method': '"""dogleg"""', 'callback': 'on_step', 'options': 'opt_options'}), "(fun=illum_err, x0=[illum_ch], method='dogleg', callback=on_step,\n options=opt_options)\n", (4343, 4433), True, 'import chumpy as ch\n'), ((4510, 4516), 'time.time', 'time', ([], {}), '()\n', (4514, 4516), False, 'from time import time\n'), ((4661, 4667), 'time.time', 'time', ([], {}), '()\n', (4665, 4667), False, 'from time import time\n'), ((4720, 4825), 'chumpy.minimize', 'ch.minimize', ([], {'fun': 'objectives', 'x0': '[normals_ch]', 'method': '"""dogleg"""', 'callback': 'on_step', 'options': 'opt_options'}), "(fun=objectives, x0=[normals_ch], method='dogleg', callback=\n on_step, options=opt_options)\n", (4731, 4825), True, 'import chumpy as ch\n'), ((4901, 4907), 'time.time', 'time', ([], {}), '()\n', (4905, 4907), False, 'from time import time\n'), ((5002, 5042), 'SHLoss.computeSHEnergy', 'sh.computeSHEnergy', (['illum_ch', 'normals_ch'], {}), '(illum_ch, normals_ch)\n', (5020, 5042), True, 'import SHLoss as sh\n'), ((6144, 6155), 'numpy.zeros', 'np.zeros', (['(9)'], {}), '(9)\n', (6152, 6155), True, 'import numpy as np\n'), ((247, 263), 'os.path.exists', 'path.exists', (['arg'], {}), '(arg)\n', (258, 263), True, 'import os.path as path\n'), ((348, 365), 'os.path.abspath', 'path.abspath', (['arg'], {}), '(arg)\n', (360, 365), True, 'import os.path as path\n'), ((1430, 1446), 'os.path.exists', 'path.exists', (['dir'], {}), '(dir)\n', (1441, 1446), True, 'import os.path as path\n'), ((1458, 1471), 'os.mkdir', 'os.mkdir', (['dir'], {}), '(dir)\n', (1466, 1471), False, 'import os\n'), ((5123, 5140), 'chumpy.array', 'ch.array', (['normals'], {}), '(normals)\n', (5131, 5140), True, 'import chumpy as ch\n'), ((6948, 6992), 'cv2.imwrite', 'cv2.imwrite', (['outputPath', '((normals + 1) * 128)'], {}), '(outputPath, (normals + 1) * 128)\n', (6959, 6992), False, 'import cv2\n'), ((6997, 7041), 'cv2.imwrite', 'cv2.imwrite', (['"""before.png"""', '(result_init * 255)'], {}), "('before.png', result_init * 255)\n", (7008, 7041), False, 'import cv2\n'), ((7048, 7087), 'cv2.imwrite', 'cv2.imwrite', (['"""result.png"""', '(result * 255)'], {}), "('result.png', result * 255)\n", (7059, 7087), False, 'import cv2\n'), ((7094, 7135), 'cv2.imwrite', 'cv2.imwrite', (['"""albedo.png"""', '(albedo_r * 255)'], {}), "('albedo.png', albedo_r * 255)\n", (7105, 7135), False, 'import cv2\n'), ((7625, 7668), 'cv2.imread', 'cv2.imread', (['imagePath', 'cv2.IMREAD_GRAYSCALE'], {}), '(imagePath, cv2.IMREAD_GRAYSCALE)\n', (7635, 7668), False, 'import cv2\n'), ((7686, 7730), 'cv2.imread', 'cv2.imread', (['albedoPath', 'cv2.IMREAD_GRAYSCALE'], {}), '(albedoPath, cv2.IMREAD_GRAYSCALE)\n', (7696, 7730), False, 'import cv2\n'), ((7896, 7937), 'cv2.imread', 'cv2.imread', (['normalsPath', 'cv2.IMREAD_COLOR'], {}), '(normalsPath, cv2.IMREAD_COLOR)\n', (7906, 7937), False, 'import cv2\n'), ((5581, 5606), 'os.path.realpath', 'path.realpath', (['outputPath'], {}), '(outputPath)\n', (5594, 5606), True, 'import os.path as path\n'), ((6023, 6073), 'scipy.sparse.linalg.cg', 'sp.linalg.cg', (['A', 'x'], {'maxiter': "opt_options['maxiter']"}), "(A, x, maxiter=opt_options['maxiter'])\n", (6035, 6073), True, 'import scipy.sparse as sp\n'), ((8182, 8209), 'numpy.hstack', 'np.hstack', (['(image.shape, 3)'], {}), '((image.shape, 3))\n', (8191, 8209), True, 'import numpy as np\n'), ((2909, 2959), 'scipy.sparse.linalg.cg', 'sp.linalg.cg', (['A', 'x'], {'maxiter': "opt_options['maxiter']"}), "(A, x, maxiter=opt_options['maxiter'])\n", (2921, 2959), True, 'import scipy.sparse as sp\n')] |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 <NAME>. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import library
from . transform import Transform
class PanZoom(Transform):
"""
2D pan & zoom transform.
:param float aspect:
Indicate what is the aspect ratio of the object displayed. This is
necessary to convert pixel drag move in oject space coordinates.
Default is None.
:param float,float pan:
Initial translation. Default is (0,0)
:param float,float zoom:
Initial zoom level. Default is (1,1)
:param float zoom_min:
Minimal zoom level. Default is 0.01
:param float zoom_max:
Minimal zoom level. Default is 1000.0
The panzoom transform allow to translate and scale a scene in the window
space coordinate (2D). This means that whatever point you grab on the
screen, it should remains under the mouse pointer. Zoom is realized using
the mouse scroll and is always centered on the mouse pointer.
The transform is connected to the following events:
* ``on_attach``: Transform initialization
* ``on_resize``: Tranform update to maintain aspect
* ``on_mouse_scroll``: Zoom in & out (user action)
* ``on_mouse_grab``: Pan (user action)
**Usage example**:
.. code:: python
vertex = '''
attribute vec2 position;
void main()
{
gl_Position = <transform>(vec4(position, 0.0, 1.0));
} '''
...
window = app.Window(width=800, height=800)
program = gloo.Program(vertex, fragment, count=4)
...
program['transform'] = PanZoom(aspect=1)
window.attach(program['transform'])
...
"""
aliases = { "pan" : "panzoom_translate",
"translate" : "panzoom_translate",
"zoom" : "panzoom_scale",
"scale" : "panzoom_scale" }
def __init__(self, *args, **kwargs):
"""
Initialize the transform.
"""
code = library.get("transforms/panzoom.glsl")
Transform.__init__(self, code, *args, **kwargs)
self._aspect = Transform._get_kwarg("aspect", kwargs) or None
self._pan = np.array(Transform._get_kwarg("pan", kwargs) or (0.,0.))
self._zoom_min = Transform._get_kwarg("zoom_min", kwargs) or 0.01
self._zoom_max = Transform._get_kwarg("zoom_max", kwargs) or 1000
self._zoom = Transform._get_kwarg("zoom", kwargs) or 1
self._width = 1
self._height = 1
self._window_aspect = np.asarray([1.,1.])
@property
def aspect(self):
""" Aspect (width/height) """
return self._aspect
@aspect.setter
def aspect(self, value):
""" Aspect (width/height) """
self._aspect = value
@property
def pan(self):
""" Panning (translation) """
return self._pan
@pan.setter
def pan(self, value):
""" Panning (translation) """
self._pan = np.asarray(value)
if self.is_attached:
self["pan"] = self._pan
@property
def zoom(self):
""" Zoom level """
return self._zoom
@zoom.setter
def zoom(self, value):
""" Zoom level """
self._zoom = np.clip(value, self._zoom_min, self._zoom_max)
if self.is_attached:
aspect = 1.0
if self._aspect is not None:
aspect = self._window_aspect * self._aspect
self["zoom"] = self._zoom * aspect
@property
def zoom_min(self):
""" Minimal zoom level """
return self._zoom_min
@zoom_min.setter
def zoom_min(self, value):
""" Minimal zoom level """
self._zoom_min = min(value, self._zoom_max)
@property
def zoom_max(self):
""" Maximal zoom level """
return self._zoom_max
@zoom_max.setter
def zoom_max(self, value):
""" Maximal zoom level """
self._zoom_max = max(value, self._zoom_min)
def reset(self):
""" Reset transform (zoom=1, pan=(0,0)) """
self.zoom = 1
self.pan = 0,0
def on_attach(self, program):
self["pan"] = self.pan
aspect = 1.0
if self._aspect is not None:
aspect = self._window_aspect * self._aspect
self["zoom"] = self.zoom * aspect
def on_resize(self, width, height):
self._width = float(width)
self._height = float(height)
aspect = self._width/self._height
if aspect > 1.0:
self._window_aspect = np.array([1.0/aspect, 1.0])
else:
self._window_aspect = np.array([1.0, aspect/1.0])
aspect = 1.0
if self._aspect is not None:
aspect = self._window_aspect * self._aspect
self["zoom"] = self.zoom * aspect
# Transmit signal to other transforms
Transform.on_resize(self, width, height)
def on_mouse_scroll(self, x, y, dx, dy):
# Normalize mouse coordinates and invert y axis
x = x/(self._width/2.) - 1.
y = 1.0 - y/(self._height/2.)
zoom = np.clip(self._zoom*(1.0+dy/100.0), self.zoom_min, self.zoom_max)
ratio = zoom / self.zoom
xpan = x-ratio*(x-self.pan[0])
ypan = y-ratio*(y-self.pan[1])
self.zoom = zoom
self.pan = xpan, ypan
def on_mouse_drag(self, x, y, dx, dy, button):
dx = 2*(dx / self._width)
dy = -2*(dy / self._height)
self.pan = self.pan + (dx,dy)
| [
"glumpy.library.get",
"numpy.asarray",
"numpy.array",
"numpy.clip"
] | [((2243, 2281), 'glumpy.library.get', 'library.get', (['"""transforms/panzoom.glsl"""'], {}), "('transforms/panzoom.glsl')\n", (2254, 2281), False, 'from glumpy import library\n'), ((2776, 2798), 'numpy.asarray', 'np.asarray', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2786, 2798), True, 'import numpy as np\n'), ((3218, 3235), 'numpy.asarray', 'np.asarray', (['value'], {}), '(value)\n', (3228, 3235), True, 'import numpy as np\n'), ((3485, 3531), 'numpy.clip', 'np.clip', (['value', 'self._zoom_min', 'self._zoom_max'], {}), '(value, self._zoom_min, self._zoom_max)\n', (3492, 3531), True, 'import numpy as np\n'), ((5338, 5408), 'numpy.clip', 'np.clip', (['(self._zoom * (1.0 + dy / 100.0))', 'self.zoom_min', 'self.zoom_max'], {}), '(self._zoom * (1.0 + dy / 100.0), self.zoom_min, self.zoom_max)\n', (5345, 5408), True, 'import numpy as np\n'), ((4788, 4817), 'numpy.array', 'np.array', (['[1.0 / aspect, 1.0]'], {}), '([1.0 / aspect, 1.0])\n', (4796, 4817), True, 'import numpy as np\n'), ((4864, 4893), 'numpy.array', 'np.array', (['[1.0, aspect / 1.0]'], {}), '([1.0, aspect / 1.0])\n', (4872, 4893), True, 'import numpy as np\n')] |
import multiprocessing
from utils.replay_memory import Memory
from utils.torch import *
import numpy as np
import math
import time
def collect_samples(pid, queue, env, policy, custom_reward,
mean_action, render, running_state, min_batch_size, count):
if pid > 0:
torch.manual_seed(torch.randint(0, 5000, (1,)) * pid)
if hasattr(env, 'np_random'):
env.np_random.seed(env.np_random.randint(5000) * pid)
if hasattr(env, 'env') and hasattr(env.env, 'np_random'):
env.env.np_random.seed(env.env.np_random.randint(5000) * pid)
log = dict()
memory = Memory()
num_steps = 0
total_reward = 0
min_reward = 1e6
max_reward = -1e6
total_c_reward = 0
min_c_reward = 1e6
max_c_reward = -1e6
num_episodes = 0
trajs = []
while num_steps < min_batch_size:
state = env.reset()
trajs.append([])
if running_state is not None:
state = running_state(state)
reward_episode = 0
for t in range(10000):
state_var = tensor(state).unsqueeze(0)
with torch.no_grad():
if mean_action:
action = policy(state_var)[0][0].numpy()
else:
action = policy.select_action(state_var)[0].numpy()
action = int(action) if policy.is_disc_action else action.astype(np.float64)
count +=1
next_state, reward, done, _ = env.step(action)
reward_episode += reward
if running_state is not None:
next_state = running_state(next_state)
if custom_reward is not None:
reward = custom_reward(state, action)
total_c_reward += reward
min_c_reward = min(min_c_reward, reward)
max_c_reward = max(max_c_reward, reward)
mask = 0 if done else 1
memory.push(state, action, mask, next_state, reward)
trajs[-1].append((state, action, mask, next_state, reward))
if render:
env.render()
if done:
break
state = next_state
# log stats
num_steps += (t + 1)
num_episodes += 1
total_reward += reward_episode
min_reward = min(min_reward, reward_episode)
max_reward = max(max_reward, reward_episode)
log['num_steps'] = num_steps
log['num_episodes'] = num_episodes
log['total_reward'] = total_reward
log['avg_reward'] = total_reward / num_episodes
log['max_reward'] = max_reward
log['min_reward'] = min_reward
if custom_reward is not None:
log['total_c_reward'] = total_c_reward
log['avg_c_reward'] = total_c_reward / num_steps
log['max_c_reward'] = max_c_reward
log['min_c_reward'] = min_c_reward
if queue is not None:
queue.put([pid, memory, log])
else:
return memory, log, count, trajs
def merge_log(log_list):
log = dict()
log['total_reward'] = sum([x['total_reward'] for x in log_list])
log['num_episodes'] = sum([x['num_episodes'] for x in log_list])
log['num_steps'] = sum([x['num_steps'] for x in log_list])
log['avg_reward'] = log['total_reward'] / log['num_episodes']
log['max_reward'] = max([x['max_reward'] for x in log_list])
log['min_reward'] = min([x['min_reward'] for x in log_list])
if 'total_c_reward' in log_list[0]:
log['total_c_reward'] = sum([x['total_c_reward'] for x in log_list])
log['avg_c_reward'] = log['total_c_reward'] / log['num_steps']
log['max_c_reward'] = max([x['max_c_reward'] for x in log_list])
log['min_c_reward'] = min([x['min_c_reward'] for x in log_list])
return log
class Agent:
def __init__(self, env, policy, device, custom_reward=None, running_state=None, num_threads=1):
self.env = env
self.policy = policy
self.device = device
self.custom_reward = custom_reward
self.running_state = running_state
self.num_threads = num_threads
def collect_samples(self, min_batch_size, mean_action=False, render=False, count=0):
t_start = time.time()
to_device(torch.device('cpu'), self.policy)
thread_batch_size = int(math.floor(min_batch_size / self.num_threads))
queue = multiprocessing.Queue()
workers = []
worker_args = (1, queue, self.env, self.policy, self.custom_reward, mean_action,
False, self.running_state, thread_batch_size)
#workers.append(multiprocessing.Process(target=collect_samples, args=worker_args))
#for worker in workers:
#worker.start()
memory, log, count, trajs = collect_samples(0, None, self.env, self.policy, self.custom_reward, mean_action,
render, self.running_state, thread_batch_size, count)
# worker_logs = [None] * len(workers)
# worker_memories = [None] * len(workers)
# for _ in workers:
# pid, worker_memory, worker_log = queue.get()
# worker_memories[pid - 1] = worker_memory
# worker_logs[pid - 1] = worker_log
# for worker_memory in worker_memories:
# memory.append(worker_memory)
batch = memory.sample()
# if self.num_threads > 1:
# log_list = [log] + worker_logs
# log = merge_log(log_list)
# to_device(self.device, self.policy)
t_end = time.time()
log['sample_time'] = t_end - t_start
log['action_mean'] = np.mean(np.vstack(batch.action), axis=0)
log['action_min'] = np.min(np.vstack(batch.action), axis=0)
log['action_max'] = np.max(np.vstack(batch.action), axis=0)
return batch, log, count, trajs | [
"math.floor",
"time.time",
"utils.replay_memory.Memory",
"multiprocessing.Queue",
"numpy.vstack"
] | [((625, 633), 'utils.replay_memory.Memory', 'Memory', ([], {}), '()\n', (631, 633), False, 'from utils.replay_memory import Memory\n'), ((4200, 4211), 'time.time', 'time.time', ([], {}), '()\n', (4209, 4211), False, 'import time\n'), ((4359, 4382), 'multiprocessing.Queue', 'multiprocessing.Queue', ([], {}), '()\n', (4380, 4382), False, 'import multiprocessing\n'), ((5520, 5531), 'time.time', 'time.time', ([], {}), '()\n', (5529, 5531), False, 'import time\n'), ((4296, 4341), 'math.floor', 'math.floor', (['(min_batch_size / self.num_threads)'], {}), '(min_batch_size / self.num_threads)\n', (4306, 4341), False, 'import math\n'), ((5614, 5637), 'numpy.vstack', 'np.vstack', (['batch.action'], {}), '(batch.action)\n', (5623, 5637), True, 'import numpy as np\n'), ((5682, 5705), 'numpy.vstack', 'np.vstack', (['batch.action'], {}), '(batch.action)\n', (5691, 5705), True, 'import numpy as np\n'), ((5750, 5773), 'numpy.vstack', 'np.vstack', (['batch.action'], {}), '(batch.action)\n', (5759, 5773), True, 'import numpy as np\n')] |
"""
Image-Target generator for training this UNet.
"""
# import packages
import numpy as np
import rasterio
from tensorflow import keras
def read_tif(path: str, channels_last: bool = True):
"""
Load a tiff file into a numpy ndarray.
Parameters
----------
path: str
File path to tif file you want to read
channels_last: bool
The tif file is saved with the channels axis first, however,
Keras/Tensorflow usually expect channels to be the last axis.
By default, return the array with the channels axis last.
Returns
-------
image: ndarray
The image from this tif file. The axis order depends on kwarg CHANNELS_LAST.
"""
try:
with rasterio.open(path) as ds:
image = ds.read()
except AttributeError as error:
raise Exception("Could not open: %s" % path) from error
n_dims = len(image.shape)
if n_dims < 3:
image = image[np.newaxis]
if channels_last:
# Let's have bands (channels) as the last rather than first axis, as
# usually expected by Keras/Tensorflow
return np.transpose(image, axes=(1, 2, 0))
return image
class DataGenerator(keras.utils.Sequence):
"""
Keras data generator.
The training data should be saved with images and targets as separate files with the same prefix.
The sample keys for this generator (e.g., train or val) should be written to a text file, one key per line.
For example:
my_data_dir/
sample_0001_image.tif
sample_0001_target.tif
sample_0002_image.tif
sample_0002_target.tif
my_data_dir/train_keys.txt contains:
sample_0001
sample_0002
Augmentations are provided as a list of transformation functions. See `transforms.py`.
"""
def __init__(
self,
data_list,
batch_size=32,
dim=(512, 512, 4),
shuffle=True,
augment=False,
transforms=None,
):
"""
Parameters
----------
data_list : str
Path of text file with list of keys.
batch_size : int
size of batch to be yielded for training
dim : list
Training image size: [npix_y, npix_x, bands]
shuffle : bool
If true, shuffle the dataset
augment : bool
If true, apply augmentations
transforms : list of functions
List of augmentation transformations to apply to the yielded samples.
Returns
-------
Tuple of (image_batch, target_batch)
image_batch has shape [batch_size, npix_x, npix_y, bands]
target_batch has shape [batch_size, npix_x, npix_y, 1]
Example
-------
trf = [
transforms.CastTransform(feature_type='float32', target_type='bool'),
transforms.SquareImageTransform(),
transforms.AdditiveNoiseTransform(additive_noise=30.),
transforms.MultiplicativeNoiseTransform(multiplicative_noise=0.3),
transforms.NormalizeFeatureTransform(mean=128., std=1.),
transforms.FlipFeatureTargetTransform(),
]
trn_generator = DataGenerator('path_to_data/train_keys.txt', batch_size=16, dim=(512,512, 4),
shuffle=True, augment=True,
transforms=trf,
)
"""
self.dim = dim
self.batch_size = batch_size
self.data_list = data_list
self.indexes = None # int indices (possibly random), set by self.on_epoch_end()
self.shuffle = shuffle
self.augment = augment
self.transforms = transforms
# read in list of keys
with open(data_list, "r") as f:
self.keys = f.read().splitlines()
self.n_keys = len(self.keys)
self.on_epoch_end()
def __len__(self):
"""
Denotes the number of batches per epoch
"""
return int(np.floor(len(self.keys) / self.batch_size))
def __getitem__(self, index):
"""
Generate one batch of data
Parameters
----------
index : int
Batch index. If batch size is 10 and index is 3, this will yield samples 30-39
"""
indexes = self.indexes[index * self.batch_size : (index + 1) * self.batch_size]
# Find list of IDs
batch_keys = [self.keys[k] for k in indexes]
# Generate data
x, y = self.__data_generation(batch_keys)
return x, y
def on_epoch_end(self):
"""
Updates indexes after each epoch
"""
self.indexes = np.arange(len(self.keys))
if self.shuffle is True:
np.random.shuffle(self.indexes)
def __data_generation(self, batch_keys):
"""
Generates data containing batch_size samples
"""
# Initialization
x = np.empty((self.batch_size, *self.dim))
y = np.empty((self.batch_size, self.dim[0], self.dim[1], 1))
# Generate data
for i, key in enumerate(batch_keys):
# load image and target
f_img = key + "_image.tif"
f_trg = key + "_target.tif"
img = read_tif(f_img, channels_last=True)
trg = read_tif(f_trg)
if self.augment and self.transforms:
for transform in self.transforms:
img, trg = transform(img, trg)
x[i, ...] = img
y[i, ...] = trg
return x, y
| [
"numpy.empty",
"rasterio.open",
"numpy.transpose",
"numpy.random.shuffle"
] | [((1131, 1166), 'numpy.transpose', 'np.transpose', (['image'], {'axes': '(1, 2, 0)'}), '(image, axes=(1, 2, 0))\n', (1143, 1166), True, 'import numpy as np\n'), ((5017, 5055), 'numpy.empty', 'np.empty', (['(self.batch_size, *self.dim)'], {}), '((self.batch_size, *self.dim))\n', (5025, 5055), True, 'import numpy as np\n'), ((5068, 5124), 'numpy.empty', 'np.empty', (['(self.batch_size, self.dim[0], self.dim[1], 1)'], {}), '((self.batch_size, self.dim[0], self.dim[1], 1))\n', (5076, 5124), True, 'import numpy as np\n'), ((728, 747), 'rasterio.open', 'rasterio.open', (['path'], {}), '(path)\n', (741, 747), False, 'import rasterio\n'), ((4825, 4856), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indexes'], {}), '(self.indexes)\n', (4842, 4856), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 10 14:12:10 2019
@author: chxy
"""
import numpy as np
import torch
from torchvision import datasets
from torchvision import transforms
def get_train_loader(data_dir,
batch_size,
random_seed,
shuffle=True,
num_workers=4,
pin_memory=True):
"""
Utility function for loading and returning a multi-process
train iterator over the CIFAR100 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Args
----
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: train set iterator.
"""
# define transforms
trans = transforms.Compose([
transforms.RandomCrop(32, padding=4), # 将图像转化为32 * 32
transforms.RandomHorizontalFlip(), # 随机水平翻转
transforms.RandomRotation(degrees=15), # 随机旋转
transforms.ToTensor(), # 将numpy数据类型转化为Tensor
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # 归一化
])
# load dataset
dataset = datasets.CIFAR100(root=data_dir,
transform=trans,
download=False,
train=True)
if shuffle:
np.random.seed(random_seed)
train_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory,
)
return train_loader
def get_test_loader(data_dir,
batch_size,
num_workers=4,
pin_memory=True):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR100 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Args
----
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: test set iterator.
"""
# define transforms
trans = transforms.Compose([
transforms.ToTensor(), # 将numpy数据类型转化为Tensor
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) # 归一化
])
# load dataset
dataset = datasets.CIFAR100(
data_dir, train=False, download=False, transform=trans
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=False,
num_workers=num_workers, pin_memory=pin_memory,
)
return data_loader
| [
"numpy.random.seed",
"torch.utils.data.DataLoader",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.RandomRotation",
"torchvision.datasets.CIFAR100",
"torchvision.transforms.Normalize",
"torchvision.transforms.RandomCrop",
"torchvision.transforms.ToTensor"
] | [((1408, 1485), 'torchvision.datasets.CIFAR100', 'datasets.CIFAR100', ([], {'root': 'data_dir', 'transform': 'trans', 'download': '(False)', 'train': '(True)'}), '(root=data_dir, transform=trans, download=False, train=True)\n', (1425, 1485), False, 'from torchvision import datasets\n'), ((1661, 1789), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'num_workers', 'pin_memory': 'pin_memory'}), '(dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers, pin_memory=pin_memory)\n', (1688, 1789), False, 'import torch\n'), ((2786, 2859), 'torchvision.datasets.CIFAR100', 'datasets.CIFAR100', (['data_dir'], {'train': '(False)', 'download': '(False)', 'transform': 'trans'}), '(data_dir, train=False, download=False, transform=trans)\n', (2803, 2859), False, 'from torchvision import datasets\n'), ((2897, 3023), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers', 'pin_memory': 'pin_memory'}), '(dataset, batch_size=batch_size, shuffle=False,\n num_workers=num_workers, pin_memory=pin_memory)\n', (2924, 3023), False, 'import torch\n'), ((1611, 1638), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (1625, 1638), True, 'import numpy as np\n'), ((1061, 1097), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(32)'], {'padding': '(4)'}), '(32, padding=4)\n', (1082, 1097), False, 'from torchvision import transforms\n'), ((1125, 1158), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (1156, 1158), False, 'from torchvision import transforms\n'), ((1178, 1215), 'torchvision.transforms.RandomRotation', 'transforms.RandomRotation', ([], {'degrees': '(15)'}), '(degrees=15)\n', (1203, 1215), False, 'from torchvision import transforms\n'), ((1234, 1255), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1253, 1255), False, 'from torchvision import transforms\n'), ((1289, 1355), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (1309, 1355), False, 'from torchvision import transforms\n'), ((2616, 2637), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2635, 2637), False, 'from torchvision import transforms\n'), ((2667, 2733), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2687, 2733), False, 'from torchvision import transforms\n')] |
import numpy as np
import cv2
# Sobel class
# Sobel class
class SobelThreshold:
def __init__(self, sobel_profile):
self.sobel_profile = sobel_profile
def sobel_dir_thresh(self, img, sobel_kernel=3, thresh=(0, np.pi / 2)):
"""
Applies sobel x and y, compute direction of gradient and apply threshold
"""
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the gradient in x and y separately
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# 3) Take the absolute value of the x and y gradients
abs_sobelx = np.absolute(sobelx)
abs_sobely = np.absolute(sobely)
# 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
sobel_gradient = np.arctan2(abs_sobely, abs_sobelx)
# 5) Create a binary mask where direction thresholds are met
binary_output = np.zeros_like(sobel_gradient)
# 6) Return this mask as your binary_output image
binary_output[((sobel_gradient >= thresh[0]) & (sobel_gradient <= thresh[1]))] = 1
return binary_output
def sobel_abs_thresh(self, img, orient='x', sobel_kernel=3, thresh=(0, 255)):
"""
Applies either sobel x or y and applies threshold on the absolute gradient
"""
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the derivative in x or y given orient = 'x' or 'y'
sobel = cv2.Sobel(gray, cv2.CV_64F, 1 if orient == 'x' else 0, 1 if orient == 'y' else 0, ksize=sobel_kernel)
# 3) Take the absolute value of the derivative or gradient
abs_sobel = np.absolute(sobel)
# 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
# 5) Create a mask of 1's where the scaled gradient magnitude
# is > thresh_min and < thresh_max
binary_output = np.zeros_like(scaled_sobel)
binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
# 6) Return this mask as your binary_output image
return binary_output
def sobel_mag_thresh(self, img, sobel_kernel=3, mag_thresh=(0, 255)):
"""
Compute magnitude of gradient from sobel x and y and apply threshold
"""
# Apply the following steps to img
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Take the gradient in x and y separately
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
# 3) Calculate the magnitude
abs_sobelxy = np.sqrt((np.square(sobelx) + np.square(sobely)))
# 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8
scaled_sobelxy = np.uint8(255 * abs_sobelxy / np.max(abs_sobelxy))
# 5) Create a binary mask where mag thresholds are met
binary_output = np.zeros_like(scaled_sobelxy)
# 6) Return this mask as your binary_output image
binary_output[(scaled_sobelxy >= mag_thresh[0]) & (scaled_sobelxy <= mag_thresh[1])] = 1
return binary_output
def apply_sobel(self, image):
"""
Apply each of the sobel functions and combined them
"""
# gradx = self.sobel_abs_thresh(image, orient='x', sobel_kernel=self.sobel_profile['sobel_abs_thresh_x']['sobel_kernel'], thresh=self.sobel_profile['sobel_abs_thresh_x']['threshold'])
# grady = self.sobel_abs_thresh(image, orient='y', sobel_kernel=self.sobel_profile['sobel_abs_thresh_y']['sobel_kernel'], thresh=self.sobel_profile['sobel_abs_thresh_y']['threshold'])
mag_binary = self.sobel_mag_thresh(image, sobel_kernel=self.sobel_profile['sobel_mag_thresh']['sobel_kernel'], mag_thresh=self.sobel_profile['sobel_mag_thresh']['threshold'])
dir_binary = self.sobel_dir_thresh(image, sobel_kernel=self.sobel_profile['sobel_dir_thresh']['sobel_kernel'], thresh=self.sobel_profile['sobel_dir_thresh']['threshold'])
combined = np.zeros_like(dir_binary)
# combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1
combined[((mag_binary == 1) & (dir_binary == 1))] = 1
return combined
| [
"numpy.absolute",
"numpy.zeros_like",
"numpy.arctan2",
"cv2.cvtColor",
"numpy.square",
"numpy.max",
"cv2.Sobel"
] | [((393, 430), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (405, 430), False, 'import cv2\n'), ((502, 555), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': 'sobel_kernel'}), '(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n', (511, 555), False, 'import cv2\n'), ((573, 626), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': 'sobel_kernel'}), '(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n', (582, 626), False, 'import cv2\n'), ((711, 730), 'numpy.absolute', 'np.absolute', (['sobelx'], {}), '(sobelx)\n', (722, 730), True, 'import numpy as np\n'), ((752, 771), 'numpy.absolute', 'np.absolute', (['sobely'], {}), '(sobely)\n', (763, 771), True, 'import numpy as np\n'), ((893, 927), 'numpy.arctan2', 'np.arctan2', (['abs_sobely', 'abs_sobelx'], {}), '(abs_sobely, abs_sobelx)\n', (903, 927), True, 'import numpy as np\n'), ((1022, 1051), 'numpy.zeros_like', 'np.zeros_like', (['sobel_gradient'], {}), '(sobel_gradient)\n', (1035, 1051), True, 'import numpy as np\n'), ((1513, 1550), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (1525, 1550), False, 'import cv2\n'), ((1637, 1742), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', "(1 if orient == 'x' else 0)", "(1 if orient == 'y' else 0)"], {'ksize': 'sobel_kernel'}), "(gray, cv2.CV_64F, 1 if orient == 'x' else 0, 1 if orient == 'y' else\n 0, ksize=sobel_kernel)\n", (1646, 1742), False, 'import cv2\n'), ((1827, 1845), 'numpy.absolute', 'np.absolute', (['sobel'], {}), '(sobel)\n', (1838, 1845), True, 'import numpy as np\n'), ((2120, 2147), 'numpy.zeros_like', 'np.zeros_like', (['scaled_sobel'], {}), '(scaled_sobel)\n', (2133, 2147), True, 'import numpy as np\n'), ((2589, 2626), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (2601, 2626), False, 'import cv2\n'), ((2698, 2751), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': 'sobel_kernel'}), '(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n', (2707, 2751), False, 'import cv2\n'), ((2769, 2822), 'cv2.Sobel', 'cv2.Sobel', (['gray', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': 'sobel_kernel'}), '(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n', (2778, 2822), False, 'import cv2\n'), ((3165, 3194), 'numpy.zeros_like', 'np.zeros_like', (['scaled_sobelxy'], {}), '(scaled_sobelxy)\n', (3178, 3194), True, 'import numpy as np\n'), ((4266, 4291), 'numpy.zeros_like', 'np.zeros_like', (['dir_binary'], {}), '(dir_binary)\n', (4279, 4291), True, 'import numpy as np\n'), ((1963, 1980), 'numpy.max', 'np.max', (['abs_sobel'], {}), '(abs_sobel)\n', (1969, 1980), True, 'import numpy as np\n'), ((2892, 2909), 'numpy.square', 'np.square', (['sobelx'], {}), '(sobelx)\n', (2901, 2909), True, 'import numpy as np\n'), ((2912, 2929), 'numpy.square', 'np.square', (['sobely'], {}), '(sobely)\n', (2921, 2929), True, 'import numpy as np\n'), ((3056, 3075), 'numpy.max', 'np.max', (['abs_sobelxy'], {}), '(abs_sobelxy)\n', (3062, 3075), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
import numpy as np
import ray
_pinned_objects = []
PINNED_OBJECT_PREFIX = "ray.tune.PinnedObject:"
def pin_in_object_store(obj):
"""Pin an object in the object store.
It will be available as long as the pinning process is alive. The pinned
object can be retrieved by calling get_pinned_object on the identifier
returned by this call.
"""
obj_id = ray.put(_to_pinnable(obj))
_pinned_objects.append(ray.get(obj_id))
return "{}{}".format(PINNED_OBJECT_PREFIX,
base64.b64encode(obj_id.id()).decode("utf-8"))
def get_pinned_object(pinned_id):
"""Retrieve a pinned object from the object store."""
from ray.raylet import ObjectID
return _from_pinnable(
ray.get(
ObjectID(base64.b64decode(pinned_id[len(PINNED_OBJECT_PREFIX):]))))
def _to_pinnable(obj):
"""Converts obj to a form that can be pinned in object store memory.
Currently only numpy arrays are pinned in memory, if you have a strong
reference to the array value.
"""
return (obj, np.zeros(1))
def _from_pinnable(obj):
"""Retrieve from _to_pinnable format."""
return obj[0]
if __name__ == '__main__':
ray.init()
X = pin_in_object_store("hello")
print(X)
result = get_pinned_object(X)
print(result)
| [
"ray.init",
"numpy.zeros",
"ray.get"
] | [((1318, 1328), 'ray.init', 'ray.init', ([], {}), '()\n', (1326, 1328), False, 'import ray\n'), ((555, 570), 'ray.get', 'ray.get', (['obj_id'], {}), '(obj_id)\n', (562, 570), False, 'import ray\n'), ((1181, 1192), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (1189, 1192), True, 'import numpy as np\n')] |
import numpy as np
def kldistance(p, q):
return np.sum(p * (np.log(p) - np.log(q)))
p = np.array([0.4, 0.6])
q = np.array([0.5, 0.5])
print(kldistance(p, q))
print(kldistance(q, p))
| [
"numpy.array",
"numpy.log"
] | [((95, 115), 'numpy.array', 'np.array', (['[0.4, 0.6]'], {}), '([0.4, 0.6])\n', (103, 115), True, 'import numpy as np\n'), ((120, 140), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (128, 140), True, 'import numpy as np\n'), ((66, 75), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (72, 75), True, 'import numpy as np\n'), ((78, 87), 'numpy.log', 'np.log', (['q'], {}), '(q)\n', (84, 87), True, 'import numpy as np\n')] |
"""Generate isotropic Gaussian blobs, 2D data, for metric demo.
https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html
"""
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
import random
import sys
import numpy as np
import argparse
from os.path import join
sys.path.append("../../")
import auxiliary.my_utils as my_utils
parser = argparse.ArgumentParser(
description='sum the integers at the command line')
parser.add_argument("--num_clusters", type=int, default=8,
help='number of clusters')
parser.add_argument(
'--num_points', type=int, default=200,
help='')
parser.add_argument(
'--std_max_size', type=int, default=8,
help='')
parser.add_argument(
'--seed', type=int, default=2,
help='')
parser.add_argument(
'--side_length', type=int, default=25,
help='')
parser.add_argument(
'--dim', type=int, default=2,
help='')
parser.add_argument(
'--save_folder', type=str, default="clusters_data",
help='')
parser.add_argument(
'--log', default=sys.stdout, type=argparse.FileType('w'),
help='the file where the sum should be written')
args = parser.parse_args()
my_utils.plant_seeds(args.seed)
num_of_clusters = args.num_clusters
color_list = ['b', 'g', 'r', 'c', 'm','y','k', 'pink', 'brown', 'cyan']
xs = np.random.randint(-1 * args.side_length, args.side_length, num_of_clusters)
ys = np.random.randint(-1 * args.side_length, args.side_length, num_of_clusters)
centers = [(x, y) for x, y in zip(xs, ys)]
for cluster_std in np.arange(1, args.std_max_size+1, 1):
plt.figure(figsize=(5,5))
#cluster_std = std_max_size * (np.random.random(num_of_clusters))
cluster_std_array = np.array([cluster_std] * num_of_clusters)
X, y = make_blobs(n_samples=args.num_points, cluster_std=cluster_std_array, centers=centers, n_features=args.dim, random_state=args.seed)
for i in range(num_of_clusters):
plt.scatter(X[y == i, 0], X[y == i, 1], color=color_list[i], s=80)
plt.xticks([])
plt.yticks([])
data_fname = f'dim{args.dim}_ncls{args.num_clusters}_side{args.side_length}_nsample{args.num_points}_seed{args.seed}_std{cluster_std}.npz'
plot_fname = data_fname.replace("npz", "png")
plt.tight_layout()
#plt.show()
plt.savefig(join(args.save_folder, plot_fname), bbox_inches="tight")
#np.savez(join(args.save_folder, data_fname),
# data=X, label=y)
| [
"sys.path.append",
"argparse.ArgumentParser",
"os.path.join",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.arange",
"numpy.array",
"sklearn.datasets.samples_generator.make_blobs",
"matplotlib.pyplot.xticks",
"matplotlib.pyp... | [((330, 355), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (345, 355), False, 'import sys\n'), ((403, 478), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""sum the integers at the command line"""'}), "(description='sum the integers at the command line')\n", (426, 478), False, 'import argparse\n'), ((1198, 1229), 'auxiliary.my_utils.plant_seeds', 'my_utils.plant_seeds', (['args.seed'], {}), '(args.seed)\n', (1218, 1229), True, 'import auxiliary.my_utils as my_utils\n'), ((1343, 1418), 'numpy.random.randint', 'np.random.randint', (['(-1 * args.side_length)', 'args.side_length', 'num_of_clusters'], {}), '(-1 * args.side_length, args.side_length, num_of_clusters)\n', (1360, 1418), True, 'import numpy as np\n'), ((1424, 1499), 'numpy.random.randint', 'np.random.randint', (['(-1 * args.side_length)', 'args.side_length', 'num_of_clusters'], {}), '(-1 * args.side_length, args.side_length, num_of_clusters)\n', (1441, 1499), True, 'import numpy as np\n'), ((1564, 1602), 'numpy.arange', 'np.arange', (['(1)', '(args.std_max_size + 1)', '(1)'], {}), '(1, args.std_max_size + 1, 1)\n', (1573, 1602), True, 'import numpy as np\n'), ((1606, 1632), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (1616, 1632), True, 'import matplotlib.pyplot as plt\n'), ((1726, 1767), 'numpy.array', 'np.array', (['([cluster_std] * num_of_clusters)'], {}), '([cluster_std] * num_of_clusters)\n', (1734, 1767), True, 'import numpy as np\n'), ((1780, 1914), 'sklearn.datasets.samples_generator.make_blobs', 'make_blobs', ([], {'n_samples': 'args.num_points', 'cluster_std': 'cluster_std_array', 'centers': 'centers', 'n_features': 'args.dim', 'random_state': 'args.seed'}), '(n_samples=args.num_points, cluster_std=cluster_std_array,\n centers=centers, n_features=args.dim, random_state=args.seed)\n', (1790, 1914), False, 'from sklearn.datasets.samples_generator import make_blobs\n'), ((2033, 2047), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (2043, 2047), True, 'import matplotlib.pyplot as plt\n'), ((2052, 2066), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (2062, 2066), True, 'import matplotlib.pyplot as plt\n'), ((2264, 2282), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2280, 2282), True, 'import matplotlib.pyplot as plt\n'), ((1093, 1115), 'argparse.FileType', 'argparse.FileType', (['"""w"""'], {}), "('w')\n", (1110, 1115), False, 'import argparse\n'), ((1957, 2023), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[y == i, 0]', 'X[y == i, 1]'], {'color': 'color_list[i]', 's': '(80)'}), '(X[y == i, 0], X[y == i, 1], color=color_list[i], s=80)\n', (1968, 2023), True, 'import matplotlib.pyplot as plt\n'), ((2315, 2349), 'os.path.join', 'join', (['args.save_folder', 'plot_fname'], {}), '(args.save_folder, plot_fname)\n', (2319, 2349), False, 'from os.path import join\n')] |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D,art3d
import math
import numpy as np
import json
def rotationMatrix3D(psi0, x1, y1, z1, eixo="yaw"):
if eixo == "yaw":
r = [[np.cos(psi0), np.sin(psi0) * -1, 0], [np.sin(psi0), np.cos(psi0), 0], [0, 0, 1]]
elif eixo == "pitch":
r = [[1, 0, 0], [0, np.cos(psi0), -np.sin(psi0)], [0, np.cos(psi0), np.cos(psi0)]]
elif eixo == "roll":
r = [[np.cos(psi0), 0, np.sin(psi0)], [0, 1, 0], [-np.sin(psi0), 0, np.cos(psi0)]]
else:
print("Axes accepted: roll, pitch, roll")
return [x1, y1, z1]
pos_local = np.dot(np.transpose(np.asarray(r)), np.asarray([x1, y1, z1]))
return pos_local
def simulate_points(x1, x2, y1, y2, juntos=False):
aux = math.ceil(max(abs(x1 - x2), abs(y1 - y2)))
aux *= 2
a1 = np.linspace(x1, x2, int(aux))
a2 = np.linspace(y1, y2, int(aux))
if juntos:
jj = []
for i in range(len(a1)):
jj.append([a1[i], a2[i]])
return jj
else:
return a1, a2
def arredondarTraj(x, y, z=0, threeD=0):
if threeD == 0:
trajX, trajY = [], []
trajXY = []
for i, j in zip(x, y):
if [round(i), round(j)] not in trajXY: trajXY.append([round(i), round(j)])
for i in trajXY:
trajX.append(i[0])
trajY.append(i[1])
return trajX, trajY
else:
trajX, trajY, trajZ = [], [], []
trajXYZ = []
for i, j, k in zip(x, y, z):
if [round(i), round(j), round(k)] not in trajXYZ: trajXYZ.append([round(i), round(j), round(k)])
for i in trajXYZ:
trajX.append(i[0])
trajY.append(i[1])
trajZ.append(i[2])
return trajX, trajY, trajZ
def readFromHouseExpo(maxX=17, maxY=10, grid=4, file='658e5214673c7a4e25b458e56bdb6144', plot=False):
grid = grid
maxX, maxY = maxX * grid, maxY * grid
px1, py1 = simulate_points(0,maxX,0,0)
px2, py2 = simulate_points(0,maxX,maxY,maxY)
px3, py3 = simulate_points(0,0,0,maxY)
px4, py4 = simulate_points(maxX,maxX,0,maxY)
c = 0
auxX, auxY = 0, 0
x, y = [], []
f = open(file + ".json",)
data = json.load(f)
for i in data['verts']:
# c = 1 if c == 0 else 0
if c == 1:
# print("para")
# print(i[0])
# print(i[1])
newX, newY = simulate_points(auxX, i[0]*grid, auxY, i[1]*grid)
x = np.concatenate([x,newX])
y = np.concatenate([y,newY])
c = 0
elif c == 0:
# print("de")
# print(i[0])
# print(i[1])
auxX, auxY = i[0]*grid, i[1]*grid
c = 1
f.close()
x = np.concatenate([x, px1, px2, px3, px4])
y = np.concatenate([y, py1, py2, py3, py4])
x, y = arredondarTraj(x, y)
if plot:
plt.plot(x, y, ".k")
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
# plt.xlim(0,20)
# plt.ylim(0,20)
plt.show()
return x, y
# x, y = readFromHouseExpo()
# print(x)
# print(y)
def readFromWarframe(grid=8, path="/home/lidiaxp/Downloads/warframe", file="A1.3dmap", plot=False):
c = 0
grid = grid
x3d, y3d, z3d = [], [], []
xyz = []
f = open(path + "/" + file, "r")
for x in f:
c += 1
if c > 1:
aux = x.split()
auxX, auxY, auxZ = int((int(aux[0])/grid)), int((int(aux[1])/grid)), int((int(aux[2])/grid))
if [auxX, auxY, auxZ] not in xyz:
xyz.append([auxX, auxY, auxZ])
x3d.append(auxX)
y3d.append(auxY)
z3d.append(auxZ)
x3d2, y3d2, z3d2 = rotationMatrix3D(math.radians(15), x3d, y3d, z3d)
# x3d2, y3d2, z3d2 = arredondarTraj(x3d2, y3d2, z3d2, True)
if plot:
ax = plt.axes(projection = "3d")
# plt.plot(x3d, y3d, z3d, ".r")
plt.plot(x3d2, y3d2, z3d2, ".k")
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_zlabel("Z (m)")
# ax.set_xlim(0,20)
ax.set_ylim(0,20)
# ax.set_zlim(0,5)
# ax.legend()
plt.pause(0.01)
plt.show()
return x3d2, y3d2, z3d2
x, y, z = readFromWarframe(plot=True)
with open('warframeMap.txt', 'w') as f:
f.write("x = [")
for i in x:
f.write(str(i)+',')
f.write("]" + "\n" + "y = [")
for i in y:
f.write(str(i)+',')
f.write("]" + "\n" + "z = [")
for i in z:
f.write(str(i)+',')
f.write("]") | [
"json.load",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"math.radians",
"matplotlib.pyplot.axes",
"numpy.asarray",
"numpy.sin",
"numpy.cos",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.pause",
"numpy.concatenate"
] | [((2234, 2246), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2243, 2246), False, 'import json\n'), ((2770, 2809), 'numpy.concatenate', 'np.concatenate', (['[x, px1, px2, px3, px4]'], {}), '([x, px1, px2, px3, px4])\n', (2784, 2809), True, 'import numpy as np\n'), ((2818, 2857), 'numpy.concatenate', 'np.concatenate', (['[y, py1, py2, py3, py4]'], {}), '([y, py1, py2, py3, py4])\n', (2832, 2857), True, 'import numpy as np\n'), ((667, 691), 'numpy.asarray', 'np.asarray', (['[x1, y1, z1]'], {}), '([x1, y1, z1])\n', (677, 691), True, 'import numpy as np\n'), ((2913, 2933), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '""".k"""'], {}), "(x, y, '.k')\n", (2921, 2933), True, 'import matplotlib.pyplot as plt\n'), ((2942, 2961), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X (m)"""'], {}), "('X (m)')\n", (2952, 2961), True, 'import matplotlib.pyplot as plt\n'), ((2970, 2989), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y (m)"""'], {}), "('Y (m)')\n", (2980, 2989), True, 'import matplotlib.pyplot as plt\n'), ((3048, 3058), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3056, 3058), True, 'import matplotlib.pyplot as plt\n'), ((3753, 3769), 'math.radians', 'math.radians', (['(15)'], {}), '(15)\n', (3765, 3769), False, 'import math\n'), ((3878, 3903), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (3886, 3903), True, 'import matplotlib.pyplot as plt\n'), ((3954, 3986), 'matplotlib.pyplot.plot', 'plt.plot', (['x3d2', 'y3d2', 'z3d2', '""".k"""'], {}), "(x3d2, y3d2, z3d2, '.k')\n", (3962, 3986), True, 'import matplotlib.pyplot as plt\n'), ((4194, 4209), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.01)'], {}), '(0.01)\n', (4203, 4209), True, 'import matplotlib.pyplot as plt\n'), ((4218, 4228), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4226, 4228), True, 'import matplotlib.pyplot as plt\n'), ((651, 664), 'numpy.asarray', 'np.asarray', (['r'], {}), '(r)\n', (661, 664), True, 'import numpy as np\n'), ((2498, 2523), 'numpy.concatenate', 'np.concatenate', (['[x, newX]'], {}), '([x, newX])\n', (2512, 2523), True, 'import numpy as np\n'), ((2540, 2565), 'numpy.concatenate', 'np.concatenate', (['[y, newY]'], {}), '([y, newY])\n', (2554, 2565), True, 'import numpy as np\n'), ((211, 223), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (217, 223), True, 'import numpy as np\n'), ((249, 261), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (255, 261), True, 'import numpy as np\n'), ((263, 275), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (269, 275), True, 'import numpy as np\n'), ((225, 237), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (231, 237), True, 'import numpy as np\n'), ((347, 359), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (353, 359), True, 'import numpy as np\n'), ((381, 393), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (387, 393), True, 'import numpy as np\n'), ((395, 407), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (401, 407), True, 'import numpy as np\n'), ((362, 374), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (368, 374), True, 'import numpy as np\n'), ((449, 461), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (455, 461), True, 'import numpy as np\n'), ((466, 478), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (472, 478), True, 'import numpy as np\n'), ((511, 523), 'numpy.cos', 'np.cos', (['psi0'], {}), '(psi0)\n', (517, 523), True, 'import numpy as np\n'), ((494, 506), 'numpy.sin', 'np.sin', (['psi0'], {}), '(psi0)\n', (500, 506), True, 'import numpy as np\n')] |
import numpy as np
import time
class Accumulator:
def __init__(self, n) -> None:
self.data = [0.0]*n
def add(self, *args):
if len(args) == len(self.data):
self.data = [a + float(b)
for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
class Timer:
"""Record multiple running times"""
def __init__(self) -> None:
self.times = []
self.start()
def start(self):
self.tik = time.time()
def stop(self):
self.times.append(time.time() - self.tik)
return self.times[-1]
def avg(self):
return sum(self.times)/len(self.times)
def sum(self):
return sum(self.times)
def cumsum(self):
return np.array(self.times).cumsum().tolist()
| [
"numpy.array",
"time.time"
] | [((579, 590), 'time.time', 'time.time', ([], {}), '()\n', (588, 590), False, 'import time\n'), ((638, 649), 'time.time', 'time.time', ([], {}), '()\n', (647, 649), False, 'import time\n'), ((848, 868), 'numpy.array', 'np.array', (['self.times'], {}), '(self.times)\n', (856, 868), True, 'import numpy as np\n')] |
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D
from keras import optimizers
from keras import backend as K
# Global variable
OUT_SHAPE = 2
INPUT_SHAPE = (120, 160, 3)
def customized_loss(y_true, y_pred, loss='euclidean'):
# Simply a mean squared error that penalizes large joystick summed values
if loss == 'L2':
L2_norm_cost = 0.001
val = K.mean(K.square((y_pred - y_true)), axis=-1) \
+ K.sum(K.square(y_pred), axis=-1)/2 * L2_norm_cost
# euclidean distance loss
elif loss == 'euclidean':
val = K.sqrt(K.sum(K.square(y_pred-y_true), axis=-1))
return val
def create_model(keep_prob = 0.8):
model = Sequential()
# NVIDIA's model
model.add(Conv2D(24, kernel_size=(5, 5), strides=(2, 2), activation='relu', input_shape= INPUT_SHAPE))
model.add(Conv2D(36, kernel_size=(5, 5), strides=(2, 2), activation='relu'))
model.add(Conv2D(48, kernel_size=(5, 5), strides=(2, 2), activation='relu'))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(1164, activation='relu'))
drop_out = 1 - keep_prob
model.add(Dropout(drop_out))
model.add(Dense(100, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(50, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(10, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(OUT_SHAPE, activation='softsign'))
return model
if __name__ == '__main__':
# Load Training Data
x_train = np.load("data/X.npy")
y_train = np.load("data/Y.npy")
print(x_train.shape[0], 'train samples')
# Training loop variables
epochs = 10
batch_size = 64
model = create_model()
model.compile(loss=customized_loss, optimizer=optimizers.adam())
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, shuffle=True, validation_split=0.1)
model.save_weights('model_weights.h5')
| [
"keras.optimizers.adam",
"numpy.load",
"keras.layers.Dropout",
"keras.layers.Flatten",
"keras.layers.Dense",
"keras.layers.Conv2D",
"keras.models.Sequential",
"keras.backend.square"
] | [((761, 773), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (771, 773), False, 'from keras.models import Sequential\n'), ((1701, 1722), 'numpy.load', 'np.load', (['"""data/X.npy"""'], {}), "('data/X.npy')\n", (1708, 1722), True, 'import numpy as np\n'), ((1737, 1758), 'numpy.load', 'np.load', (['"""data/Y.npy"""'], {}), "('data/Y.npy')\n", (1744, 1758), True, 'import numpy as np\n'), ((810, 904), 'keras.layers.Conv2D', 'Conv2D', (['(24)'], {'kernel_size': '(5, 5)', 'strides': '(2, 2)', 'activation': '"""relu"""', 'input_shape': 'INPUT_SHAPE'}), "(24, kernel_size=(5, 5), strides=(2, 2), activation='relu',\n input_shape=INPUT_SHAPE)\n", (816, 904), False, 'from keras.layers import Conv2D\n'), ((917, 982), 'keras.layers.Conv2D', 'Conv2D', (['(36)'], {'kernel_size': '(5, 5)', 'strides': '(2, 2)', 'activation': '"""relu"""'}), "(36, kernel_size=(5, 5), strides=(2, 2), activation='relu')\n", (923, 982), False, 'from keras.layers import Conv2D\n'), ((998, 1063), 'keras.layers.Conv2D', 'Conv2D', (['(48)'], {'kernel_size': '(5, 5)', 'strides': '(2, 2)', 'activation': '"""relu"""'}), "(48, kernel_size=(5, 5), strides=(2, 2), activation='relu')\n", (1004, 1063), False, 'from keras.layers import Conv2D\n'), ((1079, 1128), 'keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(64, kernel_size=(3, 3), activation='relu')\n", (1085, 1128), False, 'from keras.layers import Conv2D\n'), ((1144, 1193), 'keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(64, kernel_size=(3, 3), activation='relu')\n", (1150, 1193), False, 'from keras.layers import Conv2D\n'), ((1209, 1218), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1216, 1218), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1234, 1264), 'keras.layers.Dense', 'Dense', (['(1164)'], {'activation': '"""relu"""'}), "(1164, activation='relu')\n", (1239, 1264), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1309, 1326), 'keras.layers.Dropout', 'Dropout', (['drop_out'], {}), '(drop_out)\n', (1316, 1326), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1342, 1371), 'keras.layers.Dense', 'Dense', (['(100)'], {'activation': '"""relu"""'}), "(100, activation='relu')\n", (1347, 1371), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1387, 1404), 'keras.layers.Dropout', 'Dropout', (['drop_out'], {}), '(drop_out)\n', (1394, 1404), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1420, 1448), 'keras.layers.Dense', 'Dense', (['(50)'], {'activation': '"""relu"""'}), "(50, activation='relu')\n", (1425, 1448), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1464, 1481), 'keras.layers.Dropout', 'Dropout', (['drop_out'], {}), '(drop_out)\n', (1471, 1481), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1497, 1525), 'keras.layers.Dense', 'Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (1502, 1525), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1541, 1558), 'keras.layers.Dropout', 'Dropout', (['drop_out'], {}), '(drop_out)\n', (1548, 1558), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1574, 1613), 'keras.layers.Dense', 'Dense', (['OUT_SHAPE'], {'activation': '"""softsign"""'}), "(OUT_SHAPE, activation='softsign')\n", (1579, 1613), False, 'from keras.layers import Dense, Dropout, Flatten\n'), ((1950, 1967), 'keras.optimizers.adam', 'optimizers.adam', ([], {}), '()\n', (1965, 1967), False, 'from keras import optimizers\n'), ((463, 488), 'keras.backend.square', 'K.square', (['(y_pred - y_true)'], {}), '(y_pred - y_true)\n', (471, 488), True, 'from keras import backend as K\n'), ((662, 687), 'keras.backend.square', 'K.square', (['(y_pred - y_true)'], {}), '(y_pred - y_true)\n', (670, 687), True, 'from keras import backend as K\n'), ((531, 547), 'keras.backend.square', 'K.square', (['y_pred'], {}), '(y_pred)\n', (539, 547), True, 'from keras import backend as K\n')] |
import os
import pickle
import threading
import numpy as np
from torch.utils import data
from tqdm import tqdm
from load_audio import load_wav
from load_video import load_mp4
from utils import colorize
class DemoDataset(data.Dataset):
def __init__(self, video_path, resize, fps, sample_rate):
self.resize = resize
self.fps = fps
self.sample_rate = sample_rate
self.data_path = 'media'
self.all_vids = [video_path]
def __len__(self):
'Denotes the total number of samples'
return len(self.all_vids)
def __getitem__(self, index):
'Generates one sample of data'
assert index < self.__len__()
vid_path = self.all_vids[index]
vid_name, vid_ext = os.path.splitext(vid_path)
# -- load video
vid_path_orig = os.path.join(self.data_path, vid_path)
vid_path_25fps = os.path.join(self.data_path, vid_name + '_25fps.mp4')
# -- reencode video to 25 fps
command = (
"ffmpeg -threads 1 -loglevel error -y -i {} -an -r 25 {}".format(
vid_path_orig, vid_path_25fps))
from subprocess import call
cmd = command.split(' ')
print('Resampling {} to 25 fps'.format(vid_path_orig))
call(cmd)
video = self.__load_video__(vid_path_25fps, resize=self.resize)
aud_path = os.path.join(self.data_path, vid_name + '.wav')
if not os.path.exists(aud_path): # -- extract wav from mp4
command = (
("ffmpeg -threads 1 -loglevel error -y -i {} "
"-async 1 -ac 1 -vn -acodec pcm_s16le -ar 16000 {}")
.format(vid_path_orig, aud_path))
from subprocess import call
cmd = command.split(' ')
call(cmd)
audio = load_wav(aud_path).astype('float32')
fps = self.fps # TODO: get as param?
aud_fact = int(np.round(self.sample_rate / fps))
audio, video = self.trunkate_audio_and_video(video, audio, aud_fact)
assert aud_fact * video.shape[0] == audio.shape[0]
audio = np.array(audio)
video = video.transpose([3, 0, 1, 2]) # t c h w -> c t h w
out_dict = {
'video': video,
'audio': audio,
'sample': vid_path,
}
return out_dict
def __load_video__(self, vid_path, resize=None):
frames = load_mp4(vid_path)
if resize:
import torchvision
from PIL import Image
ims = [Image.fromarray(frm) for frm in frames]
ims = [
torchvision.transforms.functional.resize(im,
resize,
interpolation=2)
for im in ims
]
frames = np.array([np.array(im) for im in ims])
return frames.astype('float32')
def trunkate_audio_and_video(self, video, aud_feats, aud_fact):
aud_in_frames = aud_feats.shape[0] // aud_fact
# make audio exactly devisible by video frames
aud_cutoff = min(video.shape[0], int(aud_feats.shape[0] / aud_fact))
aud_feats = aud_feats[:aud_cutoff * aud_fact]
aud_in_frames = aud_feats.shape[0] // aud_fact
min_len = min(aud_in_frames, video.shape[0])
# --- trunkate all to min
video = video[:min_len]
aud_feats = aud_feats[:min_len * aud_fact]
if not aud_feats.shape[0] // aud_fact == video.shape[0]:
import ipdb
ipdb.set_trace(context=20)
return aud_feats, video
| [
"ipdb.set_trace",
"torchvision.transforms.functional.resize",
"os.path.exists",
"load_audio.load_wav",
"load_video.load_mp4",
"numpy.array",
"subprocess.call",
"os.path.splitext",
"PIL.Image.fromarray",
"numpy.round",
"os.path.join"
] | [((753, 779), 'os.path.splitext', 'os.path.splitext', (['vid_path'], {}), '(vid_path)\n', (769, 779), False, 'import os\n'), ((829, 867), 'os.path.join', 'os.path.join', (['self.data_path', 'vid_path'], {}), '(self.data_path, vid_path)\n', (841, 867), False, 'import os\n'), ((893, 946), 'os.path.join', 'os.path.join', (['self.data_path', "(vid_name + '_25fps.mp4')"], {}), "(self.data_path, vid_name + '_25fps.mp4')\n", (905, 946), False, 'import os\n'), ((1272, 1281), 'subprocess.call', 'call', (['cmd'], {}), '(cmd)\n', (1276, 1281), False, 'from subprocess import call\n'), ((1375, 1422), 'os.path.join', 'os.path.join', (['self.data_path', "(vid_name + '.wav')"], {}), "(self.data_path, vid_name + '.wav')\n", (1387, 1422), False, 'import os\n'), ((2109, 2124), 'numpy.array', 'np.array', (['audio'], {}), '(audio)\n', (2117, 2124), True, 'import numpy as np\n'), ((2411, 2429), 'load_video.load_mp4', 'load_mp4', (['vid_path'], {}), '(vid_path)\n', (2419, 2429), False, 'from load_video import load_mp4\n'), ((1439, 1463), 'os.path.exists', 'os.path.exists', (['aud_path'], {}), '(aud_path)\n', (1453, 1463), False, 'import os\n'), ((1788, 1797), 'subprocess.call', 'call', (['cmd'], {}), '(cmd)\n', (1792, 1797), False, 'from subprocess import call\n'), ((1922, 1954), 'numpy.round', 'np.round', (['(self.sample_rate / fps)'], {}), '(self.sample_rate / fps)\n', (1930, 1954), True, 'import numpy as np\n'), ((3580, 3606), 'ipdb.set_trace', 'ipdb.set_trace', ([], {'context': '(20)'}), '(context=20)\n', (3594, 3606), False, 'import ipdb\n'), ((1815, 1833), 'load_audio.load_wav', 'load_wav', (['aud_path'], {}), '(aud_path)\n', (1823, 1833), False, 'from load_audio import load_wav\n'), ((2534, 2554), 'PIL.Image.fromarray', 'Image.fromarray', (['frm'], {}), '(frm)\n', (2549, 2554), False, 'from PIL import Image\n'), ((2610, 2679), 'torchvision.transforms.functional.resize', 'torchvision.transforms.functional.resize', (['im', 'resize'], {'interpolation': '(2)'}), '(im, resize, interpolation=2)\n', (2650, 2679), False, 'import torchvision\n'), ((2869, 2881), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (2877, 2881), True, 'import numpy as np\n')] |
# coding:utf-8
import numpy as np
class CatboostDataPrepare(object):
def __init__(self, *, train_feature, test_feature):
self.__train_feature = train_feature.copy()
self.__test_feature = test_feature.copy()
self.__categorical_index = None
self.__numeric_index = None
def data_prepare(self):
""" 离散变量 缺失值填充 missing 连续变量 缺失值填充 +999/-999
:return: 训练集特征 测试集特征
"""
self.__categorical_index = np.where(self.__train_feature.dtypes == "object")[0]
self.__numeric_index = np.where(self.__train_feature.dtypes != "object")[0]
self.__train_feature.iloc[:, self.__categorical_index] = (
self.__train_feature.iloc[:, self.__categorical_index].fillna("missing")
)
self.__test_feature.iloc[:, self.__categorical_index] = (
self.__test_feature.iloc[:, self.__categorical_index].fillna("missing")
)
# 让 catboost 自行处理缺失值
# self.__train_feature.iloc[:, self.__numeric_index] = (
# self.__train_feature.iloc[:, self.__numeric_index].apply(
# lambda x: x.fillna(-999.0) if x.median() > 0 else x.fillna(999.0)
# )
# )
# self.__test_feature.iloc[:, self.__numeric_index] = (
# self.__test_feature.iloc[:, self.__numeric_index].apply(
# lambda x: x.fillna(-999.0) if x.median() > 0 else x.fillna(999.0)
# )
# )
return self.__train_feature, self.__test_feature | [
"numpy.where"
] | [((464, 513), 'numpy.where', 'np.where', (["(self.__train_feature.dtypes == 'object')"], {}), "(self.__train_feature.dtypes == 'object')\n", (472, 513), True, 'import numpy as np\n'), ((548, 597), 'numpy.where', 'np.where', (["(self.__train_feature.dtypes != 'object')"], {}), "(self.__train_feature.dtypes != 'object')\n", (556, 597), True, 'import numpy as np\n')] |
#!@PYTHON_EXECUTABLE@
# MIT License
#
# Copyright (c) 2018, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory (subject to receipt of any
# required approvals from the U.S. Dept. of Energy). All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from __future__ import absolute_import
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, The Regents of the University of California"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "@PROJECT_VERSION@"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
rank = 0
try:
import mpi4py
from mpi4py import MPI
rank = MPI.COMM_WORLD.Get_rank()
except ImportError:
pass
import os
import time
import json
import random
import unittest
import threading
import inspect
import numpy as np
import timemory as tim
from timemory import component as comp
from timemory.profiler import profile, config
from timemory.bundle import auto_timer, auto_tuple, marker
# --------------------------- helper functions ----------------------------------------- #
# compute fibonacci
def fibonacci(n, with_arg=True):
mode = "full" if not with_arg else "defer"
with marker(
["wall_clock", "peak_rss", "current_peak_rss"],
"fib({})".format(n) if with_arg else "",
mode=mode,
):
arr = np.ones([100, 100], dtype=float)
return (
n
if n < 2
else (fibonacci(n - 1, with_arg) + fibonacci(n - 2, with_arg))
)
# --------------------------- Hatchet Tests set ---------------------------------------- #
# Hatchet tests class
class TimemoryHatchetTests(unittest.TestCase):
@classmethod
def setUpClass(self):
# set up environment variables
tim.settings.verbose = 1
tim.settings.debug = False
tim.settings.tree_output = True
tim.settings.text_output = True
tim.settings.cout_output = False
tim.settings.json_output = False
tim.settings.flamegraph_output = False
tim.settings.mpi_thread = False
tim.settings.dart_output = True
tim.settings.dart_count = 1
tim.settings.banner = False
tim.settings.parse()
# generate data
fibonacci(15, False)
fibonacci(8)
def setUp(self):
pass
def tearDown(self):
pass
@classmethod
def tearDownClass(self):
pass
# ---------------------------------------------------------------------------------- #
# test handling wall-clock data from hatchet
def test_hatchet_1D_data(self):
"""hatchet_1D_data"""
try:
import hatchet as ht
except ImportError:
return
data = tim.get(hierarchy=True, components=["wall_clock"])
gf = ht.GraphFrame.from_timemory(data)
if rank == 0:
print(gf.dataframe)
print(gf.tree("sum"))
print(gf.tree("sum.inc"))
# ---------------------------------------------------------------------------------- #
# test handling multi-dimensional data from hatchet
def test_hatchet_2D_data(self):
"""hatchet_2d_data"""
try:
import hatchet as ht
except ImportError:
return
from timemory.component import CurrentPeakRss
data = tim.get(hierarchy=True, components=[CurrentPeakRss.id()])
gf = ht.GraphFrame.from_timemory(data)
if rank == 0:
print(gf.dataframe)
print(gf.tree("sum.start-peak-rss"))
print(gf.tree("sum.stop-peak-rss.inc"))
self.assertTrue(gf.tree("sum.start-peak-rss.inc") is not None)
self.assertTrue(gf.tree("sum.stop-peak-rss") is not None)
def test_hatchet_analyze(self):
"""test_hatchet_analyze"""
try:
import hatchet as ht
except ImportError:
return
from timemory.analyze import embedded_analyze
from timemory import settings
import timemory
outpath = os.path.join(
settings.output_path,
"analysis",
)
args = (
["--expression", "x > 0"]
+ "-f dot flamegraph tree -o {} --per-thread --per-rank --select peak_rss --search fibonacci -e".format(
outpath
).split()
)
if rank == 0:
print(f"arguments: {args}")
embedded_analyze(
args,
data=[timemory.get(hierarchy=True)],
)
# ----------------------------- main test runner ---------------------------------------- #
# main runner
def run():
# run all tests
unittest.main()
if __name__ == "__main__":
tim.initialize([__file__])
run()
| [
"unittest.main",
"hatchet.GraphFrame.from_timemory",
"timemory.settings.parse",
"timemory.get",
"mpi4py.MPI.COMM_WORLD.Get_rank",
"numpy.ones",
"timemory.component.CurrentPeakRss.id",
"os.path.join",
"timemory.initialize"
] | [((1681, 1706), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_WORLD.Get_rank', ([], {}), '()\n', (1704, 1706), False, 'from mpi4py import MPI\n'), ((5697, 5712), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5710, 5712), False, 'import unittest\n'), ((5746, 5772), 'timemory.initialize', 'tim.initialize', (['[__file__]'], {}), '([__file__])\n', (5760, 5772), True, 'import timemory as tim\n'), ((2374, 2406), 'numpy.ones', 'np.ones', (['[100, 100]'], {'dtype': 'float'}), '([100, 100], dtype=float)\n', (2381, 2406), True, 'import numpy as np\n'), ((3225, 3245), 'timemory.settings.parse', 'tim.settings.parse', ([], {}), '()\n', (3243, 3245), True, 'import timemory as tim\n'), ((3771, 3821), 'timemory.get', 'tim.get', ([], {'hierarchy': '(True)', 'components': "['wall_clock']"}), "(hierarchy=True, components=['wall_clock'])\n", (3778, 3821), True, 'import timemory as tim\n'), ((3835, 3868), 'hatchet.GraphFrame.from_timemory', 'ht.GraphFrame.from_timemory', (['data'], {}), '(data)\n', (3862, 3868), True, 'import hatchet as ht\n'), ((4446, 4479), 'hatchet.GraphFrame.from_timemory', 'ht.GraphFrame.from_timemory', (['data'], {}), '(data)\n', (4473, 4479), True, 'import hatchet as ht\n'), ((5076, 5122), 'os.path.join', 'os.path.join', (['settings.output_path', '"""analysis"""'], {}), "(settings.output_path, 'analysis')\n", (5088, 5122), False, 'import os\n'), ((4411, 4430), 'timemory.component.CurrentPeakRss.id', 'CurrentPeakRss.id', ([], {}), '()\n', (4428, 4430), False, 'from timemory.component import CurrentPeakRss\n'), ((5513, 5541), 'timemory.get', 'timemory.get', ([], {'hierarchy': '(True)'}), '(hierarchy=True)\n', (5525, 5541), False, 'import timemory\n')] |
import re
import numpy as np
import tqdm
from scipy.spatial.distance import pdist
from .paths import paths
from suggestion.tokenization import sentence_per_line_tokenize
import pandas as pd
def load_reviews():
data = pd.read_pickle(str(paths.preproc / 'all_data.pkl'))
reviews = data['data'].reset_index(drop=True)
# Reconstruct train/test split indices.
# TODO: put this in the preprocessing
np.random.seed(0)
train_frac = 1 - .05 - .05
num_docs = len(reviews)
indices = np.random.permutation(num_docs)
splits = (np.cumsum([train_frac, .05]) * num_docs).astype(int)
segment_indices = np.split(indices, splits)
names = ['train', 'valid', 'test']
for name, indices in zip(names, segment_indices):
indicator = np.zeros(len(reviews), dtype=bool)
indicator[indices] = True
reviews[f'is_{name}'] = indicator
## Identify the best reviews.
# Mark the top reviews: top-5 ranked reviews of restaurants with at least the median # reviews,
# as long as they have >= 10 votes.
reviews['total_votes'] = reviews['votes_cool'] + reviews['votes_funny'] + reviews['votes_useful']
reviews['total_votes_rank'] = reviews.groupby('business_id').total_votes.rank(ascending=False)
business_review_counts = reviews.groupby('business_id').review_count.mean()
median_review_count = np.median(business_review_counts)
reviews['is_best'] = (reviews.review_count >= median_review_count) & (reviews.total_votes >= 10) & (reviews.total_votes_rank <= 5)
return reviews
class WordFreqAnalyzer:
def __init__(self, vocab, counts):
self.vocab = vocab
self.counts = counts
self.word2idx = {word: idx for idx, word in enumerate(vocab)}
freqs = counts / counts.sum()
self.log_freqs = np.log(freqs)
def lookup_indices(self, toks):
word2idx = self.word2idx
tmp = (word2idx.get(word) for word in toks)
return [w for w in tmp if w is not None]
def mean_log_freq(self, indices):
return np.mean(self.log_freqs[indices]) if len(indices) else None
def min_log_freq(self, indices):
return np.min(self.log_freqs[indices]) if len(indices) else None
def __call__(self, doc):
'''Assumes doc is tokenized. [TODO: into sentences by newlines].'''
indices = self.lookup_indices(doc.split()) # for sent in doc.lower().split('\n')]
# mean_llk = list(cytoolz.filter(None, [self.mean_log_freq(indices) for indices in doc_indices]))
# min_llk = list(cytoolz.filter(None, [self.min_log_freq(indices) for indices in doc_indices]))
return dict(
mean_llk=self.mean_log_freq(indices),
min_llk=self.min_log_freq(indices))
@classmethod
def build(cls):
data = pd.read_pickle(str(paths.preproc / 'all_data.pkl'))
vocab, counts = data['vocab']
return cls(vocab, counts)
@classmethod
def get(cls):
if not hasattr(cls, 'singleton'):
cls.singleton = cls.build()
return cls.singleton
class WordPairAnalyzer:
def __init__(self, vectorizer, projection_mat, samples, prototypical_ecdf_best, mean_len_chars):
self.vectorizer = vectorizer
self.projection_mat = projection_mat
self.samples = samples
self.prototypical_ecdf_best = prototypical_ecdf_best
self.mean_len_chars = mean_len_chars
@classmethod
def build(cls, reviews):
from suggestion import clustering
cnnb = clustering.ConceptNetNumberBatch.load()
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(min_df=5, max_df=.5, stop_words='english')
all_vecs = vectorizer.fit_transform(reviews.tokenized)
import wordfreq
sklearn_vocab = vectorizer.get_feature_names()
def get_or_zero(cnnb, item):
try:
return cnnb[item]
except KeyError:
return np.zeros(cnnb.ndim)
cnnb_vecs_for_sklearn_vocab = np.array([get_or_zero(cnnb, word) for word in sklearn_vocab])
wordfreqs_for_sklearn_vocab = [wordfreq.word_frequency(word, 'en', 'large', minimum=1e-9) for word in sklearn_vocab]
if False:
projection_mat = -np.log(wordfreqs_for_sklearn_vocab)[:,None] * cnnb_vecs_for_sklearn_vocab
else:
projection_mat = cnnb_vecs_for_sklearn_vocab
len_chars = reviews.text.str.len()
mean_len_chars = np.mean(len_chars)
samples = np.linspace(0, 50, 500)
ecdfs = np.empty((len(reviews), len(samples)))
for doc_idx in tqdm.tqdm(range(len(reviews))):
words = all_vecs[doc_idx]
if len(words.indices) < 2:
ecdfs[doc_idx] = np.nan
else:
dists = pdist(words.data[:,None] * projection_mat[words.indices])# / (len_chars[doc_idx] / mean_len_chars) ** 2
ecdfs[doc_idx] = smooth_ecdf(dists, samples)
prototypical_ecdf_best = np.nanmean(ecdfs[np.flatnonzero(reviews.is_best & ~reviews.is_train)], axis=0)
return cls(vectorizer, projection_mat, samples, prototypical_ecdf_best, mean_len_chars)
def ecdf(self, doc_vectorized):
if len(doc_vectorized.indices) < 2:
return np.full_like(self.samples, np.nan)
else:
dists = pdist(doc_vectorized.data[:,None] * self.projection_mat[doc_vectorized.indices])# / (len(doc_vectorized) / mean_len_chars) ** 2
return smooth_ecdf(dists, self.samples)
def __call__(self, doc):
doc_vectorized = self.vectorizer.transform([doc])
return np.max(np.abs(self.ecdf(doc_vectorized) - self.prototypical_ecdf_best))
def smooth_ecdf(x, samples):
return np.interp(samples, np.sort(x), np.linspace(0,1,len(x)))
def _mtld(tokens, threshold=0.72):
# Roughly based on http://cpansearch.perl.org/src/AXANTHOS/Lingua-Diversity-0.06/lib/Lingua/Diversity/MTLD.pm
# TODO: this is such an ugly heuristic measure. Validate it somehow??
word_re = re.compile(r'\w+|\w+[^\s]+\w+')
factor_lengths = []
factor_weights = []
cur_token_count = 0
cur_types = set()
type_token_ratio = 1. # initialize just in case no tokens
for token in tokens:
if word_re.match(token) is None:
continue
token = token.lower()
cur_token_count += 1
cur_types.add(token)
type_token_ratio = len(cur_types) / cur_token_count
if type_token_ratio <= threshold:
factor_lengths.append(cur_token_count)
factor_weights.append(1.)
cur_token_count = 0
cur_types = set()
type_token_ratio = 1.
# Handle partial factors
if cur_token_count > 0:
if type_token_ratio == 1. and len(factor_lengths) == 0:
factor_lengths.append(0)
factor_weights.append(1.)
elif type_token_ratio < 1:
proportion = (1 - type_token_ratio) / (1 - threshold)
assert 0 <= proportion < 1
factor_lengths.append(cur_token_count / proportion)
factor_weights.append(proportion)
if len(factor_lengths) == 0:
return 0.
return sum(length * weight for length, weight in zip(factor_lengths, factor_weights)) / sum(factor_weights)
def mtld(tokens, threshold=0.72):
return (_mtld(tokens, threshold=threshold) + _mtld(reversed(tokens), threshold=threshold)) / 2
def analyze_readability_measures(text, include_word_types=False):
import readability
import traceback
from collections import OrderedDict
tokenized = sentence_per_line_tokenize(text)
res = pd.Series()
tokenized_sentences = [sent.split() for sent in tokenized.lower().split('\n')]
toks_flat = [w for sent in tokenized_sentences for w in sent]
if len(toks_flat) == 0:
return {} # invalid...
res['mtld'] = mtld(toks_flat)
try:
readability_measures = readability.getmeasures(tokenized)
except Exception:
traceback.print_exc()
else:
for k, v in readability_measures.pop('sentence info').items():
res[k] = v
num_words = res['words']
num_sents = res['sentences']
if include_word_types:
for word_type, count in readability_measures.pop('sentence beginnings').items():
res[f'word_type_sent_startswith_{word_type}'] = count / num_sents
for typ, count in readability_measures.pop('word usage').items():
res[f'word_type_overall_{typ}'] = count / num_words
for k in 'wordtypes long_words complex_words'.split():
res[k] = res[k] / num_words
# res.update(readability_measures.pop('readability grades'))
return res
| [
"numpy.random.seed",
"sklearn.feature_extraction.text.TfidfVectorizer",
"suggestion.clustering.ConceptNetNumberBatch.load",
"suggestion.tokenization.sentence_per_line_tokenize",
"numpy.mean",
"scipy.spatial.distance.pdist",
"numpy.full_like",
"traceback.print_exc",
"numpy.cumsum",
"numpy.linspace"... | [((416, 433), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (430, 433), True, 'import numpy as np\n'), ((507, 538), 'numpy.random.permutation', 'np.random.permutation', (['num_docs'], {}), '(num_docs)\n', (528, 538), True, 'import numpy as np\n'), ((628, 653), 'numpy.split', 'np.split', (['indices', 'splits'], {}), '(indices, splits)\n', (636, 653), True, 'import numpy as np\n'), ((1360, 1393), 'numpy.median', 'np.median', (['business_review_counts'], {}), '(business_review_counts)\n', (1369, 1393), True, 'import numpy as np\n'), ((6063, 6097), 're.compile', 're.compile', (['"""\\\\w+|\\\\w+[^\\\\s]+\\\\w+"""'], {}), "('\\\\w+|\\\\w+[^\\\\s]+\\\\w+')\n", (6073, 6097), False, 'import re\n'), ((7625, 7657), 'suggestion.tokenization.sentence_per_line_tokenize', 'sentence_per_line_tokenize', (['text'], {}), '(text)\n', (7651, 7657), False, 'from suggestion.tokenization import sentence_per_line_tokenize\n'), ((7668, 7679), 'pandas.Series', 'pd.Series', ([], {}), '()\n', (7677, 7679), True, 'import pandas as pd\n'), ((1802, 1815), 'numpy.log', 'np.log', (['freqs'], {}), '(freqs)\n', (1808, 1815), True, 'import numpy as np\n'), ((3516, 3555), 'suggestion.clustering.ConceptNetNumberBatch.load', 'clustering.ConceptNetNumberBatch.load', ([], {}), '()\n', (3553, 3555), False, 'from suggestion import clustering\n'), ((3646, 3705), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'min_df': '(5)', 'max_df': '(0.5)', 'stop_words': '"""english"""'}), "(min_df=5, max_df=0.5, stop_words='english')\n", (3661, 3705), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((4495, 4513), 'numpy.mean', 'np.mean', (['len_chars'], {}), '(len_chars)\n', (4502, 4513), True, 'import numpy as np\n'), ((4532, 4555), 'numpy.linspace', 'np.linspace', (['(0)', '(50)', '(500)'], {}), '(0, 50, 500)\n', (4543, 4555), True, 'import numpy as np\n'), ((5786, 5796), 'numpy.sort', 'np.sort', (['x'], {}), '(x)\n', (5793, 5796), True, 'import numpy as np\n'), ((7963, 7997), 'readability.getmeasures', 'readability.getmeasures', (['tokenized'], {}), '(tokenized)\n', (7986, 7997), False, 'import readability\n'), ((2041, 2073), 'numpy.mean', 'np.mean', (['self.log_freqs[indices]'], {}), '(self.log_freqs[indices])\n', (2048, 2073), True, 'import numpy as np\n'), ((2153, 2184), 'numpy.min', 'np.min', (['self.log_freqs[indices]'], {}), '(self.log_freqs[indices])\n', (2159, 2184), True, 'import numpy as np\n'), ((4147, 4206), 'wordfreq.word_frequency', 'wordfreq.word_frequency', (['word', '"""en"""', '"""large"""'], {'minimum': '(1e-09)'}), "(word, 'en', 'large', minimum=1e-09)\n", (4170, 4206), False, 'import wordfreq\n'), ((5299, 5333), 'numpy.full_like', 'np.full_like', (['self.samples', 'np.nan'], {}), '(self.samples, np.nan)\n', (5311, 5333), True, 'import numpy as np\n'), ((5368, 5454), 'scipy.spatial.distance.pdist', 'pdist', (['(doc_vectorized.data[:, None] * self.projection_mat[doc_vectorized.indices])'], {}), '(doc_vectorized.data[:, None] * self.projection_mat[doc_vectorized.\n indices])\n', (5373, 5454), False, 'from scipy.spatial.distance import pdist\n'), ((8028, 8049), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (8047, 8049), False, 'import traceback\n'), ((553, 582), 'numpy.cumsum', 'np.cumsum', (['[train_frac, 0.05]'], {}), '([train_frac, 0.05])\n', (562, 582), True, 'import numpy as np\n'), ((4825, 4883), 'scipy.spatial.distance.pdist', 'pdist', (['(words.data[:, None] * projection_mat[words.indices])'], {}), '(words.data[:, None] * projection_mat[words.indices])\n', (4830, 4883), False, 'from scipy.spatial.distance import pdist\n'), ((5041, 5092), 'numpy.flatnonzero', 'np.flatnonzero', (['(reviews.is_best & ~reviews.is_train)'], {}), '(reviews.is_best & ~reviews.is_train)\n', (5055, 5092), True, 'import numpy as np\n'), ((3988, 4007), 'numpy.zeros', 'np.zeros', (['cnnb.ndim'], {}), '(cnnb.ndim)\n', (3996, 4007), True, 'import numpy as np\n'), ((4281, 4316), 'numpy.log', 'np.log', (['wordfreqs_for_sklearn_vocab'], {}), '(wordfreqs_for_sklearn_vocab)\n', (4287, 4316), True, 'import numpy as np\n')] |
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pickle
import tempfile
import unittest
import nibabel as nib
import numpy as np
from parameterized import parameterized
from monai.data import PersistentDataset, json_hashing
from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform
TEST_CASE_1 = [
Compose(
[
LoadImaged(keys=["image", "label", "extra"]),
SimulateDelayd(keys=["image", "label", "extra"], delay_time=[1e-7, 1e-6, 1e-5]),
]
),
(128, 128, 128),
]
TEST_CASE_2 = [
[
LoadImaged(keys=["image", "label", "extra"]),
SimulateDelayd(keys=["image", "label", "extra"], delay_time=[1e-7, 1e-6, 1e-5]),
],
(128, 128, 128),
]
TEST_CASE_3 = [None, (128, 128, 128)]
class _InplaceXform(Transform):
def __call__(self, data):
if data:
data[0] = data[0] + np.pi
else:
data.append(1)
return data
class TestDataset(unittest.TestCase):
def test_cache(self):
"""testing no inplace change to the hashed item"""
items = [[list(range(i))] for i in range(5)]
with tempfile.TemporaryDirectory() as tempdir:
ds = PersistentDataset(
data=items,
transform=_InplaceXform(),
cache_dir=tempdir,
pickle_module="pickle",
pickle_protocol=pickle.HIGHEST_PROTOCOL,
)
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds1 = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir)
self.assertEqual(list(ds1), list(ds))
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir, hash_func=json_hashing)
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
ds1 = PersistentDataset(items, transform=_InplaceXform(), cache_dir=tempdir, hash_func=json_hashing)
self.assertEqual(list(ds1), list(ds))
self.assertEqual(items, [[[]], [[0]], [[0, 1]], [[0, 1, 2]], [[0, 1, 2, 3]]])
@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
def test_shape(self, transform, expected_shape):
test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4))
with tempfile.TemporaryDirectory() as tempdir:
nib.save(test_image, os.path.join(tempdir, "test_image1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_label1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_extra1.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_image2.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_label2.nii.gz"))
nib.save(test_image, os.path.join(tempdir, "test_extra2.nii.gz"))
test_data = [
{
"image": os.path.join(tempdir, "test_image1.nii.gz"),
"label": os.path.join(tempdir, "test_label1.nii.gz"),
"extra": os.path.join(tempdir, "test_extra1.nii.gz"),
},
{
"image": os.path.join(tempdir, "test_image2.nii.gz"),
"label": os.path.join(tempdir, "test_label2.nii.gz"),
"extra": os.path.join(tempdir, "test_extra2.nii.gz"),
},
]
cache_dir = os.path.join(os.path.join(tempdir, "cache"), "data")
dataset_precached = PersistentDataset(data=test_data, transform=transform, cache_dir=cache_dir)
data1_precached = dataset_precached[0]
data2_precached = dataset_precached[1]
dataset_postcached = PersistentDataset(data=test_data, transform=transform, cache_dir=cache_dir)
data1_postcached = dataset_postcached[0]
data2_postcached = dataset_postcached[1]
data3_postcached = dataset_postcached[0:2]
if transform is None:
self.assertEqual(data1_precached["image"], os.path.join(tempdir, "test_image1.nii.gz"))
self.assertEqual(data2_precached["label"], os.path.join(tempdir, "test_label2.nii.gz"))
self.assertEqual(data1_postcached["image"], os.path.join(tempdir, "test_image1.nii.gz"))
self.assertEqual(data2_postcached["extra"], os.path.join(tempdir, "test_extra2.nii.gz"))
else:
self.assertTupleEqual(data1_precached["image"].shape, expected_shape)
self.assertTupleEqual(data1_precached["label"].shape, expected_shape)
self.assertTupleEqual(data1_precached["extra"].shape, expected_shape)
self.assertTupleEqual(data2_precached["image"].shape, expected_shape)
self.assertTupleEqual(data2_precached["label"].shape, expected_shape)
self.assertTupleEqual(data2_precached["extra"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["image"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["label"].shape, expected_shape)
self.assertTupleEqual(data1_postcached["extra"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["image"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["label"].shape, expected_shape)
self.assertTupleEqual(data2_postcached["extra"].shape, expected_shape)
for d in data3_postcached:
self.assertTupleEqual(d["image"].shape, expected_shape)
# update the data to cache
test_data_new = [
{
"image": os.path.join(tempdir, "test_image1_new.nii.gz"),
"label": os.path.join(tempdir, "test_label1_new.nii.gz"),
"extra": os.path.join(tempdir, "test_extra1_new.nii.gz"),
},
{
"image": os.path.join(tempdir, "test_image2_new.nii.gz"),
"label": os.path.join(tempdir, "test_label2_new.nii.gz"),
"extra": os.path.join(tempdir, "test_extra2_new.nii.gz"),
},
]
dataset_postcached.set_data(data=test_data_new)
# test new exchanged cache content
if transform is None:
self.assertEqual(dataset_postcached[0]["image"], os.path.join(tempdir, "test_image1_new.nii.gz"))
self.assertEqual(dataset_postcached[0]["label"], os.path.join(tempdir, "test_label1_new.nii.gz"))
self.assertEqual(dataset_postcached[1]["extra"], os.path.join(tempdir, "test_extra2_new.nii.gz"))
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"tempfile.TemporaryDirectory",
"parameterized.parameterized.expand",
"monai.transforms.LoadImaged",
"numpy.random.randint",
"monai.data.PersistentDataset",
"numpy.eye",
"os.path.join",
"monai.transforms.SimulateDelayd"
] | [((2766, 2827), 'parameterized.parameterized.expand', 'parameterized.expand', (['[TEST_CASE_1, TEST_CASE_2, TEST_CASE_3]'], {}), '([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])\n', (2786, 2827), False, 'from parameterized import parameterized\n'), ((7387, 7402), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7400, 7402), False, 'import unittest\n'), ((1114, 1158), 'monai.transforms.LoadImaged', 'LoadImaged', ([], {'keys': "['image', 'label', 'extra']"}), "(keys=['image', 'label', 'extra'])\n", (1124, 1158), False, 'from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform\n'), ((1168, 1255), 'monai.transforms.SimulateDelayd', 'SimulateDelayd', ([], {'keys': "['image', 'label', 'extra']", 'delay_time': '[1e-07, 1e-06, 1e-05]'}), "(keys=['image', 'label', 'extra'], delay_time=[1e-07, 1e-06, \n 1e-05])\n", (1182, 1255), False, 'from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform\n'), ((904, 948), 'monai.transforms.LoadImaged', 'LoadImaged', ([], {'keys': "['image', 'label', 'extra']"}), "(keys=['image', 'label', 'extra'])\n", (914, 948), False, 'from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform\n'), ((962, 1049), 'monai.transforms.SimulateDelayd', 'SimulateDelayd', ([], {'keys': "['image', 'label', 'extra']", 'delay_time': '[1e-07, 1e-06, 1e-05]'}), "(keys=['image', 'label', 'extra'], delay_time=[1e-07, 1e-06, \n 1e-05])\n", (976, 1049), False, 'from monai.transforms import Compose, LoadImaged, SimulateDelayd, Transform\n'), ((1690, 1719), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (1717, 1719), False, 'import tempfile\n'), ((2918, 2963), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)'], {'size': '[128, 128, 128]'}), '(0, 2, size=[128, 128, 128])\n', (2935, 2963), True, 'import numpy as np\n'), ((2965, 2974), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2971, 2974), True, 'import numpy as np\n'), ((2989, 3018), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3016, 3018), False, 'import tempfile\n'), ((4167, 4242), 'monai.data.PersistentDataset', 'PersistentDataset', ([], {'data': 'test_data', 'transform': 'transform', 'cache_dir': 'cache_dir'}), '(data=test_data, transform=transform, cache_dir=cache_dir)\n', (4184, 4242), False, 'from monai.data import PersistentDataset, json_hashing\n'), ((4379, 4454), 'monai.data.PersistentDataset', 'PersistentDataset', ([], {'data': 'test_data', 'transform': 'transform', 'cache_dir': 'cache_dir'}), '(data=test_data, transform=transform, cache_dir=cache_dir)\n', (4396, 4454), False, 'from monai.data import PersistentDataset, json_hashing\n'), ((3064, 3107), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1.nii.gz"""'], {}), "(tempdir, 'test_image1.nii.gz')\n", (3076, 3107), False, 'import os\n'), ((3142, 3185), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label1.nii.gz"""'], {}), "(tempdir, 'test_label1.nii.gz')\n", (3154, 3185), False, 'import os\n'), ((3220, 3263), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra1.nii.gz"""'], {}), "(tempdir, 'test_extra1.nii.gz')\n", (3232, 3263), False, 'import os\n'), ((3298, 3341), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image2.nii.gz"""'], {}), "(tempdir, 'test_image2.nii.gz')\n", (3310, 3341), False, 'import os\n'), ((3376, 3419), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label2.nii.gz"""'], {}), "(tempdir, 'test_label2.nii.gz')\n", (3388, 3419), False, 'import os\n'), ((3454, 3497), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra2.nii.gz"""'], {}), "(tempdir, 'test_extra2.nii.gz')\n", (3466, 3497), False, 'import os\n'), ((4095, 4125), 'os.path.join', 'os.path.join', (['tempdir', '"""cache"""'], {}), "(tempdir, 'cache')\n", (4107, 4125), False, 'import os\n'), ((3572, 3615), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1.nii.gz"""'], {}), "(tempdir, 'test_image1.nii.gz')\n", (3584, 3615), False, 'import os\n'), ((3646, 3689), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label1.nii.gz"""'], {}), "(tempdir, 'test_label1.nii.gz')\n", (3658, 3689), False, 'import os\n'), ((3720, 3763), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra1.nii.gz"""'], {}), "(tempdir, 'test_extra1.nii.gz')\n", (3732, 3763), False, 'import os\n'), ((3831, 3874), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image2.nii.gz"""'], {}), "(tempdir, 'test_image2.nii.gz')\n", (3843, 3874), False, 'import os\n'), ((3905, 3948), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label2.nii.gz"""'], {}), "(tempdir, 'test_label2.nii.gz')\n", (3917, 3948), False, 'import os\n'), ((3979, 4022), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra2.nii.gz"""'], {}), "(tempdir, 'test_extra2.nii.gz')\n", (3991, 4022), False, 'import os\n'), ((4710, 4753), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1.nii.gz"""'], {}), "(tempdir, 'test_image1.nii.gz')\n", (4722, 4753), False, 'import os\n'), ((4814, 4857), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label2.nii.gz"""'], {}), "(tempdir, 'test_label2.nii.gz')\n", (4826, 4857), False, 'import os\n'), ((4919, 4962), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1.nii.gz"""'], {}), "(tempdir, 'test_image1.nii.gz')\n", (4931, 4962), False, 'import os\n'), ((5024, 5067), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra2.nii.gz"""'], {}), "(tempdir, 'test_extra2.nii.gz')\n", (5036, 5067), False, 'import os\n'), ((6362, 6409), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1_new.nii.gz"""'], {}), "(tempdir, 'test_image1_new.nii.gz')\n", (6374, 6409), False, 'import os\n'), ((6440, 6487), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label1_new.nii.gz"""'], {}), "(tempdir, 'test_label1_new.nii.gz')\n", (6452, 6487), False, 'import os\n'), ((6518, 6565), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra1_new.nii.gz"""'], {}), "(tempdir, 'test_extra1_new.nii.gz')\n", (6530, 6565), False, 'import os\n'), ((6633, 6680), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image2_new.nii.gz"""'], {}), "(tempdir, 'test_image2_new.nii.gz')\n", (6645, 6680), False, 'import os\n'), ((6711, 6758), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label2_new.nii.gz"""'], {}), "(tempdir, 'test_label2_new.nii.gz')\n", (6723, 6758), False, 'import os\n'), ((6789, 6836), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra2_new.nii.gz"""'], {}), "(tempdir, 'test_extra2_new.nii.gz')\n", (6801, 6836), False, 'import os\n'), ((7077, 7124), 'os.path.join', 'os.path.join', (['tempdir', '"""test_image1_new.nii.gz"""'], {}), "(tempdir, 'test_image1_new.nii.gz')\n", (7089, 7124), False, 'import os\n'), ((7191, 7238), 'os.path.join', 'os.path.join', (['tempdir', '"""test_label1_new.nii.gz"""'], {}), "(tempdir, 'test_label1_new.nii.gz')\n", (7203, 7238), False, 'import os\n'), ((7305, 7352), 'os.path.join', 'os.path.join', (['tempdir', '"""test_extra2_new.nii.gz"""'], {}), "(tempdir, 'test_extra2_new.nii.gz')\n", (7317, 7352), False, 'import os\n')] |
"""
.. _greedy-ar:
Autoregressive model
----------------------------------------------------------------------------------------------------
Greedy change point detection for piecewise autoregressive signals.
Sequential algorithm.
"""
import numpy as np
from numpy.lib.stride_tricks import as_strided
from numpy.linalg import lstsq
from ruptures.utils import pairwise
class GreedyAR:
"""Greedy change point detection for piecewise autoregressive processes."""
def __init__(self, order=2, jump=10):
"""
Args:
order (int, optional): order of the autoregressive process. Defaults to 2.
jump (int, optional): only consider change points multiple of *jump*. Defaults to 10.
Returns:
self
"""
self.order = max(1, order)
self.jump = max(jump, 2 * (order + 1))
self.n_samples = None
self.signal = None
self.covariates = None
self.dim = None
def seg(self, n_bkps=None, pen=None, epsilon=None):
"""Computes the greedy segmentation.
The stopping rule depends on the parameter passed to the function.
Args:
n_bkps (int): number of breakpoints to find before stopping.
penalty (float): penalty value (>0)
epsilon (float): reconstruction budget
Returns:
list: list of breakpoint indexes
"""
stop = False
n_samples = self.n_samples - self.order
bkps = [n_samples]
inds = np.arange(start=self.jump - self.order,
stop=n_samples - self.jump,
step=self.jump)
signal = self.signal[-n_samples:]
residual = signal
res_norm = residual.var() * n_samples
while not stop:
# greedy search
res_list = list()
for ind in inds: # greedy search
res_tmp = 0
y_left, y_right = residual[:ind], residual[ind:]
x_left, x_right = self.covariates[:ind], self.covariates[ind:]
for x, y in zip((x_left, x_right), (y_left, y_right)):
# linear fit
_, res_sub, _, _ = lstsq(x, y)
# error on sub-signal
res_tmp += res_sub
res_list.append(res_tmp)
# find best index
_, bkp_opt = min(zip(res_list, inds))
# orthogonal projection
proj = np.zeros(signal.shape)
for start, end in pairwise(sorted([0, bkp_opt] + bkps)):
y = signal[start:end]
x = self.covariates[start:end]
coef, _, _, _ = lstsq(x, y)
proj[start:end] = x.dot(coef).reshape(-1, 1)
residual = signal - proj
# stopping criterion
stop = True
if n_bkps is not None:
if len(bkps) - 1 < n_bkps:
stop = False
elif pen is not None:
if res_norm - residual.var() * n_samples > pen:
stop = False
elif epsilon is not None:
if residual.var() * n_samples > epsilon:
stop = False
# update
if not stop:
res_norm = residual.var() * n_samples
bkps.append(bkp_opt)
bkps.sort()
return bkps
def fit(self, signal):
"""Compute params to segment signal.
Args:
signal (array): univariate signal to segment. Shape (n_samples, 1) or (n_samples,).
Returns:
self
"""
# update some params
if signal.ndim == 1:
self.signal = signal.reshape(-1, 1) - signal.mean()
else:
self.signal = signal - signal.mean()
self.n_samples, dim = self.signal.shape
assert dim == 1, "Signal must be 1D."
# covariates are lagged sub-sequences
shape = (self.n_samples - self.order, self.order)
strides = (self.signal.itemsize, self.signal.itemsize)
covariates = np.lib.stride_tricks.as_strided(self.signal,
shape=shape, strides=strides)
intercept = np.ones(self.n_samples - self.order)
covariates = np.column_stack((covariates, intercept))
self.covariates = covariates
return self
def predict(self, n_bkps=None, pen=None, epsilon=None):
"""Return the optimal breakpoints.
Must be called after the fit method. The breakpoints are associated with the signal passed
to fit().
The stopping rule depends on the parameter passed to the function.
Args:
n_bkps (int): number of breakpoints to find before stopping.
penalty (float): penalty value (>0)
penalty (float): penalty value
Returns:
list: sorted list of breakpoints
"""
msg = "Give a parameter."
assert any(param is not None for param in (n_bkps, pen, epsilon)), msg
bkps = self.seg(n_bkps=n_bkps, pen=pen, epsilon=epsilon)
return [b + self.order for b in bkps]
def fit_predict(self, signal, n_bkps=None, pen=None, epsilon=None):
"""Helper method to call fit and predict once."""
self.fit(signal)
return self.predict(n_bkps=n_bkps, pen=pen, epsilon=epsilon)
| [
"numpy.linalg.lstsq",
"numpy.zeros",
"numpy.ones",
"numpy.lib.stride_tricks.as_strided",
"numpy.arange",
"numpy.column_stack"
] | [((1517, 1605), 'numpy.arange', 'np.arange', ([], {'start': '(self.jump - self.order)', 'stop': '(n_samples - self.jump)', 'step': 'self.jump'}), '(start=self.jump - self.order, stop=n_samples - self.jump, step=\n self.jump)\n', (1526, 1605), True, 'import numpy as np\n'), ((4106, 4180), 'numpy.lib.stride_tricks.as_strided', 'np.lib.stride_tricks.as_strided', (['self.signal'], {'shape': 'shape', 'strides': 'strides'}), '(self.signal, shape=shape, strides=strides)\n', (4137, 4180), True, 'import numpy as np\n'), ((4254, 4290), 'numpy.ones', 'np.ones', (['(self.n_samples - self.order)'], {}), '(self.n_samples - self.order)\n', (4261, 4290), True, 'import numpy as np\n'), ((4312, 4352), 'numpy.column_stack', 'np.column_stack', (['(covariates, intercept)'], {}), '((covariates, intercept))\n', (4327, 4352), True, 'import numpy as np\n'), ((2478, 2500), 'numpy.zeros', 'np.zeros', (['signal.shape'], {}), '(signal.shape)\n', (2486, 2500), True, 'import numpy as np\n'), ((2687, 2698), 'numpy.linalg.lstsq', 'lstsq', (['x', 'y'], {}), '(x, y)\n', (2692, 2698), False, 'from numpy.linalg import lstsq\n'), ((2209, 2220), 'numpy.linalg.lstsq', 'lstsq', (['x', 'y'], {}), '(x, y)\n', (2214, 2220), False, 'from numpy.linalg import lstsq\n')] |
from PIL import Image
import numpy as np
arr = np.random.uniform(size=(3,256,256))*255
arr = np.ascontiguousarray(arr.transpose(1,2,0))
img = Image.fromarray(arr, 'RGB')
img.save('out.png')
| [
"PIL.Image.fromarray",
"numpy.random.uniform"
] | [((143, 170), 'PIL.Image.fromarray', 'Image.fromarray', (['arr', '"""RGB"""'], {}), "(arr, 'RGB')\n", (158, 170), False, 'from PIL import Image\n'), ((48, 85), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3, 256, 256)'}), '(size=(3, 256, 256))\n', (65, 85), True, 'import numpy as np\n')] |
# Standard Library
from up.utils.general.fp16_helper import to_float32
import time
# Import from third library
import numpy as np
import torch
from up.utils.general.global_flag import ALIGNED_FLAG
from up.extensions import gpu_iou_overlap
GPU_MEMORY = None
def allow_empty_tensor(num=1, empty_shape=(0, 4)):
"""Return an empty tensor directly if any of first `num` argument is empty"""
def decorate(func):
def wrapper(*args, **kwargs):
for arg in args[:num]:
if torch.is_tensor(arg) and arg.numel() == 0:
return arg.new_zeros(empty_shape)
return func(*args, **kwargs)
return wrapper
return decorate
def filter_by_size(boxes, min_size, start_index=0):
if boxes.shape[0] == 0:
return boxes, []
s = start_index
w = boxes[:, s + 2] - boxes[:, s + 0] + ALIGNED_FLAG.offset
h = boxes[:, s + 3] - boxes[:, s + 1] + ALIGNED_FLAG.offset
filter_inds = (w > min_size) & (h > min_size)
return boxes[filter_inds], filter_inds
@allow_empty_tensor(2)
@to_float32
def bbox_iou_overlaps(b1, b2, aligned=False):
if not b1.is_cuda or aligned:
return vanilla_bbox_iou_overlaps(b1, b2, aligned)
global GPU_MEMORY
gbytes = 1024.0**3
if GPU_MEMORY is None:
GPU_MEMORY = torch.cuda.get_device_properties(b1.device.index).total_memory
alloated_memory = torch.cuda.memory_allocated()
spare_memory = 0.5 * gbytes
available_memory = GPU_MEMORY - alloated_memory - spare_memory
size = b1.shape[0] * b2.shape[0]
needed_memory = 2 * size * 4
if needed_memory < available_memory:
ious = gpu_iou_overlap(b1, b2, mode='IoU')
else:
ious = vanilla_bbox_iou_overlaps(b1.cpu(), b2.cpu())
res_memory = size * 4
if res_memory < available_memory:
ious = ious.to(b1.device)
return ious
@allow_empty_tensor(2)
@to_float32
def vanilla_bbox_iou_overlaps(b1, b2, aligned=False, return_union=False):
"""
Arguments:
b1: dts, [n, >=4] (x1, y1, x2, y2, ...)
b1: gts, [n, >=4] (x1, y1, x2, y2, ...)
Returns:
intersection-over-union pair-wise.
"""
area1 = (b1[:, 2] - b1[:, 0] + ALIGNED_FLAG.offset) * (b1[:, 3] - b1[:, 1] + ALIGNED_FLAG.offset)
area2 = (b2[:, 2] - b2[:, 0] + ALIGNED_FLAG.offset) * (b2[:, 3] - b2[:, 1] + ALIGNED_FLAG.offset)
if aligned:
assert b1.size(0) == b2.size(0)
if b1.size(0) * b2.size(0) == 0:
return b1.new_zeros(b1.size(0), 1)
lt = torch.max(b1[:, :2], b2[:, :2]) # [rows, 2]
rb = torch.min(b1[:, 2:], b2[:, 2:]) # [rows, 2]
wh = (rb - lt + ALIGNED_FLAG.offset).clamp(min=0) # [rows, 2]
overlap = wh[:, 0] * wh[:, 1]
union = area1 + area2 - overlap
union = torch.max(union, union.new_tensor([1e-6]))
return overlap / union
lt = torch.max(b1[:, None, :2], b2[:, :2])
rb = torch.min(b1[:, None, 2:4], b2[:, 2:4])
wh = (rb - lt + ALIGNED_FLAG.offset).clamp(min=0)
inter_area = wh[:, :, 0] * wh[:, :, 1]
union_area = area1[:, None] + area2 - inter_area
if return_union:
return inter_area / torch.clamp(union_area, min=ALIGNED_FLAG.offset), union_area
else:
return inter_area / torch.clamp(union_area, min=ALIGNED_FLAG.offset)
@allow_empty_tensor(2)
def generalized_box_iou(boxes1, boxes2, return_iou=False):
"""
Generalized IoU from https://giou.stanford.edu/
The boxes should be in [x0, y0, x1, y1] format
Returns a [N, M] pairwise matrix, where N = len(boxes1)
and M = len(boxes2)
"""
# degenerate boxes gives inf / nan results
# so do an early check
assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
iou, union = bbox_iou_overlaps(boxes1, boxes2, return_union=True) # box_iou(boxes1, boxes2)
lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
wh = (rb - lt).clamp(min=0) # [N,M,2]
area = wh[:, :, 0] * wh[:, :, 1]
if return_iou:
return iou - (area - union) / area, iou
else:
return iou - (area - union) / area
@allow_empty_tensor(2)
def bbox_iof_overlaps(b1, b2):
if not b1.is_cuda:
return vanilla_bbox_iof_overlaps(b1, b2)
global GPU_MEMORY
gbytes = 1024.0**3
if GPU_MEMORY is None:
GPU_MEMORY = torch.cuda.get_device_properties(b1.device.index).total_memory
alloated_memory = torch.cuda.memory_allocated()
spare_memory = 0.5 * gbytes
available_memory = GPU_MEMORY - alloated_memory - spare_memory
size = b1.shape[0] * b2.shape[0]
needed_memory = 2 * size * 4
if needed_memory < available_memory:
ious = gpu_iou_overlap(b1, b2, mode='IoF')
else:
ious = vanilla_bbox_iof_overlaps(b1.cpu(), b2.cpu())
res_memory = size * 4
if res_memory < available_memory:
ious = ious.to(b1.device)
return ious
@allow_empty_tensor(2)
def vanilla_bbox_iof_overlaps(b1, b2):
"""
Arguments:
b1: dts, [n, >=4] (x1, y1, x2, y2, ...)
b1: gts, [n, >=4] (x1, y1, x2, y2, ...)
Returns:
intersection-over-former-box pair-wise
"""
area1 = (b1[:, 2] - b1[:, 0] + ALIGNED_FLAG.offset) * (b1[:, 3] - b1[:, 1] + ALIGNED_FLAG.offset)
lt = torch.max(b1[:, None, :2], b2[:, :2])
rb = torch.min(b1[:, None, 2:4], b2[:, 2:4])
wh = (rb - lt + ALIGNED_FLAG.offset).clamp(min=0)
inter_area = wh[:, :, 0] * wh[:, :, 1]
return inter_area / torch.clamp(area1[:, None], min=ALIGNED_FLAG.offset)
@allow_empty_tensor(1)
def xywh2xyxy(boxes, stacked=False):
"""(x, y, w, h) -> (x1, y1, x2, y2)"""
cx, cy, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
xmin = cx - 0.5 * w
ymin = cy - 0.5 * h
xmax = cx + 0.5 * w - ALIGNED_FLAG.offset
ymax = cy + 0.5 * h - ALIGNED_FLAG.offset
if stacked:
return torch.stack([xmin, ymin, xmax, ymax], dim=1)
else:
return xmin, ymin, xmax, ymax
@allow_empty_tensor(1)
def xyxy2xywh(boxes, stacked=False):
"""(x1, y1, x2, y2) -> (x, y, w, h)"""
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
w = x2 - x1 + ALIGNED_FLAG.offset
h = y2 - y1 + ALIGNED_FLAG.offset
cx = x1 + 0.5 * w
cy = y1 + 0.5 * h
if stacked:
return torch.stack([cx, cy, w, h], dim=1)
else:
return cx, cy, w, h
@allow_empty_tensor(2)
def bbox2offset(boxes, gt_boxes, weights=(1.0, 1.0, 1.0, 1.0)):
"""
Inverse transform that computes target bounding-box regression deltas
given proposal boxes and ground-truth boxes. The weights argument should be
a 4-tuple of multiplicative weights that are applied to the regression
target.
In older versions of this code (and in py-faster-rcnn), the weights were set
such that the regression deltas would have unit standard deviation on the
training dataset. Presently, rather than computing these statistics exactly,
we use a fixed set of weights (10., 10., 5., 5.) by default. These are
approximately the weights one would get from COCO using the previous unit
stdev heuristic.
"""
assert boxes.shape[0] == gt_boxes.shape[0]
ex_ctr_x, ex_ctr_y, ex_widths, ex_heights = xyxy2xywh(boxes)
gt_ctr_x, gt_ctr_y, gt_widths, gt_heights = xyxy2xywh(gt_boxes)
wx, wy, ww, wh = weights
offset_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths
offset_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights
offset_dw = ww * torch.log(gt_widths / ex_widths)
offset_dh = wh * torch.log(gt_heights / ex_heights)
offset = torch.stack((offset_dx, offset_dy, offset_dw, offset_dh), dim=1)
return offset
@allow_empty_tensor(2)
def offset2bbox(boxes, offset, weights=(1.0, 1.0, 1.0, 1.0), max_shape=None, means=[0, 0, 0, 0], stds=[1, 1, 1, 1]):
"""
Forward transform that maps proposal boxes to predicted ground-truth
boxes using bounding-box regression deltas(offset). See bbox_transform_inv
for a description of the weights argument.
"""
ctr_x, ctr_y, widths, heights = xyxy2xywh(boxes)
means = offset.new_tensor(means).view(1, -1).repeat(1, offset.size(-1) // 4)
stds = offset.new_tensor(stds).view(1, -1).repeat(1, offset.size(-1) // 4)
offset = offset * stds + means
wx, wy, ww, wh = weights
dx = offset[:, 0::4] / wx
dy = offset[:, 1::4] / wy
dw = offset[:, 2::4] / ww
dh = offset[:, 3::4] / wh
# Prevent sending too large values into np.exp()
dw = torch.clamp(dw, max=np.log(1000. / 16.))
dh = torch.clamp(dh, max=np.log(1000. / 16.))
pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]
pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]
pred_w = torch.exp(dw) * widths[:, None]
pred_h = torch.exp(dh) * heights[:, None]
pred_boxes = offset.new_zeros(offset.shape)
# x1
pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w
# y1
pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h
pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - ALIGNED_FLAG.offset
pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - ALIGNED_FLAG.offset
if max_shape is not None:
max_shape_p = [max_shape[0], max_shape[1]]
if not isinstance(max_shape_p, torch.Tensor):
max_shape_p = pred_boxes.new_tensor(max_shape_p)
max_shape_p = max_shape_p[:2].type_as(pred_boxes)
min_xy = pred_boxes.new_tensor(0)
max_xy = torch.cat([max_shape_p] * (offset.size(-1) // 2), dim=-1).flip(-1).unsqueeze(0)
pred_boxes = torch.where(pred_boxes < min_xy, min_xy, pred_boxes)
pred_boxes = torch.where(pred_boxes > max_xy, max_xy, pred_boxes)
return pred_boxes
@allow_empty_tensor(2)
def bbox2xyxyoffset(boxes, gt_boxes, weights=(1.0, 1.0, 1.0, 1.0)):
"""
Using (dx1, dy1, dx2, dy2) corner offsets here!
Inverse transform that computes target bounding-box regression deltas
given proposal boxes and ground-truth boxes. The weights argument should be
a 4-tuple of multiplicative weights that are applied to the regression
target.
"""
assert boxes.shape[0] == gt_boxes.shape[0]
ex_ctr_x, ex_ctr_y, ex_widths, ex_heights = xyxy2xywh(boxes)
gt_x1, gt_y1, gt_x2, gt_y2 = gt_boxes[:, 0], gt_boxes[:, 1], gt_boxes[:, 2], gt_boxes[:, 3]
ex_x1, ex_y1, ex_x2, ex_y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
wx1, wy1, wx2, wy2 = weights
offset_dx1 = wx1 * (gt_x1 - ex_x1) / ex_widths
offset_dy1 = wy1 * (gt_y1 - ex_y1) / ex_heights
offset_dx2 = wx2 * (gt_x2 - ex_x2) / ex_widths
offset_dy2 = wy2 * (gt_y2 - ex_y2) / ex_heights
offset = torch.stack((offset_dx1, offset_dy1, offset_dx2, offset_dy2), dim=1)
return offset
@allow_empty_tensor(2)
def xyxyoffset2bbox(boxes, offset, weights=(1.0, 1.0, 1.0, 1.0)):
"""
Using (dx1, dy1, dx2, dy2) corner offsets here!
Forward transform that maps proposal boxes to predicted ground-truth
boxes using `xyxy` bounding-box regression deltas(offset).
"""
_, _, widths, heights = xyxy2xywh(boxes)
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
wx1, wy1, wx2, wy2 = weights
dx1 = offset[:, 0::4] / wx1
dy1 = offset[:, 1::4] / wy1
dx2 = offset[:, 2::4] / wx2
dy2 = offset[:, 3::4] / wy2
pred_x1 = dx1 * widths[:, None] + x1[:, None]
pred_y1 = dy1 * heights[:, None] + y1[:, None]
pred_x2 = dx2 * widths[:, None] + x2[:, None]
pred_y2 = dy2 * heights[:, None] + y2[:, None]
pred_boxes = offset.new_zeros(offset.shape)
# x1
pred_boxes[:, 0::4] = pred_x1
# y1
pred_boxes[:, 1::4] = pred_y1
# x2
pred_boxes[:, 2::4] = pred_x2
# y2
pred_boxes[:, 3::4] = pred_y2
return pred_boxes
@allow_empty_tensor(2)
def offset2tiled_bbox(boxes, offset, weights=(1.0, 1.0, 1.0, 1.0)):
"""
Forward transform that maps proposal boxes to predicted ground-truth
boxes using bounding-box regression deltas(offset). See bbox_transform_inv
for a description of the weights argument.
"""
if boxes.shape[0] == 0:
return boxes.new_zeros((1, offset.shape[1]))
widths = boxes[:, 2] - boxes[:, 0] + ALIGNED_FLAG.offset
heights = boxes[:, 3] - boxes[:, 1] + ALIGNED_FLAG.offset
ctr_x = boxes[:, 0] + 0.5 * widths
ctr_y = boxes[:, 1] + 0.5 * heights
wx, wy, ww, wh = weights
dx = offset[:, 0::4] / wx
dy = offset[:, 1::4] / wy
dw = offset[:, 2::4] / ww
dh = offset[:, 3::4] / wh
# Prevent sending too large values into np.exp()
dw = torch.clamp(dw, max=np.log(1000. / 16.))
dh = torch.clamp(dh, max=np.log(1000. / 16.))
pred_ctr_x = dx * widths[:, None] + ctr_x[:, None]
pred_ctr_y = dy * heights[:, None] + ctr_y[:, None]
pred_w = torch.exp(dw) * widths[:, None]
pred_h = torch.exp(dh) * heights[:, None]
pred_boxes = offset.new_zeros(offset.shape)
# x1
pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w
# y1
pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h
# x2
pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w - ALIGNED_FLAG.offset
# y2
pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h - ALIGNED_FLAG.offset
return pred_boxes
@allow_empty_tensor(1)
def normalize_offset(offset, mean, std):
mean = offset.new_tensor(mean).reshape(-1, 4)
std = offset.new_tensor(std).reshape(-1, 4)
return (offset - mean) / std
@allow_empty_tensor(1)
def unnormalize_offset(offset, mean, std):
mean = offset.new_tensor(mean).reshape(-1, 4)
std = offset.new_tensor(std).reshape(-1, 4)
return offset * std + mean
@allow_empty_tensor(1)
def clip_bbox(bbox, img_size):
h, w = img_size[:2]
dh, dw = 0, 0
if len(img_size) > 6:
dw, dh = img_size[6], img_size[7]
bbox[:, 0] = torch.clamp(bbox[:, 0], min=0, max=w - ALIGNED_FLAG.offset + dw)
bbox[:, 1] = torch.clamp(bbox[:, 1], min=0, max=h - ALIGNED_FLAG.offset + dh)
bbox[:, 2] = torch.clamp(bbox[:, 2], min=0, max=w - ALIGNED_FLAG.offset + dw)
bbox[:, 3] = torch.clamp(bbox[:, 3], min=0, max=h - ALIGNED_FLAG.offset + dh)
return bbox
@allow_empty_tensor(1)
def clip_tiled_boxes(bbox, img_size):
assert bbox.shape[1] % 4 == 0, \
'bbox.shape[1] is {}, but must be divisible by 4'.format(bbox.shape[1])
h, w = img_size[:2]
bbox[:, 0::4] = torch.clamp(bbox[:, 0::4], min=0, max=w - ALIGNED_FLAG.offset)
bbox[:, 1::4] = torch.clamp(bbox[:, 1::4], min=0, max=h - ALIGNED_FLAG.offset)
bbox[:, 2::4] = torch.clamp(bbox[:, 2::4], min=0, max=w - ALIGNED_FLAG.offset)
bbox[:, 3::4] = torch.clamp(bbox[:, 3::4], min=0, max=h - ALIGNED_FLAG.offset)
return bbox
@allow_empty_tensor(1)
def flip_tiled_bboxes(boxes, width):
boxes_flipped = boxes.clone()
boxes_flipped[:, 0::4] = width - boxes[:, 2::4] - ALIGNED_FLAG.offset
boxes_flipped[:, 2::4] = width - boxes[:, 0::4] - ALIGNED_FLAG.offset
return boxes_flipped
def test_bbox_iou_overlaps():
b1 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])
b2 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200, 200]])
overlaps = bbox_iou_overlaps(b1, b2)
print(overlaps)
def test_bbox_iof_overlaps():
b1 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])
b2 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200, 200]])
overlaps = bbox_iof_overlaps(b1, b2)
print(overlaps)
def test_xyxy_xywh():
b1 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])
b2 = xyxy2xywh(b1)
b2 = torch.stack(b2, dim=1)
b3 = xywh2xyxy(b2)
b3 = torch.stack(b3, dim=1)
print(b1)
print(b2)
print(b3)
def test_offset():
b1 = torch.FloatTensor([[0, 0, 4, 4], [1, 2, 3, 5], [4, 4, 5, 5]])
tg = torch.FloatTensor([[1, 1, 5, 5], [0, 2, 4, 5], [4, 4, 5, 5]])
offset = bbox2offset(b1, tg)
print(offset)
pred = offset2bbox(b1, offset)
print(pred)
def test_clip_bbox():
b1 = torch.FloatTensor([[0, 0, 9, 29], [1, 2, 19, 39], [4, 4, 59, 59]])
print(b1)
b2 = clip_bbox(b1, (30, 35))
print(b2)
def test_iou(iou_fn, a, b):
n = 5
s = time.time()
for i in range(n):
iou = iou_fn(a, b)
del iou
torch.cuda.synchronize()
e = time.time()
t = e - s
memory = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0 / 1024
return t, memory
def rand_bbox(n):
box = torch.randn(n, 4).cuda() * 10
x1 = torch.min(box[:, 0], box[:, 2])
x2 = torch.max(box[:, 0], box[:, 2])
y1 = torch.min(box[:, 1], box[:, 3])
y2 = torch.max(box[:, 1], box[:, 3])
return torch.stack([x1, y1, x2, y2], dim=1)
def box_voting(top_dets, all_dets, thresh, scoring_method='id', beta=1.0):
"""Apply bounding-box voting to refine `top_dets` by voting with `all_dets`.
See: https://arxiv.org/abs/1505.01749. Optional score averaging (not in the
referenced paper) can be applied by setting `scoring_method` appropriately.
"""
# top_dets is [N, 5] each row is [x1 y1 x2 y2, sore]
# all_dets is [N, 5] each row is [x1 y1 x2 y2, sore]
top_dets_out = top_dets.cpu().numpy().copy()
top_boxes = top_dets[:, :4]
all_boxes = all_dets[:, :4]
all_scores = all_dets[:, 4]
top_to_all_overlaps = bbox_iou_overlaps(top_boxes, all_boxes)
top_to_all_overlaps = top_to_all_overlaps.cpu().numpy()
all_boxes = all_boxes.cpu().numpy()
all_scores = all_scores.cpu().numpy()
for k in range(top_dets_out.shape[0]):
inds_to_vote = np.where(top_to_all_overlaps[k] >= thresh)[0]
boxes_to_vote = all_boxes[inds_to_vote, :]
ws = all_scores[inds_to_vote]
top_dets_out[k, :4] = np.average(boxes_to_vote, axis=0, weights=ws)
if scoring_method == 'id':
# Identity, nothing to do
pass
elif scoring_method == 'temp_avg':
# Average probabilities (considered as P(detected class) vs.
# P(not the detected class)) after smoothing with a temperature
# hyperparameter.
P = np.vstack((ws, 1.0 - ws))
P_max = np.max(P, axis=0)
X = np.log(P / P_max)
X_exp = np.exp(X / beta)
P_temp = X_exp / np.sum(X_exp, axis=0)
P_avg = P_temp[0].mean()
top_dets_out[k, 4] = P_avg
elif scoring_method == 'avg':
# Combine new probs from overlapping boxes
top_dets_out[k, 4] = ws.mean()
elif scoring_method == 'iou_avg':
P = ws
ws = top_to_all_overlaps[k, inds_to_vote]
P_avg = np.average(P, weights=ws)
top_dets_out[k, 4] = P_avg
elif scoring_method == 'generalized_avg':
P_avg = np.mean(ws**beta)**(1.0 / beta)
top_dets_out[k, 4] = P_avg
elif scoring_method == 'quasi_sum':
top_dets_out[k, 4] = ws.sum() / float(len(ws))**beta
else:
raise NotImplementedError('Unknown scoring method {}'.format(scoring_method))
top_dets_out = torch.from_numpy(top_dets_out).to(top_dets)
return top_dets_out
# if __name__ == '__main__':
# test_bbox_iou_overlaps()
# test_bbox_iof_overlaps()
# test_xyxy_xywh()
# test_offset()
# test_clip_bbox()
# test_box_voting()
| [
"torch.cuda.synchronize",
"numpy.sum",
"torch.cuda.max_memory_allocated",
"torch.randn",
"numpy.mean",
"numpy.exp",
"torch.FloatTensor",
"torch.exp",
"numpy.max",
"torch.is_tensor",
"torch.log",
"torch.cuda.memory_allocated",
"numpy.average",
"torch.where",
"up.extensions.gpu_iou_overlap... | [((1397, 1426), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', ([], {}), '()\n', (1424, 1426), False, 'import torch\n'), ((2893, 2930), 'torch.max', 'torch.max', (['b1[:, None, :2]', 'b2[:, :2]'], {}), '(b1[:, None, :2], b2[:, :2])\n', (2902, 2930), False, 'import torch\n'), ((2940, 2979), 'torch.min', 'torch.min', (['b1[:, None, 2:4]', 'b2[:, 2:4]'], {}), '(b1[:, None, 2:4], b2[:, 2:4])\n', (2949, 2979), False, 'import torch\n'), ((3896, 3941), 'torch.min', 'torch.min', (['boxes1[:, None, :2]', 'boxes2[:, :2]'], {}), '(boxes1[:, None, :2], boxes2[:, :2])\n', (3905, 3941), False, 'import torch\n'), ((3951, 3996), 'torch.max', 'torch.max', (['boxes1[:, None, 2:]', 'boxes2[:, 2:]'], {}), '(boxes1[:, None, 2:], boxes2[:, 2:])\n', (3960, 3996), False, 'import torch\n'), ((4503, 4532), 'torch.cuda.memory_allocated', 'torch.cuda.memory_allocated', ([], {}), '()\n', (4530, 4532), False, 'import torch\n'), ((5355, 5392), 'torch.max', 'torch.max', (['b1[:, None, :2]', 'b2[:, :2]'], {}), '(b1[:, None, :2], b2[:, :2])\n', (5364, 5392), False, 'import torch\n'), ((5402, 5441), 'torch.min', 'torch.min', (['b1[:, None, 2:4]', 'b2[:, 2:4]'], {}), '(b1[:, None, 2:4], b2[:, 2:4])\n', (5411, 5441), False, 'import torch\n'), ((7661, 7725), 'torch.stack', 'torch.stack', (['(offset_dx, offset_dy, offset_dw, offset_dh)'], {'dim': '(1)'}), '((offset_dx, offset_dy, offset_dw, offset_dh), dim=1)\n', (7672, 7725), False, 'import torch\n'), ((10688, 10756), 'torch.stack', 'torch.stack', (['(offset_dx1, offset_dy1, offset_dx2, offset_dy2)'], {'dim': '(1)'}), '((offset_dx1, offset_dy1, offset_dx2, offset_dy2), dim=1)\n', (10699, 10756), False, 'import torch\n'), ((13832, 13896), 'torch.clamp', 'torch.clamp', (['bbox[:, 0]'], {'min': '(0)', 'max': '(w - ALIGNED_FLAG.offset + dw)'}), '(bbox[:, 0], min=0, max=w - ALIGNED_FLAG.offset + dw)\n', (13843, 13896), False, 'import torch\n'), ((13914, 13978), 'torch.clamp', 'torch.clamp', (['bbox[:, 1]'], {'min': '(0)', 'max': '(h - ALIGNED_FLAG.offset + dh)'}), '(bbox[:, 1], min=0, max=h - ALIGNED_FLAG.offset + dh)\n', (13925, 13978), False, 'import torch\n'), ((13996, 14060), 'torch.clamp', 'torch.clamp', (['bbox[:, 2]'], {'min': '(0)', 'max': '(w - ALIGNED_FLAG.offset + dw)'}), '(bbox[:, 2], min=0, max=w - ALIGNED_FLAG.offset + dw)\n', (14007, 14060), False, 'import torch\n'), ((14078, 14142), 'torch.clamp', 'torch.clamp', (['bbox[:, 3]'], {'min': '(0)', 'max': '(h - ALIGNED_FLAG.offset + dh)'}), '(bbox[:, 3], min=0, max=h - ALIGNED_FLAG.offset + dh)\n', (14089, 14142), False, 'import torch\n'), ((14383, 14445), 'torch.clamp', 'torch.clamp', (['bbox[:, 0::4]'], {'min': '(0)', 'max': '(w - ALIGNED_FLAG.offset)'}), '(bbox[:, 0::4], min=0, max=w - ALIGNED_FLAG.offset)\n', (14394, 14445), False, 'import torch\n'), ((14466, 14528), 'torch.clamp', 'torch.clamp', (['bbox[:, 1::4]'], {'min': '(0)', 'max': '(h - ALIGNED_FLAG.offset)'}), '(bbox[:, 1::4], min=0, max=h - ALIGNED_FLAG.offset)\n', (14477, 14528), False, 'import torch\n'), ((14549, 14611), 'torch.clamp', 'torch.clamp', (['bbox[:, 2::4]'], {'min': '(0)', 'max': '(w - ALIGNED_FLAG.offset)'}), '(bbox[:, 2::4], min=0, max=w - ALIGNED_FLAG.offset)\n', (14560, 14611), False, 'import torch\n'), ((14632, 14694), 'torch.clamp', 'torch.clamp', (['bbox[:, 3::4]'], {'min': '(0)', 'max': '(h - ALIGNED_FLAG.offset)'}), '(bbox[:, 3::4], min=0, max=h - ALIGNED_FLAG.offset)\n', (14643, 14694), False, 'import torch\n'), ((15021, 15082), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])\n', (15038, 15082), False, 'import torch\n'), ((15092, 15179), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200, 200]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200,\n 200]])\n', (15109, 15179), False, 'import torch\n'), ((15278, 15339), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])\n', (15295, 15339), False, 'import torch\n'), ((15349, 15436), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200, 200]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5], [100, 100, 200,\n 200]])\n', (15366, 15436), False, 'import torch\n'), ((15527, 15588), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [5, 5, 5, 5]])\n', (15544, 15588), False, 'import torch\n'), ((15621, 15643), 'torch.stack', 'torch.stack', (['b2'], {'dim': '(1)'}), '(b2, dim=1)\n', (15632, 15643), False, 'import torch\n'), ((15676, 15698), 'torch.stack', 'torch.stack', (['b3'], {'dim': '(1)'}), '(b3, dim=1)\n', (15687, 15698), False, 'import torch\n'), ((15771, 15832), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 4, 4], [1, 2, 3, 5], [4, 4, 5, 5]]'], {}), '([[0, 0, 4, 4], [1, 2, 3, 5], [4, 4, 5, 5]])\n', (15788, 15832), False, 'import torch\n'), ((15842, 15903), 'torch.FloatTensor', 'torch.FloatTensor', (['[[1, 1, 5, 5], [0, 2, 4, 5], [4, 4, 5, 5]]'], {}), '([[1, 1, 5, 5], [0, 2, 4, 5], [4, 4, 5, 5]])\n', (15859, 15903), False, 'import torch\n'), ((16039, 16105), 'torch.FloatTensor', 'torch.FloatTensor', (['[[0, 0, 9, 29], [1, 2, 19, 39], [4, 4, 59, 59]]'], {}), '([[0, 0, 9, 29], [1, 2, 19, 39], [4, 4, 59, 59]])\n', (16056, 16105), False, 'import torch\n'), ((16215, 16226), 'time.time', 'time.time', ([], {}), '()\n', (16224, 16226), False, 'import time\n'), ((16293, 16317), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (16315, 16317), False, 'import torch\n'), ((16326, 16337), 'time.time', 'time.time', ([], {}), '()\n', (16335, 16337), False, 'import time\n'), ((16514, 16545), 'torch.min', 'torch.min', (['box[:, 0]', 'box[:, 2]'], {}), '(box[:, 0], box[:, 2])\n', (16523, 16545), False, 'import torch\n'), ((16555, 16586), 'torch.max', 'torch.max', (['box[:, 0]', 'box[:, 2]'], {}), '(box[:, 0], box[:, 2])\n', (16564, 16586), False, 'import torch\n'), ((16596, 16627), 'torch.min', 'torch.min', (['box[:, 1]', 'box[:, 3]'], {}), '(box[:, 1], box[:, 3])\n', (16605, 16627), False, 'import torch\n'), ((16637, 16668), 'torch.max', 'torch.max', (['box[:, 1]', 'box[:, 3]'], {}), '(box[:, 1], box[:, 3])\n', (16646, 16668), False, 'import torch\n'), ((16680, 16716), 'torch.stack', 'torch.stack', (['[x1, y1, x2, y2]'], {'dim': '(1)'}), '([x1, y1, x2, y2], dim=1)\n', (16691, 16716), False, 'import torch\n'), ((1653, 1688), 'up.extensions.gpu_iou_overlap', 'gpu_iou_overlap', (['b1', 'b2'], {'mode': '"""IoU"""'}), "(b1, b2, mode='IoU')\n", (1668, 1688), False, 'from up.extensions import gpu_iou_overlap\n'), ((2542, 2573), 'torch.max', 'torch.max', (['b1[:, :2]', 'b2[:, :2]'], {}), '(b1[:, :2], b2[:, :2])\n', (2551, 2573), False, 'import torch\n'), ((2600, 2631), 'torch.min', 'torch.min', (['b1[:, 2:]', 'b2[:, 2:]'], {}), '(b1[:, 2:], b2[:, 2:])\n', (2609, 2631), False, 'import torch\n'), ((4759, 4794), 'up.extensions.gpu_iou_overlap', 'gpu_iou_overlap', (['b1', 'b2'], {'mode': '"""IoF"""'}), "(b1, b2, mode='IoF')\n", (4774, 4794), False, 'from up.extensions import gpu_iou_overlap\n'), ((5563, 5615), 'torch.clamp', 'torch.clamp', (['area1[:, None]'], {'min': 'ALIGNED_FLAG.offset'}), '(area1[:, None], min=ALIGNED_FLAG.offset)\n', (5574, 5615), False, 'import torch\n'), ((5962, 6006), 'torch.stack', 'torch.stack', (['[xmin, ymin, xmax, ymax]'], {'dim': '(1)'}), '([xmin, ymin, xmax, ymax], dim=1)\n', (5973, 6006), False, 'import torch\n'), ((6383, 6417), 'torch.stack', 'torch.stack', (['[cx, cy, w, h]'], {'dim': '(1)'}), '([cx, cy, w, h], dim=1)\n', (6394, 6417), False, 'import torch\n'), ((7559, 7591), 'torch.log', 'torch.log', (['(gt_widths / ex_widths)'], {}), '(gt_widths / ex_widths)\n', (7568, 7591), False, 'import torch\n'), ((7613, 7647), 'torch.log', 'torch.log', (['(gt_heights / ex_heights)'], {}), '(gt_heights / ex_heights)\n', (7622, 7647), False, 'import torch\n'), ((8778, 8791), 'torch.exp', 'torch.exp', (['dw'], {}), '(dw)\n', (8787, 8791), False, 'import torch\n'), ((8823, 8836), 'torch.exp', 'torch.exp', (['dh'], {}), '(dh)\n', (8832, 8836), False, 'import torch\n'), ((9591, 9643), 'torch.where', 'torch.where', (['(pred_boxes < min_xy)', 'min_xy', 'pred_boxes'], {}), '(pred_boxes < min_xy, min_xy, pred_boxes)\n', (9602, 9643), False, 'import torch\n'), ((9665, 9717), 'torch.where', 'torch.where', (['(pred_boxes > max_xy)', 'max_xy', 'pred_boxes'], {}), '(pred_boxes > max_xy, max_xy, pred_boxes)\n', (9676, 9717), False, 'import torch\n'), ((12817, 12830), 'torch.exp', 'torch.exp', (['dw'], {}), '(dw)\n', (12826, 12830), False, 'import torch\n'), ((12862, 12875), 'torch.exp', 'torch.exp', (['dh'], {}), '(dh)\n', (12871, 12875), False, 'import torch\n'), ((17742, 17787), 'numpy.average', 'np.average', (['boxes_to_vote'], {'axis': '(0)', 'weights': 'ws'}), '(boxes_to_vote, axis=0, weights=ws)\n', (17752, 17787), True, 'import numpy as np\n'), ((1312, 1361), 'torch.cuda.get_device_properties', 'torch.cuda.get_device_properties', (['b1.device.index'], {}), '(b1.device.index)\n', (1344, 1361), False, 'import torch\n'), ((3278, 3326), 'torch.clamp', 'torch.clamp', (['union_area'], {'min': 'ALIGNED_FLAG.offset'}), '(union_area, min=ALIGNED_FLAG.offset)\n', (3289, 3326), False, 'import torch\n'), ((4418, 4467), 'torch.cuda.get_device_properties', 'torch.cuda.get_device_properties', (['b1.device.index'], {}), '(b1.device.index)\n', (4450, 4467), False, 'import torch\n'), ((8582, 8603), 'numpy.log', 'np.log', (['(1000.0 / 16.0)'], {}), '(1000.0 / 16.0)\n', (8588, 8603), True, 'import numpy as np\n'), ((8632, 8653), 'numpy.log', 'np.log', (['(1000.0 / 16.0)'], {}), '(1000.0 / 16.0)\n', (8638, 8653), True, 'import numpy as np\n'), ((12621, 12642), 'numpy.log', 'np.log', (['(1000.0 / 16.0)'], {}), '(1000.0 / 16.0)\n', (12627, 12642), True, 'import numpy as np\n'), ((12671, 12692), 'numpy.log', 'np.log', (['(1000.0 / 16.0)'], {}), '(1000.0 / 16.0)\n', (12677, 12692), True, 'import numpy as np\n'), ((17577, 17619), 'numpy.where', 'np.where', (['(top_to_all_overlaps[k] >= thresh)'], {}), '(top_to_all_overlaps[k] >= thresh)\n', (17585, 17619), True, 'import numpy as np\n'), ((19087, 19117), 'torch.from_numpy', 'torch.from_numpy', (['top_dets_out'], {}), '(top_dets_out)\n', (19103, 19117), False, 'import torch\n'), ((3179, 3227), 'torch.clamp', 'torch.clamp', (['union_area'], {'min': 'ALIGNED_FLAG.offset'}), '(union_area, min=ALIGNED_FLAG.offset)\n', (3190, 3227), False, 'import torch\n'), ((16365, 16398), 'torch.cuda.max_memory_allocated', 'torch.cuda.max_memory_allocated', ([], {}), '()\n', (16396, 16398), False, 'import torch\n'), ((16475, 16492), 'torch.randn', 'torch.randn', (['n', '(4)'], {}), '(n, 4)\n', (16486, 16492), False, 'import torch\n'), ((18116, 18141), 'numpy.vstack', 'np.vstack', (['(ws, 1.0 - ws)'], {}), '((ws, 1.0 - ws))\n', (18125, 18141), True, 'import numpy as np\n'), ((18162, 18179), 'numpy.max', 'np.max', (['P'], {'axis': '(0)'}), '(P, axis=0)\n', (18168, 18179), True, 'import numpy as np\n'), ((18196, 18213), 'numpy.log', 'np.log', (['(P / P_max)'], {}), '(P / P_max)\n', (18202, 18213), True, 'import numpy as np\n'), ((18234, 18250), 'numpy.exp', 'np.exp', (['(X / beta)'], {}), '(X / beta)\n', (18240, 18250), True, 'import numpy as np\n'), ((512, 532), 'torch.is_tensor', 'torch.is_tensor', (['arg'], {}), '(arg)\n', (527, 532), False, 'import torch\n'), ((18280, 18301), 'numpy.sum', 'np.sum', (['X_exp'], {'axis': '(0)'}), '(X_exp, axis=0)\n', (18286, 18301), True, 'import numpy as np\n'), ((18649, 18674), 'numpy.average', 'np.average', (['P'], {'weights': 'ws'}), '(P, weights=ws)\n', (18659, 18674), True, 'import numpy as np\n'), ((18784, 18803), 'numpy.mean', 'np.mean', (['(ws ** beta)'], {}), '(ws ** beta)\n', (18791, 18803), True, 'import numpy as np\n')] |
import numpy
class ClippingFilter(object):
"""Clips a value to given limits
"""
def __init__(self, min_value, max_value, u_init=None):
"""Constructor
Arguments:
min_value: the minimum value permitted for the output
max_value: the maximum value permitted for the output
u_init: optional, initial value, must lie in [min_value, max_value]
if not specified will be set to mean(min_value, max_value)
Returns:
class instance
"""
if u_init is not None:
assert u_init >= min_value and u_init <= max_value,\
'u_init must lie in [min_value, max_value]'
self._u = u_init
else:
self._u = (min_value + max_value) / 2.0
self._min_value = min_value
self._max_value = max_value
def filter_value(self, value):
"""Filter a new realization of u and return the filtered value
Arguments:
value: a new value for u which should be filtered
Returns:
u_filt: filtered value
"""
self._u = numpy.clip(value, self._min_value, self._max_value)
return self._u
@property
def u(self):
"""Getter for current value of the filter
Returns:
u: current filter value
"""
return self._u
class RateLimiter(object):
"""A simple rate limiter
"""
def __init__(self, max_slew, dt=1.0):
"""Constructor
Arguments:
max_slew: the maximimum allowable slew rate of the signal
dt: the timestep size of this filter. Optional, defaults to 1. A
timestep can also be specified at the filter time
Returns:
class instance
"""
self._x = None
self._t_1 = None
self._dt = dt
self._max_slew = max_slew
def filter_value(self, new_value, t=None):
"""Filter a value
Arguments:
new_value: new candidate value to rate limit
t: optional, the epoch this value occurs at. The timestep size
will be computed with this and the last time specified. If not
specified then the timestep specified at construction will be
used (which defaults to 1.0)
Returns:
filter_output: the rate limited output
"""
if self._x is None:
self._x = new_value
return self._x
if t is not None and self._t_1 is None:
self._t_1 = t
return self._x
if t is not None:
dt = t - self._t_1
self._t_1 = t
else:
dt = self._dt
slew_rate = (new_value - self._x) / dt
if numpy.abs(slew_rate) > self._max_slew:
self._x += self._max_slew * numpy.sign(slew_rate) * dt
else:
self._x = new_value
return self._x
| [
"numpy.abs",
"numpy.clip",
"numpy.sign"
] | [((1130, 1181), 'numpy.clip', 'numpy.clip', (['value', 'self._min_value', 'self._max_value'], {}), '(value, self._min_value, self._max_value)\n', (1140, 1181), False, 'import numpy\n'), ((2782, 2802), 'numpy.abs', 'numpy.abs', (['slew_rate'], {}), '(slew_rate)\n', (2791, 2802), False, 'import numpy\n'), ((2861, 2882), 'numpy.sign', 'numpy.sign', (['slew_rate'], {}), '(slew_rate)\n', (2871, 2882), False, 'import numpy\n')] |
#https://github.com/marload/DeepRL-TensorFlow2
import tensorflow as tf
import tensorflow.keras.layers as kl
import logging
tf.get_logger().setLevel(logging.ERROR)
import datetime
import gym
import argparse
import numpy as np
from collections import deque
import random
from gym import wrappers
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from visdom import Visdom
def argument_parse():
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default="CartPole-v0")
parser.add_argument('--gamma', type=float, default=0.99)
parser.add_argument('--learning_rate', type=float, default=0.005)
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--epsilon_init', type=float, default=1.0)
parser.add_argument('--epsilon_min', type=float, default=0.01)
parser.add_argument('--replay_memory_capacity', type=int, default=10000)
parser.add_argument('--epsilon_decay_end_step', type=int, default=15000)
parser.add_argument('--max_steps', type=int, default=30000)
parser.add_argument('--target_net_update_freq', type=int, default=1000)
parser.add_argument('--average_length_episode_rewards', type=int, default=10)
parser.add_argument('--train_end_for_average_episode_rewards', type=int, default=150)
parser.add_argument('--draw_graph_freq', type=int, default=100)
parser.add_argument('--verbose', type=bool, default=False)
parser.add_argument('--train_render', type=bool, default=False)
args = parser.parse_args()
return args
def print_args(args):
print("##############################################")
for k, v in vars(args).items():
print(k + ': ' + str(v))
print("##############################################")
print()
# pip install visdom
# python -m visdom.server
# open web page --> http://localhost:8097
vis = Visdom()
episode_reward_plt = None
avg_episode_reward_plt = None
episode_loss_plt = None
epsilon_plt = None
def vis_plt(method, args):
global episode_reward_plt
global avg_episode_reward_plt
global episode_loss_plt
global epsilon_plt
layout_opts_dict = {
'plotly': {
'xaxis': {
'range': [0, args.max_steps],
}
}
}
episode_reward_plt = vis.line(
X=[0], Y=[0],
opts={
'title': '[{0}] Episode Reward'.format(method),
'showlegend': False,
'layoutopts': layout_opts_dict
}
)
avg_episode_reward_plt = vis.line(
X=[0], Y=[0],
opts={
'title': '[{0}] Avg. Episode Reward'.format(method),
'showlegend': False,
'layoutopts': layout_opts_dict
}
)
episode_loss_plt = vis.line(
X=[0], Y=[0],
opts={
'title': '[{0}] Episode Loss'.format(method),
'showlegend': False,
'layoutopts': layout_opts_dict
}
)
epsilon_plt = vis.line(
X=[0], Y=[0],
opts={
'title': '[{0}] Epsilon'.format(method),
'showlegend': False,
'layoutopts': layout_opts_dict
}
)
current_time = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
def linear_interpolation(start_step, end_step, current_step, final_p, initial_p):
schedule_timesteps = end_step - start_step
step_offset = current_step - start_step
fraction = min(float(step_offset) / schedule_timesteps, 1)
return min(initial_p + fraction * (final_p - initial_p), initial_p)
class ReplayMemory:
def __init__(self, capacity):
self.__name__ = "Replay Memory"
self.buffer = deque(maxlen=capacity)
def put(self, transition):
self.buffer.append(transition)
def get_random_batch(self, size):
batch = random.sample(self.buffer, size)
states, actions, rewards, next_states, done = map(np.asarray, zip(*batch))
return states, actions, rewards, next_states, done
def size(self):
return len(self.buffer)
class QNetwork(tf.keras.Model):
def __init__(self, state_dim, action_dim):
super(QNetwork, self).__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.input_layer = kl.InputLayer(input_shape=(state_dim,))
self.hidden_layer_1 = kl.Dense(units=32, activation='relu')
self.hidden_layer_2 = kl.Dense(units=16, activation='relu')
self.output_layer = kl.Dense(units=action_dim, activation='linear')
self.num_actions_executed = {}
self.reset_num_actions_executed()
def reset_num_actions_executed(self):
for action in range(self.action_dim):
self.num_actions_executed[action] = 0
def call(self, state, **kwargs):
return self.forward(state)
def forward(self, state):
z = self.input_layer(state)
z = self.hidden_layer_1(z)
z = self.hidden_layer_2(z)
output = self.output_layer(z)
return output
def get_action(self, state, epsilon):
if np.random.random() < epsilon:
action = random.randint(0, self.action_dim - 1)
else:
state = np.reshape(state, [1, self.state_dim])
q_value = self.forward(state)[0]
action = int(np.argmax(q_value))
self.num_actions_executed[action] += 1
return action
class DqnAgent:
def __init__(self, env, args):
self.__name__ = "dqn"
self.env = env
self.state_dim = self.env.observation_space.shape[0]
self.action_dim = self.env.action_space.n
self.args = args
self.optimizer = tf.optimizers.Adam(args.learning_rate)
self.train_q_net = QNetwork(self.state_dim, self.action_dim)
self.target_q_net = QNetwork(self.state_dim, self.action_dim)
self.target_update()
self.buffer = ReplayMemory(args.replay_memory_capacity)
self.episode_reward_list = []
if not os.path.exists(os.path.join(os.getcwd(), 'models')):
os.makedirs(os.path.join(os.getcwd(), 'models'))
def print_q_network_and_replay_memory_type(self):
if type(self.state_dim) is int:
one_input_shape = tuple([1] + [self.state_dim,])
else:
one_input_shape = tuple([1] + list(self.state_dim))
print("one input shape: {0}".format(one_input_shape))
self.train_q_net.build(input_shape=one_input_shape)
self.train_q_net.summary()
print("Buffer: {0}\n".format(self.buffer.__name__))
vis_plt(self.__name__, self.args)
def target_update(self):
train_q_net_variables = self.train_q_net.trainable_variables
target_q_net_variables = self.target_q_net.trainable_variables
for v1, v2 in zip(train_q_net_variables, target_q_net_variables):
v2.assign(v1.numpy())
def q_net_optimize(self):
states, actions, rewards, next_states, dones = self.buffer.get_random_batch(self.args.batch_size)
next_q_values = np.where(dones, 0, np.max(self.target_q_net.forward(next_states), axis=1))
target_q_values = np.where(dones, rewards, rewards + self.args.gamma * next_q_values)
with tf.GradientTape() as tape:
current_q_values = tf.math.reduce_sum(
self.train_q_net.forward(states) * tf.one_hot(actions, self.action_dim), axis=1
)
loss = tf.math.reduce_mean(tf.square(target_q_values - current_q_values))
variables = self.train_q_net.trainable_variables
gradients = tape.gradient(loss, variables)
self.optimizer.apply_gradients(zip(gradients, variables))
return loss.numpy()
def learn(self):
recent_episode_rewards = deque(maxlen=self.args.average_length_episode_rewards)
epsilon = self.args.epsilon_init
total_steps = 0
episode = 0
train_done = False
while not train_done:
episode += 1
# new episode started
state = self.env.reset()
episode_steps = 0
episode_reward = 0
episode_loss = 0.0
done = False
while not done:
total_steps += 1
episode_steps += 1
if self.args.train_render:
self.env.render()
epsilon = linear_interpolation(
start_step=0,
end_step=self.args.epsilon_decay_end_step,
current_step=total_steps,
final_p=self.args.epsilon_min,
initial_p=self.args.epsilon_init
)
action = self.train_q_net.get_action(state, epsilon)
next_state, reward, done, info = self.env.step(action)
if self.args.verbose:
print("State: {0}, Action: {1}, Next State: {2}, Reward: {3}, Done: {4}, Info: {5}".format(
state.shape,
action,
next_state.shape if next_state is not None else "None",
reward,
done,
info
))
transition = [state, action, reward * 0.01, next_state, done]
self.buffer.put(transition)
episode_reward += reward
if self.buffer.size() >= self.args.batch_size:
episode_loss += self.q_net_optimize()
if total_steps % self.args.target_net_update_freq == 0:
self.target_update()
state = next_state
if total_steps >= self.args.max_steps:
train_done = True
break
recent_episode_rewards.append(episode_reward)
avg_episode_reward = np.array(recent_episode_rewards).mean()
self.write_performance(
episode, epsilon, episode_reward, avg_episode_reward, episode_loss, total_steps, episode_steps
)
self.episode_reward_list.append(avg_episode_reward)
self.train_q_net.reset_num_actions_executed()
if avg_episode_reward >= self.args.train_end_for_average_episode_rewards:
train_done = True
if self.args.verbose:
print()
def save_model(self):
self.train_q_net.save_weights(
os.path.join(os.getcwd(), 'models', 'dqn_{0}.tf'.format(self.__name__)), save_format="tf"
)
def load_model(self):
self.train_q_net.load_weights(
os.path.join(os.getcwd(), 'models', 'dqn_{0}.tf'.format(self.__name__))
)
def write_performance(self, episode, epsilon, episode_reward, avg_episode_reward, episode_loss, total_steps, episode_steps):
str_info = "[{0}] Episode: {1}, Eps.: {2:.3f}, Episode reward: {3}, Avg. episode reward (last 10): {4:.3f}, " \
"Episode loss: {5:.5f}, Buffer size: {6}, Total steps: {7} ({8})".format(
self.__name__, episode, epsilon, episode_reward, avg_episode_reward,
episode_loss, self.buffer.size(), total_steps, episode_steps
)
str_info += ", Number of actions: "
for action in self.train_q_net.num_actions_executed:
str_info += "[{0}: {1}] ".format(action, self.train_q_net.num_actions_executed[action])
print(str_info)
if vis:
vis.line(
X=[total_steps], Y=[episode_reward], win=episode_reward_plt, name="Episode Reward", update="append"
)
vis.line(
X=[total_steps], Y=[avg_episode_reward], win=avg_episode_reward_plt, name="Average Episode Reward", update="append"
)
vis.line(
X=[total_steps], Y=[episode_loss], win=episode_loss_plt, name="Episode Loss", update="append"
)
vis.line(
X=[total_steps], Y=[epsilon], win=epsilon_plt, name="Epsilon", update="append"
)
def execution(env, agent, make_video=False):
if make_video:
env = wrappers.Monitor(env, os.path.join(os.getcwd(), "videos"), force=True)
rewards = 0
steps = 0
epsilon = 0.0
done = False
state = env.reset()
while not done:
env.render()
action = agent.train_q_net.get_action(state, epsilon)
state, reward, done, _ = env.step(action)
steps += 1
rewards += reward
print("Testing steps: {} rewards {}: ".format(steps, rewards))
def train(args):
env = gym.make(args.env)
dqn_agent = DqnAgent(env, args)
dqn_agent.print_q_network_and_replay_memory_type()
dqn_agent.learn()
dqn_agent.save_model()
def play(args):
env = gym.make(args.env)
dqn_agent2 = DqnAgent(env, args)
dqn_agent2.load_model()
execution(env, dqn_agent2)
def main():
args = argument_parse()
print_args(args)
train(args)
# 테스트시에는 CartPole-v1을 사용하여 테스트
# CartPole-v1의 MAX 스텝: 500 vs. CartPole-v0의 MAX 스텝: 200
args.env = 'CartPole-v1'
play(args)
if __name__ == "__main__":
main()
| [
"argparse.ArgumentParser",
"tensorflow.keras.layers.Dense",
"random.sample",
"numpy.argmax",
"visdom.Visdom",
"collections.deque",
"tensorflow.get_logger",
"tensorflow.one_hot",
"random.randint",
"tensorflow.keras.layers.InputLayer",
"numpy.reshape",
"datetime.datetime.now",
"tensorflow.opti... | [((1864, 1872), 'visdom.Visdom', 'Visdom', ([], {}), '()\n', (1870, 1872), False, 'from visdom import Visdom\n'), ((412, 437), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (435, 437), False, 'import argparse\n'), ((12567, 12585), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env)\n', (12575, 12585), False, 'import gym\n'), ((12755, 12773), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env)\n', (12763, 12773), False, 'import gym\n'), ((125, 140), 'tensorflow.get_logger', 'tf.get_logger', ([], {}), '()\n', (138, 140), True, 'import tensorflow as tf\n'), ((3167, 3190), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3188, 3190), False, 'import datetime\n'), ((3649, 3671), 'collections.deque', 'deque', ([], {'maxlen': 'capacity'}), '(maxlen=capacity)\n', (3654, 3671), False, 'from collections import deque\n'), ((3798, 3830), 'random.sample', 'random.sample', (['self.buffer', 'size'], {}), '(self.buffer, size)\n', (3811, 3830), False, 'import random\n'), ((4248, 4287), 'tensorflow.keras.layers.InputLayer', 'kl.InputLayer', ([], {'input_shape': '(state_dim,)'}), '(input_shape=(state_dim,))\n', (4261, 4287), True, 'import tensorflow.keras.layers as kl\n'), ((4318, 4355), 'tensorflow.keras.layers.Dense', 'kl.Dense', ([], {'units': '(32)', 'activation': '"""relu"""'}), "(units=32, activation='relu')\n", (4326, 4355), True, 'import tensorflow.keras.layers as kl\n'), ((4386, 4423), 'tensorflow.keras.layers.Dense', 'kl.Dense', ([], {'units': '(16)', 'activation': '"""relu"""'}), "(units=16, activation='relu')\n", (4394, 4423), True, 'import tensorflow.keras.layers as kl\n'), ((4452, 4499), 'tensorflow.keras.layers.Dense', 'kl.Dense', ([], {'units': 'action_dim', 'activation': '"""linear"""'}), "(units=action_dim, activation='linear')\n", (4460, 4499), True, 'import tensorflow.keras.layers as kl\n'), ((5636, 5674), 'tensorflow.optimizers.Adam', 'tf.optimizers.Adam', (['args.learning_rate'], {}), '(args.learning_rate)\n', (5654, 5674), True, 'import tensorflow as tf\n'), ((7112, 7179), 'numpy.where', 'np.where', (['dones', 'rewards', '(rewards + self.args.gamma * next_q_values)'], {}), '(dones, rewards, rewards + self.args.gamma * next_q_values)\n', (7120, 7179), True, 'import numpy as np\n'), ((7728, 7782), 'collections.deque', 'deque', ([], {'maxlen': 'self.args.average_length_episode_rewards'}), '(maxlen=self.args.average_length_episode_rewards)\n', (7733, 7782), False, 'from collections import deque\n'), ((5045, 5063), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (5061, 5063), True, 'import numpy as np\n'), ((5096, 5134), 'random.randint', 'random.randint', (['(0)', '(self.action_dim - 1)'], {}), '(0, self.action_dim - 1)\n', (5110, 5134), False, 'import random\n'), ((5169, 5207), 'numpy.reshape', 'np.reshape', (['state', '[1, self.state_dim]'], {}), '(state, [1, self.state_dim])\n', (5179, 5207), True, 'import numpy as np\n'), ((7194, 7211), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (7209, 7211), True, 'import tensorflow as tf\n'), ((5278, 5296), 'numpy.argmax', 'np.argmax', (['q_value'], {}), '(q_value)\n', (5287, 5296), True, 'import numpy as np\n'), ((7422, 7467), 'tensorflow.square', 'tf.square', (['(target_q_values - current_q_values)'], {}), '(target_q_values - current_q_values)\n', (7431, 7467), True, 'import tensorflow as tf\n'), ((10433, 10444), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10442, 10444), False, 'import os\n'), ((10611, 10622), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10620, 10622), False, 'import os\n'), ((12146, 12157), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12155, 12157), False, 'import os\n'), ((5991, 6002), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6000, 6002), False, 'import os\n'), ((6053, 6064), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6062, 6064), False, 'import os\n'), ((7323, 7359), 'tensorflow.one_hot', 'tf.one_hot', (['actions', 'self.action_dim'], {}), '(actions, self.action_dim)\n', (7333, 7359), True, 'import tensorflow as tf\n'), ((9838, 9870), 'numpy.array', 'np.array', (['recent_episode_rewards'], {}), '(recent_episode_rewards)\n', (9846, 9870), True, 'import numpy as np\n')] |
import tensorflow as tf
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from remtime import *
from collections import deque
from remtime import printTime
# top_param
LEARNING_RATE = 0.001
BATCH_SIZE = 2000
TS_BATCH_SIZE = 1000
N_EPOCHS = 26
REG_PENALTY = 0.25
NUM_FEAT = 16
# LEARNING_RATE = 0.001
# BATCH_SIZE = 500
# TS_BATCH_SIZE = 1000
# N_EPOCHS = 15
# REG_PENALTY = 0.05
# NUM_FEAT = 50
NUM_USERS = 122537
NUM_MOVIES = 14398
user_batch = tf.placeholder(tf.int32, [None], name='user_batch')
movie_batch = tf.placeholder(tf.int32, [None], name='movie_batch')
rating_batch = tf.placeholder(tf.float32, [None], name='rating_batch')
##############################################################################################################################
################################################## ------ START HERE -------- ###############################################
##############################################################################################################################
def CollabFilterring(user_batch, movie_batch):
w_user = tf.Variable(tf.random_normal([NUM_USERS, NUM_FEAT])/np.sqrt(NUM_USERS))
w_movie = tf.Variable(tf.random_normal([NUM_MOVIES, NUM_FEAT])/np.sqrt(NUM_MOVIES), name='w_movie')
batch_w_user = tf.nn.embedding_lookup(w_user, user_batch)
batch_w_movie = tf.nn.embedding_lookup(w_movie, movie_batch)
bias = tf.Variable(tf.zeros([1]))
bias_user = tf.Variable(tf.zeros([NUM_USERS]))
bias_movie = tf.Variable(tf.zeros([NUM_MOVIES]), name='bias_movie')
batch_bias_user = tf.nn.embedding_lookup(bias_user, user_batch)
batch_bias_movie = tf.nn.embedding_lookup(bias_movie, movie_batch)
output = tf.reduce_sum(tf.multiply(batch_w_user, batch_w_movie), 1)
output = tf.add(output, bias)
output = tf.add(output, batch_bias_movie)
output = tf.add(output, batch_bias_user, name='output')
cost_reg = REG_PENALTY*tf.add(tf.nn.l2_loss(batch_w_movie), tf.nn.l2_loss(batch_w_user))
# cost_l2 = tf.reduce_mean(tf.pow(output - rating_batch, 2))
# cost_reg = 0
return output, cost_reg
def train_nn(user_batch, movie_batch, rating_batch):
num_batch_loop = int(NUM_TR_ROW/BATCH_SIZE)
prediction, cost_reg = CollabFilterring(user_batch, movie_batch)
cost_l2 = tf.nn.l2_loss(tf.subtract(prediction, rating_batch))
cost = tf.add(cost_l2, cost_reg)
#default learning rate = 0.001
optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(cost)
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
RMSEtr = []
RMSEts = []
for epoch in range(N_EPOCHS):
stime = time.time()
num_batch_loop = int(NUM_TR_ROW/BATCH_SIZE)
np.random.shuffle(train_data)
errors = deque(maxlen=num_batch_loop)
for i in range(num_batch_loop):
_, c, pred_batch = sess.run([optimizer, cost, prediction], feed_dict = {user_batch: train_data[i*BATCH_SIZE:(i+1)*BATCH_SIZE,2], movie_batch: train_data[i*BATCH_SIZE:(i+1)*BATCH_SIZE,0], rating_batch: train_data[i*BATCH_SIZE:(i+1)*BATCH_SIZE,1]})
pred_batch = np.clip(pred_batch, 1.0, 5.0)
errors.append(np.mean(np.power(pred_batch - train_data[i*BATCH_SIZE:(i+1)*BATCH_SIZE,1], 2)))
if (i+1)%25==0:
per = float(i+1)/num_batch_loop*100
print("Epoch:"+str(round(per,2))+"% Of "+str(epoch+1)+"/"+str(N_EPOCHS)+", Batch loss:"+str(round(np.sqrt(errors[i]),2)))
TR_epoch_loss = np.sqrt(np.mean(errors))
RMSEtr.append(TR_epoch_loss)
num_batch_loop = int(NUM_TS_ROW/TS_BATCH_SIZE)
errors = deque(maxlen=num_batch_loop)
for i in range(num_batch_loop):
pred_batch = prediction.eval({user_batch: test_data[i*TS_BATCH_SIZE:(i+1)*TS_BATCH_SIZE,2], movie_batch: test_data[i*TS_BATCH_SIZE:(i+1)*TS_BATCH_SIZE,0], rating_batch: test_data[i*TS_BATCH_SIZE:(i+1)*TS_BATCH_SIZE,1]})
pred_batch = np.clip(pred_batch, 1.0, 5.0)
errors.append(np.mean(np.power(pred_batch - test_data[i*TS_BATCH_SIZE:(i+1)*TS_BATCH_SIZE,1], 2)))
TS_epoch_loss = np.sqrt(np.mean(errors))
RMSEts.append(TS_epoch_loss)
ftime = time.time()
remtime = (N_EPOCHS-epoch-1)*(ftime-stime)
print("Epoch"+ str(epoch+1)+" completed out of "+str(N_EPOCHS)+"; Train loss:"+str(round(TR_epoch_loss,3))+"; Test loss:"+str(round(TS_epoch_loss,3)))
printTime(remtime)
print("Computing Final Test Loss...")
errors = deque(maxlen=num_batch_loop)
for xx in range(num_batch_loop):
pred_batch = prediction.eval({user_batch: test_data[xx*TS_BATCH_SIZE:(xx+1)*TS_BATCH_SIZE,2], movie_batch: test_data[xx*TS_BATCH_SIZE:(xx+1)*TS_BATCH_SIZE,0], rating_batch: test_data[xx*TS_BATCH_SIZE:(xx+1)*TS_BATCH_SIZE,1]})
pred_batch = np.clip(pred_batch, 1.0, 5.0)
errors.append(np.mean(np.power(pred_batch - test_data[xx*TS_BATCH_SIZE:(xx+1)*TS_BATCH_SIZE,1], 2)))
if (xx+1)%50==0:
per = float(xx+1)/(num_batch_loop)*100
print(str(per)+"% Completed")
test_loss = np.sqrt(np.mean(errors))
print("Test Loss:"+str(round(test_loss,3)))
RMSEtr[0]=RMSEts[0] #this was done to ensure the scale matching in the plot (RMSEtr[0] is around 2.16 and would ruin the plot)
plt.plot(RMSEtr, label='Training Set', color='b')
plt.plot(RMSEts, label='Test Set', color='r')
plt.legend()
plt.ylabel('----- RMSE ---->')
plt.xlabel('----- Epoch ---->')
plt.title('RMSE vs Epoch (Biased Matrix Factorization)')
plt.show()
saver.save(sess, 'cap-model')
df = pd.read_csv('data/training.csv')
data = np.array(df)
data = np.asfarray(data)
index = pd.read_csv('data/train_index.csv')
userId = data[:,2]
movId = data[:,0]
data[:,2] = index['user_index']
data[:,0] = index['mov_index']
# data[:,1]=(data[:,1]-np.mean(data[:,1]))
NUM_ROW = data.shape[0]
np.random.shuffle(data)
split = int(0.997*NUM_ROW)
train_data = data[:split]
test_data = data[split:-13]
NUM_TR_ROW = train_data.shape[0]
NUM_TS_ROW = test_data.shape[0]
print("Data preprocessing completed.")
print("Training starts here....")
train_nn(user_batch, movie_batch, rating_batch)
| [
"matplotlib.pyplot.title",
"pandas.read_csv",
"numpy.clip",
"tensorflow.train.AdamOptimizer",
"tensorflow.multiply",
"numpy.mean",
"collections.deque",
"tensorflow.subtract",
"numpy.power",
"numpy.asfarray",
"tensorflow.placeholder",
"numpy.random.shuffle",
"matplotlib.pyplot.show",
"tenso... | [((485, 536), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""user_batch"""'}), "(tf.int32, [None], name='user_batch')\n", (499, 536), True, 'import tensorflow as tf\n'), ((551, 603), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""movie_batch"""'}), "(tf.int32, [None], name='movie_batch')\n", (565, 603), True, 'import tensorflow as tf\n'), ((619, 674), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""rating_batch"""'}), "(tf.float32, [None], name='rating_batch')\n", (633, 674), True, 'import tensorflow as tf\n'), ((5403, 5435), 'pandas.read_csv', 'pd.read_csv', (['"""data/training.csv"""'], {}), "('data/training.csv')\n", (5414, 5435), True, 'import pandas as pd\n'), ((5443, 5455), 'numpy.array', 'np.array', (['df'], {}), '(df)\n', (5451, 5455), True, 'import numpy as np\n'), ((5464, 5481), 'numpy.asfarray', 'np.asfarray', (['data'], {}), '(data)\n', (5475, 5481), True, 'import numpy as np\n'), ((5491, 5526), 'pandas.read_csv', 'pd.read_csv', (['"""data/train_index.csv"""'], {}), "('data/train_index.csv')\n", (5502, 5526), True, 'import pandas as pd\n'), ((5698, 5721), 'numpy.random.shuffle', 'np.random.shuffle', (['data'], {}), '(data)\n', (5715, 5721), True, 'import numpy as np\n'), ((1306, 1348), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['w_user', 'user_batch'], {}), '(w_user, user_batch)\n', (1328, 1348), True, 'import tensorflow as tf\n'), ((1366, 1410), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['w_movie', 'movie_batch'], {}), '(w_movie, movie_batch)\n', (1388, 1410), True, 'import tensorflow as tf\n'), ((1583, 1628), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['bias_user', 'user_batch'], {}), '(bias_user, user_batch)\n', (1605, 1628), True, 'import tensorflow as tf\n'), ((1649, 1696), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['bias_movie', 'movie_batch'], {}), '(bias_movie, movie_batch)\n', (1671, 1696), True, 'import tensorflow as tf\n'), ((1777, 1797), 'tensorflow.add', 'tf.add', (['output', 'bias'], {}), '(output, bias)\n', (1783, 1797), True, 'import tensorflow as tf\n'), ((1808, 1840), 'tensorflow.add', 'tf.add', (['output', 'batch_bias_movie'], {}), '(output, batch_bias_movie)\n', (1814, 1840), True, 'import tensorflow as tf\n'), ((1851, 1897), 'tensorflow.add', 'tf.add', (['output', 'batch_bias_user'], {'name': '"""output"""'}), "(output, batch_bias_user, name='output')\n", (1857, 1897), True, 'import tensorflow as tf\n'), ((2329, 2354), 'tensorflow.add', 'tf.add', (['cost_l2', 'cost_reg'], {}), '(cost_l2, cost_reg)\n', (2335, 2354), True, 'import tensorflow as tf\n'), ((2476, 2492), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (2490, 2492), True, 'import tensorflow as tf\n'), ((1432, 1445), 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), '([1])\n', (1440, 1445), True, 'import tensorflow as tf\n'), ((1472, 1493), 'tensorflow.zeros', 'tf.zeros', (['[NUM_USERS]'], {}), '([NUM_USERS])\n', (1480, 1493), True, 'import tensorflow as tf\n'), ((1521, 1543), 'tensorflow.zeros', 'tf.zeros', (['[NUM_MOVIES]'], {}), '([NUM_MOVIES])\n', (1529, 1543), True, 'import tensorflow as tf\n'), ((1722, 1762), 'tensorflow.multiply', 'tf.multiply', (['batch_w_user', 'batch_w_movie'], {}), '(batch_w_user, batch_w_movie)\n', (1733, 1762), True, 'import tensorflow as tf\n'), ((2282, 2319), 'tensorflow.subtract', 'tf.subtract', (['prediction', 'rating_batch'], {}), '(prediction, rating_batch)\n', (2293, 2319), True, 'import tensorflow as tf\n'), ((2499, 2511), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2509, 2511), True, 'import tensorflow as tf\n'), ((4347, 4375), 'collections.deque', 'deque', ([], {'maxlen': 'num_batch_loop'}), '(maxlen=num_batch_loop)\n', (4352, 4375), False, 'from collections import deque\n'), ((5103, 5152), 'matplotlib.pyplot.plot', 'plt.plot', (['RMSEtr'], {'label': '"""Training Set"""', 'color': '"""b"""'}), "(RMSEtr, label='Training Set', color='b')\n", (5111, 5152), True, 'import matplotlib.pyplot as plt\n'), ((5155, 5200), 'matplotlib.pyplot.plot', 'plt.plot', (['RMSEts'], {'label': '"""Test Set"""', 'color': '"""r"""'}), "(RMSEts, label='Test Set', color='r')\n", (5163, 5200), True, 'import matplotlib.pyplot as plt\n'), ((5203, 5215), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5213, 5215), True, 'import matplotlib.pyplot as plt\n'), ((5218, 5250), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""----- RMSE ---->"""'], {}), "('----- RMSE ---->')\n", (5228, 5250), True, 'import matplotlib.pyplot as plt\n'), ((5253, 5286), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""----- Epoch ---->"""'], {}), "('----- Epoch ---->')\n", (5263, 5286), True, 'import matplotlib.pyplot as plt\n'), ((5289, 5345), 'matplotlib.pyplot.title', 'plt.title', (['"""RMSE vs Epoch (Biased Matrix Factorization)"""'], {}), "('RMSE vs Epoch (Biased Matrix Factorization)')\n", (5298, 5345), True, 'import matplotlib.pyplot as plt\n'), ((5348, 5358), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5356, 5358), True, 'import matplotlib.pyplot as plt\n'), ((1129, 1168), 'tensorflow.random_normal', 'tf.random_normal', (['[NUM_USERS, NUM_FEAT]'], {}), '([NUM_USERS, NUM_FEAT])\n', (1145, 1168), True, 'import tensorflow as tf\n'), ((1169, 1187), 'numpy.sqrt', 'np.sqrt', (['NUM_USERS'], {}), '(NUM_USERS)\n', (1176, 1187), True, 'import numpy as np\n'), ((1212, 1252), 'tensorflow.random_normal', 'tf.random_normal', (['[NUM_MOVIES, NUM_FEAT]'], {}), '([NUM_MOVIES, NUM_FEAT])\n', (1228, 1252), True, 'import tensorflow as tf\n'), ((1253, 1272), 'numpy.sqrt', 'np.sqrt', (['NUM_MOVIES'], {}), '(NUM_MOVIES)\n', (1260, 1272), True, 'import numpy as np\n'), ((1929, 1957), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['batch_w_movie'], {}), '(batch_w_movie)\n', (1942, 1957), True, 'import tensorflow as tf\n'), ((1959, 1986), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['batch_w_user'], {}), '(batch_w_user)\n', (1972, 1986), True, 'import tensorflow as tf\n'), ((2400, 2451), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'LEARNING_RATE'}), '(learning_rate=LEARNING_RATE)\n', (2422, 2451), True, 'import tensorflow as tf\n'), ((2532, 2565), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2563, 2565), True, 'import tensorflow as tf\n'), ((2638, 2649), 'time.time', 'time.time', ([], {}), '()\n', (2647, 2649), False, 'import time\n'), ((2700, 2729), 'numpy.random.shuffle', 'np.random.shuffle', (['train_data'], {}), '(train_data)\n', (2717, 2729), True, 'import numpy as np\n'), ((2743, 2771), 'collections.deque', 'deque', ([], {'maxlen': 'num_batch_loop'}), '(maxlen=num_batch_loop)\n', (2748, 2771), False, 'from collections import deque\n'), ((3533, 3561), 'collections.deque', 'deque', ([], {'maxlen': 'num_batch_loop'}), '(maxlen=num_batch_loop)\n', (3538, 3561), False, 'from collections import deque\n'), ((4060, 4071), 'time.time', 'time.time', ([], {}), '()\n', (4069, 4071), False, 'import time\n'), ((4275, 4293), 'remtime.printTime', 'printTime', (['remtime'], {}), '(remtime)\n', (4284, 4293), False, 'from remtime import printTime\n'), ((4656, 4685), 'numpy.clip', 'np.clip', (['pred_batch', '(1.0)', '(5.0)'], {}), '(pred_batch, 1.0, 5.0)\n', (4663, 4685), True, 'import numpy as np\n'), ((4909, 4924), 'numpy.mean', 'np.mean', (['errors'], {}), '(errors)\n', (4916, 4924), True, 'import numpy as np\n'), ((3076, 3105), 'numpy.clip', 'np.clip', (['pred_batch', '(1.0)', '(5.0)'], {}), '(pred_batch, 1.0, 5.0)\n', (3083, 3105), True, 'import numpy as np\n'), ((3421, 3436), 'numpy.mean', 'np.mean', (['errors'], {}), '(errors)\n', (3428, 3436), True, 'import numpy as np\n'), ((3839, 3868), 'numpy.clip', 'np.clip', (['pred_batch', '(1.0)', '(5.0)'], {}), '(pred_batch, 1.0, 5.0)\n', (3846, 3868), True, 'import numpy as np\n'), ((4000, 4015), 'numpy.mean', 'np.mean', (['errors'], {}), '(errors)\n', (4007, 4015), True, 'import numpy as np\n'), ((4711, 4798), 'numpy.power', 'np.power', (['(pred_batch - test_data[xx * TS_BATCH_SIZE:(xx + 1) * TS_BATCH_SIZE, 1])', '(2)'], {}), '(pred_batch - test_data[xx * TS_BATCH_SIZE:(xx + 1) * TS_BATCH_SIZE,\n 1], 2)\n', (4719, 4798), True, 'import numpy as np\n'), ((3132, 3208), 'numpy.power', 'np.power', (['(pred_batch - train_data[i * BATCH_SIZE:(i + 1) * BATCH_SIZE, 1])', '(2)'], {}), '(pred_batch - train_data[i * BATCH_SIZE:(i + 1) * BATCH_SIZE, 1], 2)\n', (3140, 3208), True, 'import numpy as np\n'), ((3895, 3981), 'numpy.power', 'np.power', (['(pred_batch - test_data[i * TS_BATCH_SIZE:(i + 1) * TS_BATCH_SIZE, 1])', '(2)'], {}), '(pred_batch - test_data[i * TS_BATCH_SIZE:(i + 1) * TS_BATCH_SIZE, \n 1], 2)\n', (3903, 3981), True, 'import numpy as np\n'), ((3368, 3386), 'numpy.sqrt', 'np.sqrt', (['errors[i]'], {}), '(errors[i])\n', (3375, 3386), True, 'import numpy as np\n')] |
from __future__ import division, print_function
import os
import sys
import argparse
import zqtflearn
import tempfile
import urllib
import numpy as np
import pandas as pd
import tensorflow as tf
#-----------------------------------------------------------------------------
COLUMNS = ["age", "workclass", "fnlwgt", "education", "education_num",
"marital_status", "occupation", "relationship", "race", "gender",
"capital_gain", "capital_loss", "hours_per_week", "native_country",
"income_bracket"]
LABEL_COLUMN = "label"
#deep侧的特征
CATEGORICAL_COLUMNS = {"workclass": 10, "education": 17, "marital_status":8,
"occupation": 16, "relationship": 7, "race": 6,
"gender": 3, "native_country": 43, "age_binned": 14}
CATEGORICAL_COLUMNS = {'video_id':100} #先假定有100个视频吧
#wide侧的特征
CONTINUOUS_COLUMNS = ["age", "education_num", "capital_gain", "capital_loss",
"hours_per_week"]
#-----------------------------------------------------------------------------
class TFLearnWideAndDeep(object):
'''
Wide and deep model, implemented using TFLearn
'''
AVAILABLE_MODELS = ["wide", "deep", "wide+deep"]
def __init__(self, model_type="wide+deep", verbose=None, name=None, tensorboard_verbose=3,
wide_learning_rate=0.001, deep_learning_rate=0.001, checkpoints_dir=None):
'''
model_type = `str`: wide or deep or wide+deep
verbose = `bool`
name = `str` used for run_id (defaults to model_type)
tensorboard_verbose = `int`: logging level for tensorboard (0, 1, 2, or 3)
wide_learning_rate = `float`: defaults to 0.001
deep_learning_rate = `float`: defaults to 0.001
checkpoints_dir = `str`: where checkpoint files will be stored (defaults to "CHECKPOINTS")
'''
self.model_type = model_type or "wide+deep"
assert self.model_type in self.AVAILABLE_MODELS
self.verbose = verbose or 0
self.tensorboard_verbose = tensorboard_verbose
self.name = name or self.model_type # name is used for the run_id
self.data_columns = COLUMNS
self.continuous_columns = CONTINUOUS_COLUMNS
self.categorical_columns = CATEGORICAL_COLUMNS # dict with category_name: category_size
self.label_column = LABEL_COLUMN
self.checkpoints_dir = checkpoints_dir or "CHECKPOINTS"
if not os.path.exists(self.checkpoints_dir):
os.mkdir(self.checkpoints_dir)
print("Created checkpoints directory %s" % self.checkpoints_dir)
self.build_model([wide_learning_rate, deep_learning_rate])
def load_data(self, train_dfn="adult.data", test_dfn="adult.test"):
'''
Load data (use files offered in the Tensorflow wide_n_deep_tutorial)
'''
if not os.path.exists(train_dfn):
urllib.urlretrieve("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", train_dfn)
print("Training data is downloaded to %s" % train_dfn)
if not os.path.exists(test_dfn):
urllib.urlretrieve("https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test", test_dfn)
print("Test data is downloaded to %s" % test_dfn)
self.train_data = pd.read_csv(train_dfn, names=COLUMNS, skipinitialspace=True)
self.test_data = pd.read_csv(test_dfn, names=COLUMNS, skipinitialspace=True, skiprows=1)
self.train_data[self.label_column] = (self.train_data["income_bracket"].apply(lambda x: ">50K" in x)).astype(int)
self.test_data[self.label_column] = (self.test_data["income_bracket"].apply(lambda x: ">50K" in x)).astype(int)
def build_model(self, learning_rate=[0.001, 0.01]):
'''
Model - wide and deep - built using zqtflearn
'''
n_cc = len(self.continuous_columns)
n_categories = 1 # two categories: is_idv and is_not_idv
#为什么不是len(self.CATEGORICAL_COLUMNS)
input_shape = [None, n_cc]
if self.verbose:
print ("="*77 + " Model %s (type=%s)" % (self.name, self.model_type))
print (" Input placeholder shape=%s" % str(input_shape))
wide_inputs = zqtflearn.input_data(shape=input_shape, name="wide_X")
if not isinstance(learning_rate, list):
learning_rate = [learning_rate, learning_rate] # wide, deep
if self.verbose:
print (" Learning rates (wide, deep)=%s" % learning_rate)
with tf.name_scope("Y"): # placeholder for target variable (i.e. trainY input)
Y_in = tf.placeholder(shape=[None, 1], dtype=tf.float32, name="Y")
with tf.variable_op_scope([wide_inputs], None, "cb_unit", reuse=False) as scope:
central_bias = zqtflearn.variables.variable('central_bias', shape=[1],
initializer=tf.constant_initializer(np.random.randn()),
trainable=True, restore=True)
tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit', central_bias)
if 'wide' in self.model_type:
wide_network = self.wide_model(wide_inputs, n_cc)
network = wide_network
wide_network_with_bias = tf.add(wide_network, central_bias, name="wide_with_bias")
if 'deep' in self.model_type:
deep_network = self.deep_model(wide_inputs, n_cc) #这里面应该是deep inputs
deep_network_with_bias = tf.add(deep_network, central_bias, name="deep_with_bias")
if 'wide' in self.model_type:
network = tf.add(wide_network, deep_network)
if self.verbose:
print ("Wide + deep model network %s" % network)
else:
network = deep_network
network = tf.add(network, central_bias, name="add_central_bias")
# add validation monitor summaries giving confusion matrix entries
with tf.name_scope('Monitors'):
predictions = tf.cast(tf.greater(network, 0), tf.int64)
print ("predictions=%s" % predictions)
Ybool = tf.cast(Y_in, tf.bool)
print ("Ybool=%s" % Ybool)
pos = tf.boolean_mask(predictions, Ybool)
neg = tf.boolean_mask(predictions, ~Ybool)
psize = tf.cast(tf.shape(pos)[0], tf.int64)
nsize = tf.cast(tf.shape(neg)[0], tf.int64)
true_positive = tf.reduce_sum(pos, name="true_positive")
false_negative = tf.subtract(psize, true_positive, name="false_negative")
false_positive = tf.reduce_sum(neg, name="false_positive")
true_negative = tf.subtract(nsize, false_positive, name="true_negative")
overall_accuracy = tf.truediv(tf.add(true_positive, true_negative), tf.add(nsize, psize), name="overall_accuracy")
vmset = [true_positive, true_negative, false_positive, false_negative, overall_accuracy]
trainable_vars = tf.trainable_variables()
tv_deep = [v for v in trainable_vars if v.name.startswith('deep_')]
tv_wide = [v for v in trainable_vars if v.name.startswith('wide_')]
if self.verbose:
print ("DEEP trainable_vars")
for v in tv_deep:
print (" Variable %s: %s" % (v.name, v))
print ("WIDE trainable_vars")
for v in tv_wide:
print (" Variable %s: %s" % (v.name, v))
if 'wide' in self.model_type:
if not 'deep' in self.model_type:
tv_wide.append(central_bias)
zqtflearn.regression(wide_network_with_bias,
placeholder=Y_in,
optimizer='sgd',
#loss='roc_auc_score',
loss='binary_crossentropy',
metric="accuracy",
learning_rate=learning_rate[0],
validation_monitors=vmset,
trainable_vars=tv_wide,
op_name="wide_regression",
name="Y")
if 'deep' in self.model_type:
if not 'wide' in self.model_type:
tv_wide.append(central_bias)
zqtflearn.regression(deep_network_with_bias,
placeholder=Y_in,
optimizer='adam',
#loss='roc_auc_score',
loss='binary_crossentropy',
metric="accuracy",
learning_rate=learning_rate[1],
validation_monitors=vmset if not 'wide' in self.model_type else None,
trainable_vars=tv_deep,
op_name="deep_regression",
name="Y")
if self.model_type=='wide+deep': # learn central bias separately for wide+deep
zqtflearn.regression(network,
placeholder=Y_in,
optimizer='adam',
loss='binary_crossentropy',
metric="accuracy",
learning_rate=learning_rate[0], # use wide learning rate
trainable_vars=[central_bias],
op_name="central_bias_regression",
name="Y")
self.model = zqtflearn.DNN(network,
tensorboard_verbose=self.tensorboard_verbose,
max_checkpoints=5,
checkpoint_path="%s/%s.tfl" % (self.checkpoints_dir, self.name),
)
if 'deep' in self.model_type:#对于深层这边希望使用预先训练好的向量
# Retrieve embedding layer weights (only a single weight matrix, so index is 0)
embeddingWeights = zqtflearn.get_layer_variables_by_name('EmbeddingLayer')[0]
# Assign your own weights (for example, a numpy array [input_dim, output_dim])
model.set_weights(embeddingWeights, YOUR_WEIGHTS)
if self.verbose:
print ("Target variables:")
for v in tf.get_collection(tf.GraphKeys.TARGETS):
print (" variable %s: %s" % (v.name, v))
print ("="*77)
def deep_model(self, wide_inputs, n_inputs, n_nodes=[100, 50], use_dropout=False):
cc_input_var = {}
cc_embed_var = {}
flat_vars = []
if self.verbose:
print ("--> deep model: %s categories, %d continuous" % (len(self.categorical_columns), n_inputs))
# for cc, cc_size in self.categorical_columns.items():
# cc_input_var[cc] = zqtflearn.input_data(shape=[None, 1], name="%s_in" % cc, dtype=tf.int32)
# # embedding layers only work on CPU! No GPU implementation in tensorflow, yet!
# cc_embed_var[cc] = zqtflearn.layers.embedding_ops.embedding(cc_input_var[cc], cc_size, 512, name="deep_%s_embed" % cc)
#
# if self.verbose:
# print (" %s_embed = %s" % (cc, cc_embed_var[cc]))
# flat_vars.append(tf.squeeze(cc_embed_var[cc], squeeze_dims=[1], name="%s_squeeze" % cc))
net = zqtflearn.input_data(shape=[None, 1], name="deep_in", dtype=tf.int32)
net = zqtflearn.embedding(net, input_dim=20000, output_dim=768, trainable=False, name="EmbeddingLayer")
network = tf.concat([wide_inputs] + net,axis = 1, name="deep_concat")
for k in range(len(n_nodes)):
network = zqtflearn.fully_connected(network, n_nodes[k], activation="relu", name="deep_fc%d" % (k + 1))
if use_dropout:
network = zqtflearn.dropout(network, 0.5, name="deep_dropout%d" % (k + 1))
if self.verbose:
print ("Deep model network before output %s" % network)
network = zqtflearn.fully_connected(network, 1, activation="linear", name="deep_fc_output", bias=False)
network = tf.reshape(network, [-1, 1]) # so that accuracy is binary_accuracy
if self.verbose:
print ("Deep model network %s" % network)
return network
def wide_model(self, inputs, n_inputs):
'''
Model - wide, i.e. normal linear model (for logistic regression)
'''
network = inputs
# use fully_connected (instad of single_unit) because fc works properly with batches, whereas single_unit is 1D only
network = zqtflearn.fully_connected(network, n_inputs, activation="linear", name="wide_linear", bias=False) # x*W (no bias)
network = tf.reduce_sum(network, 1, name="reduce_sum") # batched sum, to produce logits
network = tf.reshape(network, [-1, 1]) # so that accuracy is binary_accuracy
if self.verbose:
print ("Wide model network %s" % network)
return network
def prepare_input_data(self, input_data, name="", category_map=None):
'''
Prepare input data dicts
'''
print ("-"*40 + " Preparing %s" % name)
X = input_data[self.continuous_columns].values.astype(np.float32)
Y = input_data[self.label_column].values.astype(np.float32)
Y = Y.reshape([-1, 1])
if self.verbose:
print (" Y shape=%s, X shape=%s" % (Y.shape, X.shape))
X_dict = {"wide_X": X}
if 'deep' in self.model_type:
# map categorical value strings to integers
td = input_data
if category_map is None:
category_map = {}
for cc in self.categorical_columns:
if not cc in td.columns:
continue
cc_values = sorted(td[cc].unique())
cc_max = 1+len(cc_values)
cc_map = dict(zip(cc_values, range(1, cc_max))) # start from 1 to avoid 0:0 mapping (save 0 for missing)
if self.verbose:
print (" category %s max=%s, map=%s" % (cc, cc_max, cc_map))
category_map[cc] = cc_map
td = td.replace(category_map)
# bin ages (cuts off extreme values)
age_bins = [ 0, 12, 18, 25, 30, 35, 40, 45, 50, 55, 60, 65, 80, 65535 ]
td['age_binned'] = pd.cut(td['age'], age_bins, labels=False)
td = td.replace({'age_binned': {np.nan: 0}})
print (" %d age bins: age bins = %s" % (len(age_bins), age_bins))
X_dict.update({ ("%s_in" % cc): td[cc].values.astype(np.int32).reshape([-1, 1]) for cc in self.categorical_columns})
Y_dict = {"Y": Y}
if self.verbose:
print ("-"*40)
return X_dict, Y_dict, category_map
def train(self, n_epoch=1000, snapshot_step=10, batch_size=None):
self.X_dict, self.Y_dict, category_map = self.prepare_input_data(self.train_data, "train data")
self.testX_dict, self.testY_dict, _ = self.prepare_input_data(self.test_data, "test data", category_map)
validation_batch_size = batch_size or self.testY_dict['Y'].shape[0]
batch_size = batch_size or self.Y_dict['Y'].shape[0]
print ("Input data shape = %s; output data shape=%s, batch_size=%s" % (str(self.X_dict['wide_X'].shape),
str(self.Y_dict['Y'].shape),
batch_size))
print ("Test data shape = %s; output data shape=%s, validation_batch_size=%s" % (str(self.testX_dict['wide_X'].shape),
str(self.testY_dict['Y'].shape),
validation_batch_size))
print ("="*60 + " Training")
self.model.fit(self.X_dict,
self.Y_dict,
n_epoch=n_epoch,
validation_set=(self.testX_dict, self.testY_dict),
snapshot_step=snapshot_step,
batch_size=batch_size,
validation_batch_size=validation_batch_size,
show_metric=True,
snapshot_epoch=False,
shuffle=True,
run_id=self.name,
)
def evaluate(self):
logits = np.array(self.model.predict(self.testX_dict)).reshape([-1])
print ("="*60 + " Evaluation")
print (" logits: %s, min=%s, max=%s" % (logits.shape, logits.min(), logits.max()))
probs = 1.0 / (1.0 + np.exp(-logits))
y_pred = pd.Series((probs > 0.5).astype(np.int32))
Y = pd.Series(self.testY_dict['Y'].astype(np.int32).reshape([-1]))
self.confusion_matrix = self.output_confusion_matrix(Y, y_pred)
print ("="*60)
def output_confusion_matrix(self, y, y_pred):
assert y.size == y_pred.size
print("Actual IDV")
print(y.value_counts())
print("Predicted IDV")
print(y_pred.value_counts())
print()
print("Confusion matrix:")
cmat = pd.crosstab(y_pred, y, rownames=['predictions'], colnames=['actual'])
print(cmat)
sys.stdout.flush()
return cmat
#-----------------------------------------------------------------------------
def CommandLine(args=None):
'''
Main command line. Accepts args, to allow for simple unit testing.
'''
flags = tf.app.flags
FLAGS = flags.FLAGS
if args:
print("added by zhengquan. I think it didn't get here, test it tomorrow")
FLAGS.__init__()
FLAGS.__dict__.update(args)
try:
flags.DEFINE_string("model_type", "wide+deep","Valid model types: {'wide', 'deep', 'wide+deep'}.")
flags.DEFINE_string("run_name", None, "name for this run (defaults to model type)")
flags.DEFINE_string("load_weights", None, "filename with initial weights to load")
flags.DEFINE_string("checkpoints_dir", None, "name of directory where checkpoints should be saved")
flags.DEFINE_integer("n_epoch", 200, "Number of training epoch steps")
flags.DEFINE_integer("snapshot_step", 100, "Step number when snapshot (and validation testing) is done")
flags.DEFINE_float("wide_learning_rate", 0.001, "learning rate for the wide part of the model")
flags.DEFINE_float("deep_learning_rate", 0.001, "learning rate for the deep part of the model")
flags.DEFINE_boolean("verbose", False, "Verbose output")
flags.DEFINE_boolean("continue_train", False, "continue_train")
except argparse.ArgumentError:
pass # so that CommandLine can be run more than once, for testing
twad = TFLearnWideAndDeep(model_type=FLAGS.model_type, verbose=FLAGS.verbose,
name=FLAGS.run_name, wide_learning_rate=FLAGS.wide_learning_rate,
deep_learning_rate=FLAGS.deep_learning_rate,
checkpoints_dir=FLAGS.checkpoints_dir)
twad.load_data()
if FLAGS.load_weights:
print ("Loading initial weights from %s" % FLAGS.load_weights)
twad.model.load(FLAGS.load_weights)
if FLAGS.continue_train:
twad.train(n_epoch=FLAGS.n_epoch, snapshot_step=FLAGS.snapshot_step)
twad.evaluate()
return twad
#-----------------------------------------------------------------------------
# unit tests
def test_wide_and_deep():
import glob
tf.reset_default_graph()
cdir = "test_checkpoints"
if os.path.exists(cdir):
os.system("rm -rf %s" % cdir)
twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type="wide+deep", snapshot_step=5,
wide_learning_rate=0.0001, checkpoints_dir=cdir))
cfiles = glob.glob("%s/*.tfl-*" % cdir)
print ("cfiles=%s" % cfiles)
assert(len(cfiles))
cm = twad.confusion_matrix.values.astype(np.float32)
assert(cm[1][1])
def test_deep():
import glob
tf.reset_default_graph()
cdir = "test_checkpoints"
if os.path.exists(cdir):
os.system("rm -rf %s" % cdir)
twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type="deep", snapshot_step=5,
wide_learning_rate=0.0001, checkpoints_dir=cdir))
cfiles = glob.glob("%s/*.tfl-*" % cdir)
print ("cfiles=%s" % cfiles)
assert(len(cfiles))
cm = twad.confusion_matrix.values.astype(np.float32)
assert(cm[1][1])
def test_wide():
import glob
tf.reset_default_graph()
cdir = "test_checkpoints"
if os.path.exists(cdir):
os.system("rm -rf %s" % cdir)
twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type="wide", snapshot_step=5,
wide_learning_rate=0.0001, checkpoints_dir=cdir))
cfiles = glob.glob("%s/*.tfl-*" % cdir)
print ("cfiles=%s" % cfiles)
assert(len(cfiles))
cm = twad.confusion_matrix.values.astype(np.float32)
assert(cm[1][1])
#-----------------------------------------------------------------------------
if __name__=="__main__":
CommandLine()
None
| [
"os.mkdir",
"tensorflow.reduce_sum",
"tensorflow.trainable_variables",
"pandas.read_csv",
"tensorflow.reset_default_graph",
"tensorflow.get_collection",
"tensorflow.reshape",
"sys.stdout.flush",
"numpy.exp",
"glob.glob",
"zqtflearn.embedding",
"tensorflow.greater",
"tensorflow.subtract",
"... | [((19811, 19835), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (19833, 19835), True, 'import tensorflow as tf\n'), ((19873, 19893), 'os.path.exists', 'os.path.exists', (['cdir'], {}), '(cdir)\n', (19887, 19893), False, 'import os\n'), ((20129, 20159), 'glob.glob', 'glob.glob', (["('%s/*.tfl-*' % cdir)"], {}), "('%s/*.tfl-*' % cdir)\n", (20138, 20159), False, 'import glob\n'), ((20333, 20357), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (20355, 20357), True, 'import tensorflow as tf\n'), ((20395, 20415), 'os.path.exists', 'os.path.exists', (['cdir'], {}), '(cdir)\n', (20409, 20415), False, 'import os\n'), ((20646, 20676), 'glob.glob', 'glob.glob', (["('%s/*.tfl-*' % cdir)"], {}), "('%s/*.tfl-*' % cdir)\n", (20655, 20676), False, 'import glob\n'), ((20850, 20874), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (20872, 20874), True, 'import tensorflow as tf\n'), ((20912, 20932), 'os.path.exists', 'os.path.exists', (['cdir'], {}), '(cdir)\n', (20926, 20932), False, 'import os\n'), ((21163, 21193), 'glob.glob', 'glob.glob', (["('%s/*.tfl-*' % cdir)"], {}), "('%s/*.tfl-*' % cdir)\n", (21172, 21193), False, 'import glob\n'), ((3315, 3375), 'pandas.read_csv', 'pd.read_csv', (['train_dfn'], {'names': 'COLUMNS', 'skipinitialspace': '(True)'}), '(train_dfn, names=COLUMNS, skipinitialspace=True)\n', (3326, 3375), True, 'import pandas as pd\n'), ((3401, 3472), 'pandas.read_csv', 'pd.read_csv', (['test_dfn'], {'names': 'COLUMNS', 'skipinitialspace': '(True)', 'skiprows': '(1)'}), '(test_dfn, names=COLUMNS, skipinitialspace=True, skiprows=1)\n', (3412, 3472), True, 'import pandas as pd\n'), ((4240, 4294), 'zqtflearn.input_data', 'zqtflearn.input_data', ([], {'shape': 'input_shape', 'name': '"""wide_X"""'}), "(shape=input_shape, name='wide_X')\n", (4260, 4294), False, 'import zqtflearn\n'), ((5869, 5923), 'tensorflow.add', 'tf.add', (['network', 'central_bias'], {'name': '"""add_central_bias"""'}), "(network, central_bias, name='add_central_bias')\n", (5875, 5923), True, 'import tensorflow as tf\n'), ((7023, 7047), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (7045, 7047), True, 'import tensorflow as tf\n'), ((9647, 9807), 'zqtflearn.DNN', 'zqtflearn.DNN', (['network'], {'tensorboard_verbose': 'self.tensorboard_verbose', 'max_checkpoints': '(5)', 'checkpoint_path': "('%s/%s.tfl' % (self.checkpoints_dir, self.name))"}), "(network, tensorboard_verbose=self.tensorboard_verbose,\n max_checkpoints=5, checkpoint_path='%s/%s.tfl' % (self.checkpoints_dir,\n self.name))\n", (9660, 9807), False, 'import zqtflearn\n'), ((11478, 11547), 'zqtflearn.input_data', 'zqtflearn.input_data', ([], {'shape': '[None, 1]', 'name': '"""deep_in"""', 'dtype': 'tf.int32'}), "(shape=[None, 1], name='deep_in', dtype=tf.int32)\n", (11498, 11547), False, 'import zqtflearn\n'), ((11562, 11663), 'zqtflearn.embedding', 'zqtflearn.embedding', (['net'], {'input_dim': '(20000)', 'output_dim': '(768)', 'trainable': '(False)', 'name': '"""EmbeddingLayer"""'}), "(net, input_dim=20000, output_dim=768, trainable=False,\n name='EmbeddingLayer')\n", (11581, 11663), False, 'import zqtflearn\n'), ((11679, 11737), 'tensorflow.concat', 'tf.concat', (['([wide_inputs] + net)'], {'axis': '(1)', 'name': '"""deep_concat"""'}), "([wide_inputs] + net, axis=1, name='deep_concat')\n", (11688, 11737), True, 'import tensorflow as tf\n'), ((12124, 12222), 'zqtflearn.fully_connected', 'zqtflearn.fully_connected', (['network', '(1)'], {'activation': '"""linear"""', 'name': '"""deep_fc_output"""', 'bias': '(False)'}), "(network, 1, activation='linear', name=\n 'deep_fc_output', bias=False)\n", (12149, 12222), False, 'import zqtflearn\n'), ((12236, 12264), 'tensorflow.reshape', 'tf.reshape', (['network', '[-1, 1]'], {}), '(network, [-1, 1])\n', (12246, 12264), True, 'import tensorflow as tf\n'), ((12715, 12817), 'zqtflearn.fully_connected', 'zqtflearn.fully_connected', (['network', 'n_inputs'], {'activation': '"""linear"""', 'name': '"""wide_linear"""', 'bias': '(False)'}), "(network, n_inputs, activation='linear', name=\n 'wide_linear', bias=False)\n", (12740, 12817), False, 'import zqtflearn\n'), ((12847, 12891), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['network', '(1)'], {'name': '"""reduce_sum"""'}), "(network, 1, name='reduce_sum')\n", (12860, 12891), True, 'import tensorflow as tf\n'), ((12943, 12971), 'tensorflow.reshape', 'tf.reshape', (['network', '[-1, 1]'], {}), '(network, [-1, 1])\n', (12953, 12971), True, 'import tensorflow as tf\n'), ((17442, 17511), 'pandas.crosstab', 'pd.crosstab', (['y_pred', 'y'], {'rownames': "['predictions']", 'colnames': "['actual']"}), "(y_pred, y, rownames=['predictions'], colnames=['actual'])\n", (17453, 17511), True, 'import pandas as pd\n'), ((17540, 17558), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (17556, 17558), False, 'import sys\n'), ((19903, 19932), 'os.system', 'os.system', (["('rm -rf %s' % cdir)"], {}), "('rm -rf %s' % cdir)\n", (19912, 19932), False, 'import os\n'), ((20425, 20454), 'os.system', 'os.system', (["('rm -rf %s' % cdir)"], {}), "('rm -rf %s' % cdir)\n", (20434, 20454), False, 'import os\n'), ((20942, 20971), 'os.system', 'os.system', (["('rm -rf %s' % cdir)"], {}), "('rm -rf %s' % cdir)\n", (20951, 20971), False, 'import os\n'), ((2437, 2473), 'os.path.exists', 'os.path.exists', (['self.checkpoints_dir'], {}), '(self.checkpoints_dir)\n', (2451, 2473), False, 'import os\n'), ((2487, 2517), 'os.mkdir', 'os.mkdir', (['self.checkpoints_dir'], {}), '(self.checkpoints_dir)\n', (2495, 2517), False, 'import os\n'), ((2851, 2876), 'os.path.exists', 'os.path.exists', (['train_dfn'], {}), '(train_dfn)\n', (2865, 2876), False, 'import os\n'), ((2890, 3007), 'urllib.urlretrieve', 'urllib.urlretrieve', (['"""https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"""', 'train_dfn'], {}), "(\n 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'\n , train_dfn)\n", (2908, 3007), False, 'import urllib\n'), ((3081, 3105), 'os.path.exists', 'os.path.exists', (['test_dfn'], {}), '(test_dfn)\n', (3095, 3105), False, 'import os\n'), ((3119, 3235), 'urllib.urlretrieve', 'urllib.urlretrieve', (['"""https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test"""', 'test_dfn'], {}), "(\n 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'\n , test_dfn)\n", (3137, 3235), False, 'import urllib\n'), ((4526, 4544), 'tensorflow.name_scope', 'tf.name_scope', (['"""Y"""'], {}), "('Y')\n", (4539, 4544), True, 'import tensorflow as tf\n'), ((4621, 4680), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, 1]', 'dtype': 'tf.float32', 'name': '"""Y"""'}), "(shape=[None, 1], dtype=tf.float32, name='Y')\n", (4635, 4680), True, 'import tensorflow as tf\n'), ((4695, 4760), 'tensorflow.variable_op_scope', 'tf.variable_op_scope', (['[wide_inputs]', 'None', '"""cb_unit"""'], {'reuse': '(False)'}), "([wide_inputs], None, 'cb_unit', reuse=False)\n", (4715, 4760), True, 'import tensorflow as tf\n'), ((5064, 5141), 'tensorflow.add_to_collection', 'tf.add_to_collection', (["(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit')", 'central_bias'], {}), "(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit', central_bias)\n", (5084, 5141), True, 'import tensorflow as tf\n'), ((5315, 5372), 'tensorflow.add', 'tf.add', (['wide_network', 'central_bias'], {'name': '"""wide_with_bias"""'}), "(wide_network, central_bias, name='wide_with_bias')\n", (5321, 5372), True, 'import tensorflow as tf\n'), ((5530, 5587), 'tensorflow.add', 'tf.add', (['deep_network', 'central_bias'], {'name': '"""deep_with_bias"""'}), "(deep_network, central_bias, name='deep_with_bias')\n", (5536, 5587), True, 'import tensorflow as tf\n'), ((6013, 6038), 'tensorflow.name_scope', 'tf.name_scope', (['"""Monitors"""'], {}), "('Monitors')\n", (6026, 6038), True, 'import tensorflow as tf\n'), ((6179, 6201), 'tensorflow.cast', 'tf.cast', (['Y_in', 'tf.bool'], {}), '(Y_in, tf.bool)\n', (6186, 6201), True, 'import tensorflow as tf\n'), ((6259, 6294), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['predictions', 'Ybool'], {}), '(predictions, Ybool)\n', (6274, 6294), True, 'import tensorflow as tf\n'), ((6313, 6349), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['predictions', '(~Ybool)'], {}), '(predictions, ~Ybool)\n', (6328, 6349), True, 'import tensorflow as tf\n'), ((6490, 6530), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['pos'], {'name': '"""true_positive"""'}), "(pos, name='true_positive')\n", (6503, 6530), True, 'import tensorflow as tf\n'), ((6560, 6616), 'tensorflow.subtract', 'tf.subtract', (['psize', 'true_positive'], {'name': '"""false_negative"""'}), "(psize, true_positive, name='false_negative')\n", (6571, 6616), True, 'import tensorflow as tf\n'), ((6646, 6687), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['neg'], {'name': '"""false_positive"""'}), "(neg, name='false_positive')\n", (6659, 6687), True, 'import tensorflow as tf\n'), ((6716, 6772), 'tensorflow.subtract', 'tf.subtract', (['nsize', 'false_positive'], {'name': '"""true_negative"""'}), "(nsize, false_positive, name='true_negative')\n", (6727, 6772), True, 'import tensorflow as tf\n'), ((7628, 7888), 'zqtflearn.regression', 'zqtflearn.regression', (['wide_network_with_bias'], {'placeholder': 'Y_in', 'optimizer': '"""sgd"""', 'loss': '"""binary_crossentropy"""', 'metric': '"""accuracy"""', 'learning_rate': 'learning_rate[0]', 'validation_monitors': 'vmset', 'trainable_vars': 'tv_wide', 'op_name': '"""wide_regression"""', 'name': '"""Y"""'}), "(wide_network_with_bias, placeholder=Y_in, optimizer=\n 'sgd', loss='binary_crossentropy', metric='accuracy', learning_rate=\n learning_rate[0], validation_monitors=vmset, trainable_vars=tv_wide,\n op_name='wide_regression', name='Y')\n", (7648, 7888), False, 'import zqtflearn\n'), ((8370, 8679), 'zqtflearn.regression', 'zqtflearn.regression', (['deep_network_with_bias'], {'placeholder': 'Y_in', 'optimizer': '"""adam"""', 'loss': '"""binary_crossentropy"""', 'metric': '"""accuracy"""', 'learning_rate': 'learning_rate[1]', 'validation_monitors': "(vmset if not 'wide' in self.model_type else None)", 'trainable_vars': 'tv_deep', 'op_name': '"""deep_regression"""', 'name': '"""Y"""'}), "(deep_network_with_bias, placeholder=Y_in, optimizer=\n 'adam', loss='binary_crossentropy', metric='accuracy', learning_rate=\n learning_rate[1], validation_monitors=vmset if not 'wide' in self.\n model_type else None, trainable_vars=tv_deep, op_name='deep_regression',\n name='Y')\n", (8390, 8679), False, 'import zqtflearn\n'), ((9114, 9348), 'zqtflearn.regression', 'zqtflearn.regression', (['network'], {'placeholder': 'Y_in', 'optimizer': '"""adam"""', 'loss': '"""binary_crossentropy"""', 'metric': '"""accuracy"""', 'learning_rate': 'learning_rate[0]', 'trainable_vars': '[central_bias]', 'op_name': '"""central_bias_regression"""', 'name': '"""Y"""'}), "(network, placeholder=Y_in, optimizer='adam', loss=\n 'binary_crossentropy', metric='accuracy', learning_rate=learning_rate[0\n ], trainable_vars=[central_bias], op_name='central_bias_regression',\n name='Y')\n", (9134, 9348), False, 'import zqtflearn\n'), ((10421, 10460), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TARGETS'], {}), '(tf.GraphKeys.TARGETS)\n', (10438, 10460), True, 'import tensorflow as tf\n'), ((11800, 11898), 'zqtflearn.fully_connected', 'zqtflearn.fully_connected', (['network', 'n_nodes[k]'], {'activation': '"""relu"""', 'name': "('deep_fc%d' % (k + 1))"}), "(network, n_nodes[k], activation='relu', name=\n 'deep_fc%d' % (k + 1))\n", (11825, 11898), False, 'import zqtflearn\n'), ((14539, 14580), 'pandas.cut', 'pd.cut', (["td['age']", 'age_bins'], {'labels': '(False)'}), "(td['age'], age_bins, labels=False)\n", (14545, 14580), True, 'import pandas as pd\n'), ((5656, 5690), 'tensorflow.add', 'tf.add', (['wide_network', 'deep_network'], {}), '(wide_network, deep_network)\n', (5662, 5690), True, 'import tensorflow as tf\n'), ((6074, 6096), 'tensorflow.greater', 'tf.greater', (['network', '(0)'], {}), '(network, 0)\n', (6084, 6096), True, 'import tensorflow as tf\n'), ((6815, 6851), 'tensorflow.add', 'tf.add', (['true_positive', 'true_negative'], {}), '(true_positive, true_negative)\n', (6821, 6851), True, 'import tensorflow as tf\n'), ((6853, 6873), 'tensorflow.add', 'tf.add', (['nsize', 'psize'], {}), '(nsize, psize)\n', (6859, 6873), True, 'import tensorflow as tf\n'), ((10122, 10177), 'zqtflearn.get_layer_variables_by_name', 'zqtflearn.get_layer_variables_by_name', (['"""EmbeddingLayer"""'], {}), "('EmbeddingLayer')\n", (10159, 10177), False, 'import zqtflearn\n'), ((11948, 12012), 'zqtflearn.dropout', 'zqtflearn.dropout', (['network', '(0.5)'], {'name': "('deep_dropout%d' % (k + 1))"}), "(network, 0.5, name='deep_dropout%d' % (k + 1))\n", (11965, 12012), False, 'import zqtflearn\n'), ((16914, 16929), 'numpy.exp', 'np.exp', (['(-logits)'], {}), '(-logits)\n', (16920, 16929), True, 'import numpy as np\n'), ((6378, 6391), 'tensorflow.shape', 'tf.shape', (['pos'], {}), '(pos)\n', (6386, 6391), True, 'import tensorflow as tf\n'), ((6434, 6447), 'tensorflow.shape', 'tf.shape', (['neg'], {}), '(neg)\n', (6442, 6447), True, 'import tensorflow as tf\n'), ((4946, 4963), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (4961, 4963), True, 'import numpy as np\n')] |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD-3
import copy
import pytest
import numpy as np
from braindecode.datasets import MOABBDataset
from braindecode.datautil.preprocess import preprocess, zscore, scale, \
Preprocessor, filterbank, exponential_moving_demean, \
exponential_moving_standardize, MNEPreproc, NumpyPreproc
from braindecode.datautil.windowers import create_fixed_length_windows
# We can't use fixtures with scope='module' as the dataset objects are modified
# inplace during preprocessing. To avoid the long setup time caused by calling
# the dataset/windowing functions multiple times, we instantiate the dataset
# objects once and deep-copy them in fixture.
raw_ds = MOABBDataset(dataset_name='BNCI2014001', subject_ids=[1, 2])
windows_ds = create_fixed_length_windows(
raw_ds, start_offset_samples=100, stop_offset_samples=None,
window_size_samples=1000, window_stride_samples=1000,
drop_last_window=True, mapping=None, preload=True)
@pytest.fixture
def base_concat_ds():
return copy.deepcopy(raw_ds)
@pytest.fixture
def windows_concat_ds():
return copy.deepcopy(windows_ds)
def modify_windows_object(epochs, factor=1):
epochs._data *= factor
def test_not_list():
with pytest.raises(AssertionError):
preprocess(None, {'test': 1})
def test_no_raw_or_epochs():
class EmptyDataset(object):
def __init__(self):
self.datasets = [1, 2, 3]
ds = EmptyDataset()
with pytest.raises(AssertionError):
preprocess(ds, ["dummy", "dummy"])
def test_deprecated_preprocs(base_concat_ds):
msg1 = 'MNEPreproc is deprecated. Use Preprocessor with ' \
'`apply_on_array=False` instead.'
msg2 = 'NumpyPreproc is deprecated. Use Preprocessor with ' \
'`apply_on_array=True` instead.'
with pytest.warns(UserWarning, match=msg1):
mne_preproc = MNEPreproc('pick_types', eeg=True, meg=False, stim=False)
factor = 1e6
with pytest.warns(UserWarning, match=msg2):
np_preproc = NumpyPreproc(scale, factor=factor)
raw_timepoint = base_concat_ds[0][0][:22] # only keep EEG channels
preprocess(base_concat_ds, [mne_preproc, np_preproc])
np.testing.assert_allclose(base_concat_ds[0][0], raw_timepoint * factor,
rtol=1e-4, atol=1e-4)
def test_method_not_available(base_concat_ds):
preprocessors = [Preprocessor('this_method_is_not_real', )]
with pytest.raises(AttributeError):
preprocess(base_concat_ds, preprocessors)
def test_preprocess_raw_str(base_concat_ds):
preprocessors = [Preprocessor('crop', tmax=10, include_tmax=False)]
preprocess(base_concat_ds, preprocessors)
assert len(base_concat_ds.datasets[0].raw.times) == 2500
def test_preprocess_windows_str(windows_concat_ds):
preprocessors = [
Preprocessor('crop', tmin=0, tmax=0.1, include_tmax=False)]
preprocess(windows_concat_ds, preprocessors)
assert windows_concat_ds[0][0].shape[1] == 25
def test_preprocess_raw_callable_on_array(base_concat_ds):
# Case tested in test_zscore_continuous
pass
def test_preprocess_windows_callable_on_array(windows_concat_ds):
# Case tested in test_zscore_windows
pass
def test_preprocess_raw_callable_on_object(base_concat_ds):
# Case tested in test_filterbank
pass
def test_preprocess_windows_callable_on_object(windows_concat_ds):
factor = 10
preprocessors = [Preprocessor(modify_windows_object, apply_on_array=False,
factor=factor)]
raw_window = windows_concat_ds[0][0]
preprocess(windows_concat_ds, preprocessors)
np.testing.assert_allclose(windows_concat_ds[0][0], raw_window * factor,
rtol=1e-4, atol=1e-4)
def test_zscore_continuous(base_concat_ds):
preprocessors = [
Preprocessor('pick_types', eeg=True, meg=False, stim=False),
Preprocessor(zscore, channel_wise=True)
]
preprocess(base_concat_ds, preprocessors)
for ds in base_concat_ds.datasets:
raw_data = ds.raw.get_data()
shape = raw_data.shape
# zero mean
expected = np.zeros(shape[:-1])
np.testing.assert_allclose(
raw_data.mean(axis=-1), expected, rtol=1e-4, atol=1e-4)
# unit variance
expected = np.ones(shape[:-1])
np.testing.assert_allclose(
raw_data.std(axis=-1), expected, rtol=1e-4, atol=1e-4)
def test_zscore_windows(windows_concat_ds):
preprocessors = [
Preprocessor('pick_types', eeg=True, meg=False, stim=False),
Preprocessor(zscore)
]
preprocess(windows_concat_ds, preprocessors)
for ds in windows_concat_ds.datasets:
windowed_data = ds.windows.get_data()
shape = windowed_data.shape
# zero mean
expected = np.zeros(shape[:-1])
np.testing.assert_allclose(
windowed_data.mean(axis=-1), expected, rtol=1e-4, atol=1e-4)
# unit variance
expected = np.ones(shape[:-1])
np.testing.assert_allclose(
windowed_data.std(axis=-1), expected, rtol=1e-4, atol=1e-4)
def test_scale_continuous(base_concat_ds):
factor = 1e6
preprocessors = [
Preprocessor('pick_types', eeg=True, meg=False, stim=False),
Preprocessor(scale, factor=factor)
]
raw_timepoint = base_concat_ds[0][0][:22] # only keep EEG channels
preprocess(base_concat_ds, preprocessors)
np.testing.assert_allclose(base_concat_ds[0][0], raw_timepoint * factor,
rtol=1e-4, atol=1e-4)
def test_scale_windows(windows_concat_ds):
factor = 1e6
preprocessors = [
Preprocessor('pick_types', eeg=True, meg=False, stim=False),
Preprocessor(scale, factor=factor)
]
raw_window = windows_concat_ds[0][0][:22] # only keep EEG channels
preprocess(windows_concat_ds, preprocessors)
np.testing.assert_allclose(windows_concat_ds[0][0], raw_window * factor,
rtol=1e-4, atol=1e-4)
@pytest.fixture(scope='module')
def mock_data():
mock_input = np.random.RandomState(20200217).rand(2, 10).reshape(2, 10)
expected_standardized = np.array(
[[ 0. , -1.41385996, -1.67770482, 1.95328935, 0.61618697,
-0.55294099, -1.08890304, 1.04546089, -1.368485 , -1.08669994],
[ 0. , -1.41385996, -0.41117774, 1.65212819, -0.5392431 ,
-0.23009334, 0.15087203, -1.45238971, 1.88407553, -0.38583499]])
expected_demeaned = np.array(
[[ 0. , -0.02547392, -0.10004415, 0.47681459, 0.1399319 ,
-0.11764405, -0.23535964, 0.22749205, -0.3155749 , -0.25316515],
[ 0. , -0.29211105, -0.07138808, 0.44137798, -0.13274718,
-0.0519248 , 0.03156507, -0.33137195, 0.52134583, -0.1020266 ]])
return mock_input, expected_standardized, expected_demeaned
def test_exponential_running_standardize(mock_data):
mock_input, expected_data, _ = mock_data
standardized_data = exponential_moving_standardize(mock_input)
assert mock_input.shape == standardized_data.shape == expected_data.shape
np.testing.assert_allclose(
standardized_data, expected_data, rtol=1e-4, atol=1e-4)
def test_exponential_running_demean(mock_data):
mock_input, _, expected_data = mock_data
demeaned_data = exponential_moving_demean(mock_input)
assert mock_input.shape == demeaned_data.shape == expected_data.shape
np.testing.assert_allclose(
demeaned_data, expected_data, rtol=1e-4, atol=1e-4)
def test_exponential_running_init_block_size(mock_data):
mock_input, _, _ = mock_data
init_block_size = 3
standardized_data = exponential_moving_standardize(
mock_input, init_block_size=init_block_size)
# mean over time axis (1!) should give 0 per channel
np.testing.assert_allclose(
standardized_data[:, :init_block_size].mean(axis=1), 0,
rtol=1e-4, atol=1e-4)
np.testing.assert_allclose(
standardized_data[:, :init_block_size].std(axis=1), 1,
rtol=1e-4, atol=1e-4)
# mean over time axis (1!) should give 0 per channel
demeaned_data = exponential_moving_demean(
mock_input, init_block_size=init_block_size)
np.testing.assert_allclose(
demeaned_data[:, :init_block_size].mean(axis=1), 0, rtol=1e-4,
atol=1e-4)
def test_filterbank(base_concat_ds):
base_concat_ds = base_concat_ds.split([[0]])['0']
preprocessors = [
Preprocessor('pick_channels', ch_names=sorted(['C4', 'Cz']),
ordered=True),
Preprocessor(filterbank, frequency_bands=[(0, 4), (4, 8), (8, 13)],
drop_original_signals=False, apply_on_array=False)
]
preprocess(base_concat_ds, preprocessors)
for x, y in base_concat_ds:
break
assert x.shape[0] == 8
freq_band_annots = [
ch.split('_')[-1]
for ch in base_concat_ds.datasets[0].raw.ch_names
if '_' in ch]
assert len(np.unique(freq_band_annots)) == 3
np.testing.assert_array_equal(base_concat_ds.datasets[0].raw.ch_names, [
'C4', 'C4_0-4', 'C4_4-8', 'C4_8-13',
'Cz', 'Cz_0-4', 'Cz_4-8', 'Cz_8-13',
])
def test_filterbank_order_channels_by_freq(base_concat_ds):
base_concat_ds = base_concat_ds.split([[0]])['0']
preprocessors = [
Preprocessor(
'pick_channels', ch_names=sorted(['C4', 'Cz']), ordered=True),
Preprocessor(
filterbank, frequency_bands=[(0, 4), (4, 8), (8, 13)],
drop_original_signals=False, order_by_frequency_band=True,
apply_on_array=False)]
preprocess(base_concat_ds, preprocessors)
np.testing.assert_array_equal(base_concat_ds.datasets[0].raw.ch_names, [
'C4', 'Cz', 'C4_0-4', 'Cz_0-4',
'C4_4-8', 'Cz_4-8', 'C4_8-13', 'Cz_8-13'
])
| [
"braindecode.datautil.preprocess.exponential_moving_standardize",
"braindecode.datautil.preprocess.Preprocessor",
"braindecode.datautil.preprocess.MNEPreproc",
"numpy.ones",
"braindecode.datautil.preprocess.preprocess",
"numpy.unique",
"pytest.warns",
"numpy.random.RandomState",
"pytest.raises",
"... | [((726, 786), 'braindecode.datasets.MOABBDataset', 'MOABBDataset', ([], {'dataset_name': '"""BNCI2014001"""', 'subject_ids': '[1, 2]'}), "(dataset_name='BNCI2014001', subject_ids=[1, 2])\n", (738, 786), False, 'from braindecode.datasets import MOABBDataset\n'), ((800, 1004), 'braindecode.datautil.windowers.create_fixed_length_windows', 'create_fixed_length_windows', (['raw_ds'], {'start_offset_samples': '(100)', 'stop_offset_samples': 'None', 'window_size_samples': '(1000)', 'window_stride_samples': '(1000)', 'drop_last_window': '(True)', 'mapping': 'None', 'preload': '(True)'}), '(raw_ds, start_offset_samples=100,\n stop_offset_samples=None, window_size_samples=1000,\n window_stride_samples=1000, drop_last_window=True, mapping=None,\n preload=True)\n', (827, 1004), False, 'from braindecode.datautil.windowers import create_fixed_length_windows\n'), ((6059, 6089), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (6073, 6089), False, 'import pytest\n'), ((1057, 1078), 'copy.deepcopy', 'copy.deepcopy', (['raw_ds'], {}), '(raw_ds)\n', (1070, 1078), False, 'import copy\n'), ((1133, 1158), 'copy.deepcopy', 'copy.deepcopy', (['windows_ds'], {}), '(windows_ds)\n', (1146, 1158), False, 'import copy\n'), ((2164, 2217), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', '[mne_preproc, np_preproc]'], {}), '(base_concat_ds, [mne_preproc, np_preproc])\n', (2174, 2217), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2222, 2324), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['base_concat_ds[0][0]', '(raw_timepoint * factor)'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(base_concat_ds[0][0], raw_timepoint * factor,\n rtol=0.0001, atol=0.0001)\n', (2248, 2324), True, 'import numpy as np\n'), ((2674, 2715), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (2684, 2715), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2925, 2969), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['windows_concat_ds', 'preprocessors'], {}), '(windows_concat_ds, preprocessors)\n', (2935, 2969), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((3619, 3663), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['windows_concat_ds', 'preprocessors'], {}), '(windows_concat_ds, preprocessors)\n', (3629, 3663), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((3668, 3770), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['windows_concat_ds[0][0]', '(raw_window * factor)'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(windows_concat_ds[0][0], raw_window * factor,\n rtol=0.0001, atol=0.0001)\n', (3694, 3770), True, 'import numpy as np\n'), ((3989, 4030), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (3999, 4030), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((4644, 4688), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['windows_concat_ds', 'preprocessors'], {}), '(windows_concat_ds, preprocessors)\n', (4654, 4688), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5431, 5472), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (5441, 5472), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5477, 5579), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['base_concat_ds[0][0]', '(raw_timepoint * factor)'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(base_concat_ds[0][0], raw_timepoint * factor,\n rtol=0.0001, atol=0.0001)\n', (5503, 5579), True, 'import numpy as np\n'), ((5881, 5925), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['windows_concat_ds', 'preprocessors'], {}), '(windows_concat_ds, preprocessors)\n', (5891, 5925), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5930, 6032), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['windows_concat_ds[0][0]', '(raw_window * factor)'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(windows_concat_ds[0][0], raw_window * factor,\n rtol=0.0001, atol=0.0001)\n', (5956, 6032), True, 'import numpy as np\n'), ((6211, 6475), 'numpy.array', 'np.array', (['[[0.0, -1.41385996, -1.67770482, 1.95328935, 0.61618697, -0.55294099, -\n 1.08890304, 1.04546089, -1.368485, -1.08669994], [0.0, -1.41385996, -\n 0.41117774, 1.65212819, -0.5392431, -0.23009334, 0.15087203, -\n 1.45238971, 1.88407553, -0.38583499]]'], {}), '([[0.0, -1.41385996, -1.67770482, 1.95328935, 0.61618697, -\n 0.55294099, -1.08890304, 1.04546089, -1.368485, -1.08669994], [0.0, -\n 1.41385996, -0.41117774, 1.65212819, -0.5392431, -0.23009334, \n 0.15087203, -1.45238971, 1.88407553, -0.38583499]])\n', (6219, 6475), True, 'import numpy as np\n'), ((6548, 6811), 'numpy.array', 'np.array', (['[[0.0, -0.02547392, -0.10004415, 0.47681459, 0.1399319, -0.11764405, -\n 0.23535964, 0.22749205, -0.3155749, -0.25316515], [0.0, -0.29211105, -\n 0.07138808, 0.44137798, -0.13274718, -0.0519248, 0.03156507, -\n 0.33137195, 0.52134583, -0.1020266]]'], {}), '([[0.0, -0.02547392, -0.10004415, 0.47681459, 0.1399319, -\n 0.11764405, -0.23535964, 0.22749205, -0.3155749, -0.25316515], [0.0, -\n 0.29211105, -0.07138808, 0.44137798, -0.13274718, -0.0519248, \n 0.03156507, -0.33137195, 0.52134583, -0.1020266]])\n', (6556, 6811), True, 'import numpy as np\n'), ((7049, 7091), 'braindecode.datautil.preprocess.exponential_moving_standardize', 'exponential_moving_standardize', (['mock_input'], {}), '(mock_input)\n', (7079, 7091), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((7174, 7264), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['standardized_data', 'expected_data'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(standardized_data, expected_data, rtol=0.0001,\n atol=0.0001)\n', (7200, 7264), True, 'import numpy as np\n'), ((7381, 7418), 'braindecode.datautil.preprocess.exponential_moving_demean', 'exponential_moving_demean', (['mock_input'], {}), '(mock_input)\n', (7406, 7418), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((7497, 7584), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['demeaned_data', 'expected_data'], {'rtol': '(0.0001)', 'atol': '(0.0001)'}), '(demeaned_data, expected_data, rtol=0.0001, atol=\n 0.0001)\n', (7523, 7584), True, 'import numpy as np\n'), ((7725, 7800), 'braindecode.datautil.preprocess.exponential_moving_standardize', 'exponential_moving_standardize', (['mock_input'], {'init_block_size': 'init_block_size'}), '(mock_input, init_block_size=init_block_size)\n', (7755, 7800), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((8196, 8266), 'braindecode.datautil.preprocess.exponential_moving_demean', 'exponential_moving_demean', (['mock_input'], {'init_block_size': 'init_block_size'}), '(mock_input, init_block_size=init_block_size)\n', (8221, 8266), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((8776, 8817), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (8786, 8817), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((9075, 9226), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['base_concat_ds.datasets[0].raw.ch_names', "['C4', 'C4_0-4', 'C4_4-8', 'C4_8-13', 'Cz', 'Cz_0-4', 'Cz_4-8', 'Cz_8-13']"], {}), "(base_concat_ds.datasets[0].raw.ch_names, [\n 'C4', 'C4_0-4', 'C4_4-8', 'C4_8-13', 'Cz', 'Cz_0-4', 'Cz_4-8', 'Cz_8-13'])\n", (9104, 9226), True, 'import numpy as np\n'), ((9679, 9720), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (9689, 9720), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((9725, 9876), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['base_concat_ds.datasets[0].raw.ch_names', "['C4', 'Cz', 'C4_0-4', 'Cz_0-4', 'C4_4-8', 'Cz_4-8', 'C4_8-13', 'Cz_8-13']"], {}), "(base_concat_ds.datasets[0].raw.ch_names, [\n 'C4', 'Cz', 'C4_0-4', 'Cz_0-4', 'C4_4-8', 'Cz_4-8', 'C4_8-13', 'Cz_8-13'])\n", (9754, 9876), True, 'import numpy as np\n'), ((1265, 1294), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (1278, 1294), False, 'import pytest\n'), ((1304, 1333), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['None', "{'test': 1}"], {}), "(None, {'test': 1})\n", (1314, 1333), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((1497, 1526), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (1510, 1526), False, 'import pytest\n'), ((1536, 1570), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['ds', "['dummy', 'dummy']"], {}), "(ds, ['dummy', 'dummy'])\n", (1546, 1570), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((1847, 1884), 'pytest.warns', 'pytest.warns', (['UserWarning'], {'match': 'msg1'}), '(UserWarning, match=msg1)\n', (1859, 1884), False, 'import pytest\n'), ((1908, 1965), 'braindecode.datautil.preprocess.MNEPreproc', 'MNEPreproc', (['"""pick_types"""'], {'eeg': '(True)', 'meg': '(False)', 'stim': '(False)'}), "('pick_types', eeg=True, meg=False, stim=False)\n", (1918, 1965), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((1992, 2029), 'pytest.warns', 'pytest.warns', (['UserWarning'], {'match': 'msg2'}), '(UserWarning, match=msg2)\n', (2004, 2029), False, 'import pytest\n'), ((2052, 2086), 'braindecode.datautil.preprocess.NumpyPreproc', 'NumpyPreproc', (['scale'], {'factor': 'factor'}), '(scale, factor=factor)\n', (2064, 2086), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2418, 2457), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""this_method_is_not_real"""'], {}), "('this_method_is_not_real')\n", (2430, 2457), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2470, 2499), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (2483, 2499), False, 'import pytest\n'), ((2509, 2550), 'braindecode.datautil.preprocess.preprocess', 'preprocess', (['base_concat_ds', 'preprocessors'], {}), '(base_concat_ds, preprocessors)\n', (2519, 2550), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2619, 2668), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""crop"""'], {'tmax': '(10)', 'include_tmax': '(False)'}), "('crop', tmax=10, include_tmax=False)\n", (2631, 2668), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((2861, 2919), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""crop"""'], {'tmin': '(0)', 'tmax': '(0.1)', 'include_tmax': '(False)'}), "('crop', tmin=0, tmax=0.1, include_tmax=False)\n", (2873, 2919), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((3466, 3538), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['modify_windows_object'], {'apply_on_array': '(False)', 'factor': 'factor'}), '(modify_windows_object, apply_on_array=False, factor=factor)\n', (3478, 3538), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((3870, 3929), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""pick_types"""'], {'eeg': '(True)', 'meg': '(False)', 'stim': '(False)'}), "('pick_types', eeg=True, meg=False, stim=False)\n", (3882, 3929), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((3939, 3978), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['zscore'], {'channel_wise': '(True)'}), '(zscore, channel_wise=True)\n', (3951, 3978), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((4177, 4197), 'numpy.zeros', 'np.zeros', (['shape[:-1]'], {}), '(shape[:-1])\n', (4185, 4197), True, 'import numpy as np\n'), ((4345, 4364), 'numpy.ones', 'np.ones', (['shape[:-1]'], {}), '(shape[:-1])\n', (4352, 4364), True, 'import numpy as np\n'), ((4544, 4603), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""pick_types"""'], {'eeg': '(True)', 'meg': '(False)', 'stim': '(False)'}), "('pick_types', eeg=True, meg=False, stim=False)\n", (4556, 4603), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((4613, 4633), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['zscore'], {}), '(zscore)\n', (4625, 4633), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((4852, 4872), 'numpy.zeros', 'np.zeros', (['shape[:-1]'], {}), '(shape[:-1])\n', (4860, 4872), True, 'import numpy as np\n'), ((5025, 5044), 'numpy.ones', 'np.ones', (['shape[:-1]'], {}), '(shape[:-1])\n', (5032, 5044), True, 'import numpy as np\n'), ((5245, 5304), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""pick_types"""'], {'eeg': '(True)', 'meg': '(False)', 'stim': '(False)'}), "('pick_types', eeg=True, meg=False, stim=False)\n", (5257, 5304), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5314, 5348), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['scale'], {'factor': 'factor'}), '(scale, factor=factor)\n', (5326, 5348), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5695, 5754), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['"""pick_types"""'], {'eeg': '(True)', 'meg': '(False)', 'stim': '(False)'}), "('pick_types', eeg=True, meg=False, stim=False)\n", (5707, 5754), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((5764, 5798), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['scale'], {'factor': 'factor'}), '(scale, factor=factor)\n', (5776, 5798), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((8626, 8748), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['filterbank'], {'frequency_bands': '[(0, 4), (4, 8), (8, 13)]', 'drop_original_signals': '(False)', 'apply_on_array': '(False)'}), '(filterbank, frequency_bands=[(0, 4), (4, 8), (8, 13)],\n drop_original_signals=False, apply_on_array=False)\n', (8638, 8748), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((9488, 9644), 'braindecode.datautil.preprocess.Preprocessor', 'Preprocessor', (['filterbank'], {'frequency_bands': '[(0, 4), (4, 8), (8, 13)]', 'drop_original_signals': '(False)', 'order_by_frequency_band': '(True)', 'apply_on_array': '(False)'}), '(filterbank, frequency_bands=[(0, 4), (4, 8), (8, 13)],\n drop_original_signals=False, order_by_frequency_band=True,\n apply_on_array=False)\n', (9500, 9644), False, 'from braindecode.datautil.preprocess import preprocess, zscore, scale, Preprocessor, filterbank, exponential_moving_demean, exponential_moving_standardize, MNEPreproc, NumpyPreproc\n'), ((9037, 9064), 'numpy.unique', 'np.unique', (['freq_band_annots'], {}), '(freq_band_annots)\n', (9046, 9064), True, 'import numpy as np\n'), ((6124, 6155), 'numpy.random.RandomState', 'np.random.RandomState', (['(20200217)'], {}), '(20200217)\n', (6145, 6155), True, 'import numpy as np\n')] |
# Copyright (c) 2019, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pytest
import cudf
import numpy as np
import pandas as pd
from cuml import Lasso as cuLasso
from sklearn.linear_model import Lasso
from cuml.linear_model import ElasticNet as cuElasticNet
from sklearn.linear_model import ElasticNet
from cuml.test.utils import array_equal
from sklearn.datasets import make_regression
def unit_param(*args, **kwargs):
return pytest.param(*args, **kwargs, marks=pytest.mark.unit)
def quality_param(*args, **kwargs):
return pytest.param(*args, **kwargs, marks=pytest.mark.quality)
def stress_param(*args, **kwargs):
return pytest.param(*args, **kwargs, marks=pytest.mark.stress)
@pytest.mark.parametrize('datatype', [np.float32, np.float64])
@pytest.mark.parametrize('X_type', ['dataframe', 'ndarray'])
@pytest.mark.parametrize('lr', [0.1, 0.001])
@pytest.mark.parametrize('algorithm', ['cyclic', 'random'])
@pytest.mark.parametrize('nrows', [unit_param(20), quality_param(5000),
stress_param(500000)])
@pytest.mark.parametrize('ncols', [unit_param(3), quality_param(100),
stress_param(1000)])
@pytest.mark.parametrize('n_info', [unit_param(2), quality_param(50),
stress_param(500)])
def test_lasso(datatype, X_type, lr, algorithm,
nrows, ncols, n_info):
train_rows = np.int32(nrows*0.8)
X, y = make_regression(n_samples=nrows, n_features=ncols,
n_informative=n_info, random_state=0)
X_test = np.asarray(X[train_rows:, 0:], dtype=datatype)
X_train = np.asarray(X[0:train_rows, :], dtype=datatype)
y_train = np.asarray(y[0:train_rows, ], dtype=datatype)
if nrows != 500000:
sk_lasso = Lasso(alpha=np.array([lr]), fit_intercept=True,
normalize=False, max_iter=1000,
selection=algorithm, tol=1e-10)
sk_lasso.fit(X_train, y_train)
cu_lasso = cuLasso(alpha=np.array([lr]), fit_intercept=True,
normalize=False, max_iter=1000,
selection=algorithm, tol=1e-10)
if X_type == 'dataframe':
y_train = pd.DataFrame({'fea0': y_train[0:, ]})
X_train = pd.DataFrame(
{'fea%d' % i: X_train[0:, i] for i in range(X_train.shape[1])})
X_test = pd.DataFrame(
{'fea%d' % i: X_test[0:, i] for i in range(X_test.shape[1])})
X_cudf = cudf.DataFrame.from_pandas(X_train)
X_cudf_test = cudf.DataFrame.from_pandas(X_test)
y_cudf = y_train.values
y_cudf = y_cudf[:, 0]
y_cudf = cudf.Series(y_cudf)
cu_lasso.fit(X_cudf, y_cudf)
cu_predict = cu_lasso.predict(X_cudf_test)
elif X_type == 'ndarray':
cu_lasso.fit(X_train, y_train)
cu_predict = cu_lasso.predict(X_test)
if nrows != 500000:
sk_predict = sk_lasso.predict(X_test)
assert array_equal(sk_predict, cu_predict, 1e-1, with_sign=True)
@pytest.mark.parametrize('datatype', [np.float32, np.float64])
@pytest.mark.parametrize('X_type', ['dataframe', 'ndarray'])
@pytest.mark.parametrize('lr', [0.1, 0.001])
@pytest.mark.parametrize('algorithm', ['cyclic', 'random'])
@pytest.mark.parametrize('nrows', [unit_param(20), quality_param(5000),
stress_param(500000)])
@pytest.mark.parametrize('ncols', [unit_param(3), quality_param(100),
stress_param(1000)])
@pytest.mark.parametrize('n_info', [unit_param(2), quality_param(50),
stress_param(500)])
def test_elastic_net(datatype, X_type, lr, algorithm,
nrows, ncols, n_info):
train_rows = np.int32(nrows*0.8)
X, y = make_regression(n_samples=nrows, n_features=ncols,
n_informative=n_info, random_state=0)
X_test = np.asarray(X[train_rows:, 0:], dtype=datatype)
X_train = np.asarray(X[0:train_rows, :], dtype=datatype)
y_train = np.asarray(y[0:train_rows, ], dtype=datatype)
if nrows != 500000:
elastic_sk = ElasticNet(alpha=np.array([0.1]), fit_intercept=True,
normalize=False, max_iter=1000,
selection=algorithm, tol=1e-10)
elastic_sk.fit(X_train, y_train)
elastic_cu = cuElasticNet(alpha=np.array([0.1]), fit_intercept=True,
normalize=False, max_iter=1000,
selection=algorithm, tol=1e-10)
if X_type == 'dataframe':
y_train = pd.DataFrame({'fea0': y_train[0:, ]})
X_train = pd.DataFrame(
{'fea%d' % i: X_train[0:, i] for i in range(X_train.shape[1])})
X_test = pd.DataFrame(
{'fea%d' % i: X_test[0:, i] for i in range(X_test.shape[1])})
X_cudf = cudf.DataFrame.from_pandas(X_train)
X_cudf_test = cudf.DataFrame.from_pandas(X_test)
y_cudf = y_train.values
y_cudf = y_cudf[:, 0]
y_cudf = cudf.Series(y_cudf)
elastic_cu.fit(X_cudf, y_cudf)
cu_predict = elastic_cu.predict(X_cudf_test)
elif X_type == 'ndarray':
elastic_cu.fit(X_train, y_train)
cu_predict = elastic_cu.predict(X_test)
if nrows != 500000:
sk_predict = elastic_sk.predict(X_test)
assert array_equal(sk_predict, cu_predict, 1e-1, with_sign=True)
| [
"pandas.DataFrame",
"cuml.test.utils.array_equal",
"cudf.Series",
"cudf.DataFrame.from_pandas",
"numpy.asarray",
"sklearn.datasets.make_regression",
"pytest.param",
"numpy.array",
"numpy.int32",
"pytest.mark.parametrize"
] | [((1228, 1289), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""datatype"""', '[np.float32, np.float64]'], {}), "('datatype', [np.float32, np.float64])\n", (1251, 1289), False, 'import pytest\n'), ((1291, 1350), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""X_type"""', "['dataframe', 'ndarray']"], {}), "('X_type', ['dataframe', 'ndarray'])\n", (1314, 1350), False, 'import pytest\n'), ((1352, 1395), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""lr"""', '[0.1, 0.001]'], {}), "('lr', [0.1, 0.001])\n", (1375, 1395), False, 'import pytest\n'), ((1397, 1455), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""algorithm"""', "['cyclic', 'random']"], {}), "('algorithm', ['cyclic', 'random'])\n", (1420, 1455), False, 'import pytest\n'), ((3521, 3582), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""datatype"""', '[np.float32, np.float64]'], {}), "('datatype', [np.float32, np.float64])\n", (3544, 3582), False, 'import pytest\n'), ((3584, 3643), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""X_type"""', "['dataframe', 'ndarray']"], {}), "('X_type', ['dataframe', 'ndarray'])\n", (3607, 3643), False, 'import pytest\n'), ((3645, 3688), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""lr"""', '[0.1, 0.001]'], {}), "('lr', [0.1, 0.001])\n", (3668, 3688), False, 'import pytest\n'), ((3690, 3748), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""algorithm"""', "['cyclic', 'random']"], {}), "('algorithm', ['cyclic', 'random'])\n", (3713, 3748), False, 'import pytest\n'), ((961, 1014), 'pytest.param', 'pytest.param', (['*args'], {'marks': 'pytest.mark.unit'}), '(*args, **kwargs, marks=pytest.mark.unit)\n', (973, 1014), False, 'import pytest\n'), ((1064, 1120), 'pytest.param', 'pytest.param', (['*args'], {'marks': 'pytest.mark.quality'}), '(*args, **kwargs, marks=pytest.mark.quality)\n', (1076, 1120), False, 'import pytest\n'), ((1169, 1224), 'pytest.param', 'pytest.param', (['*args'], {'marks': 'pytest.mark.stress'}), '(*args, **kwargs, marks=pytest.mark.stress)\n', (1181, 1224), False, 'import pytest\n'), ((1911, 1932), 'numpy.int32', 'np.int32', (['(nrows * 0.8)'], {}), '(nrows * 0.8)\n', (1919, 1932), True, 'import numpy as np\n'), ((1942, 2034), 'sklearn.datasets.make_regression', 'make_regression', ([], {'n_samples': 'nrows', 'n_features': 'ncols', 'n_informative': 'n_info', 'random_state': '(0)'}), '(n_samples=nrows, n_features=ncols, n_informative=n_info,\n random_state=0)\n', (1957, 2034), False, 'from sklearn.datasets import make_regression\n'), ((2071, 2117), 'numpy.asarray', 'np.asarray', (['X[train_rows:, 0:]'], {'dtype': 'datatype'}), '(X[train_rows:, 0:], dtype=datatype)\n', (2081, 2117), True, 'import numpy as np\n'), ((2132, 2178), 'numpy.asarray', 'np.asarray', (['X[0:train_rows, :]'], {'dtype': 'datatype'}), '(X[0:train_rows, :], dtype=datatype)\n', (2142, 2178), True, 'import numpy as np\n'), ((2193, 2237), 'numpy.asarray', 'np.asarray', (['y[0:train_rows,]'], {'dtype': 'datatype'}), '(y[0:train_rows,], dtype=datatype)\n', (2203, 2237), True, 'import numpy as np\n'), ((4216, 4237), 'numpy.int32', 'np.int32', (['(nrows * 0.8)'], {}), '(nrows * 0.8)\n', (4224, 4237), True, 'import numpy as np\n'), ((4247, 4339), 'sklearn.datasets.make_regression', 'make_regression', ([], {'n_samples': 'nrows', 'n_features': 'ncols', 'n_informative': 'n_info', 'random_state': '(0)'}), '(n_samples=nrows, n_features=ncols, n_informative=n_info,\n random_state=0)\n', (4262, 4339), False, 'from sklearn.datasets import make_regression\n'), ((4377, 4423), 'numpy.asarray', 'np.asarray', (['X[train_rows:, 0:]'], {'dtype': 'datatype'}), '(X[train_rows:, 0:], dtype=datatype)\n', (4387, 4423), True, 'import numpy as np\n'), ((4438, 4484), 'numpy.asarray', 'np.asarray', (['X[0:train_rows, :]'], {'dtype': 'datatype'}), '(X[0:train_rows, :], dtype=datatype)\n', (4448, 4484), True, 'import numpy as np\n'), ((4499, 4543), 'numpy.asarray', 'np.asarray', (['y[0:train_rows,]'], {'dtype': 'datatype'}), '(y[0:train_rows,], dtype=datatype)\n', (4509, 4543), True, 'import numpy as np\n'), ((2709, 2745), 'pandas.DataFrame', 'pd.DataFrame', (["{'fea0': y_train[0:,]}"], {}), "({'fea0': y_train[0:,]})\n", (2721, 2745), True, 'import pandas as pd\n'), ((2977, 3012), 'cudf.DataFrame.from_pandas', 'cudf.DataFrame.from_pandas', (['X_train'], {}), '(X_train)\n', (3003, 3012), False, 'import cudf\n'), ((3035, 3069), 'cudf.DataFrame.from_pandas', 'cudf.DataFrame.from_pandas', (['X_test'], {}), '(X_test)\n', (3061, 3069), False, 'import cudf\n'), ((3149, 3168), 'cudf.Series', 'cudf.Series', (['y_cudf'], {}), '(y_cudf)\n', (3160, 3168), False, 'import cudf\n'), ((3460, 3516), 'cuml.test.utils.array_equal', 'array_equal', (['sk_predict', 'cu_predict', '(0.1)'], {'with_sign': '(True)'}), '(sk_predict, cu_predict, 0.1, with_sign=True)\n', (3471, 3516), False, 'from cuml.test.utils import array_equal\n'), ((5062, 5098), 'pandas.DataFrame', 'pd.DataFrame', (["{'fea0': y_train[0:,]}"], {}), "({'fea0': y_train[0:,]})\n", (5074, 5098), True, 'import pandas as pd\n'), ((5330, 5365), 'cudf.DataFrame.from_pandas', 'cudf.DataFrame.from_pandas', (['X_train'], {}), '(X_train)\n', (5356, 5365), False, 'import cudf\n'), ((5388, 5422), 'cudf.DataFrame.from_pandas', 'cudf.DataFrame.from_pandas', (['X_test'], {}), '(X_test)\n', (5414, 5422), False, 'import cudf\n'), ((5502, 5521), 'cudf.Series', 'cudf.Series', (['y_cudf'], {}), '(y_cudf)\n', (5513, 5521), False, 'import cudf\n'), ((5823, 5879), 'cuml.test.utils.array_equal', 'array_equal', (['sk_predict', 'cu_predict', '(0.1)'], {'with_sign': '(True)'}), '(sk_predict, cu_predict, 0.1, with_sign=True)\n', (5834, 5879), False, 'from cuml.test.utils import array_equal\n'), ((2514, 2528), 'numpy.array', 'np.array', (['[lr]'], {}), '([lr])\n', (2522, 2528), True, 'import numpy as np\n'), ((4852, 4867), 'numpy.array', 'np.array', (['[0.1]'], {}), '([0.1])\n', (4860, 4867), True, 'import numpy as np\n'), ((2295, 2309), 'numpy.array', 'np.array', (['[lr]'], {}), '([lr])\n', (2303, 2309), True, 'import numpy as np\n'), ((4608, 4623), 'numpy.array', 'np.array', (['[0.1]'], {}), '([0.1])\n', (4616, 4623), True, 'import numpy as np\n')] |
import numpy as np
n = int(input())
a = np.array([input().split() for _ in range(n)],int)
b = np.array([input().split() for _ in range(n)],int)
print(np.dot(a,b)) | [
"numpy.dot"
] | [((152, 164), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (158, 164), True, 'import numpy as np\n')] |
import time
import requests
import multiprocessing
import numpy as np
from keras.models import load_model
from utils.img_process import process, yolo_img_process
import utils.yolo_util as yolo_util
from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset
from deepgtav.client import Client
import tensorflow as tf
import cv2
from PIL import Image
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
gamepad = None
url = "https://www.pixeldesert.com/compare"
config_position = "state.config"
client = None
scenario = None
IMAGE_H, IMAGE_W = 416, 416
CAP_IMG_W, CAP_IMG_H = 320, 240
dataset = Dataset(rate=10,
frame=[CAP_IMG_W, CAP_IMG_H],
throttle=True,
brake=True,
steering=True,
location=True,
drivingMode=True,
speed=True,
time=True
)
def state():
while True:
response = requests.request("POST", url)
fo = open(config_position, "w")
if response.text[1] == '0':
fo.write("0")
elif response.text[1] == '1':
fo.write("1")
fo.close()
time.sleep(2)
def set_gamepad(control, throttle, breakk):
if control == -1: # stop the car
client.sendMessage(Commands(0.0, 1, control))
return
client.sendMessage(Commands(float(throttle), float(breakk), float(control)))
# print(str(control)+","+str(throttle)+","+str(breakk))
# client.sendMessage(Commands(1, 0, 0))
def drive(model, image, speed, warning):
throttle = 0
breakk = 0
roi, radar = process(image)
controls = model.predict([np.array([roi]), np.array([radar]), np.array([speed])], batch_size=1)
controls = controls[0][0]*5/3.14
if controls > 0:
controls = controls
print("-->" + " speed=" + str(speed)+",controls="+str(controls))
else:
print("<--" + " speed=" + str(speed)+",controls="+str(controls))
if warning:
return controls, 0, 1
if speed < 5: # control speed
throttle = 1
elif speed < 20:
throttle = 0.5
elif speed > 25:
throttle = 0.0
breakk = 0.4
return controls, throttle, breakk
def main():
global client, scenario
client = Client(ip='localhost', port=8000) # Default interface
scenario = Scenario(weather='EXTRASUNNY', vehicle='blista', time=[12, 0], drivingMode=-1
, location=[-2583.6708984375, 3501.88232421875, 12.7711820602417])
client.sendMessage(Start(scenario=scenario, dataset=dataset))
print("load deepGTAV successfully! \nbegin")
# load yolo v3
classes = yolo_util.read_coco_names('./files/coco/coco.names')
num_classes = len(classes)
input_tensor, output_tensors = yolo_util.read_pb_return_tensors(tf.get_default_graph(),
"./files/trained_models/yolov3.pb",
["Placeholder:0", "concat_9:0", "mul_6:0"])
print("load yolo v3 successfully!")
with tf.Session() as sess:
model = load_model("files/trained_models/main_model.h5")
print("load main_model successfully!")
while True:
fo = open(config_position, "r") # 配置1
txt = fo.read()
fo.close()
if txt == '0':
set_gamepad(-1, -1, 0)
time.sleep(0.7)
print('=====================end=====================')
exit(0)
elif txt == '1':
message = client.recvMessage()
frame = frame2numpy(message['frame'], (CAP_IMG_W, CAP_IMG_H))
image_obj = Image.fromarray(frame)
speed = message['speed']
boxes, scores = sess.run(output_tensors, feed_dict={input_tensor: np.expand_dims(yolo_img_process(frame), axis=0)})
boxes, scores, labels = yolo_util.cpu_nms(boxes, scores, num_classes, score_thresh=0.4, iou_thresh=0.1)
image, warning = yolo_util.draw_boxes(image_obj, boxes, scores, labels, classes, (IMAGE_H, IMAGE_W), show=False)
control, throttle, breakk = drive(model=model, image=frame, speed=speed, warning=warning)
print(warning)
set_gamepad(control, throttle, breakk)
# show
# result = np.asarray(image)
# info = "warning:%s" % (str(warning))
# cv2.putText(result, text=info, org=(50, 70), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
# fontScale=1, color=(255, 0, 0), thickness=2)
# result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)
# cv2.imshow("result", result)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# break
# show end
if __name__ == '__main__':
while True:
response = requests.request("POST", url)
if response.text[1] == '1':
fo = open(config_position, "w")
fo.write("1")
fo.close()
print('$$$$$$$$$$$$$$$$$$$ after 3s will begin $$$$$$$$$$$$$$$$$$$')
i = 3
while i > 0:
print(i)
i = i - 1
time.sleep(1)
print('=====================start now!======================')
break
print("waiting for instructions...")
time.sleep(1)
p1 = multiprocessing.Process(target=state)
p2 = multiprocessing.Process(target=main)
p1.start()
p2.start()
| [
"keras.models.load_model",
"deepgtav.messages.Scenario",
"deepgtav.messages.Commands",
"tensorflow.ConfigProto",
"utils.yolo_util.read_coco_names",
"utils.yolo_util.cpu_nms",
"tensorflow.get_default_graph",
"deepgtav.messages.Dataset",
"deepgtav.messages.frame2numpy",
"requests.request",
"deepgt... | [((384, 400), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (398, 400), True, 'import tensorflow as tf\n'), ((447, 472), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (457, 472), True, 'import tensorflow as tf\n'), ((668, 816), 'deepgtav.messages.Dataset', 'Dataset', ([], {'rate': '(10)', 'frame': '[CAP_IMG_W, CAP_IMG_H]', 'throttle': '(True)', 'brake': '(True)', 'steering': '(True)', 'location': '(True)', 'drivingMode': '(True)', 'speed': '(True)', 'time': '(True)'}), '(rate=10, frame=[CAP_IMG_W, CAP_IMG_H], throttle=True, brake=True,\n steering=True, location=True, drivingMode=True, speed=True, time=True)\n', (675, 816), False, 'from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset\n'), ((1703, 1717), 'utils.img_process.process', 'process', (['image'], {}), '(image)\n', (1710, 1717), False, 'from utils.img_process import process, yolo_img_process\n'), ((2379, 2412), 'deepgtav.client.Client', 'Client', ([], {'ip': '"""localhost"""', 'port': '(8000)'}), "(ip='localhost', port=8000)\n", (2385, 2412), False, 'from deepgtav.client import Client\n'), ((2449, 2597), 'deepgtav.messages.Scenario', 'Scenario', ([], {'weather': '"""EXTRASUNNY"""', 'vehicle': '"""blista"""', 'time': '[12, 0]', 'drivingMode': '(-1)', 'location': '[-2583.6708984375, 3501.88232421875, 12.7711820602417]'}), "(weather='EXTRASUNNY', vehicle='blista', time=[12, 0], drivingMode=\n -1, location=[-2583.6708984375, 3501.88232421875, 12.7711820602417])\n", (2457, 2597), False, 'from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset\n'), ((2767, 2819), 'utils.yolo_util.read_coco_names', 'yolo_util.read_coco_names', (['"""./files/coco/coco.names"""'], {}), "('./files/coco/coco.names')\n", (2792, 2819), True, 'import utils.yolo_util as yolo_util\n'), ((5603, 5640), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'state'}), '(target=state)\n', (5626, 5640), False, 'import multiprocessing\n'), ((5650, 5686), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'main'}), '(target=main)\n', (5673, 5686), False, 'import multiprocessing\n'), ((1026, 1055), 'requests.request', 'requests.request', (['"""POST"""', 'url'], {}), "('POST', url)\n", (1042, 1055), False, 'import requests\n'), ((1249, 1262), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (1259, 1262), False, 'import time\n'), ((2641, 2682), 'deepgtav.messages.Start', 'Start', ([], {'scenario': 'scenario', 'dataset': 'dataset'}), '(scenario=scenario, dataset=dataset)\n', (2646, 2682), False, 'from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset\n'), ((2919, 2941), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2939, 2941), True, 'import tensorflow as tf\n'), ((3209, 3221), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3219, 3221), True, 'import tensorflow as tf\n'), ((3247, 3295), 'keras.models.load_model', 'load_model', (['"""files/trained_models/main_model.h5"""'], {}), "('files/trained_models/main_model.h5')\n", (3257, 3295), False, 'from keras.models import load_model\n'), ((5069, 5098), 'requests.request', 'requests.request', (['"""POST"""', 'url'], {}), "('POST', url)\n", (5085, 5098), False, 'import requests\n'), ((5579, 5592), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (5589, 5592), False, 'import time\n'), ((1381, 1406), 'deepgtav.messages.Commands', 'Commands', (['(0.0)', '(1)', 'control'], {}), '(0.0, 1, control)\n', (1389, 1406), False, 'from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset\n'), ((1749, 1764), 'numpy.array', 'np.array', (['[roi]'], {}), '([roi])\n', (1757, 1764), True, 'import numpy as np\n'), ((1766, 1783), 'numpy.array', 'np.array', (['[radar]'], {}), '([radar])\n', (1774, 1783), True, 'import numpy as np\n'), ((1785, 1802), 'numpy.array', 'np.array', (['[speed]'], {}), '([speed])\n', (1793, 1802), True, 'import numpy as np\n'), ((3547, 3562), 'time.sleep', 'time.sleep', (['(0.7)'], {}), '(0.7)\n', (3557, 3562), False, 'import time\n'), ((5419, 5432), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (5429, 5432), False, 'import time\n'), ((3758, 3811), 'deepgtav.messages.frame2numpy', 'frame2numpy', (["message['frame']", '(CAP_IMG_W, CAP_IMG_H)'], {}), "(message['frame'], (CAP_IMG_W, CAP_IMG_H))\n", (3769, 3811), False, 'from deepgtav.messages import Start, Stop, Scenario, Commands, frame2numpy, Dataset\n'), ((3840, 3862), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (3855, 3862), False, 'from PIL import Image\n'), ((4080, 4159), 'utils.yolo_util.cpu_nms', 'yolo_util.cpu_nms', (['boxes', 'scores', 'num_classes'], {'score_thresh': '(0.4)', 'iou_thresh': '(0.1)'}), '(boxes, scores, num_classes, score_thresh=0.4, iou_thresh=0.1)\n', (4097, 4159), True, 'import utils.yolo_util as yolo_util\n'), ((4193, 4292), 'utils.yolo_util.draw_boxes', 'yolo_util.draw_boxes', (['image_obj', 'boxes', 'scores', 'labels', 'classes', '(IMAGE_H, IMAGE_W)'], {'show': '(False)'}), '(image_obj, boxes, scores, labels, classes, (IMAGE_H,\n IMAGE_W), show=False)\n', (4213, 4292), True, 'import utils.yolo_util as yolo_util\n'), ((4005, 4028), 'utils.img_process.yolo_img_process', 'yolo_img_process', (['frame'], {}), '(frame)\n', (4021, 4028), False, 'from utils.img_process import process, yolo_img_process\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.