code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
""" Tests for cram.py """
import unittest
import numpy as np
import scipy.sparse as sp
from opendeplete.integrator import CRAM16, CRAM48
class TestCram(unittest.TestCase):
""" Tests for cram.py
Compares a few Mathematica matrix exponentials to CRAM16/CRAM48.
"""
def test_CRAM16(self):
""" Test 16-term CRAM. """
x = np.array([1.0, 1.0])
mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]])
dt = 0.1
z = CRAM16(mat, x, dt)
# Solution from mathematica
z0 = np.array((0.904837418035960, 0.576799023327476))
tol = 1.0e-15
self.assertLess(np.linalg.norm(z - z0), tol)
def test_CRAM48(self):
""" Test 48-term CRAM. """
x = np.array([1.0, 1.0])
mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]])
dt = 0.1
z = CRAM48(mat, x, dt)
# Solution from mathematica
z0 = np.array((0.904837418035960, 0.576799023327476))
tol = 1.0e-15
self.assertLess(np.linalg.norm(z - z0), tol)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"scipy.sparse.csr_matrix",
"numpy.array",
"opendeplete.integrator.CRAM48",
"numpy.linalg.norm",
"opendeplete.integrator.CRAM16"
] | [((1069, 1084), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1082, 1084), False, 'import unittest\n'), ((355, 375), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (363, 375), True, 'import numpy as np\n'), ((390, 432), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['[[-1.0, 0.0], [-2.0, -3.0]]'], {}), '([[-1.0, 0.0], [-2.0, -3.0]])\n', (403, 432), True, 'import scipy.sparse as sp\n'), ((463, 481), 'opendeplete.integrator.CRAM16', 'CRAM16', (['mat', 'x', 'dt'], {}), '(mat, x, dt)\n', (469, 481), False, 'from opendeplete.integrator import CRAM16, CRAM48\n'), ((532, 579), 'numpy.array', 'np.array', (['(0.90483741803596, 0.576799023327476)'], {}), '((0.90483741803596, 0.576799023327476))\n', (540, 579), True, 'import numpy as np\n'), ((733, 753), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (741, 753), True, 'import numpy as np\n'), ((768, 810), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['[[-1.0, 0.0], [-2.0, -3.0]]'], {}), '([[-1.0, 0.0], [-2.0, -3.0]])\n', (781, 810), True, 'import scipy.sparse as sp\n'), ((841, 859), 'opendeplete.integrator.CRAM48', 'CRAM48', (['mat', 'x', 'dt'], {}), '(mat, x, dt)\n', (847, 859), False, 'from opendeplete.integrator import CRAM16, CRAM48\n'), ((910, 957), 'numpy.array', 'np.array', (['(0.90483741803596, 0.576799023327476)'], {}), '((0.90483741803596, 0.576799023327476))\n', (918, 957), True, 'import numpy as np\n'), ((629, 651), 'numpy.linalg.norm', 'np.linalg.norm', (['(z - z0)'], {}), '(z - z0)\n', (643, 651), True, 'import numpy as np\n'), ((1007, 1029), 'numpy.linalg.norm', 'np.linalg.norm', (['(z - z0)'], {}), '(z - z0)\n', (1021, 1029), True, 'import numpy as np\n')] |
import numpy as np
import datetime
from datetime import timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
from util.app_util import AppUtil
from matplotlib.font_manager import FontProperties
class CapitalCurve(object):
@staticmethod
def draw_curve_demo():
dates = []
idx = 0.1
today = AppUtil.get_today_obj()
curr_date = AppUtil.parse_date('20190101')
ys = []
mu = 0
sigma = 10
num = 100
rand_data = np.random.normal(mu, sigma, num)
print(rand_data)
i = 0
while curr_date <= today:
dates.append(AppUtil.format_date(curr_date, AppUtil.DF_HYPHEN))
curr_date += timedelta(days=1)
ys.append(idx*idx + 100 + rand_data[i])
idx += 0.1
i += 1
xs = [datetime.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
font = FontProperties(fname='./work/simsun.ttc') # 载入中文字体
plt.rcParams['axes.unicode_minus']=False # 正确显示负号
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=(mdates.MO)))
plt.title('总资产变化曲线', fontproperties=font)
plt.xlabel('日期', fontproperties=font)
plt.ylabel('总资产(万元)' , fontproperties=font)
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"util.app_util.AppUtil.format_date",
"matplotlib.font_manager.FontProperties",
"matplotlib.pyplot.plot",
"util.app_util.AppUtil.parse_date",
"matplotlib.dates.WeekdayLocator",
"matplotlib.dates.DateFormatter",
"datetime.datetime.strptime",
"date... | [((377, 400), 'util.app_util.AppUtil.get_today_obj', 'AppUtil.get_today_obj', ([], {}), '()\n', (398, 400), False, 'from util.app_util import AppUtil\n'), ((421, 451), 'util.app_util.AppUtil.parse_date', 'AppUtil.parse_date', (['"""20190101"""'], {}), "('20190101')\n", (439, 451), False, 'from util.app_util import AppUtil\n'), ((540, 572), 'numpy.random.normal', 'np.random.normal', (['mu', 'sigma', 'num'], {}), '(mu, sigma, num)\n', (556, 572), True, 'import numpy as np\n'), ((954, 995), 'matplotlib.font_manager.FontProperties', 'FontProperties', ([], {'fname': '"""./work/simsun.ttc"""'}), "(fname='./work/simsun.ttc')\n", (968, 995), False, 'from matplotlib.font_manager import FontProperties\n'), ((1237, 1278), 'matplotlib.pyplot.title', 'plt.title', (['"""总资产变化曲线"""'], {'fontproperties': 'font'}), "('总资产变化曲线', fontproperties=font)\n", (1246, 1278), True, 'import matplotlib.pyplot as plt\n'), ((1287, 1324), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""日期"""'], {'fontproperties': 'font'}), "('日期', fontproperties=font)\n", (1297, 1324), True, 'import matplotlib.pyplot as plt\n'), ((1333, 1375), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""总资产(万元)"""'], {'fontproperties': 'font'}), "('总资产(万元)', fontproperties=font)\n", (1343, 1375), True, 'import matplotlib.pyplot as plt\n'), ((1385, 1401), 'matplotlib.pyplot.plot', 'plt.plot', (['xs', 'ys'], {}), '(xs, ys)\n', (1393, 1401), True, 'import matplotlib.pyplot as plt\n'), ((1445, 1455), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1453, 1455), True, 'import matplotlib.pyplot as plt\n'), ((747, 764), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (756, 764), False, 'from datetime import timedelta\n'), ((1107, 1139), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (1127, 1139), True, 'import matplotlib.dates as mdates\n'), ((1183, 1225), 'matplotlib.dates.WeekdayLocator', 'mdates.WeekdayLocator', ([], {'byweekday': 'mdates.MO'}), '(byweekday=mdates.MO)\n', (1204, 1225), True, 'import matplotlib.dates as mdates\n'), ((671, 720), 'util.app_util.AppUtil.format_date', 'AppUtil.format_date', (['curr_date', 'AppUtil.DF_HYPHEN'], {}), '(curr_date, AppUtil.DF_HYPHEN)\n', (690, 720), False, 'from util.app_util import AppUtil\n'), ((1410, 1419), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (1417, 1419), True, 'import matplotlib.pyplot as plt\n'), ((874, 915), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['d', '"""%Y-%m-%d"""'], {}), "(d, '%Y-%m-%d')\n", (900, 915), False, 'import datetime\n'), ((1071, 1080), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1078, 1080), True, 'import matplotlib.pyplot as plt\n'), ((1149, 1158), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1156, 1158), True, 'import matplotlib.pyplot as plt\n')] |
"""
Converter for the Kojak XL-MS search engine output formats.
"""
from itertools import chain
import numpy as np
import pandas as pd
def kojak(kojak_txt: str, perc_inter: str, perc_intra: str, out_file: str,
version: str = "2.0-dev", max_charge: int = 8,
decoy_prefix: str = "decoy_", to_pin: bool = False) -> None:
"""
Convert Kojak search results to xenith tab-delimited format.
For conversion, the Kojak searches must have been configured to
output files for Percolator.
Parameters
----------
kojak_txt : str
The path to the main kojak result file (.kojak.txt).
perc_inter : str
The path to the interprotein Percolator input file from Kojak
(.perc.inter.txt).
perc_intra : str
The path to the intraprotein Percolator input file from Kojak
(.perc.intra.txt)
out_file : str
The path to write the xenith tab-delimited output file.
version : str
The Kojak version that results are from.
max_charge : int
The maximum charge to consider. This should match the training
set.
decoy_prefix : str
The prefix used to indicate decoy sequences.
to_pin : bool
If true, convert results to a Percolator input file instead of
a xenith tab-delimited file.
"""
kojak_df, key_cols = _read_kojak(kojak_txt, decoy_prefix)
inter = _read_percolator(perc_inter)
inter.SpecId = inter.SpecId + "-inter"
intra = _read_percolator(perc_intra)
#intra["intraprotein"] = 1
intra.SpecId = intra.SpecId + "-intra"
perc_df = pd.concat([inter, intra])
merged = pd.merge(perc_df, kojak_df, how="inner", on=key_cols,
validate="one_to_one")
merged["intraprotein"] = _is_intraprotein(merged.ProteinA, merged.ProteinB,
decoy_prefix)
# In the case where there are only two unique proteins, set the
# intraprotein feature to 0.
num_proteins = _count_proteins(merged)
#if num_proteins <= 2:
# merged["intraprotein"] = 0
# Drop unwanted columns
xenith_target = ["NumTarget"]
xenith_tail = ["ProteinLinkSiteA", "ProteinLinkSiteB", "PeptideLinkSiteA",
"PeptideLinkSiteB", "ProteinA", "ProteinB", "PeptideA",
"PeptideB"]
perc_target = ["Label"]
perc_tail = ["Peptide", "Proteins"]
if to_pin:
target = perc_target
tail = perc_tail
drop_cols = xenith_target + xenith_tail
else:
target = xenith_target
tail = xenith_tail
drop_cols = perc_target + perc_tail
# Drop columns specific to Kojak version
#if version == "2.0-dev":
# drop_cols = drop_cols + ["dScore", "NormRank"]
merged = merged.drop(columns=drop_cols)
# Reformat E-Values
e_vals = [col for col in merged.columns if "eVal" in col]
for val in e_vals:
merged[val] = -np.log10(merged[val] + np.finfo(np.float64).tiny)
# Remove linear dependent information
merged["LenRat"] = (merged.LenShort / merged.LenLong)
# One-hot encode charge
for i in range(1, max_charge + 1):
new_col = merged.Charge == i
merged[f"Charge_{str(i)}"] = new_col.astype(int)
merged = merged.drop(columns=["Charge", "LenShort", "LenLong"])
# Reorder columns for output
head = ["SpecId"] + target + ["scannr"]
cols = merged.columns.tolist()
middle = [col for col in cols if col not in head + tail]
merged = merged.loc[:, head + middle + tail]
merged = merged.rename(columns={"SpecId": "PsmId"})
if not to_pin:
merged.to_csv(out_file, sep="\t", index=False)
else:
_write_pin(merged, out_file)
return out_file
# Utility Functions -----------------------------------------------------------
def _count_proteins(psm_df):
"""
Count the number of proteins in the dataset.
If the number of proteins is 2, intraprotein should be constant.
"""
all_prot = psm_df.ProteinA + ";" + psm_df.ProteinB
prot_set = [p.split(";") for p in all_prot.tolist()]
prot_set = set(chain.from_iterable(prot_set))
return len(prot_set)
def _write_pin(pin_df, pin_file):
"""
Write a dataframe to pin format.
This is only necessary, because pandas *always* must either quote or escape
the string containing a delimiter.
"""
with open(pin_file, "w") as pin_out:
pin_out.write("\t".join(pin_df.columns.tolist()) + "\n")
for _, row in pin_df.iterrows():
row = row.values.astype(str)
pin_out.write("\t".join(row.tolist()) + "\n")
def _read_kojak(kojak_file, decoy_prefix):
"""
Read a kojak results file and generate key columns
Parameters
----------
kojak_file : str
The kojak result file to read.
decoy_prefix : str
Decoy prefix string.
Returns
-------
tuple(pandas.DataFrame, list)
A dataframe containing the parsed PSMs and a list naming the
key columns to join with the Percolator data.
"""
dat = pd.read_csv(kojak_file, sep="\t", skiprows=1)
dat = dat.loc[dat["Protein #2"] != "-"]
key_cols = ["scannr", "Peptide", "Label"]
pep1 = dat["Peptide #1"].str.replace(r"\[.+?\]", "")
pep2 = dat["Peptide #2"].str.replace(r"\[.+?\]", "")
link1 = dat["Linked AA #1"]
link2 = dat["Linked AA #2"]
decoy1 = _all_decoy(dat["Protein #1"], decoy_prefix)
decoy2 = _all_decoy(dat["Protein #2"], decoy_prefix)
dat["Protein #1"] = _parse_proteins(dat["Protein #1"])
dat["Protein #2"] = _parse_proteins(dat["Protein #2"])
dat["scannr"] = dat["Scan Number"]
dat["Peptide"] = ("-." + pep1 + "(" + link1 + ")--"
+ pep2 + "(" + link2 + ").-")
dat["Label"] = (((decoy1.values - 1) * (decoy2.values - 1))*2 - 1)
# rename some columns for the final file
dat["NumTarget"] = (decoy1.values + decoy2.values - 2) * -1
dat = dat.rename(columns={"Protein #1 Site": "ProteinLinkSiteA",
"Protein #2 Site": "ProteinLinkSiteB",
"Linked AA #1": "PeptideLinkSiteA",
"Linked AA #2": "PeptideLinkSiteB",
"Protein #1": "ProteinA",
"Protein #2": "ProteinB",
"Peptide #1": "PeptideA",
"Peptide #2": "PeptideB"})
final_cols = ["NumTarget", "ProteinA", "ProteinB", "PeptideA", "PeptideB",
"ProteinLinkSiteA", "ProteinLinkSiteB",
"PeptideLinkSiteA", "PeptideLinkSiteB"]
dat = dat.loc[:, key_cols + final_cols]
return (dat, key_cols)
def _read_percolator(percolator_file):
"""Parse a PIN formatted file. Return a dataframe"""
with open(percolator_file, "r") as pin:
header = pin.readline()
splits = header.count("\t")
header = header.replace("\n", "")
header = header.split("\t")
rows = [line.replace("\n", "").split("\t", splits) for line in pin]
data = pd.DataFrame(columns=header, data=rows)
return data.apply(pd.to_numeric, errors="ignore")
def _parse_proteins(protein_col):
"""Remove description from protein id."""
protein_col = protein_col.str.split(";")
prot = [";".join([p.strip().split(" ", 1)[0] for p in r]) for r in protein_col]
return prot
def _is_intraprotein(protein_col_a, protein_col_b, decoy_prefix):
"""Determine if the cross-link is between the same protein or it's decoy"""
protein_col_a = protein_col_a.str.replace(decoy_prefix, "").str.split(";")
protein_col_b = protein_col_b.str.replace(decoy_prefix, "").str.split(";")
return [int(set(a) == set(b)) for a, b in zip(protein_col_a, protein_col_b)]
def _all_decoy(protein_col, decoy_prefix):
"""Returns 1 if all proteins are decoys, 0 otherwise."""
ret = []
protein_col = protein_col.str.split(";")
for row in protein_col:
decoy = all([p.startswith(decoy_prefix) for p in row])
ret.append(decoy)
return pd.Series(ret).astype(int)
| [
"pandas.DataFrame",
"pandas.read_csv",
"pandas.merge",
"numpy.finfo",
"pandas.Series",
"itertools.chain.from_iterable",
"pandas.concat"
] | [((1610, 1635), 'pandas.concat', 'pd.concat', (['[inter, intra]'], {}), '([inter, intra])\n', (1619, 1635), True, 'import pandas as pd\n'), ((1649, 1725), 'pandas.merge', 'pd.merge', (['perc_df', 'kojak_df'], {'how': '"""inner"""', 'on': 'key_cols', 'validate': '"""one_to_one"""'}), "(perc_df, kojak_df, how='inner', on=key_cols, validate='one_to_one')\n", (1657, 1725), True, 'import pandas as pd\n'), ((5099, 5144), 'pandas.read_csv', 'pd.read_csv', (['kojak_file'], {'sep': '"""\t"""', 'skiprows': '(1)'}), "(kojak_file, sep='\\t', skiprows=1)\n", (5110, 5144), True, 'import pandas as pd\n'), ((7114, 7153), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'header', 'data': 'rows'}), '(columns=header, data=rows)\n', (7126, 7153), True, 'import pandas as pd\n'), ((4135, 4164), 'itertools.chain.from_iterable', 'chain.from_iterable', (['prot_set'], {}), '(prot_set)\n', (4154, 4164), False, 'from itertools import chain\n'), ((8114, 8128), 'pandas.Series', 'pd.Series', (['ret'], {}), '(ret)\n', (8123, 8128), True, 'import pandas as pd\n'), ((2976, 2996), 'numpy.finfo', 'np.finfo', (['np.float64'], {}), '(np.float64)\n', (2984, 2996), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import re
from skimage import io
from skimage.util import img_as_float
from skimage.measure import label, regionprops, regionprops_table
from skimage.color import label2rgb
import matplotlib.pyplot as plt
from typing import List
import time
def measureTime(func):
def wrapper(*args, **kwargs):
starttime = time.perf_counter()
temp = func(*args, **kwargs)
endtime = time.perf_counter()
print(f"Time needed to run {func.__name__}: {endtime - starttime} seconds")
return(temp)
return wrapper
def createPixelVector(x_coordinate: int,y_coordinate: int, image_list: List[np.array], norm:str ="L2") -> np.array:
"""
Creates a pixel vector of a pixel by taking that pixel's values across a list of images and normalizing it.
Parameters
----------
x_coordinate : int
X coördinate of the pixel
y_coordinate : int
Y coördinate of the pixel
image_list : list[np.array]
List of images that will be used to track down the pixel's values
norm : str
String representing what kind of normalization to perform on the returned array.
Returns
-------
np.array
np.array representing the intenisty of a given pixel throughout the image list, normalized
"""
barcode_list = [0 for image in image_list] # start with empty barcode
for i, actual_image in enumerate(image_list):
barcode_list[i] = actual_image[y_coordinate, x_coordinate] # first y then x cause array indexing is row, col
barcode_array = np.array(barcode_list)
# only normalize if it's not a zero vector, otherwise you get timeout problems
if norm=="L2" and np.any(barcode_array):
barcode_array = barcode_array/np.linalg.norm(barcode_array)
return barcode_array
def createBarcodeVector(barcode: str) -> np.array:
"""
Creates a normalized numpy representation of a barcode
Parameters
----------
barcode : str
String represtentation of a barcode (e.g.: "0010010")
Returns
-------
np.array
Numpy array representation of that barcode, scaled to unit length.
"""
# Turn string barcode into array of floats
array = np.array([float(char) for char in str(barcode)])
return array/np.linalg.norm(array)
def parseBarcodes(codebook: str, bit_len: int) -> pd.DataFrame:
"""
Parsed the binary barcodes in a codebook into a dataframe representing the same barcodes.
Parameters
----------
codebook : str
Path to codebook.csv
bit_len : int
Length of the binary barcodes in the codebook
Returns
-------
pd.DataFrame
Dataframe representing the codebook with a column of barcodes usable in pixel-based decoding applications.
"""
df = pd.read_csv(codebook)
df['Barcode'] = [f"{barcode:0{bit_len}}" for barcode in list(df['Barcode'])] #This adds leading 0's back, because converting 001 to df makes it 1 since pandas thinks it's just an int
df['Index'] = list(range(1,len(df)+1)) # add an index row, to be used to label images later on
df['Vector'] = [createBarcodeVector(barcode) for barcode in df['Barcode']] # convert string barcodes into int
return df
def decodePixels(x_dim: int, y_dim: int, codebook: str, bit_len: int, img_path_list: List[str], img_prefix: str, threshold:float = 0.5176) -> pd.DataFrame:
"""
Decodes a list of images in a pixelwise manner, assigning each pixel to the closest barcode in the codebook.
Parameters
----------
x_dim : int
X dimension of input images
y_dim : int
Y dimension of input images
codebook : str
Path to codebook
bit_len : int
Length of the expected bins = number of images in img_path_list
img_path_list : List[str]
List of paths to the input images
img_prefix : str
Prefix used to sort the input images in ascending order
threshold : float
Distance threshold for a pixel vector to be assigned to a barcode vector.
Returns
-------
pd.DataFrame
Dataframe with every pixel being assigned to the closest barcode in the codebook.
"""
codebook_df = parseBarcodes(codebook,bit_len)
# Very important thing here is to sort based on the passed img_prexi, because the iteration needs to be done in order
r = re.compile(rf"{img_prefix}(\d+)")
def key_func(m):
return int(r.search(m).group(1))
img_path_list.sort(key=key_func)
# Convert images to float for correct distance comparisan
image_list = [img_as_float(io.imread(img)) for img in img_path_list]
rows_list = [] # rows list is used to store the rows of the df that will be returned
# Iterate over every pixel
for x in range(0,x_dim):
for y in range(0,y_dim):
# Attribute dics store the key: values of the row's entries
attribute_dict = {}
attribute_dict['X'] = x
attribute_dict['Y'] = y
pixel_vector = createPixelVector(x,y,image_list)
minimal_distance = np.inf
gene_label = ""
gene_name = ""
barcode = ""
for row in codebook_df.itertuples():
distance = np.linalg.norm(row.Vector - pixel_vector)
if distance < minimal_distance:
minimal_distance = distance
gene_label = row.Index
gene_name = row.Gene
barcode = row.Barcode
attribute_dict['Barcode'] = barcode
attribute_dict['Distance'] = minimal_distance
attribute_dict['Gene'] = gene_name
# If minimal distance not passing the threshold, it will be labeled as background
if minimal_distance > threshold:
gene_label = 0
attribute_dict['Gene_Label'] = gene_label
rows_list.append(attribute_dict)
result_df = pd.DataFrame(rows_list)
return result_df
# this code assumes that all pixel combinations are present in the decoded_pixels_df
def createSpotsFromDecodedPixels(x_dim: int, y_dim: int, decoded_pixels_df: pd.DataFrame, min_area: int = 4, max_area: int = 10000) -> pd.DataFrame:
"""
Creates a labeled image using the dataframe created by decodePixels.
Parameters
----------
x_dim : int
X dimension of the images used to create the pixel vectors
y_dim : int
Y dimension of the images used to create the pixel vectors
decoded_pixels_df : pd.DataFrame
Dataframe returned by the decodePixels function
min_area : int
Minimum number of neighbouring pixels necessary to form a spot
max_area : int
Maximum number of neighbouring pixels necessary to form a spot
Returns
-------
pd.DataFrame
Dataframe where each row is a detected and decoded spot.
"""
# Create an empty image to store the gene labels in
gene_labeled_image = np.zeros((y_dim, x_dim))
# Create a labeled image using the labels from the dataframe
for row in decoded_pixels_df.itertuples():
gene_labeled_image[row.Y, row.X] = row.Gene_Label
# aggregate the pixels with the same gene label
region_labeled_image, num_spots = label(gene_labeled_image, background=0, return_num=True)
# Convert the found "spot" regions into a dataframe
regions_table = regionprops_table(region_labeled_image, properties=("label", "area", "centroid"))
regions_df = pd.DataFrame(regions_table)
# Remove spots that only have an area of min_area and max_area
regions_df = regions_df[(regions_df['area'] >=min_area) & (regions_df['area'] <= max_area)]
# Rename some columns to be more meaningful to this usecase.
regions_df['Y'] = [int(y) for y in list(regions_df['centroid-0'])]
regions_df['X'] = [int(x) for x in list(regions_df['centroid-1'])]
regions_df = regions_df.drop(columns=[ "centroid-0", "centroid-1" ])
regions_df = regions_df.rename(columns={"label":"Spot_label"})
# combine with the decoded pixels dataframe to add gene name and barcode to the spots
merged_df = regions_df.merge(decoded_pixels_df, on=["X", "Y"], how="left")
return merged_df
# threshold based on a 1-bit error in euclidean distance
@measureTime
def decodePixelBased(x_dim, y_dim, codebook, bit_len, img_path_list, img_prefix:str, threshold = 0.5176):
# First decode each pixel in the image
decoded_pixels_df = decodePixels(x_dim, y_dim, codebook, bit_len, img_path_list,img_prefix, threshold)
decoded_pixels_df.to_csv("decoded_pixels_df.csv")
# Then combine neighbouring similarly labeled pixels into spot objects
decoded_spots_df = createSpotsFromDecodedPixels(x_dim, y_dim, decoded_pixels_df)
return decoded_spots_df
if __name__=="__main__":
# x_dim = 2048
# y_dim = 2048
# x_dim = 405
# y_dim = 205
# tile_nr = sys.argv[3]
# tile_nr_int = int(re.findall(r"\d+", tile_nr)[0])
codebook_path = "/home/nacho/Documents/communISS/data/merfish/codebook.csv"
image_path_list = [f"/media/tool/starfish_test_data/MERFISH/processed/cropped/merfish_{i}.tif" for i in range(1, 17)]
bit_len = 16
threshold = 0.5176
x_dim, y_dim = (405,205)
image_prefix="merfish_"
result_df = decodePixelBased(x_dim, y_dim, codebook=codebook_path, bit_len=bit_len, img_path_list=image_path_list, img_prefix=image_prefix)
result_df['Tile'] = [1 for i in range(0,len(result_df))]
result_df.to_csv("decoded.csv", index=False)
| [
"pandas.DataFrame",
"skimage.measure.regionprops_table",
"pandas.read_csv",
"numpy.zeros",
"time.perf_counter",
"numpy.any",
"skimage.measure.label",
"numpy.array",
"numpy.linalg.norm",
"skimage.io.imread",
"re.compile"
] | [((1617, 1639), 'numpy.array', 'np.array', (['barcode_list'], {}), '(barcode_list)\n', (1625, 1639), True, 'import numpy as np\n'), ((2904, 2925), 'pandas.read_csv', 'pd.read_csv', (['codebook'], {}), '(codebook)\n', (2915, 2925), True, 'import pandas as pd\n'), ((4533, 4566), 're.compile', 're.compile', (['f"""{img_prefix}(\\\\d+)"""'], {}), "(f'{img_prefix}(\\\\d+)')\n", (4543, 4566), False, 'import re\n'), ((6120, 6143), 'pandas.DataFrame', 'pd.DataFrame', (['rows_list'], {}), '(rows_list)\n', (6132, 6143), True, 'import pandas as pd\n'), ((7195, 7219), 'numpy.zeros', 'np.zeros', (['(y_dim, x_dim)'], {}), '((y_dim, x_dim))\n', (7203, 7219), True, 'import numpy as np\n'), ((7480, 7536), 'skimage.measure.label', 'label', (['gene_labeled_image'], {'background': '(0)', 'return_num': '(True)'}), '(gene_labeled_image, background=0, return_num=True)\n', (7485, 7536), False, 'from skimage.measure import label, regionprops, regionprops_table\n'), ((7613, 7698), 'skimage.measure.regionprops_table', 'regionprops_table', (['region_labeled_image'], {'properties': "('label', 'area', 'centroid')"}), "(region_labeled_image, properties=('label', 'area',\n 'centroid'))\n", (7630, 7698), False, 'from skimage.measure import label, regionprops, regionprops_table\n'), ((7712, 7739), 'pandas.DataFrame', 'pd.DataFrame', (['regions_table'], {}), '(regions_table)\n', (7724, 7739), True, 'import pandas as pd\n'), ((358, 377), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (375, 377), False, 'import time\n'), ((433, 452), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (450, 452), False, 'import time\n'), ((1746, 1767), 'numpy.any', 'np.any', (['barcode_array'], {}), '(barcode_array)\n', (1752, 1767), True, 'import numpy as np\n'), ((2355, 2376), 'numpy.linalg.norm', 'np.linalg.norm', (['array'], {}), '(array)\n', (2369, 2376), True, 'import numpy as np\n'), ((1807, 1836), 'numpy.linalg.norm', 'np.linalg.norm', (['barcode_array'], {}), '(barcode_array)\n', (1821, 1836), True, 'import numpy as np\n'), ((4763, 4777), 'skimage.io.imread', 'io.imread', (['img'], {}), '(img)\n', (4772, 4777), False, 'from skimage import io\n'), ((5418, 5459), 'numpy.linalg.norm', 'np.linalg.norm', (['(row.Vector - pixel_vector)'], {}), '(row.Vector - pixel_vector)\n', (5432, 5459), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
def bin_array_along_axis(x, num_bins, axis):
"""
Creates equally spaced bins with respective labels for the bins from a
given array x for each column along given axis. num_bins gives the number
of created bins.
x: Array to bin.
num_bins: the number of bins to create.
axis: Axis along which the bins are created.
Returns:
bins: Array of shape ((x.shape[axis], num_bins+1)) indicating start and
stop for the bins.
labels: Array of shape ((x.shape[axis], num_bins)) indicating the center
of each bin.
"""
try:
bins = np.empty((x.shape[axis], num_bins + 1))
except IndexError:
raise np.AxisError(
"axis {} is out of bounds for array of dimension {}".format(
axis, x.ndim
)
)
labels = np.empty((x.shape[axis], num_bins))
# binning for each entry starts at minimum and ends at maximum value
axis_list = list(range(x.ndim))
del axis_list[axis]
axis_list = tuple(axis_list)
pos_min = x.min(axis=axis_list)
pos_max = x.max(axis=axis_list)
for i in range(x.shape[axis]):
bins[i, :] = np.linspace(
pos_min[i], pos_max[i], num_bins + 1, endpoint=True
)
labels[i, :] = bins[i, :-1] + (bins[i, 1]-bins[i, 0]) / 2
return bins, labels
def bin_a_from_b(a, b, num_bins):
"""
Creates histograms for a based on b. Values in a are pooled together, when
they fall into the same bin in b. num_bins gives the number of bins, that
are created.
a: array of shape ((num_elems, num_prop1))
b: array of shape ((num_elems, num_prop2))
num_bins: number of bins to create
Returns:
mu_sigma: array of shape((num_prop1, num_prop2, num_bins, 4)). For each bin
in a for each property of a gives the mean, sigma and normalized values of
those for b.
"""
if not a.shape[0] == b.shape[0]:
raise ValueError("a and b must have same length in first dimension")
num_prop1 = a.shape[1]
num_prop2 = b.shape[1]
# Create bins for b
bins, labels = bin_array_along_axis(b, num_bins, 1)
# to be sure, that no elements at the left most and right most edges are
# lost, we subtract -1 and add 1 add the lower and upper ends
bins[:, 0] -= 1
bins[:, -1] += 1
mu_sigma = np.empty((num_prop1, num_prop2, num_bins, 2))
dfs = [[] for i in range(num_prop1)]
pdf = np.empty_like(labels)
for i in range(num_prop1):
for j in range(num_prop2):
ab = np.stack((a[:, i], b[:, j]), axis=-1)
df = pd.DataFrame(ab, columns=["prop1", "prop2"])
df["binned"] = pd.cut(
df["prop2"],
bins=bins[j, :], labels=labels[j, :]
)
tmp_groups = df.groupby("binned")
if i == 0:
counts = tmp_groups["prop2"].count()
pdf[j, :] = counts / counts.sum()
mu_sigma[i, j, :, 0] = tmp_groups["prop1"].mean()
mu_sigma[i, j, :, 1] = tmp_groups["prop1"].std()
dfs[i].append(df)
return mu_sigma, dfs, pdf, labels, bins
| [
"numpy.stack",
"pandas.DataFrame",
"numpy.empty",
"numpy.empty_like",
"pandas.cut",
"numpy.linspace"
] | [((860, 895), 'numpy.empty', 'np.empty', (['(x.shape[axis], num_bins)'], {}), '((x.shape[axis], num_bins))\n', (868, 895), True, 'import numpy as np\n'), ((2369, 2414), 'numpy.empty', 'np.empty', (['(num_prop1, num_prop2, num_bins, 2)'], {}), '((num_prop1, num_prop2, num_bins, 2))\n', (2377, 2414), True, 'import numpy as np\n'), ((2466, 2487), 'numpy.empty_like', 'np.empty_like', (['labels'], {}), '(labels)\n', (2479, 2487), True, 'import numpy as np\n'), ((630, 669), 'numpy.empty', 'np.empty', (['(x.shape[axis], num_bins + 1)'], {}), '((x.shape[axis], num_bins + 1))\n', (638, 669), True, 'import numpy as np\n'), ((1192, 1256), 'numpy.linspace', 'np.linspace', (['pos_min[i]', 'pos_max[i]', '(num_bins + 1)'], {'endpoint': '(True)'}), '(pos_min[i], pos_max[i], num_bins + 1, endpoint=True)\n', (1203, 1256), True, 'import numpy as np\n'), ((2572, 2609), 'numpy.stack', 'np.stack', (['(a[:, i], b[:, j])'], {'axis': '(-1)'}), '((a[:, i], b[:, j]), axis=-1)\n', (2580, 2609), True, 'import numpy as np\n'), ((2628, 2672), 'pandas.DataFrame', 'pd.DataFrame', (['ab'], {'columns': "['prop1', 'prop2']"}), "(ab, columns=['prop1', 'prop2'])\n", (2640, 2672), True, 'import pandas as pd\n'), ((2700, 2757), 'pandas.cut', 'pd.cut', (["df['prop2']"], {'bins': 'bins[j, :]', 'labels': 'labels[j, :]'}), "(df['prop2'], bins=bins[j, :], labels=labels[j, :])\n", (2706, 2757), True, 'import pandas as pd\n')] |
import pickle
import torch
import time
import glob
from torch import nn, optim
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import numpy as np
from skimage.color import rgb2lab, lab2rgb
from matplotlib import cm
import matplotlib.pyplot as plt
from tqdm import tqdm
# Hyperparameters and the such
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
print(DEVICE)
BATCH_SIZE = 16
SIZE = 64
# Load the training and validation dataset into a huge array called Xtrain
train_in = open("mini-imagenet-cache-train.pkl", "rb")
train = pickle.load(train_in)
Xtrain = train["image_data"]
train_data = Xtrain.reshape([64, 600, 84, 84, 3])
# val_in = open("mini-imagenet-cache-val.pkl", "rb")
# val = pickle.load(train_in)
# Xval = train["image_data"]
# val_data = Xtrain.reshape([64, 600, 84, 84, 3])
paths = glob.glob("E:/COCO/train2014" + "/*.jpg") # Grabbing all the image file names
np.random.seed(123)
paths_subset = np.random.choice(paths, 10_000, replace=False) # choosing 1000 images randomly
rand_idxs = np.random.permutation(10_000)
train_idxs = rand_idxs[:8000] # choosing the first 8000 as training set
val_idxs = rand_idxs[8000:] # choosing last 2000 as validation set
train_paths = paths_subset[train_idxs]
val_paths = paths_subset[val_idxs]
print(len(train_paths), len(val_paths))
# Define the custom Dataset for this data
class ColorizationDataset(Dataset):
def __init__(self, paths):
self.size = SIZE
self.transforms = transforms.Resize((self.size, self.size))
self.paths = paths
def __getitem__(self, idx):
img = Image.open(self.paths[idx]).convert("RGB")
img = self.transforms(img)
img_lab = rgb2lab(img).astype("float32")
img_lab = transforms.ToTensor()(img_lab)
L = img_lab[[0], ...] / 50. - 1.
ab = img_lab[[1, 2], ...] / 110.
return {'L': L, 'ab': ab}
def __len__(self):
return len(self.paths)
# Create dataloader for the above dataset
dataset = ColorizationDataset(train_paths)
train_dl = DataLoader(dataset, batch_size=BATCH_SIZE)
val_dl = DataLoader(dataset, batch_size=BATCH_SIZE)
class UnetBlock(nn.Module):
def __init__(self, nf, ni, submodule=None, input_c=None, dropout=False,
innermost=False, outermost=False):
super().__init__()
self.outermost = outermost
if input_c is None: input_c = nf
downconv = nn.Conv2d(input_c, ni, kernel_size=4,
stride=2, padding=1, bias=False)
downrelu = nn.LeakyReLU(0.2, True)
downnorm = nn.BatchNorm2d(ni)
uprelu = nn.ReLU(True)
upnorm = nn.BatchNorm2d(nf)
if outermost:
# print("outermost")
upconv = nn.ConvTranspose2d(ni * 2, nf, kernel_size=4,
stride=2, padding=1)
down = [downconv]
up = [uprelu, upconv, nn.Tanh()]
model = down + [submodule] + up
elif innermost:
# print("innermost")
upconv = nn.ConvTranspose2d(ni, nf, kernel_size=4,
stride=2, padding=1, bias=False)
down = [downrelu, downconv]
up = [uprelu, upconv, upnorm]
model = down + up
else:
# print("sup")
upconv = nn.ConvTranspose2d(ni * 2, nf, kernel_size=4,
stride=2, padding=1, bias=False)
down = [downrelu, downconv, downnorm]
up = [uprelu, upconv, upnorm]
if dropout: up += [nn.Dropout(0.5)]
model = down + [submodule] + up
self.model = nn.Sequential(*model)
def forward(self, x):
if self.outermost:
return self.model(x)
else:
return torch.cat([x, self.model(x)], 1)
class Unet(nn.Module):
def __init__(self, input_c=1, output_c=2, n_down=6, num_filters=64):
super().__init__()
unet_block = UnetBlock(num_filters * 8, num_filters * 8, innermost=True)
for _ in range(n_down - 5):
unet_block = UnetBlock(num_filters * 8, num_filters * 8, submodule=unet_block, dropout=True)
out_filters = num_filters * 8
for _ in range(1):
unet_block = UnetBlock(out_filters // 2, out_filters, submodule=unet_block)
out_filters //= 2
self.model = UnetBlock(output_c, out_filters, input_c=input_c, submodule=unet_block, outermost=True)
def forward(self, x):
return self.model(x)
class PatchDiscriminator(nn.Module):
def __init__(self, input_c, num_filters=64, n_down=3):
super().__init__()
model = [self.get_layers(input_c, num_filters, norm=False)]
model += [self.get_layers(num_filters * 2 ** i, num_filters * 2 ** (i + 1), s=1 if i == (n_down-1) else 2)
for i in range(n_down)] # the 'if' statement is taking care of not using
# stride of 2 for the last block in this loop
model += [self.get_layers(num_filters * 2 ** n_down, 1, s=1, norm=False, act=False)] # Make sure to not use normalization or
# activation for the last layer of the model
self.model = nn.Sequential(*model)
def get_layers(self, ni, nf, k=4, s=2, p=1, norm=True, act=True): # when needing to make some repeatitive blocks of layers,
layers = [nn.Conv2d(ni, nf, k, s, p, bias=not norm)] # it's always helpful to make a separate method for that purpose
if norm: layers += [nn.BatchNorm2d(nf)]
if act: layers += [nn.LeakyReLU(0.2, True)]
return nn.Sequential(*layers)
def forward(self, x):
return self.model(x)
class GANLoss(nn.Module):
def __init__(self, gan_mode='vanilla', real_label=1.0, fake_label=0.0):
super().__init__()
self.register_buffer('real_label', torch.tensor(real_label))
self.register_buffer('fake_label', torch.tensor(fake_label))
if gan_mode == 'vanilla':
self.loss = nn.BCEWithLogitsLoss()
elif gan_mode == 'lsgan':
self.loss = nn.MSELoss()
def get_labels(self, preds, target_is_real):
if target_is_real:
labels = self.real_label
else:
labels = self.fake_label
return labels.expand_as(preds)
def __call__(self, preds, target_is_real):
labels = self.get_labels(preds, target_is_real)
loss = self.loss(preds, labels)
return loss
def init_weights(net, init='norm', gain=0.02):
def init_func(m):
classname = m.__class__.__name__
if hasattr(m, 'weight') and 'Conv' in classname:
if init == 'norm':
nn.init.normal_(m.weight.data, mean=0.0, std=gain)
elif init == 'xavier':
nn.init.xavier_normal_(m.weight.data, gain=gain)
elif init == 'kaiming':
nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
if hasattr(m, 'bias') and m.bias is not None:
nn.init.constant_(m.bias.data, 0.0)
elif 'BatchNorm2d' in classname:
nn.init.normal_(m.weight.data, 1., gain)
nn.init.constant_(m.bias.data, 0.)
net.apply(init_func)
print(f"model initialized with {init} initialization")
return net
def init_model(model, device):
model = model.to(device)
model = init_weights(model)
return model
class MainModel(nn.Module):
def __init__(self, net_G=None, lr_G=2e-4, lr_D=2e-4,
beta1=0.5, beta2=0.999, lambda_L1=100.):
super().__init__()
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.lambda_L1 = lambda_L1
if net_G is None:
self.net_G = init_model(Unet(input_c=1, output_c=2, n_down=8, num_filters=64), self.device)
else:
self.net_G = net_G.to(self.device)
self.net_D = init_model(PatchDiscriminator(input_c=3, n_down=3, num_filters=64), self.device)
self.GANcriterion = GANLoss(gan_mode='vanilla').to(self.device)
self.L1criterion = nn.L1Loss()
self.opt_G = optim.Adam(self.net_G.parameters(), lr=lr_G, betas=(beta1, beta2))
self.opt_D = optim.Adam(self.net_D.parameters(), lr=lr_D, betas=(beta1, beta2))
def set_requires_grad(self, model, requires_grad=True):
for p in model.parameters():
p.requires_grad = requires_grad
def setup_input(self, data):
self.L = data['L'].to(self.device)
self.ab = data['ab'].to(self.device)
def forward(self):
self.fake_color = self.net_G(self.L)
def backward_D(self):
fake_image = torch.cat([self.L, self.fake_color], dim=1)
fake_preds = self.net_D(fake_image.detach())
self.loss_D_fake = self.GANcriterion(fake_preds, False)
real_image = torch.cat([self.L, self.ab], dim=1)
real_preds = self.net_D(real_image)
self.loss_D_real = self.GANcriterion(real_preds, True)
self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5
self.loss_D.backward()
def backward_G(self):
fake_image = torch.cat([self.L, self.fake_color], dim=1)
fake_preds = self.net_D(fake_image)
self.loss_G_GAN = self.GANcriterion(fake_preds, True)
self.loss_G_L1 = self.L1criterion(self.fake_color, self.ab) * self.lambda_L1
self.loss_G = self.loss_G_GAN + self.loss_G_L1
self.loss_G.backward()
def optimize(self):
self.forward()
self.net_D.train()
self.set_requires_grad(self.net_D, True)
self.opt_D.zero_grad()
self.backward_D()
self.opt_D.step()
self.net_G.train()
self.set_requires_grad(self.net_D, False)
self.opt_G.zero_grad()
self.backward_G()
self.opt_G.step()
class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
self.count, self.avg, self.sum = [0.] * 3
def update(self, val, count=1):
self.count += count
self.sum += count * val
self.avg = self.sum / self.count
def create_loss_meters():
loss_D_fake = AverageMeter()
loss_D_real = AverageMeter()
loss_D = AverageMeter()
loss_G_GAN = AverageMeter()
loss_G_L1 = AverageMeter()
loss_G = AverageMeter()
return {'loss_D_fake': loss_D_fake,
'loss_D_real': loss_D_real,
'loss_D': loss_D,
'loss_G_GAN': loss_G_GAN,
'loss_G_L1': loss_G_L1,
'loss_G': loss_G}
def update_losses(model, loss_meter_dict, count):
for loss_name, loss_meter in loss_meter_dict.items():
loss = getattr(model, loss_name)
loss_meter.update(loss.item(), count=count)
def lab_to_rgb(L, ab):
L = (L + 1.) * 50.
ab = ab * 110.
Lab = torch.cat([L, ab], dim=1).permute(0, 2, 3, 1).cpu().numpy()
rgb_imgs = []
for img in Lab:
img_rgb = lab2rgb(img)
rgb_imgs.append(img_rgb)
return np.stack(rgb_imgs, axis=0)
def visualize(model, data, save=True):
model.net_G.eval()
with torch.no_grad():
model.setup_input(data)
model.forward()
model.net_G.train()
fake_color = model.fake_color.detach()
real_color = model.ab
L = model.L
fake_imgs = lab_to_rgb(L, fake_color)
real_imgs = lab_to_rgb(L, real_color)
fig = plt.figure(figsize=(15, 8))
for i in range(5):
ax = plt.subplot(3, 5, i + 1)
ax.imshow(L[i][0].cpu(), cmap='gray')
ax.axis("off")
ax = plt.subplot(3, 5, i + 1 + 5)
ax.imshow(fake_imgs[i])
ax.axis("off")
ax = plt.subplot(3, 5, i + 1 + 10)
ax.imshow(real_imgs[i])
ax.axis("off")
if save:
fig.savefig(f"colorization_{time.time()}.png")
else:
plt.show()
def log_results(loss_meter_dict):
for loss_name, loss_meter in loss_meter_dict.items():
print(f"{loss_name}: {loss_meter.avg:.5f}")
def train_model(model, train_dl, epochs, display_every=500):
data = next(iter(val_dl)) # getting a batch for visualizing the model output after fixed intrvals
for e in range(epochs):
loss_meter_dict = create_loss_meters() # function returing a dictionary of objects to
i = 0 # log the losses of the complete network
for data in tqdm(train_dl):
model.setup_input(data)
model.optimize()
update_losses(model, loss_meter_dict, count=data['L'].size(0)) # function updating the log objects
i += 1
if i % display_every == 0:
print(f"\nEpoch {e+1}/{epochs}")
print(f"Iteration {i}/{len(train_dl)}")
log_results(loss_meter_dict) # function to print out the losses
visualize(model, data, save=True) # function displaying the model's outputs
model = torch.load('colorization.pth')
train_model(model, train_dl, 15)
torch.save(model, 'colorization.pth') | [
"torch.nn.Dropout",
"numpy.random.seed",
"torch.cat",
"matplotlib.pyplot.figure",
"pickle.load",
"torch.nn.init.constant_",
"glob.glob",
"torch.no_grad",
"skimage.color.rgb2lab",
"torch.nn.MSELoss",
"torch.nn.init.kaiming_normal_",
"torch.utils.data.DataLoader",
"torch.load",
"numpy.random... | [((620, 641), 'pickle.load', 'pickle.load', (['train_in'], {}), '(train_in)\n', (631, 641), False, 'import pickle\n'), ((902, 943), 'glob.glob', 'glob.glob', (["('E:/COCO/train2014' + '/*.jpg')"], {}), "('E:/COCO/train2014' + '/*.jpg')\n", (911, 943), False, 'import glob\n'), ((981, 1000), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (995, 1000), True, 'import numpy as np\n'), ((1017, 1062), 'numpy.random.choice', 'np.random.choice', (['paths', '(10000)'], {'replace': '(False)'}), '(paths, 10000, replace=False)\n', (1033, 1062), True, 'import numpy as np\n'), ((1109, 1137), 'numpy.random.permutation', 'np.random.permutation', (['(10000)'], {}), '(10000)\n', (1130, 1137), True, 'import numpy as np\n'), ((2074, 2116), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'BATCH_SIZE'}), '(dataset, batch_size=BATCH_SIZE)\n', (2084, 2116), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((2127, 2169), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'BATCH_SIZE'}), '(dataset, batch_size=BATCH_SIZE)\n', (2137, 2169), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((11756, 11786), 'torch.load', 'torch.load', (['"""colorization.pth"""'], {}), "('colorization.pth')\n", (11766, 11786), False, 'import torch\n'), ((11822, 11859), 'torch.save', 'torch.save', (['model', '"""colorization.pth"""'], {}), "(model, 'colorization.pth')\n", (11832, 11859), False, 'import torch\n'), ((393, 418), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (416, 418), False, 'import torch\n'), ((10066, 10092), 'numpy.stack', 'np.stack', (['rgb_imgs'], {'axis': '(0)'}), '(rgb_imgs, axis=0)\n', (10074, 10092), True, 'import numpy as np\n'), ((10416, 10443), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 8)'}), '(figsize=(15, 8))\n', (10426, 10443), True, 'import matplotlib.pyplot as plt\n'), ((1549, 1590), 'torchvision.transforms.Resize', 'transforms.Resize', (['(self.size, self.size)'], {}), '((self.size, self.size))\n', (1566, 1590), False, 'from torchvision import transforms\n'), ((2418, 2488), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_c', 'ni'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)', 'bias': '(False)'}), '(input_c, ni, kernel_size=4, stride=2, padding=1, bias=False)\n', (2427, 2488), False, 'from torch import nn, optim\n'), ((2512, 2535), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)', '(True)'], {}), '(0.2, True)\n', (2524, 2535), False, 'from torch import nn, optim\n'), ((2550, 2568), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['ni'], {}), '(ni)\n', (2564, 2568), False, 'from torch import nn, optim\n'), ((2581, 2594), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (2588, 2594), False, 'from torch import nn, optim\n'), ((2607, 2625), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['nf'], {}), '(nf)\n', (2621, 2625), False, 'from torch import nn, optim\n'), ((3388, 3409), 'torch.nn.Sequential', 'nn.Sequential', (['*model'], {}), '(*model)\n', (3401, 3409), False, 'from torch import nn, optim\n'), ((4822, 4843), 'torch.nn.Sequential', 'nn.Sequential', (['*model'], {}), '(*model)\n', (4835, 4843), False, 'from torch import nn, optim\n'), ((5213, 5235), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (5226, 5235), False, 'from torch import nn, optim\n'), ((7444, 7455), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (7453, 7455), False, 'from torch import nn, optim\n'), ((7972, 8015), 'torch.cat', 'torch.cat', (['[self.L, self.fake_color]'], {'dim': '(1)'}), '([self.L, self.fake_color], dim=1)\n', (7981, 8015), False, 'import torch\n'), ((8139, 8174), 'torch.cat', 'torch.cat', (['[self.L, self.ab]'], {'dim': '(1)'}), '([self.L, self.ab], dim=1)\n', (8148, 8174), False, 'import torch\n'), ((8402, 8445), 'torch.cat', 'torch.cat', (['[self.L, self.fake_color]'], {'dim': '(1)'}), '([self.L, self.fake_color], dim=1)\n', (8411, 8445), False, 'import torch\n'), ((10016, 10028), 'skimage.color.lab2rgb', 'lab2rgb', (['img'], {}), '(img)\n', (10023, 10028), False, 'from skimage.color import rgb2lab, lab2rgb\n'), ((10164, 10179), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10177, 10179), False, 'import torch\n'), ((10473, 10497), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(5)', '(i + 1)'], {}), '(3, 5, i + 1)\n', (10484, 10497), True, 'import matplotlib.pyplot as plt\n'), ((10565, 10593), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(5)', '(i + 1 + 5)'], {}), '(3, 5, i + 1 + 5)\n', (10576, 10593), True, 'import matplotlib.pyplot as plt\n'), ((10647, 10676), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(5)', '(i + 1 + 10)'], {}), '(3, 5, i + 1 + 10)\n', (10658, 10676), True, 'import matplotlib.pyplot as plt\n'), ((10794, 10804), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10802, 10804), True, 'import matplotlib.pyplot as plt\n'), ((11301, 11315), 'tqdm.tqdm', 'tqdm', (['train_dl'], {}), '(train_dl)\n', (11305, 11315), False, 'from tqdm import tqdm\n'), ((1784, 1805), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1803, 1805), False, 'from torchvision import transforms\n'), ((2685, 2751), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(ni * 2)', 'nf'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(ni * 2, nf, kernel_size=4, stride=2, padding=1)\n', (2703, 2751), False, 'from torch import nn, optim\n'), ((5002, 5043), 'torch.nn.Conv2d', 'nn.Conv2d', (['ni', 'nf', 'k', 's', 'p'], {'bias': '(not norm)'}), '(ni, nf, k, s, p, bias=not norm)\n', (5011, 5043), False, 'from torch import nn, optim\n'), ((5450, 5474), 'torch.tensor', 'torch.tensor', (['real_label'], {}), '(real_label)\n', (5462, 5474), False, 'import torch\n'), ((5514, 5538), 'torch.tensor', 'torch.tensor', (['fake_label'], {}), '(fake_label)\n', (5526, 5538), False, 'import torch\n'), ((5585, 5607), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (5605, 5607), False, 'from torch import nn, optim\n'), ((1654, 1681), 'PIL.Image.open', 'Image.open', (['self.paths[idx]'], {}), '(self.paths[idx])\n', (1664, 1681), False, 'from PIL import Image\n'), ((1740, 1752), 'skimage.color.rgb2lab', 'rgb2lab', (['img'], {}), '(img)\n', (1747, 1752), False, 'from skimage.color import rgb2lab, lab2rgb\n'), ((2811, 2820), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (2818, 2820), False, 'from torch import nn, optim\n'), ((2915, 2989), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['ni', 'nf'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)', 'bias': '(False)'}), '(ni, nf, kernel_size=4, stride=2, padding=1, bias=False)\n', (2933, 2989), False, 'from torch import nn, optim\n'), ((3130, 3208), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(ni * 2)', 'nf'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)', 'bias': '(False)'}), '(ni * 2, nf, kernel_size=4, stride=2, padding=1, bias=False)\n', (3148, 3208), False, 'from torch import nn, optim\n'), ((5136, 5154), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['nf'], {}), '(nf)\n', (5150, 5154), False, 'from torch import nn, optim\n'), ((5178, 5201), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)', '(True)'], {}), '(0.2, True)\n', (5190, 5201), False, 'from torch import nn, optim\n'), ((5653, 5665), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (5663, 5665), False, 'from torch import nn, optim\n'), ((6177, 6227), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight.data'], {'mean': '(0.0)', 'std': 'gain'}), '(m.weight.data, mean=0.0, std=gain)\n', (6192, 6227), False, 'from torch import nn, optim\n'), ((6461, 6496), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias.data', '(0.0)'], {}), '(m.bias.data, 0.0)\n', (6478, 6496), False, 'from torch import nn, optim\n'), ((6537, 6578), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight.data', '(1.0)', 'gain'], {}), '(m.weight.data, 1.0, gain)\n', (6552, 6578), False, 'from torch import nn, optim\n'), ((6582, 6617), 'torch.nn.init.constant_', 'nn.init.constant_', (['m.bias.data', '(0.0)'], {}), '(m.bias.data, 0.0)\n', (6599, 6617), False, 'from torch import nn, optim\n'), ((7021, 7046), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7044, 7046), False, 'import torch\n'), ((6260, 6308), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['m.weight.data'], {'gain': 'gain'}), '(m.weight.data, gain=gain)\n', (6282, 6308), False, 'from torch import nn, optim\n'), ((10764, 10775), 'time.time', 'time.time', ([], {}), '()\n', (10773, 10775), False, 'import time\n'), ((3319, 3334), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (3329, 3334), False, 'from torch import nn, optim\n'), ((6342, 6400), 'torch.nn.init.kaiming_normal_', 'nn.init.kaiming_normal_', (['m.weight.data'], {'a': '(0)', 'mode': '"""fan_in"""'}), "(m.weight.data, a=0, mode='fan_in')\n", (6365, 6400), False, 'from torch import nn, optim\n'), ((9909, 9934), 'torch.cat', 'torch.cat', (['[L, ab]'], {'dim': '(1)'}), '([L, ab], dim=1)\n', (9918, 9934), False, 'import torch\n')] |
import os
import numpy as np
import torch
import matplotlib.pyplot as plt
import matplotlib
from lib.growth_net import GrowthNet
import lib.utils as utils
from lib.viz_scrna import trajectory_to_video, save_vectors
from lib.viz_scrna import (
save_trajectory_density,
save_2d_trajectory,
save_2d_trajectory_v2,
)
# from train_misc import standard_normal_logprob
from train_misc import set_cnf_options, count_nfe, count_parameters
from train_misc import count_total_time
from train_misc import add_spectral_norm, spectral_norm_power_iteration
from train_misc import create_regularization_fns, get_regularization
from train_misc import append_regularization_to_log
from train_misc import build_model_tabular
import eval_utils
import dataset
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
def save_trajectory(
prior_logdensity,
prior_sampler,
model,
data_samples,
savedir,
ntimes=101,
end_times=None,
memory=0.01,
device="cpu",
):
model.eval()
# Sample from prior
z_samples = prior_sampler(1000, 2).to(device)
# sample from a grid
npts = 100
side = np.linspace(-4, 4, npts)
xx, yy = np.meshgrid(side, side)
xx = torch.from_numpy(xx).type(torch.float32).to(device)
yy = torch.from_numpy(yy).type(torch.float32).to(device)
z_grid = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1)], 1)
with torch.no_grad():
# We expect the model is a chain of CNF layers wrapped in a SequentialFlow container.
logp_samples = prior_logdensity(z_samples)
logp_grid = prior_logdensity(z_grid)
t = 0
for cnf in model.chain:
# Construct integration_list
if end_times is None:
end_times = [(cnf.sqrt_end_time * cnf.sqrt_end_time)]
integration_list = [torch.linspace(0, end_times[0], ntimes).to(device)]
for i, et in enumerate(end_times[1:]):
integration_list.append(
torch.linspace(end_times[i], et, ntimes).to(device)
)
full_times = torch.cat(integration_list, 0)
print(full_times.shape)
# Integrate over evenly spaced samples
z_traj, logpz = cnf(
z_samples,
logp_samples,
integration_times=integration_list[0],
reverse=True,
)
full_traj = [(z_traj, logpz)]
for int_times in integration_list[1:]:
prev_z, prev_logp = full_traj[-1]
z_traj, logpz = cnf(
prev_z[-1], prev_logp[-1], integration_times=int_times, reverse=True
)
full_traj.append((z_traj[1:], logpz[1:]))
full_zip = list(zip(*full_traj))
z_traj = torch.cat(full_zip[0], 0)
# z_logp = torch.cat(full_zip[1], 0)
z_traj = z_traj.cpu().numpy()
grid_z_traj, grid_logpz_traj = [], []
inds = torch.arange(0, z_grid.shape[0]).to(torch.int64)
for ii in torch.split(inds, int(z_grid.shape[0] * memory)):
_grid_z_traj, _grid_logpz_traj = cnf(
z_grid[ii],
logp_grid[ii],
integration_times=integration_list[0],
reverse=True,
)
full_traj = [(_grid_z_traj, _grid_logpz_traj)]
for int_times in integration_list[1:]:
prev_z, prev_logp = full_traj[-1]
_grid_z_traj, _grid_logpz_traj = cnf(
prev_z[-1],
prev_logp[-1],
integration_times=int_times,
reverse=True,
)
full_traj.append((_grid_z_traj, _grid_logpz_traj))
full_zip = list(zip(*full_traj))
_grid_z_traj = torch.cat(full_zip[0], 0).cpu().numpy()
_grid_logpz_traj = torch.cat(full_zip[1], 0).cpu().numpy()
print(_grid_z_traj.shape)
grid_z_traj.append(_grid_z_traj)
grid_logpz_traj.append(_grid_logpz_traj)
grid_z_traj = np.concatenate(grid_z_traj, axis=1)
grid_logpz_traj = np.concatenate(grid_logpz_traj, axis=1)
plt.figure(figsize=(8, 8))
for _ in range(z_traj.shape[0]):
plt.clf()
# plot target potential function
ax = plt.subplot(1, 1, 1, aspect="equal")
"""
ax.hist2d(data_samples[:, 0], data_samples[:, 1], range=[[-4, 4], [-4, 4]], bins=200)
ax.invert_yaxis()
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
ax.set_title("Target", fontsize=32)
"""
# plot the density
# ax = plt.subplot(2, 2, 2, aspect="equal")
z, logqz = grid_z_traj[t], grid_logpz_traj[t]
xx = z[:, 0].reshape(npts, npts)
yy = z[:, 1].reshape(npts, npts)
qz = np.exp(logqz).reshape(npts, npts)
rgb = plt.cm.Spectral(t / z_traj.shape[0])
print(t, rgb)
background_color = "white"
cvals = [0, np.percentile(qz, 0.1)]
colors = [
background_color,
rgb,
]
norm = plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm, cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
from matplotlib.colors import LogNorm
plt.pcolormesh(
xx,
yy,
qz,
# norm=LogNorm(vmin=qz.min(), vmax=qz.max()),
cmap=cmap,
)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
cmap = matplotlib.cm.get_cmap(None)
ax.set_facecolor(background_color)
ax.invert_yaxis()
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
ax.set_title("Density", fontsize=32)
"""
# plot the samples
ax = plt.subplot(2, 2, 3, aspect="equal")
zk = z_traj[t]
ax.hist2d(zk[:, 0], zk[:, 1], range=[[-4, 4], [-4, 4]], bins=200)
ax.invert_yaxis()
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
ax.set_title("Samples", fontsize=32)
# plot vector field
ax = plt.subplot(2, 2, 4, aspect="equal")
K = 13j
y, x = np.mgrid[-4:4:K, -4:4:K]
K = int(K.imag)
zs = torch.from_numpy(np.stack([x, y], -1).reshape(K * K, 2)).to(device, torch.float32)
logps = torch.zeros(zs.shape[0], 1).to(device, torch.float32)
dydt = cnf.odefunc(full_times[t], (zs, logps))[0]
dydt = -dydt.cpu().detach().numpy()
dydt = dydt.reshape(K, K, 2)
logmag = 2 * np.log(np.hypot(dydt[:, :, 0], dydt[:, :, 1]))
ax.quiver(
x, y, dydt[:, :, 0], -dydt[:, :, 1],
# x, y, dydt[:, :, 0], dydt[:, :, 1],
np.exp(logmag), cmap="coolwarm", scale=20., width=0.015, pivot="mid"
)
ax.set_xlim(-4, 4)
ax.set_ylim(4, -4)
#ax.set_ylim(-4, 4)
ax.axis("off")
ax.set_title("Vector Field", fontsize=32)
"""
makedirs(savedir)
plt.savefig(os.path.join(savedir, f"viz-{t:05d}.jpg"))
t += 1
def get_trajectory_samples(device, model, data, n=2000):
ntimes = 5
model.eval()
z_samples = data.base_sample()(n, 2).to(device)
integration_list = [torch.linspace(0, args.int_tps[0], ntimes).to(device)]
for i, et in enumerate(args.int_tps[1:]):
integration_list.append(torch.linspace(args.int_tps[i], et, ntimes).to(device))
print(integration_list)
def plot_output(device, args, model, data):
# logger.info('Plotting trajectory to {}'.format(save_traj_dir))
data_samples = data.get_data()[data.sample_index(2000, 0)]
start_points = data.base_sample()(1000, 2)
# start_points = data.get_data()[idx]
# start_points = torch.from_numpy(start_points).type(torch.float32)
"""
save_vectors(
data.base_density(),
model,
start_points,
data.get_data()[data.get_times() == 1],
data.get_times()[data.get_times() == 1],
args.save,
device=device,
end_times=args.int_tps,
ntimes=100,
memory=1.0,
lim=1.5,
)
save_traj_dir = os.path.join(args.save, "trajectory_2d")
save_2d_trajectory_v2(
data.base_density(),
data.base_sample(),
model,
data_samples,
save_traj_dir,
device=device,
end_times=args.int_tps,
ntimes=3,
memory=1.0,
limit=2.5,
)
"""
density_dir = os.path.join(args.save, "density2")
save_trajectory_density(
data.base_density(),
model,
data_samples,
density_dir,
device=device,
end_times=args.int_tps,
ntimes=100,
memory=1,
)
trajectory_to_video(density_dir)
def integrate_backwards(end_samples, model, savedir, ntimes=100, memory=0.1, device='cpu'):
""" Integrate some samples backwards and save the results.
"""
with torch.no_grad():
z = torch.from_numpy(end_samples).type(torch.float32).to(device)
zero = torch.zeros(z.shape[0], 1).to(z)
cnf = model.chain[0]
zs = [z]
deltas = []
int_tps = np.linspace(args.int_tps[0], args.int_tps[-1], ntimes)
for i, itp in enumerate(int_tps[::-1][:-1]):
# tp counts down from last
timescale = int_tps[1] - int_tps[0]
integration_times = torch.tensor([itp - timescale, itp])
# integration_times = torch.tensor([np.linspace(itp - args.time_scale, itp, ntimes)])
integration_times = integration_times.type(torch.float32).to(device)
# transform to previous timepoint
z, delta_logp = cnf(zs[-1], zero, integration_times=integration_times)
zs.append(z)
deltas.append(delta_logp)
zs = torch.stack(zs, 0)
zs = zs.cpu().numpy()
np.save(os.path.join(savedir, 'backward_trajectories.npy'), zs)
def main(args):
device = torch.device(
"cuda:" + str(args.gpu) if torch.cuda.is_available() else "cpu"
)
if args.use_cpu:
device = torch.device("cpu")
data = dataset.SCData.factory(args.dataset, args)
args.timepoints = data.get_unique_times()
# Use maximum timepoint to establish integration_times
# as some timepoints may be left out for validation etc.
args.int_tps = (np.arange(max(args.timepoints) + 1) + 1.0) * args.time_scale
regularization_fns, regularization_coeffs = create_regularization_fns(args)
model = build_model_tabular(args, data.get_shape()[0], regularization_fns).to(
device
)
if args.use_growth:
growth_model_path = data.get_growth_net_path()
#growth_model_path = "/home/atong/TrajectoryNet/data/externel/growth_model_v2.ckpt"
growth_model = torch.load(growth_model_path, map_location=device)
if args.spectral_norm:
add_spectral_norm(model)
set_cnf_options(args, model)
state_dict = torch.load(args.save + "/checkpt.pth", map_location=device)
model.load_state_dict(state_dict["state_dict"])
#plot_output(device, args, model, data)
#exit()
# get_trajectory_samples(device, model, data)
args.data = data
args.timepoints = args.data.get_unique_times()
args.int_tps = (np.arange(max(args.timepoints) + 1) + 1.0) * args.time_scale
print('integrating backwards')
#end_time_data = data.data_dict[args.embedding_name]
end_time_data = data.get_data()[args.data.get_times()==np.max(args.data.get_times())]
#np.random.permutation(end_time_data)
#rand_idx = np.random.randint(end_time_data.shape[0], size=5000)
#end_time_data = end_time_data[rand_idx,:]
integrate_backwards(end_time_data, model, args.save, ntimes=100, device=device)
exit()
losses_list = []
#for factor in np.linspace(0.05, 0.95, 19):
#for factor in np.linspace(0.91, 0.99, 9):
if args.dataset == 'CHAFFER': # Do timepoint adjustment
print('adjusting_timepoints')
lt = args.leaveout_timepoint
if lt == 1:
factor = 0.6799872494335812
factor = 0.95
elif lt == 2:
factor = 0.2905983814032348
factor = 0.01
else:
raise RuntimeError('Unknown timepoint %d' % args.leaveout_timepoint)
args.int_tps[lt] = (1 - factor) * args.int_tps[lt-1] + factor * args.int_tps[lt+1]
losses = eval_utils.evaluate_kantorovich_v2(device, args, model)
losses_list.append(losses)
print(np.array(losses_list))
np.save(os.path.join(args.save, 'emd_list'), np.array(losses_list))
#zs = np.load(os.path.join(args.save, 'backward_trajectories'))
#losses = eval_utils.evaluate_mse(device, args, model)
#losses = eval_utils.evaluate_kantorovich(device, args, model)
#print(losses)
# eval_utils.generate_samples(device, args, model, growth_model, timepoint=args.timepoints[-1])
# eval_utils.calculate_path_length(device, args, model, data, args.int_tps[-1])
if __name__ == "__main__":
from parse import parser
args = parser.parse_args()
main(args)
| [
"matplotlib.cm.get_cmap",
"matplotlib.pyplot.clf",
"torch.cat",
"matplotlib.pyplot.figure",
"train_misc.set_cnf_options",
"dataset.SCData.factory",
"torch.arange",
"numpy.exp",
"torch.device",
"torch.no_grad",
"os.path.join",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.mesh... | [((1169, 1193), 'numpy.linspace', 'np.linspace', (['(-4)', '(4)', 'npts'], {}), '(-4, 4, npts)\n', (1180, 1193), True, 'import numpy as np\n'), ((1207, 1230), 'numpy.meshgrid', 'np.meshgrid', (['side', 'side'], {}), '(side, side)\n', (1218, 1230), True, 'import numpy as np\n'), ((9340, 9375), 'os.path.join', 'os.path.join', (['args.save', '"""density2"""'], {}), "(args.save, 'density2')\n", (9352, 9375), False, 'import os\n'), ((9595, 9627), 'lib.viz_scrna.trajectory_to_video', 'trajectory_to_video', (['density_dir'], {}), '(density_dir)\n', (9614, 9627), False, 'from lib.viz_scrna import trajectory_to_video, save_vectors\n'), ((10989, 11031), 'dataset.SCData.factory', 'dataset.SCData.factory', (['args.dataset', 'args'], {}), '(args.dataset, args)\n', (11011, 11031), False, 'import dataset\n'), ((11330, 11361), 'train_misc.create_regularization_fns', 'create_regularization_fns', (['args'], {}), '(args)\n', (11355, 11361), False, 'from train_misc import create_regularization_fns, get_regularization\n'), ((11775, 11803), 'train_misc.set_cnf_options', 'set_cnf_options', (['args', 'model'], {}), '(args, model)\n', (11790, 11803), False, 'from train_misc import set_cnf_options, count_nfe, count_parameters\n'), ((11822, 11881), 'torch.load', 'torch.load', (["(args.save + '/checkpt.pth')"], {'map_location': 'device'}), "(args.save + '/checkpt.pth', map_location=device)\n", (11832, 11881), False, 'import torch\n'), ((13257, 13312), 'eval_utils.evaluate_kantorovich_v2', 'eval_utils.evaluate_kantorovich_v2', (['device', 'args', 'model'], {}), '(device, args, model)\n', (13291, 13312), False, 'import eval_utils\n'), ((13916, 13935), 'parse.parser.parse_args', 'parser.parse_args', ([], {}), '()\n', (13933, 13935), False, 'from parse import parser\n'), ((790, 813), 'os.path.exists', 'os.path.exists', (['dirname'], {}), '(dirname)\n', (804, 813), False, 'import os\n'), ((823, 843), 'os.makedirs', 'os.makedirs', (['dirname'], {}), '(dirname)\n', (834, 843), False, 'import os\n'), ((1429, 1444), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1442, 1444), False, 'import torch\n'), ((9803, 9818), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9816, 9818), False, 'import torch\n'), ((10026, 10080), 'numpy.linspace', 'np.linspace', (['args.int_tps[0]', 'args.int_tps[-1]', 'ntimes'], {}), '(args.int_tps[0], args.int_tps[-1], ntimes)\n', (10037, 10080), True, 'import numpy as np\n'), ((10675, 10693), 'torch.stack', 'torch.stack', (['zs', '(0)'], {}), '(zs, 0)\n', (10686, 10693), False, 'import torch\n'), ((10957, 10976), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (10969, 10976), False, 'import torch\n'), ((11660, 11710), 'torch.load', 'torch.load', (['growth_model_path'], {'map_location': 'device'}), '(growth_model_path, map_location=device)\n', (11670, 11710), False, 'import torch\n'), ((11746, 11770), 'train_misc.add_spectral_norm', 'add_spectral_norm', (['model'], {}), '(model)\n', (11763, 11770), False, 'from train_misc import add_spectral_norm, spectral_norm_power_iteration\n'), ((13354, 13375), 'numpy.array', 'np.array', (['losses_list'], {}), '(losses_list)\n', (13362, 13375), True, 'import numpy as np\n'), ((13389, 13424), 'os.path.join', 'os.path.join', (['args.save', '"""emd_list"""'], {}), "(args.save, 'emd_list')\n", (13401, 13424), False, 'import os\n'), ((13426, 13447), 'numpy.array', 'np.array', (['losses_list'], {}), '(losses_list)\n', (13434, 13447), True, 'import numpy as np\n'), ((2119, 2149), 'torch.cat', 'torch.cat', (['integration_list', '(0)'], {}), '(integration_list, 0)\n', (2128, 2149), False, 'import torch\n'), ((2838, 2863), 'torch.cat', 'torch.cat', (['full_zip[0]', '(0)'], {}), '(full_zip[0], 0)\n', (2847, 2863), False, 'import torch\n'), ((4237, 4272), 'numpy.concatenate', 'np.concatenate', (['grid_z_traj'], {'axis': '(1)'}), '(grid_z_traj, axis=1)\n', (4251, 4272), True, 'import numpy as np\n'), ((4303, 4342), 'numpy.concatenate', 'np.concatenate', (['grid_logpz_traj'], {'axis': '(1)'}), '(grid_logpz_traj, axis=1)\n', (4317, 4342), True, 'import numpy as np\n'), ((4356, 4382), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (4366, 4382), True, 'import matplotlib.pyplot as plt\n'), ((10253, 10289), 'torch.tensor', 'torch.tensor', (['[itp - timescale, itp]'], {}), '([itp - timescale, itp])\n', (10265, 10289), False, 'import torch\n'), ((10740, 10790), 'os.path.join', 'os.path.join', (['savedir', '"""backward_trajectories.npy"""'], {}), "(savedir, 'backward_trajectories.npy')\n", (10752, 10790), False, 'import os\n'), ((10876, 10901), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10899, 10901), False, 'import torch\n'), ((4445, 4454), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4452, 4454), True, 'import matplotlib.pyplot as plt\n'), ((4526, 4562), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(1)', '(1)'], {'aspect': '"""equal"""'}), "(1, 1, 1, aspect='equal')\n", (4537, 4562), True, 'import matplotlib.pyplot as plt\n'), ((5217, 5253), 'matplotlib.pyplot.cm.Spectral', 'plt.cm.Spectral', (['(t / z_traj.shape[0])'], {}), '(t / z_traj.shape[0])\n', (5232, 5253), True, 'import matplotlib.pyplot as plt\n'), ((5632, 5695), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'matplotlib.colors.LinearSegmentedColormap.from_list', (['""""""', 'tuples'], {}), "('', tuples)\n", (5683, 5695), False, 'import matplotlib\n'), ((5767, 5804), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['xx', 'yy', 'qz'], {'cmap': 'cmap'}), '(xx, yy, qz, cmap=cmap)\n', (5781, 5804), True, 'import matplotlib.pyplot as plt\n'), ((6063, 6091), 'matplotlib.cm.get_cmap', 'matplotlib.cm.get_cmap', (['None'], {}), '(None)\n', (6085, 6091), False, 'import matplotlib\n'), ((8108, 8150), 'torch.linspace', 'torch.linspace', (['(0)', 'args.int_tps[0]', 'ntimes'], {}), '(0, args.int_tps[0], ntimes)\n', (8122, 8150), False, 'import torch\n'), ((9908, 9934), 'torch.zeros', 'torch.zeros', (['z.shape[0]', '(1)'], {}), '(z.shape[0], 1)\n', (9919, 9934), False, 'import torch\n'), ((1240, 1260), 'torch.from_numpy', 'torch.from_numpy', (['xx'], {}), '(xx)\n', (1256, 1260), False, 'import torch\n'), ((1301, 1321), 'torch.from_numpy', 'torch.from_numpy', (['yy'], {}), '(yy)\n', (1317, 1321), False, 'import torch\n'), ((3025, 3057), 'torch.arange', 'torch.arange', (['(0)', 'z_grid.shape[0]'], {}), '(0, z_grid.shape[0])\n', (3037, 3057), False, 'import torch\n'), ((5355, 5377), 'numpy.percentile', 'np.percentile', (['qz', '(0.1)'], {}), '(qz, 0.1)\n', (5368, 5377), True, 'import numpy as np\n'), ((7874, 7915), 'os.path.join', 'os.path.join', (['savedir', 'f"""viz-{t:05d}.jpg"""'], {}), "(savedir, f'viz-{t:05d}.jpg')\n", (7886, 7915), False, 'import os\n'), ((8241, 8284), 'torch.linspace', 'torch.linspace', (['args.int_tps[i]', 'et', 'ntimes'], {}), '(args.int_tps[i], et, ntimes)\n', (8255, 8284), False, 'import torch\n'), ((1860, 1899), 'torch.linspace', 'torch.linspace', (['(0)', 'end_times[0]', 'ntimes'], {}), '(0, end_times[0], ntimes)\n', (1874, 1899), False, 'import torch\n'), ((5161, 5174), 'numpy.exp', 'np.exp', (['logqz'], {}), '(logqz)\n', (5167, 5174), True, 'import numpy as np\n'), ((9832, 9861), 'torch.from_numpy', 'torch.from_numpy', (['end_samples'], {}), '(end_samples)\n', (9848, 9861), False, 'import torch\n'), ((2024, 2064), 'torch.linspace', 'torch.linspace', (['end_times[i]', 'et', 'ntimes'], {}), '(end_times[i], et, ntimes)\n', (2038, 2064), False, 'import torch\n'), ((3947, 3972), 'torch.cat', 'torch.cat', (['full_zip[0]', '(0)'], {}), '(full_zip[0], 0)\n', (3956, 3972), False, 'import torch\n'), ((4022, 4047), 'torch.cat', 'torch.cat', (['full_zip[1]', '(0)'], {}), '(full_zip[1], 0)\n', (4031, 4047), False, 'import torch\n')] |
import torch
import numpy as np
import v2.mesh_op as mesh_op
from lie_learn.spaces import S2
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
def e2f(torch_edges, torch_faces):
""" Calculate the intersection point from the edge to the face
Args:
torch_edges (Tensor): a m x 2 x 3 array, m is the number of cameras, 2 is two points, 3 is xyz coords
torch_faces (Tensor): a n x 3 x 3 array, n is the number of faces, 3 is three points, 3 is xyz coords
"""
# Get all intersected points using point-normal form
# Reference, simple math for calculating the intersection of a plane and a line in a 3D space
p0 = torch.mean(torch_faces, dim=1)
e1 = torch_faces[:, 0, :] - torch_faces[:, 2, :]
e2 = torch_faces[:, 1, :] - torch_faces[:, 2, :]
n = torch.cross(e1, e2)
l0 = torch_edges[:, 0, :] # To be used in the next stage
l = torch_edges[:, 1, :] - torch_edges[:, 0, :]
p0 = p0.repeat(len(l0), 1, 1).permute(1, 0, 2)
n = n.repeat(len(l0), 1, 1).permute(1, 0, 2)
p0_l0_n = torch.sum((p0 - l0) * n, dim=2)
# Calculate sin and cos
l_repeat = l.repeat(len(n), 1, 1)
# l_repeat_2norm = torch.norm(l_repeat, dim=2) # all norm for my camera ray is 1
n_2norm = torch.norm(n, dim=2)
n_l_cross = torch.cross(n, l_repeat, dim=2)
n_l_cross_2norm = torch.norm(n_l_cross, dim=2)
n_l_dot = torch.sum(n * l_repeat, dim=2)
n_l_sin = n_l_cross_2norm / n_2norm
n_l_cos = n_l_dot / n_2norm
# Keep calculating the intersected points
l_n = torch.sum(l * n, dim=2) # To be used in the next stage
d = p0_l0_n / l_n
d = torch.stack((d, d, d), dim=2)
ip = d * l + l0 # Intersected points. To be used in the next stage
bp = torch.ones(d.shape, dtype=d.dtype, device=d.device) * l + l0 # Boundary points.
# Determine whether the intersected points is inside of the plane
a = torch_faces[:, 0, :].repeat(len(l0), 1, 1).permute(1, 0, 2)
b = torch_faces[:, 1, :].repeat(len(l0), 1, 1).permute(1, 0, 2)
c = torch_faces[:, 2, :].repeat(len(l0), 1, 1).permute(1, 0, 2)
v0 = c - a
v1 = b - a
v2 = ip - a
v00 = torch.sum(v0 * v0, dim=2)
v01 = torch.sum(v0 * v1, dim=2)
v02 = torch.sum(v0 * v2, dim=2)
v11 = torch.sum(v1 * v1, dim=2)
v12 = torch.sum(v1 * v2, dim=2)
denominator = v00 * v11 - v01 * v01
u = (v11 * v02 - v01 * v12) / denominator
v = (v00 * v12 - v01 * v02) / denominator
inface = (u + v) <= (1 + 1e-6)
inface[(u < (0 - 1e-6)) | (u > (1 + 1e-6))] = False
inface[(v < (0 - 1e-6)) | (v > (1 + 1e-6))] = False
ip2l0_d = torch.norm(ip - l0, dim=2)
ip2l0_d[~inface] = 1 # equals to the diameter of the sphere
ip2l0_d[l_n == 0] = 1 # equals to the diameter of the sphere
# Get minimum distance
ip2l0_d_min, ip2l0_d_argmin = torch.min(ip2l0_d, dim=0)
# Get the coords of the intersected points with minimum distance
ip2l0 = ip[ip2l0_d_argmin]
bp2l0 = bp[ip2l0_d_argmin]
ip2l0[~inface[ip2l0_d_argmin]] = bp2l0[~inface[ip2l0_d_argmin]]
ip2l0[(l_n == 0)[ip2l0_d_argmin]] = bp2l0[(l_n == 0)[ip2l0_d_argmin]]
n_l_sin = n_l_sin[ip2l0_d_argmin]
n_l_cos = n_l_cos[ip2l0_d_argmin]
ip2l0_diag = torch.diagonal(ip2l0, dim1=0, dim2=1).transpose(1, 0)
ip2l0_sin = torch.diagonal(n_l_sin)
ip2l0_cos = torch.diagonal(n_l_cos)
return ip2l0_diag, ip2l0_d_min, ip2l0_sin, ip2l0_cos
def e2f_stepped(ray_edges, mesh_triangles, face_interval, edge_interval):
""" GPU has very limited memory, so I have to split rays and triangles into small batches
Args:
ray_edges:
mesh_triangles:
face_interval (int): The interval per mini-batch to split triangles
edge_interval (int): The interval per mini-batch to split rays
"""
face_steps = int(np.ceil(mesh_triangles.size()[0] / face_interval))
edge_steps = int(np.ceil(ray_edges.size()[0] / edge_interval))
ip2l0_diag_all = torch.zeros(face_steps, ray_edges.size()[0], 3, device=DEVICE)
ip2l0_d_min_all = torch.zeros(face_steps, ray_edges.size()[0], device=DEVICE)
ip2l0_sin_all = torch.zeros(face_steps, ray_edges.size()[0], device=DEVICE)
ip2l0_cos_all = torch.zeros(face_steps, ray_edges.size()[0], device=DEVICE)
print('Total steps: %d' % face_steps)
for i in range(face_steps):
for j in range(edge_steps):
ip2l0_diag, ip2l0_d_min, ip2l0_sin, ip2l0_cos = e2f(
ray_edges[j * edge_interval: min((j + 1) * edge_interval, ray_edges.size()[0])],
mesh_triangles[i * face_interval:(i + 1) * face_interval]
)
ip2l0_diag_all[i,
j * edge_interval:min((j + 1) * edge_interval, ray_edges.size()[0])] = ip2l0_diag
ip2l0_d_min_all[i,
j * edge_interval:min((j + 1) * edge_interval, ray_edges.size()[0])] = ip2l0_d_min
ip2l0_sin_all[i,
j * edge_interval:min((j + 1) * edge_interval, ray_edges.size()[0])] = ip2l0_sin
ip2l0_cos_all[i,
j * edge_interval:min((j + 1) * edge_interval, ray_edges.size()[0])] = ip2l0_cos
ip2l0_d_min, ip2l0_d_argmin_all = torch.min(ip2l0_d_min_all, dim=0)
ip2l0_sin, _ = torch.min(ip2l0_sin_all, dim=0)
ip2l0_cos, _ = torch.min(ip2l0_cos_all, dim=0)
ip2l0_d_argmin_all = ip2l0_d_argmin_all.repeat(3, 1).transpose(0, 1).unsqueeze(0)
ip2l0_diag = ip2l0_diag_all.gather(0, ip2l0_d_argmin_all).squeeze()
return ip2l0_diag, ip2l0_d_min, ip2l0_sin, ip2l0_cos
class ProjectOnSphere:
def __init__(self, bandwidth):
self.bandwidth = bandwidth
self.sgrid = self.make_sgrid(bandwidth, alpha=0, beta=0, gamma=0, grid_type='SOFT')
def __call__(self, mesh):
im = self.render_model(mesh, self.sgrid)
return im
def __repr__(self):
return self.__class__.__name__ + '(bandwidth={0})'.format(self.bandwidth)
@staticmethod
def make_sgrid(b, alpha, beta, gamma, grid_type):
theta, phi = S2.meshgrid(b=b, grid_type=grid_type)
sgrid = S2.change_coordinates(np.c_[theta[..., None], phi[..., None]], p_from='S', p_to='C')
sgrid = sgrid.reshape((-1, 3))
R = mesh_op.rotmat(alpha, beta, gamma, hom_coord=False)
sgrid = np.einsum('ij,nj->ni', R, sgrid)
return sgrid
@staticmethod
def render_model(mesh, sgrid):
# Cast rays
# triangle_indices = mesh.ray.intersects_first(ray_origins=sgrid, ray_directions=-sgrid)
index_tri, index_ray, loc = mesh.ray.intersects_id(
ray_origins=sgrid, ray_directions=-sgrid, multiple_hits=False, return_locations=True)
loc = loc.reshape((-1, 3)) # fix bug if loc is empty
# Each ray is in 1-to-1 correspondence with a grid point. Find the position of these points
grid_hits = sgrid[index_ray]
grid_hits_normalized = grid_hits / np.linalg.norm(grid_hits, axis=1, keepdims=True)
# Compute the distance from the grid points to the intersection pionts
dist = np.linalg.norm(grid_hits - loc, axis=-1)
# For each intersection, look up the normal of the triangle that was hit
normals = mesh.face_normals[index_tri]
normalized_normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
# Construct spherical images
dist_im = np.ones(sgrid.shape[0])
dist_im[index_ray] = dist
# dist_im = dist_im.reshape(theta.shape)
# shaded_im = np.zeros(sgrid.shape[0])
# shaded_im[index_ray] = normals.dot(light_dir)
# shaded_im = shaded_im.reshape(theta.shape) + 0.4
n_dot_ray_im = np.zeros(sgrid.shape[0])
# n_dot_ray_im[index_ray] = np.abs(np.einsum("ij,ij->i", normals, grid_hits_normalized))
n_dot_ray_im[index_ray] = np.einsum("ij,ij->i", normalized_normals, grid_hits_normalized)
nx, ny, nz = normalized_normals[:, 0], normalized_normals[:, 1], normalized_normals[:, 2]
gx, gy, gz = grid_hits_normalized[:, 0], grid_hits_normalized[:, 1], grid_hits_normalized[:, 2]
wedge_norm = np.sqrt((nx * gy - ny * gx) ** 2 + (nx * gz - nz * gx) ** 2 + (ny * gz - nz * gy) ** 2)
n_wedge_ray_im = np.zeros(sgrid.shape[0])
n_wedge_ray_im[index_ray] = wedge_norm
# Combine channels to construct final image
# im = dist_im.reshape((1,) + dist_im.shape)
im = np.stack((dist_im, n_dot_ray_im, n_wedge_ray_im), axis=0)
return im
| [
"torch.mean",
"numpy.stack",
"torch.ones",
"torch.stack",
"torch.diagonal",
"lie_learn.spaces.S2.meshgrid",
"torch.norm",
"numpy.einsum",
"numpy.ones",
"numpy.zeros",
"lie_learn.spaces.S2.change_coordinates",
"torch.cuda.is_available",
"numpy.linalg.norm",
"v2.mesh_op.rotmat",
"torch.cro... | [((114, 139), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (137, 139), False, 'import torch\n'), ((658, 688), 'torch.mean', 'torch.mean', (['torch_faces'], {'dim': '(1)'}), '(torch_faces, dim=1)\n', (668, 688), False, 'import torch\n'), ((803, 822), 'torch.cross', 'torch.cross', (['e1', 'e2'], {}), '(e1, e2)\n', (814, 822), False, 'import torch\n'), ((1052, 1083), 'torch.sum', 'torch.sum', (['((p0 - l0) * n)'], {'dim': '(2)'}), '((p0 - l0) * n, dim=2)\n', (1061, 1083), False, 'import torch\n'), ((1251, 1271), 'torch.norm', 'torch.norm', (['n'], {'dim': '(2)'}), '(n, dim=2)\n', (1261, 1271), False, 'import torch\n'), ((1288, 1319), 'torch.cross', 'torch.cross', (['n', 'l_repeat'], {'dim': '(2)'}), '(n, l_repeat, dim=2)\n', (1299, 1319), False, 'import torch\n'), ((1342, 1370), 'torch.norm', 'torch.norm', (['n_l_cross'], {'dim': '(2)'}), '(n_l_cross, dim=2)\n', (1352, 1370), False, 'import torch\n'), ((1385, 1415), 'torch.sum', 'torch.sum', (['(n * l_repeat)'], {'dim': '(2)'}), '(n * l_repeat, dim=2)\n', (1394, 1415), False, 'import torch\n'), ((1545, 1568), 'torch.sum', 'torch.sum', (['(l * n)'], {'dim': '(2)'}), '(l * n, dim=2)\n', (1554, 1568), False, 'import torch\n'), ((1632, 1661), 'torch.stack', 'torch.stack', (['(d, d, d)'], {'dim': '(2)'}), '((d, d, d), dim=2)\n', (1643, 1661), False, 'import torch\n'), ((2158, 2183), 'torch.sum', 'torch.sum', (['(v0 * v0)'], {'dim': '(2)'}), '(v0 * v0, dim=2)\n', (2167, 2183), False, 'import torch\n'), ((2194, 2219), 'torch.sum', 'torch.sum', (['(v0 * v1)'], {'dim': '(2)'}), '(v0 * v1, dim=2)\n', (2203, 2219), False, 'import torch\n'), ((2230, 2255), 'torch.sum', 'torch.sum', (['(v0 * v2)'], {'dim': '(2)'}), '(v0 * v2, dim=2)\n', (2239, 2255), False, 'import torch\n'), ((2266, 2291), 'torch.sum', 'torch.sum', (['(v1 * v1)'], {'dim': '(2)'}), '(v1 * v1, dim=2)\n', (2275, 2291), False, 'import torch\n'), ((2302, 2327), 'torch.sum', 'torch.sum', (['(v1 * v2)'], {'dim': '(2)'}), '(v1 * v2, dim=2)\n', (2311, 2327), False, 'import torch\n'), ((2625, 2651), 'torch.norm', 'torch.norm', (['(ip - l0)'], {'dim': '(2)'}), '(ip - l0, dim=2)\n', (2635, 2651), False, 'import torch\n'), ((2845, 2870), 'torch.min', 'torch.min', (['ip2l0_d'], {'dim': '(0)'}), '(ip2l0_d, dim=0)\n', (2854, 2870), False, 'import torch\n'), ((3310, 3333), 'torch.diagonal', 'torch.diagonal', (['n_l_sin'], {}), '(n_l_sin)\n', (3324, 3333), False, 'import torch\n'), ((3350, 3373), 'torch.diagonal', 'torch.diagonal', (['n_l_cos'], {}), '(n_l_cos)\n', (3364, 3373), False, 'import torch\n'), ((5170, 5203), 'torch.min', 'torch.min', (['ip2l0_d_min_all'], {'dim': '(0)'}), '(ip2l0_d_min_all, dim=0)\n', (5179, 5203), False, 'import torch\n'), ((5223, 5254), 'torch.min', 'torch.min', (['ip2l0_sin_all'], {'dim': '(0)'}), '(ip2l0_sin_all, dim=0)\n', (5232, 5254), False, 'import torch\n'), ((5274, 5305), 'torch.min', 'torch.min', (['ip2l0_cos_all'], {'dim': '(0)'}), '(ip2l0_cos_all, dim=0)\n', (5283, 5305), False, 'import torch\n'), ((6009, 6046), 'lie_learn.spaces.S2.meshgrid', 'S2.meshgrid', ([], {'b': 'b', 'grid_type': 'grid_type'}), '(b=b, grid_type=grid_type)\n', (6020, 6046), False, 'from lie_learn.spaces import S2\n'), ((6063, 6151), 'lie_learn.spaces.S2.change_coordinates', 'S2.change_coordinates', (['np.c_[theta[..., None], phi[..., None]]'], {'p_from': '"""S"""', 'p_to': '"""C"""'}), "(np.c_[theta[..., None], phi[..., None]], p_from='S',\n p_to='C')\n", (6084, 6151), False, 'from lie_learn.spaces import S2\n'), ((6200, 6251), 'v2.mesh_op.rotmat', 'mesh_op.rotmat', (['alpha', 'beta', 'gamma'], {'hom_coord': '(False)'}), '(alpha, beta, gamma, hom_coord=False)\n', (6214, 6251), True, 'import v2.mesh_op as mesh_op\n'), ((6268, 6300), 'numpy.einsum', 'np.einsum', (['"""ij,nj->ni"""', 'R', 'sgrid'], {}), "('ij,nj->ni', R, sgrid)\n", (6277, 6300), True, 'import numpy as np\n'), ((7039, 7079), 'numpy.linalg.norm', 'np.linalg.norm', (['(grid_hits - loc)'], {'axis': '(-1)'}), '(grid_hits - loc, axis=-1)\n', (7053, 7079), True, 'import numpy as np\n'), ((7351, 7374), 'numpy.ones', 'np.ones', (['sgrid.shape[0]'], {}), '(sgrid.shape[0])\n', (7358, 7374), True, 'import numpy as np\n'), ((7645, 7669), 'numpy.zeros', 'np.zeros', (['sgrid.shape[0]'], {}), '(sgrid.shape[0])\n', (7653, 7669), True, 'import numpy as np\n'), ((7801, 7864), 'numpy.einsum', 'np.einsum', (['"""ij,ij->i"""', 'normalized_normals', 'grid_hits_normalized'], {}), "('ij,ij->i', normalized_normals, grid_hits_normalized)\n", (7810, 7864), True, 'import numpy as np\n'), ((8089, 8180), 'numpy.sqrt', 'np.sqrt', (['((nx * gy - ny * gx) ** 2 + (nx * gz - nz * gx) ** 2 + (ny * gz - nz * gy) ** 2\n )'], {}), '((nx * gy - ny * gx) ** 2 + (nx * gz - nz * gx) ** 2 + (ny * gz - nz *\n gy) ** 2)\n', (8096, 8180), True, 'import numpy as np\n'), ((8202, 8226), 'numpy.zeros', 'np.zeros', (['sgrid.shape[0]'], {}), '(sgrid.shape[0])\n', (8210, 8226), True, 'import numpy as np\n'), ((8393, 8450), 'numpy.stack', 'np.stack', (['(dist_im, n_dot_ray_im, n_wedge_ray_im)'], {'axis': '(0)'}), '((dist_im, n_dot_ray_im, n_wedge_ray_im), axis=0)\n', (8401, 8450), True, 'import numpy as np\n'), ((1744, 1795), 'torch.ones', 'torch.ones', (['d.shape'], {'dtype': 'd.dtype', 'device': 'd.device'}), '(d.shape, dtype=d.dtype, device=d.device)\n', (1754, 1795), False, 'import torch\n'), ((3240, 3277), 'torch.diagonal', 'torch.diagonal', (['ip2l0'], {'dim1': '(0)', 'dim2': '(1)'}), '(ip2l0, dim1=0, dim2=1)\n', (3254, 3277), False, 'import torch\n'), ((6895, 6943), 'numpy.linalg.norm', 'np.linalg.norm', (['grid_hits'], {'axis': '(1)', 'keepdims': '(True)'}), '(grid_hits, axis=1, keepdims=True)\n', (6909, 6943), True, 'import numpy as np\n'), ((7248, 7294), 'numpy.linalg.norm', 'np.linalg.norm', (['normals'], {'axis': '(1)', 'keepdims': '(True)'}), '(normals, axis=1, keepdims=True)\n', (7262, 7294), True, 'import numpy as np\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
from random import shuffle
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument(
'--file',
type=str,
required=1,
help='Absolute path to the csv file.')
parser.add_argument(
'--label_index',
type=int,
required = 1,
help='index of label value in csv sample')
args = parser.parse_args()
samples = []
f_in = open(args.file, 'r')
index = 0
for line in f_in:
if index == 0: # First line feature names
num_features = line.count(',')
else:
sample = np.array(line.split(','))
sample = sample.astype(np.float)
temp = sample[0]
sample[0] = sample[args.label_index]
sample[args.label_index] = temp
samples.append(sample)
index += 1
num_samples = index-1
samples = np.asarray(samples)
print('samples.shape: ' + str(samples.shape) )
f_out = open(args.file + '_raw_' + str(samples.shape[0]) + '_' + str(samples.shape[1]), 'w');
samples.tofile(f_out)
f_out.close() | [
"numpy.asarray",
"argparse.ArgumentParser"
] | [((204, 229), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (227, 229), False, 'import argparse\n'), ((856, 875), 'numpy.asarray', 'np.asarray', (['samples'], {}), '(samples)\n', (866, 875), True, 'import numpy as np\n')] |
import sys
from os import path
current_dir = path.dirname(path.abspath(__file__))
while path.split(current_dir)[-1] != r'Heron':
current_dir = path.dirname(current_dir)
sys.path.insert(0, path.dirname(current_dir))
import numpy as np
import h5py
from datetime import datetime
from Heron.communication.socket_for_serialization import Socket
from Heron import general_utils as gu
need_parameters = True
time_stamp: bool
expand: bool
on_axis: int
disk_array: h5py.Dataset
file_name: str
input_shape = None
input_type: type
output_type: str
shape_step: list
hdf5_file: h5py.File
def initialise(worker_object):
return True
def add_timestamp_to_filename():
global file_name
filename = file_name.split('.')
date_time = '{}'.format(datetime.now()).replace(':', '-').replace(' ', '_').split('.')[0]
file_name = '{}_{}.{}'.format(filename[0], date_time, filename[1])
def add_data_to_array(data):
global disk_array
global shape_step
global on_axis
disk_array.resize(np.array(disk_array.shape) + shape_step)
slice = [np.s_[:] for i in range(len(data.shape))]
slice[on_axis] = np.s_[int(disk_array.shape[on_axis] - shape_step[on_axis]):disk_array.shape[on_axis]]
disk_array[tuple(slice)] = data
def save_array(data, parameters):
global need_parameters
global time_stamp
global expand
global on_axis
global file_name
global disk_array
global input_shape
global input_type
global output_type
global shape_step
global hdf5_file
# Once the parameters are received at the starting of the graph then they cannot be updated any more.
if need_parameters:
try:
file_name = parameters[0]
time_stamp = parameters[1]
expand = parameters[2]
on_axis = parameters[3]
output_type = parameters[4]
need_parameters = False
worker_object.relic_create_parameters_df(file_name=file_name, time_stamp=time_stamp, expand=expand,
on_axis=on_axis, output_type=output_type)
except:
return
message = data[1:] # data[0] is the topic
array = Socket.reconstruct_array_from_bytes_message(message)
if input_shape is None:
try:
input_type = array.dtype
if expand:
input_shape = list(array.shape)
shape_step = np.zeros(len(input_shape))
input_shape[on_axis] = 0
shape_step[on_axis] = array.shape[on_axis]
else:
input_shape = []
shape_step = []
for i, n in enumerate(array.shape):
if i == on_axis:
input_shape.append(0)
shape_step.append(1)
input_shape.append(n)
shape_step.append(0)
max_shape = np.copy(input_shape)
max_shape = list(max_shape)
max_shape[np.where(np.array(input_shape) == 0)[0][0]] = None
input_shape = tuple(input_shape)
max_shape = tuple(max_shape)
if output_type == 'Same':
output_type = input_type
else:
output_type = np.dtype(output_type)
if time_stamp:
add_timestamp_to_filename()
hdf5_file = h5py.File(file_name, 'w')
disk_array = hdf5_file.create_dataset('data', shape=input_shape, maxshape=max_shape, dtype=output_type,
chunks=True)
if not expand:
array = np.expand_dims(array, on_axis)
add_data_to_array(array)
except Exception as e:
print(e)
else:
try:
if not expand:
array = np.expand_dims(array, on_axis)
add_data_to_array(array)
except Exception as e:
print(e)
def on_end_of_life():
global hdf5_file
try:
hdf5_file.close()
except:
pass
if __name__ == "__main__":
worker_object = gu.start_the_sink_worker_process(initialisation_function=initialise,
work_function=save_array,
end_of_life_function=on_end_of_life)
worker_object.start_ioloop()
| [
"os.path.abspath",
"h5py.File",
"numpy.copy",
"os.path.dirname",
"Heron.communication.socket_for_serialization.Socket.reconstruct_array_from_bytes_message",
"numpy.dtype",
"numpy.expand_dims",
"Heron.general_utils.start_the_sink_worker_process",
"numpy.array",
"os.path.split",
"datetime.datetime... | [((64, 86), 'os.path.abspath', 'path.abspath', (['__file__'], {}), '(__file__)\n', (76, 86), False, 'from os import path\n'), ((155, 180), 'os.path.dirname', 'path.dirname', (['current_dir'], {}), '(current_dir)\n', (167, 180), False, 'from os import path\n'), ((201, 226), 'os.path.dirname', 'path.dirname', (['current_dir'], {}), '(current_dir)\n', (213, 226), False, 'from os import path\n'), ((2273, 2325), 'Heron.communication.socket_for_serialization.Socket.reconstruct_array_from_bytes_message', 'Socket.reconstruct_array_from_bytes_message', (['message'], {}), '(message)\n', (2316, 2325), False, 'from Heron.communication.socket_for_serialization import Socket\n'), ((4258, 4393), 'Heron.general_utils.start_the_sink_worker_process', 'gu.start_the_sink_worker_process', ([], {'initialisation_function': 'initialise', 'work_function': 'save_array', 'end_of_life_function': 'on_end_of_life'}), '(initialisation_function=initialise,\n work_function=save_array, end_of_life_function=on_end_of_life)\n', (4290, 4393), True, 'from Heron import general_utils as gu\n'), ((95, 118), 'os.path.split', 'path.split', (['current_dir'], {}), '(current_dir)\n', (105, 118), False, 'from os import path\n'), ((1052, 1078), 'numpy.array', 'np.array', (['disk_array.shape'], {}), '(disk_array.shape)\n', (1060, 1078), True, 'import numpy as np\n'), ((3023, 3043), 'numpy.copy', 'np.copy', (['input_shape'], {}), '(input_shape)\n', (3030, 3043), True, 'import numpy as np\n'), ((3502, 3527), 'h5py.File', 'h5py.File', (['file_name', '"""w"""'], {}), "(file_name, 'w')\n", (3511, 3527), False, 'import h5py\n'), ((3380, 3401), 'numpy.dtype', 'np.dtype', (['output_type'], {}), '(output_type)\n', (3388, 3401), True, 'import numpy as np\n'), ((3764, 3794), 'numpy.expand_dims', 'np.expand_dims', (['array', 'on_axis'], {}), '(array, on_axis)\n', (3778, 3794), True, 'import numpy as np\n'), ((3969, 3999), 'numpy.expand_dims', 'np.expand_dims', (['array', 'on_axis'], {}), '(array, on_axis)\n', (3983, 3999), True, 'import numpy as np\n'), ((3117, 3138), 'numpy.array', 'np.array', (['input_shape'], {}), '(input_shape)\n', (3125, 3138), True, 'import numpy as np\n'), ((789, 803), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (801, 803), False, 'from datetime import datetime\n')] |
import math
import numpy as np
import scipy as sp
from scipy import pi as PI
import scipy.integrate as integrate
J = sp.sqrt(-1)
'''
ecgsyn implementation
function [s, ipeaks] = ecgsyn(sfecg,N,Anoise,hrmean,hrstd,lfhfratio,sfint,ti,ai,bi)
sfecg: sampling freq ecg
N: heart beat number
anoise: additive noise
hrmean
hrstd
lfhfratio: LF/HF ratio
sfint: internal sampling frequency
ti: angles of extremea [-70 -15 0 15 100] degrees
ai = z-position of extrema [1.2 -5 30 -7.5 0.75]
bi = Gaussian width of peaks [0.25 0.1 0.1 0.1 0.4]
====================================================================
Original copyrights:
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
ecgsyn.m and its dependents are freely availble from Physionet -
http://www.physionet.org/ - please report any bugs to the authors above.
====================================================================
'''
def ecgsyn(sfecg=256,
N=256,
anoise=0,
hrmean=60,
hrstd=1,
lfhfratio=0.6,
sfint=512,
ti=[-70, -15, 0, 15, 100],
ai=[1.2, -5, 30, -7.5, 0.75], # PQRST
bi=[0.25, 0.1, 0.1, 0.1, 0.4] # PQRST
):
# adjust extrema parameters for mean heart rate
hrfact = math.sqrt(hrmean / 60)
hrfact2 = math.sqrt(hrfact)
bi = [b*hrfact for b in bi]
ti = [tii*PI/180 for tii in ti]
ti = [hrfact2*ti[0], hrfact*ti[1], ti[2], hrfact*ti[3], hrfact2*ti[4]]
# check that sfint is an integer multiple of sfecg
q = np.round(sfint/sfecg)
qd = sfint//sfecg
if not q == qd:
print('sfint must be integer multiple of sfecg')
return
# define frequency parameters for rr process
# flo and fhi correspond to the Mayer waves and respiratory rate respectively
flo = 0.1
fhi = 0.25
flostd = 0.01
fhistd = 0.01
# calculate time scales for rr and total output
sampfreqrr = 1
trr = 1 / sampfreqrr
tstep = 1 / sfecg
rrmean = (60 / hrmean)
Nrr = 2 ** (math.ceil(sp.log2(N * rrmean / trr)))
# compute rr process
rr0 = rrprocess(flo, fhi, flostd, fhistd, lfhfratio, hrmean, hrstd, sampfreqrr, Nrr)
# upsample rr time series from 1 Hz to sfint Hz
idx = np.arange(0.0, len(rr0), 1.0)
idx_interp = np.arange(0.0, len(rr0), 1/sfint)
rr = np.interp(idx_interp, idx, rr0)
# make the rr n time series
dt = 1 / sfint
rrn = np.zeros(len(rr))
tecg = 0
i = 0
while i < len(rr):
tecg += rr[i]
ip = int(np.round(tecg / dt))-1
for ii in np.arange(i, ip):
if ii >= len(rr):
break
rrn[ii] = rr[i]
i = ip
Nt = len(rr)-1
x0 = [1, 0, 0.04]
Tspan = np.arange(0, (Nt)*dt, dt)
'''ode with dop853'''
# solver = integrate.ode(desrivecgsyn)
# solver.set_integrator('dop853')
# solver.set_f_params([], rrn, sfint, ti, ai, bi)
# t0 = 0.0
# solver.set_initial_value(x0, t0)
# X0 = np.empty((len(Tspan), 3))
# X0[0] = x0
# k = 1
# while solver.successful() and solver.t < (Nt-1)*dt:
# solver.integrate(Tspan[k])
# X0[k] = solver.y
# k += 1
X0 = sp.integrate.odeint(desrivecgsyn, x0, Tspan, args=([], rrn, sfint, ti, ai, bi))
# downsample to required sfecg
X = X0[::int(q)]
# extract R - peaks times
ipeaks = detectpeaks(X, ti, sfecg)
# Scale signal to line between - 0.4 and 1.2 mV
z = [xx[2] for xx in X]
zmin = np.min(z)
zmax = np.max(z)
zrange = zmax - zmin
z = (z - zmin) * (1.6) / zrange - 0.4
# include additive uniformly distributed measurement noise
eta = 2 * np.random.rand(len(z)) - 1
s = z + anoise * eta
return (s, ipeaks)
def rrprocess(flo, fhi, flostd, fhistd, lfhfratio, hrmean, hrstd, sfrr, n):
w1 = 2*PI*flo
w2 = 2*PI*fhi
c1 = 2*PI*flostd
c2 = 2*PI*fhistd
sig2 = 1
sig1 = lfhfratio
rrmean = 60/hrmean
rrstd = 60*hrstd/(hrmean*hrmean)
df = sfrr/n
w = np.arange(0, n)*2*PI*df
dw1 = w-w1
dw2 = w-w2
Hw1 = sig1*sp.exp(-0.5*(dw1/c1)**2)/sp.sqrt(2*PI*c1**2)
Hw2 = sig2*sp.exp(-0.5*(dw2/c2)**2)/sp.sqrt(2*PI*c2**2)
Hw = Hw1 + Hw2
Hw0 = []
for h in Hw[0:n//2]:
Hw0.append(h)
for h in Hw[n//2-1::-1]:
Hw0.append(h)
Sw = [sfrr/2*sp.sqrt(h) for h in Hw0]
ph0 = 2*PI*sp.random.rand(n//2-1)
ph = []
ph.append(0)
for v in ph0:
ph.append(v)
ph.append(0)
for v in ph0[::-1]:
ph.append(-v)
SwC = [Sw[m]*sp.exp(J*ph[m]) for m in range(len(Sw))]
x = (1/n)*sp.real(sp.ifft(SwC))
xstd = sp.std(x)
ratio = rrstd/xstd
rr = rrmean + x*ratio
return rr
def detectpeaks(X, thetap, sfecg):
N = len(X)
irpeaks = np.zeros(N)
theta = [sp.arctan2(X[m][1], X[m][0]) for m in range(len(X))]
ind0 = -1*np.ones(N)
for i in range(N-1):
j = [v for v in filter(lambda x:theta[i]<= thetap[x] and thetap[x] <= theta[i+1], range(len(thetap)))]
if len(j) > 0:
d1 = thetap[j[0]] - theta[i]
d2 = theta[i + 1] - thetap[j[0]]
if d1 < d2:
ind0[i] = j[0]
else:
ind0[i+1] = j[0]
d = sp.ceil(sfecg / 64)
d = np.max([2, d])
ind = -1*np.ones(N)
z = [xx[2] for xx in X]
zmin = np.min(z)
zmax = np.max(z)
zext = [zmin, zmax, zmin, zmax, zmin]
sext = [1, -1, 1, -1, 1]
for i in range(5):
# clear ind1 Z k vmax imax iext
ind1 = [v for v in filter(lambda a: ind0[a]==i, range(len(ind0)))]
if len(ind1) == 0:
continue
n = len(ind1)
Z = np.ones(shape=(n, int(2 * d + 1))) * zext[i] * sext[i]
for j in np.arange(-d,d+1,1):
k = [v for v in filter(lambda a: 0<= ind1[a]+j and ind1[a]+j <= N-1, range(len(ind1)))]
for kk in k:
Z[kk][int(d + j)] = z[int(ind1[kk] + j-1)] * sext[i]
vmax = np.max(Z, axis=1)
ivmax = np.argmax(Z, axis=1)
iext = np.add(ivmax,ind1)
iext = np.add(iext, -d-2)
for ii in iext:
ind[int(ii)] = i
return ind
def desrivecgsyn(y0, t, flag, rr, sfint, ti, ai, bi):
# def desrivecgsyn(t, y0, flag, rr, sfint, ti, ai, bi):
# function dxdt = derivsecgsyn(t, x, flag, rr, sfint, ti, ai, bi)
# dxdt = derivsecgsyn(t, x, flag, rr, sampfreq, ti, ai, bi)
# ODE file for generating the synthetic ECG
# This file provides dxdt = F(t, x) taking input paramters:
# rr: rr process
# sfint: Internal sampling frequency[Hertz]
# Order of extrema: [P Q R S T]
# ti = angles of extrema[radians]
# ai = z - position of extrema
# bi = Gaussian width of peaks
# Copyright(c) 2003 by <NAME> & <NAME>, All Rights Reserved
# See IEEE Transactions On Biomedical Engineering, 50(3), 289 - 294, March 2003.
# Contact P.McSharry(patrick AT mcsharry DOT net) or % G.D.Clifford(gari AT mit DOT edu)
xi = sp.cos(ti)
yi = sp.sin(ti)
ta = sp.arctan2(y0[1], y0[0])
r0 = 1
a0 = 1.0 - sp.sqrt(y0[0] ** 2 + y0[1]**2 ) / r0
ip = int(sp.floor(t * sfint))
w0 = 2 * PI / rr[ip]
fresp = 0.25
zbase = 0.005 * sp.sin(2 * PI * fresp * t)
dx1dt = a0 * y0[0] - w0 * y0[1]
dx2dt = a0 * y0[1] + w0 * y0[0]
# dti = np.remainder(ta - ti, 2 * PI)
dti = [ta-tii for tii in ti]
for m in range(len(dti)):
if dti[m] >= 0:
dti[m] = np.remainder(dti[m], 2*PI)
else:
dti[m] = -np.remainder(-dti[m],2*PI)
dx3dt = -np.sum([ai[m]*dti[m]*np.exp(-0.5*(dti[m]/bi[m])**2) for m in range(len(ai))]) - 1.0*(y0[2]-zbase)
return [dx1dt, dx2dt, dx3dt]
| [
"scipy.cos",
"numpy.argmax",
"numpy.ones",
"scipy.random.rand",
"numpy.arange",
"scipy.log2",
"numpy.exp",
"numpy.interp",
"scipy.ceil",
"numpy.round",
"scipy.exp",
"scipy.integrate.odeint",
"numpy.max",
"scipy.arctan2",
"numpy.add",
"math.sqrt",
"numpy.remainder",
"numpy.min",
"... | [((120, 131), 'scipy.sqrt', 'sp.sqrt', (['(-1)'], {}), '(-1)\n', (127, 131), True, 'import scipy as sp\n'), ((1881, 1903), 'math.sqrt', 'math.sqrt', (['(hrmean / 60)'], {}), '(hrmean / 60)\n', (1890, 1903), False, 'import math\n'), ((1918, 1935), 'math.sqrt', 'math.sqrt', (['hrfact'], {}), '(hrfact)\n', (1927, 1935), False, 'import math\n'), ((2144, 2167), 'numpy.round', 'np.round', (['(sfint / sfecg)'], {}), '(sfint / sfecg)\n', (2152, 2167), True, 'import numpy as np\n'), ((2945, 2976), 'numpy.interp', 'np.interp', (['idx_interp', 'idx', 'rr0'], {}), '(idx_interp, idx, rr0)\n', (2954, 2976), True, 'import numpy as np\n'), ((3351, 3376), 'numpy.arange', 'np.arange', (['(0)', '(Nt * dt)', 'dt'], {}), '(0, Nt * dt, dt)\n', (3360, 3376), True, 'import numpy as np\n'), ((3808, 3887), 'scipy.integrate.odeint', 'sp.integrate.odeint', (['desrivecgsyn', 'x0', 'Tspan'], {'args': '([], rrn, sfint, ti, ai, bi)'}), '(desrivecgsyn, x0, Tspan, args=([], rrn, sfint, ti, ai, bi))\n', (3827, 3887), True, 'import scipy as sp\n'), ((4108, 4117), 'numpy.min', 'np.min', (['z'], {}), '(z)\n', (4114, 4117), True, 'import numpy as np\n'), ((4129, 4138), 'numpy.max', 'np.max', (['z'], {}), '(z)\n', (4135, 4138), True, 'import numpy as np\n'), ((5257, 5266), 'scipy.std', 'sp.std', (['x'], {}), '(x)\n', (5263, 5266), True, 'import scipy as sp\n'), ((5399, 5410), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (5407, 5410), True, 'import numpy as np\n'), ((5864, 5883), 'scipy.ceil', 'sp.ceil', (['(sfecg / 64)'], {}), '(sfecg / 64)\n', (5871, 5883), True, 'import scipy as sp\n'), ((5892, 5906), 'numpy.max', 'np.max', (['[2, d]'], {}), '([2, d])\n', (5898, 5906), True, 'import numpy as np\n'), ((5970, 5979), 'numpy.min', 'np.min', (['z'], {}), '(z)\n', (5976, 5979), True, 'import numpy as np\n'), ((5991, 6000), 'numpy.max', 'np.max', (['z'], {}), '(z)\n', (5997, 6000), True, 'import numpy as np\n'), ((7613, 7623), 'scipy.cos', 'sp.cos', (['ti'], {}), '(ti)\n', (7619, 7623), True, 'import scipy as sp\n'), ((7633, 7643), 'scipy.sin', 'sp.sin', (['ti'], {}), '(ti)\n', (7639, 7643), True, 'import scipy as sp\n'), ((7653, 7677), 'scipy.arctan2', 'sp.arctan2', (['y0[1]', 'y0[0]'], {}), '(y0[1], y0[0])\n', (7663, 7677), True, 'import scipy as sp\n'), ((3184, 3200), 'numpy.arange', 'np.arange', (['i', 'ip'], {}), '(i, ip)\n', (3193, 3200), True, 'import numpy as np\n'), ((4729, 4754), 'scipy.sqrt', 'sp.sqrt', (['(2 * PI * c1 ** 2)'], {}), '(2 * PI * c1 ** 2)\n', (4736, 4754), True, 'import scipy as sp\n'), ((4789, 4814), 'scipy.sqrt', 'sp.sqrt', (['(2 * PI * c2 ** 2)'], {}), '(2 * PI * c2 ** 2)\n', (4796, 4814), True, 'import scipy as sp\n'), ((4997, 5023), 'scipy.random.rand', 'sp.random.rand', (['(n // 2 - 1)'], {}), '(n // 2 - 1)\n', (5011, 5023), True, 'import scipy as sp\n'), ((5425, 5453), 'scipy.arctan2', 'sp.arctan2', (['X[m][1]', 'X[m][0]'], {}), '(X[m][1], X[m][0])\n', (5435, 5453), True, 'import scipy as sp\n'), ((5492, 5502), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (5499, 5502), True, 'import numpy as np\n'), ((5920, 5930), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (5927, 5930), True, 'import numpy as np\n'), ((6366, 6389), 'numpy.arange', 'np.arange', (['(-d)', '(d + 1)', '(1)'], {}), '(-d, d + 1, 1)\n', (6375, 6389), True, 'import numpy as np\n'), ((6597, 6614), 'numpy.max', 'np.max', (['Z'], {'axis': '(1)'}), '(Z, axis=1)\n', (6603, 6614), True, 'import numpy as np\n'), ((6631, 6651), 'numpy.argmax', 'np.argmax', (['Z'], {'axis': '(1)'}), '(Z, axis=1)\n', (6640, 6651), True, 'import numpy as np\n'), ((6667, 6686), 'numpy.add', 'np.add', (['ivmax', 'ind1'], {}), '(ivmax, ind1)\n', (6673, 6686), True, 'import numpy as np\n'), ((6701, 6721), 'numpy.add', 'np.add', (['iext', '(-d - 2)'], {}), '(iext, -d - 2)\n', (6707, 6721), True, 'import numpy as np\n'), ((7754, 7773), 'scipy.floor', 'sp.floor', (['(t * sfint)'], {}), '(t * sfint)\n', (7762, 7773), True, 'import scipy as sp\n'), ((7838, 7864), 'scipy.sin', 'sp.sin', (['(2 * PI * fresp * t)'], {}), '(2 * PI * fresp * t)\n', (7844, 7864), True, 'import scipy as sp\n'), ((2649, 2674), 'scipy.log2', 'sp.log2', (['(N * rrmean / trr)'], {}), '(N * rrmean / trr)\n', (2656, 2674), True, 'import scipy as sp\n'), ((4704, 4734), 'scipy.exp', 'sp.exp', (['(-0.5 * (dw1 / c1) ** 2)'], {}), '(-0.5 * (dw1 / c1) ** 2)\n', (4710, 4734), True, 'import scipy as sp\n'), ((4764, 4794), 'scipy.exp', 'sp.exp', (['(-0.5 * (dw2 / c2) ** 2)'], {}), '(-0.5 * (dw2 / c2) ** 2)\n', (4770, 4794), True, 'import scipy as sp\n'), ((4956, 4966), 'scipy.sqrt', 'sp.sqrt', (['h'], {}), '(h)\n', (4963, 4966), True, 'import scipy as sp\n'), ((5168, 5185), 'scipy.exp', 'sp.exp', (['(J * ph[m])'], {}), '(J * ph[m])\n', (5174, 5185), True, 'import scipy as sp\n'), ((5231, 5243), 'scipy.ifft', 'sp.ifft', (['SwC'], {}), '(SwC)\n', (5238, 5243), True, 'import scipy as sp\n'), ((7704, 7736), 'scipy.sqrt', 'sp.sqrt', (['(y0[0] ** 2 + y0[1] ** 2)'], {}), '(y0[0] ** 2 + y0[1] ** 2)\n', (7711, 7736), True, 'import scipy as sp\n'), ((8089, 8117), 'numpy.remainder', 'np.remainder', (['dti[m]', '(2 * PI)'], {}), '(dti[m], 2 * PI)\n', (8101, 8117), True, 'import numpy as np\n'), ((3143, 3162), 'numpy.round', 'np.round', (['(tecg / dt)'], {}), '(tecg / dt)\n', (3151, 3162), True, 'import numpy as np\n'), ((4634, 4649), 'numpy.arange', 'np.arange', (['(0)', 'n'], {}), '(0, n)\n', (4643, 4649), True, 'import numpy as np\n'), ((8152, 8181), 'numpy.remainder', 'np.remainder', (['(-dti[m])', '(2 * PI)'], {}), '(-dti[m], 2 * PI)\n', (8164, 8181), True, 'import numpy as np\n'), ((8214, 8250), 'numpy.exp', 'np.exp', (['(-0.5 * (dti[m] / bi[m]) ** 2)'], {}), '(-0.5 * (dti[m] / bi[m]) ** 2)\n', (8220, 8250), True, 'import numpy as np\n')] |
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from math import exp
try:
import numba as nb
nonumba = False
except:
nonumba = True
def avgKernel(envKernelDict,zeta):
'''
Compute the average global kernel.
:param envKernelDict: dictionary of environmental kernel whose keys are the corresponding
(i,j) index in the global kernel matrix.
:param zeta: int. Raise the environmental kernel matrices to the power of zeta
:return: np.array. Global average kernel matrix
'''
keys = envKernelDict.keys()
rows = np.array([key[0] for key in keys])
cols = np.array([key[1] for key in keys])
N = rows.max() + 1
M = cols.max() + 1
Similarity = np.zeros((N,M),dtype=np.float64)
for key,envKernel in envKernelDict.items():
Similarity[key[0],key[1]] = np.power(envKernel,zeta).mean()
if N == M:
diag = np.diag(Similarity)
return Similarity + Similarity.T - np.diag(diag)
else:
return Similarity
def rematchKernel(envKernelDict, gamma=2., eps=1e-6, nthreads=8):
'''
Compute the global rematch kernel matrix.
:param envKernelDict: dictionary of environmental kernel whose keys are the corresponding
(i,j) index in the global kernel matrix.
:param gamma: float. Entropy regularitation parameter (between 10 and 0.01 typically)
:param eps: float. Convergence threshold for the sinkhorn algorithm.
:param nthreads: int. Number of threads to compute the elements of the global kernel matrix
:return: np.array. Global REMatch kernel matrix
'''
keys = envKernelDict.keys()
envKernels = envKernelDict.values()
rows = np.array([key[0] for key in keys])
cols = np.array([key[1] for key in keys])
N = int(rows.max() + 1)
M = int(cols.max() + 1)
globalSimilarity = np.zeros((N, M), dtype=np.float64)
if nonumba:
print('Using the numpy version of rematch algorithm')
for key, envKernel in envKernelDict.items():
globalSimilarity[key[0], key[1]] = np_rematch(envKernel, gamma, eps=eps)
else:
nb_rematch = compile_rematch()
if nthreads == 1:
for key, envKernel in envKernelDict.items():
globalSimilarity[key[0], key[1]] = nb_rematch(envKernel, gamma, eps=eps)
else:
def nb_rematch_wrapper(kargs):
return nb_rematch(**kargs)
kargs = [{'envKernel': envKernel, 'gamma': gamma, 'eps': eps} for envKernel in envKernels]
# Create a pool of threads over the environmental matrices
pool = ThreadPool(nthreads)
results = pool.map(nb_rematch_wrapper, kargs)
pool.close()
pool.join()
for key, result in zip(keys, results):
globalSimilarity[key[0], key[1]] = result
diag = np.diag(globalSimilarity)
return globalSimilarity + globalSimilarity.T - np.diag(diag)
def compile_rematch():
'''
Compile the rematch function with numba.
:return: Compiled version of the rematch function.
'''
signatureRem = nb.double(nb.double[:, :], nb.double, nb.double)
nb_rematch = nb.jit(signatureRem, nopython=True, nogil=True,cache=True)(rematch)
return nb_rematch
def rematch(envKernel, gamma, eps):
'''
Sinkhorn algorithm for entropy regularized optimal transport problem.Computes the global similarity between two frames.
This version needs to be compiled with numba.
:param envKernel: np.array. Environmental kernel matrix between two frames or Cost matrix of the OT problem.
:param gamma: float. Regularization parameter
:param eps: float. Convergence threshold
:return: float. Global similarity between two frames
'''
n, m = envKernel.shape
mf = float(m)
nf = float(n)
K = np.zeros((n, m))
lamb = 1. / gamma
for it in range(n):
for jt in range(m):
K[it, jt] = exp(- (1 - envKernel[it, jt]) * lamb)
u = np.ones((n,)) / nf
v = np.ones((m,)) / mf
Kp = nf * K
iii = 0
err = 1
while (err > eps):
uprev = u
vprev = v
for jt in range(m):
kk = 0.
for it in range(n):
kk += K[it, jt] * u[it]
v[jt] = 1. / kk / mf
for it in range(n):
kk = 0.
for jt in range(m):
kk += Kp[it, jt] * v[jt]
u[it] = 1. / kk
if iii % 5:
erru = 0.
errv = 0.
for it in range(n):
erru += (u[it] - uprev[it]) * (u[it] - uprev[it]) / (u[it] * u[it])
for jt in range(m):
errv += (v[jt] - vprev[jt]) * (v[jt] - vprev[jt]) / (v[jt] * v[jt])
err = erru + errv
iii += 1
RematchSimilarity = 0.
for it in range(n):
rrow = 0.
for jt in range(m):
rrow += K[it, jt] * envKernel[it, jt] * v[jt]
RematchSimilarity += u[it] * rrow
return RematchSimilarity
def np_rematch(envKernel, gamma, eps=1e-6):
'''
Sinkhorn algorithm for entropy regularized optimal transport problem. Computes the global similarity between two frames.
This is the numpy version .
:param envKernel: np.array. Environmental kernel matrix between two frames or Cost matrix of the OT problem.
:param gamma: float. Regularization parameter
:param eps: float. Convergence threshold
:return: float. Global similarity between two frames
'''
n, m = envKernel.shape
K = np.exp(- (1 - envKernel) / gamma)
u = np.ones((n,)) / n
v = np.ones((m,)) / m
a = np.ones((n,)) / float(n)
b = np.ones((m,)) / float(m)
Kp = (1 / a).reshape(-1, 1) * K
iii = 0
err = 1
while (err > eps):
uprev = u
vprev = v
v = np.divide(b, np.dot(K.T, u))
u = 1. / np.dot(Kp, v)
if iii % 5:
err = np.sum((u - uprev) ** 2) / np.sum((u) ** 2) + np.sum((v - vprev) ** 2) / np.sum((v) ** 2)
iii += 1
rval = 0
for it in range(n):
rrow = np.sum(K[it, :] * envKernel[it, :] * v)
rval += u[it] * rrow
return rval
def normalizeKernel(kernel,nomralization_diagonal):
'''
Normalize a kernel matrix.
:param kernel: np.array. kernel matrix
:return: np.array. a copy of the normalized kernel
'''
n,m = kernel.shape
if n == m:
# needs to copy here to avoid pointer side effects
diag = np.diag(kernel).copy()
for it in range(n):
kernel[it,:] /= np.sqrt(diag[it] * diag)
else:
diag_n = nomralization_diagonal[0]
diag_m = nomralization_diagonal[1]
for ii in range(n):
for jj in range(m):
kernel[ii,jj] /= np.sqrt(diag_n[ii] * diag_m[jj])
return kernel
| [
"math.exp",
"numpy.sum",
"multiprocessing.dummy.Pool",
"numpy.power",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.exp",
"numba.jit",
"numpy.dot",
"numpy.diag",
"numba.double",
"numpy.sqrt"
] | [((578, 612), 'numpy.array', 'np.array', (['[key[0] for key in keys]'], {}), '([key[0] for key in keys])\n', (586, 612), True, 'import numpy as np\n'), ((624, 658), 'numpy.array', 'np.array', (['[key[1] for key in keys]'], {}), '([key[1] for key in keys])\n', (632, 658), True, 'import numpy as np\n'), ((722, 756), 'numpy.zeros', 'np.zeros', (['(N, M)'], {'dtype': 'np.float64'}), '((N, M), dtype=np.float64)\n', (730, 756), True, 'import numpy as np\n'), ((1679, 1713), 'numpy.array', 'np.array', (['[key[0] for key in keys]'], {}), '([key[0] for key in keys])\n', (1687, 1713), True, 'import numpy as np\n'), ((1725, 1759), 'numpy.array', 'np.array', (['[key[1] for key in keys]'], {}), '([key[1] for key in keys])\n', (1733, 1759), True, 'import numpy as np\n'), ((1839, 1873), 'numpy.zeros', 'np.zeros', (['(N, M)'], {'dtype': 'np.float64'}), '((N, M), dtype=np.float64)\n', (1847, 1873), True, 'import numpy as np\n'), ((2854, 2879), 'numpy.diag', 'np.diag', (['globalSimilarity'], {}), '(globalSimilarity)\n', (2861, 2879), True, 'import numpy as np\n'), ((3105, 3153), 'numba.double', 'nb.double', (['nb.double[:, :]', 'nb.double', 'nb.double'], {}), '(nb.double[:, :], nb.double, nb.double)\n', (3114, 3153), True, 'import numba as nb\n'), ((3826, 3842), 'numpy.zeros', 'np.zeros', (['(n, m)'], {}), '((n, m))\n', (3834, 3842), True, 'import numpy as np\n'), ((5530, 5562), 'numpy.exp', 'np.exp', (['(-(1 - envKernel) / gamma)'], {}), '(-(1 - envKernel) / gamma)\n', (5536, 5562), True, 'import numpy as np\n'), ((903, 922), 'numpy.diag', 'np.diag', (['Similarity'], {}), '(Similarity)\n', (910, 922), True, 'import numpy as np\n'), ((2931, 2944), 'numpy.diag', 'np.diag', (['diag'], {}), '(diag)\n', (2938, 2944), True, 'import numpy as np\n'), ((3171, 3230), 'numba.jit', 'nb.jit', (['signatureRem'], {'nopython': '(True)', 'nogil': '(True)', 'cache': '(True)'}), '(signatureRem, nopython=True, nogil=True, cache=True)\n', (3177, 3230), True, 'import numba as nb\n'), ((3988, 4001), 'numpy.ones', 'np.ones', (['(n,)'], {}), '((n,))\n', (3995, 4001), True, 'import numpy as np\n'), ((4015, 4028), 'numpy.ones', 'np.ones', (['(m,)'], {}), '((m,))\n', (4022, 4028), True, 'import numpy as np\n'), ((5572, 5585), 'numpy.ones', 'np.ones', (['(n,)'], {}), '((n,))\n', (5579, 5585), True, 'import numpy as np\n'), ((5598, 5611), 'numpy.ones', 'np.ones', (['(m,)'], {}), '((m,))\n', (5605, 5611), True, 'import numpy as np\n'), ((5625, 5638), 'numpy.ones', 'np.ones', (['(n,)'], {}), '((n,))\n', (5632, 5638), True, 'import numpy as np\n'), ((5658, 5671), 'numpy.ones', 'np.ones', (['(m,)'], {}), '((m,))\n', (5665, 5671), True, 'import numpy as np\n'), ((6074, 6113), 'numpy.sum', 'np.sum', (['(K[it, :] * envKernel[it, :] * v)'], {}), '(K[it, :] * envKernel[it, :] * v)\n', (6080, 6113), True, 'import numpy as np\n'), ((966, 979), 'numpy.diag', 'np.diag', (['diag'], {}), '(diag)\n', (973, 979), True, 'import numpy as np\n'), ((2605, 2625), 'multiprocessing.dummy.Pool', 'ThreadPool', (['nthreads'], {}), '(nthreads)\n', (2615, 2625), True, 'from multiprocessing.dummy import Pool as ThreadPool\n'), ((3941, 3977), 'math.exp', 'exp', (['(-(1 - envKernel[it, jt]) * lamb)'], {}), '(-(1 - envKernel[it, jt]) * lamb)\n', (3944, 3977), False, 'from math import exp\n'), ((5829, 5843), 'numpy.dot', 'np.dot', (['K.T', 'u'], {}), '(K.T, u)\n', (5835, 5843), True, 'import numpy as np\n'), ((5862, 5875), 'numpy.dot', 'np.dot', (['Kp', 'v'], {}), '(Kp, v)\n', (5868, 5875), True, 'import numpy as np\n'), ((6549, 6573), 'numpy.sqrt', 'np.sqrt', (['(diag[it] * diag)'], {}), '(diag[it] * diag)\n', (6556, 6573), True, 'import numpy as np\n'), ((840, 865), 'numpy.power', 'np.power', (['envKernel', 'zeta'], {}), '(envKernel, zeta)\n', (848, 865), True, 'import numpy as np\n'), ((6470, 6485), 'numpy.diag', 'np.diag', (['kernel'], {}), '(kernel)\n', (6477, 6485), True, 'import numpy as np\n'), ((6764, 6796), 'numpy.sqrt', 'np.sqrt', (['(diag_n[ii] * diag_m[jj])'], {}), '(diag_n[ii] * diag_m[jj])\n', (6771, 6796), True, 'import numpy as np\n'), ((5914, 5938), 'numpy.sum', 'np.sum', (['((u - uprev) ** 2)'], {}), '((u - uprev) ** 2)\n', (5920, 5938), True, 'import numpy as np\n'), ((5941, 5955), 'numpy.sum', 'np.sum', (['(u ** 2)'], {}), '(u ** 2)\n', (5947, 5955), True, 'import numpy as np\n'), ((5960, 5984), 'numpy.sum', 'np.sum', (['((v - vprev) ** 2)'], {}), '((v - vprev) ** 2)\n', (5966, 5984), True, 'import numpy as np\n'), ((5987, 6001), 'numpy.sum', 'np.sum', (['(v ** 2)'], {}), '(v ** 2)\n', (5993, 6001), True, 'import numpy as np\n')] |
import warnings
import spikewarp as sw
"""
ANGLE HELPERS
Helper functions for calculating bootstrap correlation angles and confidence intervals
"""
import math
import numpy as np
from sklearn.decomposition import PCA
def run_pca_and_get_positive_first_component_angle(spikes):
pca = PCA(n_components=2)
pca.fit_transform(spikes)
pca_angle_unadjusted = np.arctan2([pca.components_[0][1]], [pca.components_[0][0]]) * 180 / np.pi
pca_angle = pca_angle_unadjusted
if (pca_angle < 0.0):
pca_angle = pca_angle + 180.0
pca_angle_half = pca_angle
pca_angle_half_expanded_to_360 = pca_angle_half * 2.0
pca_angle_half_expanded_to_360_radians = math.radians(pca_angle_half_expanded_to_360)
pca_angle_half_expanded_to_360_x_y = [math.cos(pca_angle_half_expanded_to_360_radians), math.sin(pca_angle_half_expanded_to_360_radians)]
return pca, pca_angle[0], pca_angle_unadjusted[0], pca_angle_half_expanded_to_360_x_y
def empirical_confidence_bound_new(all_angles):
alpha = 0.95
p_lower = ((1.0-alpha)/2.0) * 100
lower = np.percentile(all_angles, p_lower)
p_upper = (alpha+((1.0-alpha)/2.0)) * 100
upper = np.percentile(all_angles, p_upper)
return lower, upper
def empirical_confidence_bound(all_angles):
alpha = 0.95
p_lower = ((1.0-alpha)/2.0) * 100
lower = np.percentile(all_angles, p_lower)
p_upper = (alpha+((1.0-alpha)/2.0)) * 100
upper = np.percentile(all_angles, p_upper)
return lower - np.mean(all_angles), upper - np.mean(all_angles)
def convert_expanded_360_xy_to_180_angle_degrees(expanded_points_x, expanded_points_y):
angle = convert_expanded_360_xy_to_360_angle_degrees(expanded_points_x, expanded_points_y)
angle = angle / 2.0
return angle
def convert_expanded_360_xy_to_360_angle_degrees(expanded_points_x, expanded_points_y):
angle = convert_xy_to_degrees_basic(expanded_points_x, expanded_points_y)
where_angle_less_than_0 = np.where(angle < 0.0)
angle[where_angle_less_than_0] = angle[where_angle_less_than_0] + 360.0
# if (angle < 0.0):
# angle = angle + 360.0
return angle
def convert_xy_to_degrees_basic(expanded_points_x, expanded_points_y):
angle = np.arctan2(expanded_points_y, expanded_points_x) * 180 / np.pi
return angle
def dotproduct(v1, v2):
return sum((a*b) for a, b in zip(v1, v2))
def length(v):
return math.sqrt(dotproduct(v, v))
def angle(v1, v2):
return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))
def angle_degrees(v1, v2):
return math.degrees(angle(v1, v2))
def signed_angle_degrees(v1, v2):
return math.degrees(math.atan2(v2[1], v2[0]) - math.atan2(v1[1], v1[0]))
"""
BOOTSTRAP PCA
Helper function for bootstrap PCA
"""
import numpy as np
from scipy import stats
import math
from shapely.geometry.point import Point
from shapely import affinity
def create_ellipse(center, width, height, angle):
circ = Point(center).buffer(1)
ell = affinity.scale(circ, width, height)
ellr = affinity.rotate(ell, angle)
return ellr
def bootstrap_PCA_body(spikes_to_use, number_of_bootstrap_iterations, single_cluster_holder_options=None):
number_of_samples_per_bootstrap = spikes_to_use.shape[0]
BS_PCA_angle_half_expanded_to_360_x_ys = []
BS_PCA_component_0s = []
BS_PCA_component_1s = []
BS_PCA_component_0_sds = []
BS_PCA_component_1_sds = []
BS_PCA_mean_0s = []
BS_PCA_mean_1s = []
BS_PCA_covariance_matrices = []
for bootstrap_iteration in range(number_of_bootstrap_iterations):
bootstrap_sample_indices = np.random.choice(number_of_samples_per_bootstrap, number_of_samples_per_bootstrap)
bootstrap_sample = spikes_to_use[bootstrap_sample_indices]
pca, _, _, pca_angle_half_expanded_to_360_x_y = sw.run_pca_and_get_positive_first_component_angle(bootstrap_sample)
BS_PCA_angle_half_expanded_to_360_x_ys.append(pca_angle_half_expanded_to_360_x_y)
BS_PCA_component_0_sds.append(np.sqrt(pca.explained_variance_[0]))
BS_PCA_component_1_sds.append(np.sqrt(pca.explained_variance_[1]))
BS_PCA_mean_0s.append(pca.mean_[0])
BS_PCA_mean_1s.append(pca.mean_[1])
BS_PCA_covariance_matrices.append(pca.get_covariance())
BS_PCA_angle_half_expanded_to_360_x_y_mean = np.mean(BS_PCA_angle_half_expanded_to_360_x_ys, axis=0)
BS_PCA_angle_back_to_180_mean = sw.convert_expanded_360_xy_to_180_angle_degrees([BS_PCA_angle_half_expanded_to_360_x_y_mean[0]], [BS_PCA_angle_half_expanded_to_360_x_y_mean[1]])[0]
BS_PCA_angle_half_expanded_to_360_x_ys = np.asarray(BS_PCA_angle_half_expanded_to_360_x_ys)
angle_differences_to_45_which_is_90_expanded = []
for i in range(number_of_bootstrap_iterations):
angle_differences_to_45_which_is_90_expanded.append(sw.signed_angle_degrees(BS_PCA_angle_half_expanded_to_360_x_ys[i, :], [0.0, 1.0]))
angle_differences_to_0_which_is_0_expanded = []
for i in range(number_of_bootstrap_iterations):
angle_differences_to_0_which_is_0_expanded.append(sw.signed_angle_degrees(BS_PCA_angle_half_expanded_to_360_x_ys[i, :], [0.0, 0.0]))
angles_from_mean_half_expanded_to_360 = []
for i in range(number_of_bootstrap_iterations):
angle_from_mean_half_expanded_to_360 = sw.signed_angle_degrees(BS_PCA_angle_half_expanded_to_360_x_y_mean, BS_PCA_angle_half_expanded_to_360_x_ys[i,:])
angles_from_mean_half_expanded_to_360.append(angle_from_mean_half_expanded_to_360)
std_of_angles_from_mean_half_expanded_to_360 = np.std(angles_from_mean_half_expanded_to_360)
std_of_angles_from_mean_back_to_half = std_of_angles_from_mean_half_expanded_to_360 / 2.0
######################################################################################################
BS_PCA_mean_component_0_sd = np.mean(BS_PCA_component_0_sds)
BS_PCA_mean_component_1_sd = np.mean(BS_PCA_component_1_sds)
BS_PCA_mean_of_mean0 = np.mean(BS_PCA_mean_0s)
BS_PCA_mean_of_mean1 = np.mean(BS_PCA_mean_1s)
BS_PCA_mean_sd_area = BS_PCA_mean_component_0_sd * BS_PCA_mean_component_1_sd
BS_PCA_mean_covariance_matrix = np.mean(BS_PCA_covariance_matrices, axis=0)
PCA_BS_empirical_CI_lower_expanded, PCA_BS_empirical_CI_upper_expanded = sw.empirical_confidence_bound_new(angles_from_mean_half_expanded_to_360)
PCA_BS_empirical_CI_lower = abs(PCA_BS_empirical_CI_lower_expanded / 2.0)
PCA_BS_empirical_CI_upper = abs(PCA_BS_empirical_CI_upper_expanded / 2.0)
PCA_BS_empirical_CI_lower_original = PCA_BS_empirical_CI_lower
PCA_BS_empirical_CI_upper_original = PCA_BS_empirical_CI_upper
# ANGLE CALCULATION
BS_PCA_angle_sd = std_of_angles_from_mean_back_to_half
BS_PCA_mean_angle = BS_PCA_angle_back_to_180_mean
BS_PCA_mean_angle_up_to_45 = BS_PCA_mean_angle
if (BS_PCA_mean_angle_up_to_45 > 45.0):
BS_PCA_mean_angle_up_to_45 = 90.0 - BS_PCA_mean_angle_up_to_45
temp = PCA_BS_empirical_CI_lower
PCA_BS_empirical_CI_lower = PCA_BS_empirical_CI_upper
PCA_BS_empirical_CI_upper = temp
BS_PCA_mean_angle_difference_from_45 = 45.0 - BS_PCA_mean_angle
# Empirical p-value calculation
number_less_than_45 = np.sum(np.asarray(angle_differences_to_45_which_is_90_expanded) < 0.0)
pvalue_1 = float(number_less_than_45) / float(number_of_bootstrap_iterations)
number_greater_than_45 = np.sum(np.asarray(angle_differences_to_45_which_is_90_expanded) > 0.0)
pvalue_2 = float(number_greater_than_45) / float(number_of_bootstrap_iterations)
empirical_pvalue_different_from_45 = 2.0*np.min([pvalue_1, pvalue_2])
# Empirical p-value calculation
number_less_than_0 = np.sum(np.asarray(angle_differences_to_0_which_is_0_expanded) < 0.0)
pvalue_1 = float(number_less_than_0) / float(number_of_bootstrap_iterations)
number_greater_than_0 = np.sum(np.asarray(angle_differences_to_0_which_is_0_expanded) > 0.0)
pvalue_2 = float(number_greater_than_0) / float(number_of_bootstrap_iterations)
empirical_pvalue_different_from_0 = 2.0*np.min([pvalue_1, pvalue_2])
# P-VALUES DIFFERENT FROM 45
new_temp = stats.norm(np.mean(angle_differences_to_45_which_is_90_expanded), np.std(angle_differences_to_45_which_is_90_expanded)).sf(0.0)
if (new_temp > 0.5):
new_temp = 1.0 - new_temp
BS_PCA_different_from_45_sd_method = 2.0*new_temp
local_data_dict = {}
local_data_dict['BS_PCA_mean_angle_up_to_45'] = BS_PCA_mean_angle_up_to_45
local_data_dict['PCA_BS_empirical_CI_lower'] = PCA_BS_empirical_CI_lower
local_data_dict['PCA_BS_empirical_CI_upper'] = PCA_BS_empirical_CI_upper
local_data_dict['PCA_BS_empirical_CI_lower_original'] = PCA_BS_empirical_CI_lower_original
local_data_dict['PCA_BS_empirical_CI_upper_original'] = PCA_BS_empirical_CI_upper_original
local_data_dict['PCA_BS_empirical_pvalue_different_from_45'] = empirical_pvalue_different_from_45
local_data_dict['is_PCA_BS_empirical_pvalue_different_from_45'] = empirical_pvalue_different_from_45 <= 0.025
local_data_dict['PCA_BS_empirical_pvalue_different_from_0'] = empirical_pvalue_different_from_0
local_data_dict['is_PCA_BS_empirical_pvalue_different_from_0'] = empirical_pvalue_different_from_0 <= 0.025
local_data_dict['BS_PCA_different_from_45_sd_method'] = BS_PCA_different_from_45_sd_method
local_data_dict['is_BS_PCA_different_from_45_sd_method'] = BS_PCA_different_from_45_sd_method < 0.05
local_data_dict['BS_PCA_mean_component_0_sd'] = BS_PCA_mean_component_0_sd
local_data_dict['BS_PCA_mean_component_1_sd'] = BS_PCA_mean_component_1_sd
local_data_dict['BS_PCA_mean_of_mean0'] = BS_PCA_mean_of_mean0
local_data_dict['BS_PCA_mean_of_mean1'] = BS_PCA_mean_of_mean1
local_data_dict['BS_PCA_mean_sd_area'] = BS_PCA_mean_sd_area
local_data_dict['BS_PCA_mean_covariance_matrix'] = BS_PCA_mean_covariance_matrix
local_data_dict['BS_PCA_angle_sd'] = BS_PCA_angle_sd
local_data_dict['BS_PCA_mean_angle'] = BS_PCA_mean_angle
# local_data_dict['BS_PCA_mean_angle_right_half'] = BS_PCA_mean_angle_right_half
local_data_dict['BS_PCA_mean_angle_difference_from_45'] = BS_PCA_mean_angle_difference_from_45
local_data_dict['BS_PCA_different_from_45_sd_method'] = BS_PCA_different_from_45_sd_method
local_data_dict['BS_PCA_different_from_45_generalised_method'] = -1.0
local_data_dict['BS_PCA_ellipses'] = []
local_data_dict['BS_PCA_ellipses_mean_zeroed'] = []
local_data_dict['BS_PCA_ellipses_ORIGINAL_ELLIPSE_AT_NEW_MEAN'] = []
if (single_cluster_holder_options != None):
for ring in single_cluster_holder_options.rings:
pca_ellr = create_ellipse([BS_PCA_mean_of_mean0, BS_PCA_mean_of_mean1], BS_PCA_mean_component_0_sd*ring, BS_PCA_mean_component_1_sd*ring, BS_PCA_mean_angle)
local_data_dict['BS_PCA_ellipses'].append(pca_ellr)
pca_ellr_mean_zeroed = create_ellipse([0, 0], BS_PCA_mean_component_0_sd*ring, BS_PCA_mean_component_1_sd*ring, BS_PCA_mean_angle)
local_data_dict['BS_PCA_ellipses_mean_zeroed'].append(pca_ellr_mean_zeroed)
local_data_dict['PCA_BS_intersection_ellipse'] = create_ellipse([BS_PCA_mean_of_mean0, BS_PCA_mean_of_mean1], BS_PCA_mean_component_0_sd*single_cluster_holder_options.intersection_dist, BS_PCA_mean_component_1_sd*single_cluster_holder_options.intersection_dist, BS_PCA_mean_angle)
components_ = np.asarray([1.0, math.tan(math.radians(BS_PCA_mean_angle))])
# print(BS_PCA_mean_angle, components_)
means_ = np.asarray([local_data_dict['BS_PCA_mean_of_mean0'], local_data_dict['BS_PCA_mean_of_mean1']])
local_data_dict['PCA_predicited_state_for_cluster_trials'] = np.dot(spikes_to_use - means_, components_)
factor_line_m = components_[1] / components_[0]
factor_line_c = means_[1] - factor_line_m * means_[0]
perpendicular_m = -1.0 / factor_line_m
perpendicular_c = spikes_to_use[:,1] - perpendicular_m * spikes_to_use[:,0]
intersect_x = (perpendicular_c - factor_line_c) / (factor_line_m - perpendicular_m)
intersect_y = factor_line_m * intersect_x + factor_line_c
local_data_dict['distances_from_factor_line'] = np.sqrt((intersect_x - spikes_to_use[:,0])**2 + (intersect_y - spikes_to_use[:,1])**2) / BS_PCA_mean_component_1_sd
return local_data_dict
"""
ELLIPSE HELPER
"""
from scipy.spatial.distance import cdist
def indices_within_x_mahalanobis_distances(mean, covariance_matrix, spike_pair_distribution_spikes, distance_criterion):
mahalanobis_distances = cdist(spike_pair_distribution_spikes, [mean], metric='mahalanobis', VI=np.linalg.inv(covariance_matrix))
indices_within_bound = np.argwhere(mahalanobis_distances <= distance_criterion).T[0]
return indices_within_bound
"""
AUTOCORRELATION HELPERS
Helper functions for calculating autocorrelations and partial autocorrelation p values
"""
from scipy.stats import linregress
from scipy import stats
def calculate_acf_pvalues_for_spikes(spikes, spikes2, number_of_lags):
acf_rvalues_0 = []
acf_pvals_0 = []
acf_positive_pvals_0 = []
acf_negative_pvals_0 = []
for shift in range(1,number_of_lags + 1):
lr_0 = linregress(spikes[:-shift], spikes2[shift:]);
acf_rvalues_0.append(lr_0.rvalue)
acf_pvals_0.append(lr_0.pvalue)
df = len(spikes[:-shift]) - 1
t_statistic = (lr_0.slope - 0.0) / lr_0.stderr
p_greater_than_0 = 1 - stats.t.cdf(t_statistic,df=df)
acf_positive_pvals_0.append(p_greater_than_0)
t_statistic = (lr_0.slope) / lr_0.stderr
p_less_than_0 = stats.t.cdf(t_statistic,df=df)
acf_negative_pvals_0.append(p_less_than_0)
return acf_rvalues_0, acf_pvals_0, acf_positive_pvals_0, acf_negative_pvals_0
def calculate_pacf_pvalues_for_spikes(spikes, residuals, number_of_lags):
pacf_rvalues = []
pacf_pvals = []
pacf_positive_pvals = []
pacf_negative_pvals = []
for shift in range(1,number_of_lags + 1):
lr = linregress(spikes[:-shift], residuals[1:]); slope = lr.slope; intercept = lr.intercept
pacf_rvalues.append(lr.rvalue)
pacf_pvals.append(lr.pvalue)
df = len(spikes[:-shift]) - 1
t_statistic = (lr.slope - 0.0) / lr.stderr
p_greater_than = 1 - stats.t.cdf(t_statistic,df=df)
pacf_positive_pvals.append(p_greater_than)
t_statistic = (lr.slope) / lr.stderr
p_less_than = stats.t.cdf(t_statistic,df=df)
pacf_negative_pvals.append(p_less_than)
estimate = intercept + slope * spikes[:-shift]
residuals = residuals[1:] - estimate
return pacf_rvalues, pacf_pvals, pacf_positive_pvals, pacf_negative_pvals
"""
DIFFERENCING & ARIMA HELPERS
Helper functions for making differencing decision & calculating ARIMA orders
"""
def calculate_arima_variables_for_acf_and_pacf_postive_arrays(acf_rvalues, acf_pvalues, pacf_pvalues, acf_positive_pvalues, pacf_positive_pvalues):
AR_p = 0
MA_q = 0
use_arima_model = False
# From https://people.duke.edu/~rnau/411arim2.htm (Rest of the differencing rules below)
# Rule 6: If the PACF of the differenced series displays a sharp cutoff and/or the lag-1 autocorrelation is positive--i.e., if the series appears slightly "underdifferenced"--then consider adding an AR term to the model. The lag at which the PACF cuts off is the indicated number of AR terms.
# Rule 7: If the ACF of the differenced series displays a sharp cutoff and/or the lag-1 autocorrelation is negative--i.e., if the series appears slightly "overdifferenced"--then consider adding an MA term to the model. The lag at which the ACF cuts off is the indicated number of MA terms.
if (acf_rvalues[0] < -0.1): # If negative first autocorrelation
last_pval = 0.0
for acf_pval_index, acf_pval in enumerate(acf_pvalues[:4]):
if (acf_pval < 0.05):
last_pval = acf_pval
if (acf_pval > 0.05):
difference_to_last = acf_pval - last_pval
if (difference_to_last > 0.15):
MA_q = acf_pval_index
use_arima_model = True
break
if (acf_rvalues[0] > 0.1): # If positive first autocorrelation
last_pval = 0.0
for pacf_pval_index, pacf_pval in enumerate(pacf_pvalues[:4]):
if (pacf_pval < 0.05):
last_pval = pacf_pval
if (pacf_pval > 0.05):
difference_to_last = pacf_pval - last_pval
if (difference_to_last > 0.15):
AR_p = pacf_pval_index
use_arima_model = True
break
return AR_p, MA_q, use_arima_model
def decisions_for_selective_differencing(TI_Vs_SpikeTimes_LR_pvalue, KPSS_SpikeTimes_pvalue, AutoCorr1_SpikeTimes_pvalue, TI_Vs_PairsDifferenced_LR_pvalue, KPSS_PairsDifferenced_pvalue):
# https://people.duke.edu/~rnau/411arim2.htm
# Rule 1: If the series has positive autocorrelations out to a high number of lags, then it probably needs a higher order of differencing.
# Rule 2: If the lag-1 autocorrelation is zero or negative, or the autocorrelations are all small and patternless, then the series does not need a higher order of differencing. If the lag-1 autocorrelation is -0.5 or more negative, the series may be overdifferenced. BEWARE OF OVERDIFFERENCING!!
# Rule 3: The optimal order of differencing is often the order of differencing at which the standard deviation is lowest.
# Rule 4: A model with no orders of differencing assumes that the original series is stationary (mean-reverting). A model with one order of differencing assumes that the original series has a constant average trend (e.g. a random walk or SES-type model, with or without growth). A model with two orders of total differencing assumes that the original series has a time-varying trend (e.g. a random trend or LES-type model).
# Rule 5: A model with no orders of differencing normally includes a constant term (which allows for a non-zero mean value). A model with two orders of total differencing normally does not include a constant term. In a model with one order of total differencing, a constant term should be included if the series has a non-zero average trend.
# Rule 6: If the PACF of the differenced series displays a sharp cutoff and/or the lag-1 autocorrelation is positive--i.e., if the series appears slightly "underdifferenced"--then consider adding an AR term to the model. The lag at which the PACF cuts off is the indicated number of AR terms.
# Rule 7: If the ACF of the differenced series displays a sharp cutoff and/or the lag-1 autocorrelation is negative--i.e., if the series appears slightly "overdifferenced"--then consider adding an MA term to the model. The lag at which the ACF cuts off is the indicated number of MA terms.
UNCORR_ORIG = False
UNCORR_DIFF = False
STAT_ORIG = False
STAT_DIFF = False
AUTO_ORIG = False
# AUTO_DIFF = False
threshold_1 = 0.05
if (TI_Vs_SpikeTimes_LR_pvalue >= threshold_1):
UNCORR_ORIG = True
if (TI_Vs_PairsDifferenced_LR_pvalue >= threshold_1):
UNCORR_DIFF = True
threshold_2 = 0.05
if (KPSS_SpikeTimes_pvalue >= threshold_2):
STAT_ORIG = True
if (KPSS_PairsDifferenced_pvalue >= threshold_2):
STAT_DIFF = True
threshold_3 = 0.05
if (AutoCorr1_SpikeTimes_pvalue >= threshold_3):
AUTO_ORIG = True
# if (AutoCorr1_PairsDifferenced_pvalue >= threshold_2):
# AUTO_DIFF = True
index_to_use = -1
original_needs_differencing = False
if ((not UNCORR_ORIG) | (not STAT_ORIG) | (not AUTO_ORIG)):
original_needs_differencing = True
else:
index_to_use = 0
if (original_needs_differencing):
differencining_fixed_original = False
if (UNCORR_DIFF & STAT_DIFF):
differencining_fixed_original = True
index_to_use = 1
return index_to_use
"""
BOOTSTRAP FACTOR ANALYSIS
Helper functions for bootstrap factor analysis
"""
from sklearn.decomposition import FactorAnalysis
import numpy as np
import math
from scipy import linalg
def bootstrap_factor_analysis(cluster, number_of_bootstrap_iterations, analysis_dict_key):
if (analysis_dict_key == "Original"):
spikes_to_use = cluster.cluster_spike_pairs
number_of_samples_per_bootstrap = cluster.number_of_samples_in_ellipse
elif (analysis_dict_key == "SelectivelyDifferenced"):
if (cluster.use_selective_differences):
spikes_to_use = cluster.selective_differences_scaled_down
number_of_samples_per_bootstrap = cluster.number_of_samples_for_selective_differences
else:
return
elif (analysis_dict_key == "SelectivelyDifferencedBoxJenkins"):
if (cluster.use_selective_differences):
spikes_to_use = cluster.selective_differences_arima_residuals
number_of_samples_per_bootstrap = cluster.number_of_samples_for_selective_differences
else:
return
angle_half_expanded_to_360_x_ys = []
bootstrapped_angles = []
bootstrapped_FA_N0_sds = []
bootstrapped_FA_N1_sds = []
bootstrapped_FA_1sd_areas = []
bootstrapped_FA_1sd_estimated_difference_area = []
bootstrapped_FA_mean_0s = []
bootstrapped_FA_mean_1s = []
bootstrapped_FA_components_0s = []
bootstrapped_FA_components_1s = []
bootstrapped_FA_noise_variances_0 = []
bootstrapped_FA_noise_variances_1 = []
bootstrapped_FA_predicited_states_for_cluster_trials = []
for bootstrap_iteration in range(number_of_bootstrap_iterations):
bootstrap_sample_indices = np.random.choice(number_of_samples_per_bootstrap, number_of_samples_per_bootstrap)
bootstrap_sample = spikes_to_use[bootstrap_sample_indices]
factor_analysis = FactorAnalysis(n_components=1, random_state=bootstrap_iteration)
factor_analysis.fit(bootstrap_sample)
FA_N0_sd = np.sqrt(factor_analysis.noise_variance_[0])
FA_N1_sd = np.sqrt(factor_analysis.noise_variance_[1])
FA_1sd_area = FA_N0_sd * FA_N1_sd
FA_1sd_estimated_difference_area = np.sqrt(factor_analysis.noise_variance_[0] + factor_analysis.noise_variance_[1])
factor_analysis_angle = (np.arctan2([factor_analysis.components_[0][1]], [factor_analysis.components_[0][0]]) * 180 / np.pi)[0]
if (factor_analysis_angle < 0.0):
factor_analysis_angle = factor_analysis_angle + 180.0
bootstrapped_FA_components_0s.append(-factor_analysis.components_[0][0])
bootstrapped_FA_components_1s.append(-factor_analysis.components_[0][1])
else:
bootstrapped_FA_components_0s.append(factor_analysis.components_[0][0])
bootstrapped_FA_components_1s.append(factor_analysis.components_[0][1])
angle_half_expanded_to_360 = factor_analysis_angle * 2.0
angle_half_expanded_to_360_radians = math.radians(angle_half_expanded_to_360)
angle_half_expanded_to_360_x_y = [math.cos(angle_half_expanded_to_360_radians), math.sin(angle_half_expanded_to_360_radians)]
angle_half_expanded_to_360_x_ys.append(angle_half_expanded_to_360_x_y)
bootstrapped_FA_predicited_states_for_cluster_trials.append(factor_analysis.transform(bootstrap_sample))
bootstrapped_angles.append(factor_analysis_angle)
bootstrapped_FA_N0_sds.append(FA_N0_sd)
bootstrapped_FA_N1_sds.append(FA_N1_sd)
bootstrapped_FA_1sd_areas.append(FA_1sd_area)
bootstrapped_FA_1sd_estimated_difference_area.append(FA_1sd_estimated_difference_area)
bootstrapped_FA_mean_0s.append(factor_analysis.mean_[0])
bootstrapped_FA_mean_1s.append(factor_analysis.mean_[1])
bootstrapped_FA_noise_variances_0.append(factor_analysis.noise_variance_[0])
bootstrapped_FA_noise_variances_1.append(factor_analysis.noise_variance_[1])
angle_half_expanded_to_360_x_y_mean = np.mean(angle_half_expanded_to_360_x_ys, axis=0)
angle_back_to_180_mean = sw.convert_expanded_360_xy_to_180_angle_degrees([angle_half_expanded_to_360_x_y_mean[0]], [angle_half_expanded_to_360_x_y_mean[1]])[0]
FA_angle_BS_mean_45d = angle_back_to_180_mean
if (FA_angle_BS_mean_45d > 45.0):
FA_angle_BS_mean_45d = 90.0 - FA_angle_BS_mean_45d
array_of_extra_analysis_keys = [analysis_dict_key]
if (analysis_dict_key in ["Original", "SelectivelyDifferenced", "SelectivelyDifferencedBoxJenkins"]):
sublist_suffixes = ["TestsPassed", "TestsPassedAndNormal"]
for sublist_suffix in sublist_suffixes:
if (not cluster.analysis_dicts[analysis_dict_key + sublist_suffix]['is_empty']):
array_of_extra_analysis_keys.append(analysis_dict_key + sublist_suffix)
if (analysis_dict_key == "SelectivelyDifferenced"):
if (not cluster.analysis_dicts[analysis_dict_key + "TestsPassedActuallyDifferenced"]['is_empty']):
array_of_extra_analysis_keys.append(analysis_dict_key + "TestsPassedActuallyDifferenced")
for extra_analysis_dict_key in array_of_extra_analysis_keys:
bootstrapped_FA_predicited_states_for_cluster_trials = np.asarray(bootstrapped_FA_predicited_states_for_cluster_trials)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_predicited_state_for_cluster_trials'] = np.mean(bootstrapped_FA_predicited_states_for_cluster_trials, axis=0)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_angle_BS_mean'] = angle_back_to_180_mean
cluster.analysis_dicts[extra_analysis_dict_key]['FA_N0_sd_BS_mean'] = np.mean(bootstrapped_FA_N0_sds)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_N1_sd_BS_mean'] = np.mean(bootstrapped_FA_N1_sds)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_1sd_area_BS_mean'] = np.mean(bootstrapped_FA_1sd_areas)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_1sd_estimated_difference_area_BS_mean'] = np.mean(bootstrapped_FA_1sd_estimated_difference_area)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_mean_0_mean'] = np.mean(bootstrapped_FA_mean_0s)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_mean_1_mean'] = np.mean(bootstrapped_FA_mean_1s)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_0_mean'] = np.mean(bootstrapped_FA_components_0s)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_1_mean'] = np.mean(bootstrapped_FA_components_1s)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_noise_variance_0_mean'] = np.mean(bootstrapped_FA_noise_variances_0)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_noise_variance_1_mean'] = np.mean(bootstrapped_FA_noise_variances_1)
cluster.analysis_dicts[extra_analysis_dict_key]['FA_angle_BS_mean_45d'] = FA_angle_BS_mean_45d
cluster.analysis_dicts[extra_analysis_dict_key]['FA_angle_BS_empirical_CI'] = sw.empirical_confidence_bound(bootstrapped_angles)
mean_ = np.asarray([cluster.analysis_dicts[extra_analysis_dict_key]['FA_mean_0_mean'], cluster.analysis_dicts[extra_analysis_dict_key]['FA_mean_1_mean']])
components_ = np.asarray([[cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_0_mean'], cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_1_mean']]])
noise_variance_ = np.asarray([cluster.analysis_dicts[extra_analysis_dict_key]['FA_noise_variance_0_mean'], cluster.analysis_dicts[extra_analysis_dict_key]['FA_noise_variance_1_mean']])
cluster.analysis_dicts[extra_analysis_dict_key]['FA_predicited_state_for_cluster_trials'] = mean_fa_transform(spikes_to_use, mean_, components_, noise_variance_)
def mean_fa_transform(X, mean_, components_, noise_variance_):
# JI: Adapted from FactorAnalysis 'transform' function to take arguments
"""Apply dimensionality reduction to X using the model.
Compute the expected mean of the latent variables.
See Barber, 21.2.33 (or Bishop, 12.66).
Parameters
"""
Ih = np.eye(len(components_))
X_transformed = X - mean_
Wpsi = components_ / noise_variance_
cov_z = linalg.inv(Ih + np.dot(Wpsi, components_.T))
tmp = np.dot(X_transformed, Wpsi.T)
X_transformed = np.dot(tmp, cov_z)
return X_transformed
"""
CHI SQUARED (FISHER STATISTIC)
Helper function for chi squared (Fisher) statistic
"""
from scipy.stats import combine_pvalues
def calculate_chi_squared_string_for_values(values_for_histogram_in_range):
number_of_values = len(values_for_histogram_in_range)
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
chi_sqaured_statistic, chi_sqaured_p_value = combine_pvalues(values_for_histogram_in_range)
chi_squared_latex_string = ""
part_of_table_string = ""
if (not math.isnan(chi_sqaured_p_value)):
chi_squared_latex_string = "$\\chi^{2}(" + str(2 * number_of_values) + ", N = " + str(number_of_values) + ") = " + str(round(chi_sqaured_statistic, 1)) + ", $ $" + str(sw.string_with_pval_lessthan_to_lower_limit(chi_sqaured_p_value)) + "$"
part_of_table_string = "df=" + str(2 * number_of_values) + ", N=" + str(number_of_values) + ", " + str(round(chi_sqaured_statistic, 1)) + ", " + str(chi_sqaured_p_value)
return number_of_values, chi_sqaured_statistic, chi_sqaured_p_value, chi_squared_latex_string, part_of_table_string
"""
Matrix Helpers
"""
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
| [
"scipy.stats.combine_pvalues",
"numpy.linalg.eigvals",
"shapely.geometry.point.Point",
"numpy.arctan2",
"math.atan2",
"spikewarp.run_pca_and_get_positive_first_component_angle",
"spikewarp.string_with_pval_lessthan_to_lower_limit",
"numpy.mean",
"spikewarp.convert_expanded_360_xy_to_180_angle_degree... | [((290, 309), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (293, 309), False, 'from sklearn.decomposition import PCA\n'), ((653, 697), 'math.radians', 'math.radians', (['pca_angle_half_expanded_to_360'], {}), '(pca_angle_half_expanded_to_360)\n', (665, 697), False, 'import math\n'), ((1043, 1077), 'numpy.percentile', 'np.percentile', (['all_angles', 'p_lower'], {}), '(all_angles, p_lower)\n', (1056, 1077), True, 'import numpy as np\n'), ((1141, 1175), 'numpy.percentile', 'np.percentile', (['all_angles', 'p_upper'], {}), '(all_angles, p_upper)\n', (1154, 1175), True, 'import numpy as np\n'), ((1316, 1350), 'numpy.percentile', 'np.percentile', (['all_angles', 'p_lower'], {}), '(all_angles, p_lower)\n', (1329, 1350), True, 'import numpy as np\n'), ((1414, 1448), 'numpy.percentile', 'np.percentile', (['all_angles', 'p_upper'], {}), '(all_angles, p_upper)\n', (1427, 1448), True, 'import numpy as np\n'), ((1929, 1950), 'numpy.where', 'np.where', (['(angle < 0.0)'], {}), '(angle < 0.0)\n', (1937, 1950), True, 'import numpy as np\n'), ((2905, 2940), 'shapely.affinity.scale', 'affinity.scale', (['circ', 'width', 'height'], {}), '(circ, width, height)\n', (2919, 2940), False, 'from shapely import affinity\n'), ((2949, 2976), 'shapely.affinity.rotate', 'affinity.rotate', (['ell', 'angle'], {}), '(ell, angle)\n', (2964, 2976), False, 'from shapely import affinity\n'), ((4154, 4209), 'numpy.mean', 'np.mean', (['BS_PCA_angle_half_expanded_to_360_x_ys'], {'axis': '(0)'}), '(BS_PCA_angle_half_expanded_to_360_x_ys, axis=0)\n', (4161, 4209), True, 'import numpy as np\n'), ((4434, 4484), 'numpy.asarray', 'np.asarray', (['BS_PCA_angle_half_expanded_to_360_x_ys'], {}), '(BS_PCA_angle_half_expanded_to_360_x_ys)\n', (4444, 4484), True, 'import numpy as np\n'), ((5339, 5384), 'numpy.std', 'np.std', (['angles_from_mean_half_expanded_to_360'], {}), '(angles_from_mean_half_expanded_to_360)\n', (5345, 5384), True, 'import numpy as np\n'), ((5612, 5643), 'numpy.mean', 'np.mean', (['BS_PCA_component_0_sds'], {}), '(BS_PCA_component_0_sds)\n', (5619, 5643), True, 'import numpy as np\n'), ((5674, 5705), 'numpy.mean', 'np.mean', (['BS_PCA_component_1_sds'], {}), '(BS_PCA_component_1_sds)\n', (5681, 5705), True, 'import numpy as np\n'), ((5730, 5753), 'numpy.mean', 'np.mean', (['BS_PCA_mean_0s'], {}), '(BS_PCA_mean_0s)\n', (5737, 5753), True, 'import numpy as np\n'), ((5778, 5801), 'numpy.mean', 'np.mean', (['BS_PCA_mean_1s'], {}), '(BS_PCA_mean_1s)\n', (5785, 5801), True, 'import numpy as np\n'), ((5914, 5957), 'numpy.mean', 'np.mean', (['BS_PCA_covariance_matrices'], {'axis': '(0)'}), '(BS_PCA_covariance_matrices, axis=0)\n', (5921, 5957), True, 'import numpy as np\n'), ((6035, 6107), 'spikewarp.empirical_confidence_bound_new', 'sw.empirical_confidence_bound_new', (['angles_from_mean_half_expanded_to_360'], {}), '(angles_from_mean_half_expanded_to_360)\n', (6068, 6107), True, 'import spikewarp as sw\n'), ((11072, 11171), 'numpy.asarray', 'np.asarray', (["[local_data_dict['BS_PCA_mean_of_mean0'], local_data_dict[\n 'BS_PCA_mean_of_mean1']]"], {}), "([local_data_dict['BS_PCA_mean_of_mean0'], local_data_dict[\n 'BS_PCA_mean_of_mean1']])\n", (11082, 11171), True, 'import numpy as np\n'), ((11229, 11272), 'numpy.dot', 'np.dot', (['(spikes_to_use - means_)', 'components_'], {}), '(spikes_to_use - means_, components_)\n', (11235, 11272), True, 'import numpy as np\n'), ((22644, 22692), 'numpy.mean', 'np.mean', (['angle_half_expanded_to_360_x_ys'], {'axis': '(0)'}), '(angle_half_expanded_to_360_x_ys, axis=0)\n', (22651, 22692), True, 'import numpy as np\n'), ((26641, 26670), 'numpy.dot', 'np.dot', (['X_transformed', 'Wpsi.T'], {}), '(X_transformed, Wpsi.T)\n', (26647, 26670), True, 'import numpy as np\n'), ((26688, 26706), 'numpy.dot', 'np.dot', (['tmp', 'cov_z'], {}), '(tmp, cov_z)\n', (26694, 26706), True, 'import numpy as np\n'), ((737, 785), 'math.cos', 'math.cos', (['pca_angle_half_expanded_to_360_radians'], {}), '(pca_angle_half_expanded_to_360_radians)\n', (745, 785), False, 'import math\n'), ((787, 835), 'math.sin', 'math.sin', (['pca_angle_half_expanded_to_360_radians'], {}), '(pca_angle_half_expanded_to_360_radians)\n', (795, 835), False, 'import math\n'), ((3485, 3571), 'numpy.random.choice', 'np.random.choice', (['number_of_samples_per_bootstrap', 'number_of_samples_per_bootstrap'], {}), '(number_of_samples_per_bootstrap,\n number_of_samples_per_bootstrap)\n', (3501, 3571), True, 'import numpy as np\n'), ((3680, 3747), 'spikewarp.run_pca_and_get_positive_first_component_angle', 'sw.run_pca_and_get_positive_first_component_angle', (['bootstrap_sample'], {}), '(bootstrap_sample)\n', (3729, 3747), True, 'import spikewarp as sw\n'), ((4243, 4398), 'spikewarp.convert_expanded_360_xy_to_180_angle_degrees', 'sw.convert_expanded_360_xy_to_180_angle_degrees', (['[BS_PCA_angle_half_expanded_to_360_x_y_mean[0]]', '[BS_PCA_angle_half_expanded_to_360_x_y_mean[1]]'], {}), '([\n BS_PCA_angle_half_expanded_to_360_x_y_mean[0]], [\n BS_PCA_angle_half_expanded_to_360_x_y_mean[1]])\n', (4290, 4398), True, 'import spikewarp as sw\n'), ((5093, 5210), 'spikewarp.signed_angle_degrees', 'sw.signed_angle_degrees', (['BS_PCA_angle_half_expanded_to_360_x_y_mean', 'BS_PCA_angle_half_expanded_to_360_x_ys[i, :]'], {}), '(BS_PCA_angle_half_expanded_to_360_x_y_mean,\n BS_PCA_angle_half_expanded_to_360_x_ys[i, :])\n', (5116, 5210), True, 'import spikewarp as sw\n'), ((7296, 7324), 'numpy.min', 'np.min', (['[pvalue_1, pvalue_2]'], {}), '([pvalue_1, pvalue_2])\n', (7302, 7324), True, 'import numpy as np\n'), ((7745, 7773), 'numpy.min', 'np.min', (['[pvalue_1, pvalue_2]'], {}), '([pvalue_1, pvalue_2])\n', (7751, 7773), True, 'import numpy as np\n'), ((11690, 11786), 'numpy.sqrt', 'np.sqrt', (['((intersect_x - spikes_to_use[:, 0]) ** 2 + (intersect_y - spikes_to_use[:,\n 1]) ** 2)'], {}), '((intersect_x - spikes_to_use[:, 0]) ** 2 + (intersect_y -\n spikes_to_use[:, 1]) ** 2)\n', (11697, 11786), True, 'import numpy as np\n'), ((12668, 12712), 'scipy.stats.linregress', 'linregress', (['spikes[:-shift]', 'spikes2[shift:]'], {}), '(spikes[:-shift], spikes2[shift:])\n', (12678, 12712), False, 'from scipy.stats import linregress\n'), ((13034, 13065), 'scipy.stats.t.cdf', 'stats.t.cdf', (['t_statistic'], {'df': 'df'}), '(t_statistic, df=df)\n', (13045, 13065), False, 'from scipy import stats\n'), ((13410, 13452), 'scipy.stats.linregress', 'linregress', (['spikes[:-shift]', 'residuals[1:]'], {}), '(spikes[:-shift], residuals[1:])\n', (13420, 13452), False, 'from scipy.stats import linregress\n'), ((13800, 13831), 'scipy.stats.t.cdf', 'stats.t.cdf', (['t_statistic'], {'df': 'df'}), '(t_statistic, df=df)\n', (13811, 13831), False, 'from scipy import stats\n'), ((20526, 20612), 'numpy.random.choice', 'np.random.choice', (['number_of_samples_per_bootstrap', 'number_of_samples_per_bootstrap'], {}), '(number_of_samples_per_bootstrap,\n number_of_samples_per_bootstrap)\n', (20542, 20612), True, 'import numpy as np\n'), ((20691, 20755), 'sklearn.decomposition.FactorAnalysis', 'FactorAnalysis', ([], {'n_components': '(1)', 'random_state': 'bootstrap_iteration'}), '(n_components=1, random_state=bootstrap_iteration)\n', (20705, 20755), False, 'from sklearn.decomposition import FactorAnalysis\n'), ((20813, 20856), 'numpy.sqrt', 'np.sqrt', (['factor_analysis.noise_variance_[0]'], {}), '(factor_analysis.noise_variance_[0])\n', (20820, 20856), True, 'import numpy as np\n'), ((20870, 20913), 'numpy.sqrt', 'np.sqrt', (['factor_analysis.noise_variance_[1]'], {}), '(factor_analysis.noise_variance_[1])\n', (20877, 20913), True, 'import numpy as np\n'), ((20987, 21072), 'numpy.sqrt', 'np.sqrt', (['(factor_analysis.noise_variance_[0] + factor_analysis.noise_variance_[1])'], {}), '(factor_analysis.noise_variance_[0] + factor_analysis.noise_variance_[1]\n )\n', (20994, 21072), True, 'import numpy as np\n'), ((21704, 21744), 'math.radians', 'math.radians', (['angle_half_expanded_to_360'], {}), '(angle_half_expanded_to_360)\n', (21716, 21744), False, 'import math\n'), ((22719, 22860), 'spikewarp.convert_expanded_360_xy_to_180_angle_degrees', 'sw.convert_expanded_360_xy_to_180_angle_degrees', (['[angle_half_expanded_to_360_x_y_mean[0]]', '[angle_half_expanded_to_360_x_y_mean[1]]'], {}), '([\n angle_half_expanded_to_360_x_y_mean[0]], [\n angle_half_expanded_to_360_x_y_mean[1]])\n', (22766, 22860), True, 'import spikewarp as sw\n'), ((23786, 23850), 'numpy.asarray', 'np.asarray', (['bootstrapped_FA_predicited_states_for_cluster_trials'], {}), '(bootstrapped_FA_predicited_states_for_cluster_trials)\n', (23796, 23850), True, 'import numpy as np\n'), ((23946, 24015), 'numpy.mean', 'np.mean', (['bootstrapped_FA_predicited_states_for_cluster_trials'], {'axis': '(0)'}), '(bootstrapped_FA_predicited_states_for_cluster_trials, axis=0)\n', (23953, 24015), True, 'import numpy as np\n'), ((24184, 24215), 'numpy.mean', 'np.mean', (['bootstrapped_FA_N0_sds'], {}), '(bootstrapped_FA_N0_sds)\n', (24191, 24215), True, 'import numpy as np\n'), ((24288, 24319), 'numpy.mean', 'np.mean', (['bootstrapped_FA_N1_sds'], {}), '(bootstrapped_FA_N1_sds)\n', (24295, 24319), True, 'import numpy as np\n'), ((24395, 24429), 'numpy.mean', 'np.mean', (['bootstrapped_FA_1sd_areas'], {}), '(bootstrapped_FA_1sd_areas)\n', (24402, 24429), True, 'import numpy as np\n'), ((24526, 24580), 'numpy.mean', 'np.mean', (['bootstrapped_FA_1sd_estimated_difference_area'], {}), '(bootstrapped_FA_1sd_estimated_difference_area)\n', (24533, 24580), True, 'import numpy as np\n'), ((24651, 24683), 'numpy.mean', 'np.mean', (['bootstrapped_FA_mean_0s'], {}), '(bootstrapped_FA_mean_0s)\n', (24658, 24683), True, 'import numpy as np\n'), ((24754, 24786), 'numpy.mean', 'np.mean', (['bootstrapped_FA_mean_1s'], {}), '(bootstrapped_FA_mean_1s)\n', (24761, 24786), True, 'import numpy as np\n'), ((24862, 24900), 'numpy.mean', 'np.mean', (['bootstrapped_FA_components_0s'], {}), '(bootstrapped_FA_components_0s)\n', (24869, 24900), True, 'import numpy as np\n'), ((24976, 25014), 'numpy.mean', 'np.mean', (['bootstrapped_FA_components_1s'], {}), '(bootstrapped_FA_components_1s)\n', (24983, 25014), True, 'import numpy as np\n'), ((25095, 25137), 'numpy.mean', 'np.mean', (['bootstrapped_FA_noise_variances_0'], {}), '(bootstrapped_FA_noise_variances_0)\n', (25102, 25137), True, 'import numpy as np\n'), ((25218, 25260), 'numpy.mean', 'np.mean', (['bootstrapped_FA_noise_variances_1'], {}), '(bootstrapped_FA_noise_variances_1)\n', (25225, 25260), True, 'import numpy as np\n'), ((25438, 25488), 'spikewarp.empirical_confidence_bound', 'sw.empirical_confidence_bound', (['bootstrapped_angles'], {}), '(bootstrapped_angles)\n', (25467, 25488), True, 'import spikewarp as sw\n'), ((25501, 25657), 'numpy.asarray', 'np.asarray', (["[cluster.analysis_dicts[extra_analysis_dict_key]['FA_mean_0_mean'], cluster\n .analysis_dicts[extra_analysis_dict_key]['FA_mean_1_mean']]"], {}), "([cluster.analysis_dicts[extra_analysis_dict_key][\n 'FA_mean_0_mean'], cluster.analysis_dicts[extra_analysis_dict_key][\n 'FA_mean_1_mean']])\n", (25511, 25657), True, 'import numpy as np\n'), ((25664, 25832), 'numpy.asarray', 'np.asarray', (["[[cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_0_mean'],\n cluster.analysis_dicts[extra_analysis_dict_key]['FA_component_1_mean']]]"], {}), "([[cluster.analysis_dicts[extra_analysis_dict_key][\n 'FA_component_0_mean'], cluster.analysis_dicts[extra_analysis_dict_key]\n ['FA_component_1_mean']]])\n", (25674, 25832), True, 'import numpy as np\n'), ((25843, 26019), 'numpy.asarray', 'np.asarray', (["[cluster.analysis_dicts[extra_analysis_dict_key]['FA_noise_variance_0_mean'\n ], cluster.analysis_dicts[extra_analysis_dict_key][\n 'FA_noise_variance_1_mean']]"], {}), "([cluster.analysis_dicts[extra_analysis_dict_key][\n 'FA_noise_variance_0_mean'], cluster.analysis_dicts[\n extra_analysis_dict_key]['FA_noise_variance_1_mean']])\n", (25853, 26019), True, 'import numpy as np\n'), ((27003, 27028), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (27026, 27028), False, 'import warnings\n'), ((27032, 27065), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (27055, 27065), False, 'import warnings\n'), ((27113, 27159), 'scipy.stats.combine_pvalues', 'combine_pvalues', (['values_for_histogram_in_range'], {}), '(values_for_histogram_in_range)\n', (27128, 27159), False, 'from scipy.stats import combine_pvalues\n'), ((27228, 27259), 'math.isnan', 'math.isnan', (['chi_sqaured_p_value'], {}), '(chi_sqaured_p_value)\n', (27238, 27259), False, 'import math\n'), ((361, 421), 'numpy.arctan2', 'np.arctan2', (['[pca.components_[0][1]]', '[pca.components_[0][0]]'], {}), '([pca.components_[0][1]], [pca.components_[0][0]])\n', (371, 421), True, 'import numpy as np\n'), ((1469, 1488), 'numpy.mean', 'np.mean', (['all_angles'], {}), '(all_angles)\n', (1476, 1488), True, 'import numpy as np\n'), ((1498, 1517), 'numpy.mean', 'np.mean', (['all_angles'], {}), '(all_angles)\n', (1505, 1517), True, 'import numpy as np\n'), ((2167, 2215), 'numpy.arctan2', 'np.arctan2', (['expanded_points_y', 'expanded_points_x'], {}), '(expanded_points_y, expanded_points_x)\n', (2177, 2215), True, 'import numpy as np\n'), ((2571, 2595), 'math.atan2', 'math.atan2', (['v2[1]', 'v2[0]'], {}), '(v2[1], v2[0])\n', (2581, 2595), False, 'import math\n'), ((2598, 2622), 'math.atan2', 'math.atan2', (['v1[1]', 'v1[0]'], {}), '(v1[1], v1[0])\n', (2608, 2622), False, 'import math\n'), ((2874, 2887), 'shapely.geometry.point.Point', 'Point', (['center'], {}), '(center)\n', (2879, 2887), False, 'from shapely.geometry.point import Point\n'), ((3865, 3900), 'numpy.sqrt', 'np.sqrt', (['pca.explained_variance_[0]'], {}), '(pca.explained_variance_[0])\n', (3872, 3900), True, 'import numpy as np\n'), ((3934, 3969), 'numpy.sqrt', 'np.sqrt', (['pca.explained_variance_[1]'], {}), '(pca.explained_variance_[1])\n', (3941, 3969), True, 'import numpy as np\n'), ((4640, 4725), 'spikewarp.signed_angle_degrees', 'sw.signed_angle_degrees', (['BS_PCA_angle_half_expanded_to_360_x_ys[i, :]', '[0.0, 1.0]'], {}), '(BS_PCA_angle_half_expanded_to_360_x_ys[i, :], [0.0,\n 1.0])\n', (4663, 4725), True, 'import spikewarp as sw\n'), ((4874, 4959), 'spikewarp.signed_angle_degrees', 'sw.signed_angle_degrees', (['BS_PCA_angle_half_expanded_to_360_x_ys[i, :]', '[0.0, 0.0]'], {}), '(BS_PCA_angle_half_expanded_to_360_x_ys[i, :], [0.0,\n 0.0])\n', (4897, 4959), True, 'import spikewarp as sw\n'), ((6932, 6988), 'numpy.asarray', 'np.asarray', (['angle_differences_to_45_which_is_90_expanded'], {}), '(angle_differences_to_45_which_is_90_expanded)\n', (6942, 6988), True, 'import numpy as np\n'), ((7108, 7164), 'numpy.asarray', 'np.asarray', (['angle_differences_to_45_which_is_90_expanded'], {}), '(angle_differences_to_45_which_is_90_expanded)\n', (7118, 7164), True, 'import numpy as np\n'), ((7389, 7443), 'numpy.asarray', 'np.asarray', (['angle_differences_to_0_which_is_0_expanded'], {}), '(angle_differences_to_0_which_is_0_expanded)\n', (7399, 7443), True, 'import numpy as np\n'), ((7561, 7615), 'numpy.asarray', 'np.asarray', (['angle_differences_to_0_which_is_0_expanded'], {}), '(angle_differences_to_0_which_is_0_expanded)\n', (7571, 7615), True, 'import numpy as np\n'), ((12117, 12149), 'numpy.linalg.inv', 'np.linalg.inv', (['covariance_matrix'], {}), '(covariance_matrix)\n', (12130, 12149), True, 'import numpy as np\n'), ((12175, 12231), 'numpy.argwhere', 'np.argwhere', (['(mahalanobis_distances <= distance_criterion)'], {}), '(mahalanobis_distances <= distance_criterion)\n', (12186, 12231), True, 'import numpy as np\n'), ((12893, 12924), 'scipy.stats.t.cdf', 'stats.t.cdf', (['t_statistic'], {'df': 'df'}), '(t_statistic, df=df)\n', (12904, 12924), False, 'from scipy import stats\n'), ((13668, 13699), 'scipy.stats.t.cdf', 'stats.t.cdf', (['t_statistic'], {'df': 'df'}), '(t_statistic, df=df)\n', (13679, 13699), False, 'from scipy import stats\n'), ((21781, 21825), 'math.cos', 'math.cos', (['angle_half_expanded_to_360_radians'], {}), '(angle_half_expanded_to_360_radians)\n', (21789, 21825), False, 'import math\n'), ((21827, 21871), 'math.sin', 'math.sin', (['angle_half_expanded_to_360_radians'], {}), '(angle_half_expanded_to_360_radians)\n', (21835, 21871), False, 'import math\n'), ((26605, 26632), 'numpy.dot', 'np.dot', (['Wpsi', 'components_.T'], {}), '(Wpsi, components_.T)\n', (26611, 26632), True, 'import numpy as np\n'), ((27854, 27874), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['x'], {}), '(x)\n', (27871, 27874), True, 'import numpy as np\n'), ((7829, 7882), 'numpy.mean', 'np.mean', (['angle_differences_to_45_which_is_90_expanded'], {}), '(angle_differences_to_45_which_is_90_expanded)\n', (7836, 7882), True, 'import numpy as np\n'), ((7884, 7936), 'numpy.std', 'np.std', (['angle_differences_to_45_which_is_90_expanded'], {}), '(angle_differences_to_45_which_is_90_expanded)\n', (7890, 7936), True, 'import numpy as np\n'), ((10984, 11015), 'math.radians', 'math.radians', (['BS_PCA_mean_angle'], {}), '(BS_PCA_mean_angle)\n', (10996, 11015), False, 'import math\n'), ((21096, 21185), 'numpy.arctan2', 'np.arctan2', (['[factor_analysis.components_[0][1]]', '[factor_analysis.components_[0][0]]'], {}), '([factor_analysis.components_[0][1]], [factor_analysis.\n components_[0][0]])\n', (21106, 21185), True, 'import numpy as np\n'), ((27432, 27496), 'spikewarp.string_with_pval_lessthan_to_lower_limit', 'sw.string_with_pval_lessthan_to_lower_limit', (['chi_sqaured_p_value'], {}), '(chi_sqaured_p_value)\n', (27475, 27496), True, 'import spikewarp as sw\n')] |
import cv2
import numpy as np
from pasportrecogniotion.util.docdescription import DocDescription
from pasportrecogniotion.util.pipeline import Pipeline
from datavalidation.passportdata import PassportData
def show(img):
cv2.imshow("test", img)
cv2.waitKey(0)
class OpenCVPreProc(object):
"""Preperocessing for OpenCV"""
__depends__ = []
__provides__ = ['rectKernel','sqKernel']
def __init__(self):
self.rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5))
self.sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 17))
def __call__(self):
return self.rectKernel, self.sqKernel
class GrayConverter(object):
"""Convert img to GRAY"""
__depends__ = ['rectKernel']
__provides__ = ['img', 'img_real']
def __init__(self, img):
self.img = img
def __call__(self, rectKernel):
img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(img, (3, 3), 0)
blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, rectKernel)
return blackhat, img
class BooneTransform(object):
"""Processes `img_small` according to Hans Boone's method
(http://www.pyimagesearch.com/2015/11/30/detecting-machine-readable-zones-in-passport-images/)
Outputs a `img_binary` - a result of threshold_otsu(closing(sobel(black_tophat(img_small)))"""
__depends__ = ['img', 'rectKernel', 'sqKernel']
__provides__ = ['img_binary']
def __init__(self, square_size=5):
self.square_size = square_size
def __call__(self, img, rectKernel, sqKernel):
gradX = cv2.Sobel(img, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal))).astype("uint8")
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
thresh = cv2.threshold(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)
res = cv2.erode(thresh, None, iterations=4)
return res
class MRZBoxLocator(object):
"""Extracts putative passport's data as DataBlock-s instances from the contours of `img_binary`"""
__depends__ = ['img_binary','img_real']
__provides__ = ['boxes']
def __init__(self, doc_description):
self.doc_description = doc_description
def __call__(self, img_binary, img_real):
cs, hierarchy = cv2.findContours(img_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
self.doc_description.extract_data(img_real, cs)
return self.doc_description.blocks
class BoxToData(object):
__depends__ = ['boxes']
__provides__ = ['data']
def __call__(self, boxes):
data = PassportData()
data.name = "".join(boxes["Имя"].data).replace("\n"," ").replace(".","")
data.lastName = "".join(boxes["Фамилия"].data).replace("\n"," ").replace(".","")
data.midName = "".join(boxes["Отчество"].data).replace("\n"," ").replace(".","")
data.serial = "".join(boxes["Серия1"].data)
if (len(data.serial)!=4):
data.serial = "".join(boxes["Серия2"].data)
data.number = "".join(boxes["Номер1"].data)
if (len(data.serial) != 6):
data.serial = "".join(boxes["Серия2"].data)
dateBirth = "".join(filter(lambda x: len(x.replace(".",""))>2,boxes["Дата рождения"].data))
if len(dateBirth)>=9:
data.dateBirth = dateBirth[0:10]
data.male = "".join(boxes["Пол"].data)
data.place = "".join(filter(lambda x: len(x.replace(".",""))>2,boxes["Место рождения"].data)).replace("\n", " ")
data.placeExtradition = "".join(filter(
lambda x : len(x.replace(" ","").replace(".","").replace("-",""))>3,
boxes["Паспорт выдан"].data)).replace("\n", " ")
data.dataExtradition = "".join(filter(lambda x: len(x.replace(".",""))>2,
boxes["Дата выдачи"].data))
data.code="".join(boxes["Код подразделения"].data).replace("\n", "")
return data
class MRZPipeline(Pipeline):
"""This is the pipeline for parsing passport' data from a given image file."""
def __init__(self, img, docfile, extra_cmdline_params=''):
super(MRZPipeline, self).__init__()
self.version = '1.0'
self.add_component('opencv', OpenCVPreProc())
self.add_component('loader', GrayConverter(img))
self.add_component('boone', BooneTransform())
self.add_component('box_locator', MRZBoxLocator(DocDescription(docfile)))
self.add_component('box_to_mrz', BoxToData())
@property
def result(self):
return self['data']
def recognise_doc(img, doc_descr):
"""The main interface function to this module, encapsulating the recognition pipeline.
Given an image filename, runs MRZPipeline on it, returning the parsed MRZ object.
:param img: A img to read the file data from.
:param doc_descr: A file to read document description from.
"""
p = MRZPipeline(img, doc_descr)
result = p.result
return result
| [
"cv2.GaussianBlur",
"numpy.absolute",
"cv2.waitKey",
"cv2.getStructuringElement",
"cv2.cvtColor",
"cv2.morphologyEx",
"cv2.threshold",
"numpy.min",
"numpy.max",
"pasportrecogniotion.util.docdescription.DocDescription",
"datavalidation.passportdata.PassportData",
"cv2.erode",
"cv2.imshow",
... | [((225, 248), 'cv2.imshow', 'cv2.imshow', (['"""test"""', 'img'], {}), "('test', img)\n", (235, 248), False, 'import cv2\n'), ((253, 267), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (264, 267), False, 'import cv2\n'), ((453, 503), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(13, 5)'], {}), '(cv2.MORPH_RECT, (13, 5))\n', (478, 503), False, 'import cv2\n'), ((528, 579), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(17, 17)'], {}), '(cv2.MORPH_RECT, (17, 17))\n', (553, 579), False, 'import cv2\n'), ((891, 933), 'cv2.cvtColor', 'cv2.cvtColor', (['self.img', 'cv2.COLOR_BGR2GRAY'], {}), '(self.img, cv2.COLOR_BGR2GRAY)\n', (903, 933), False, 'import cv2\n'), ((949, 981), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img', '(3, 3)', '(0)'], {}), '(img, (3, 3), 0)\n', (965, 981), False, 'import cv2\n'), ((1001, 1055), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gray', 'cv2.MORPH_BLACKHAT', 'rectKernel'], {}), '(gray, cv2.MORPH_BLACKHAT, rectKernel)\n', (1017, 1055), False, 'import cv2\n'), ((1612, 1667), 'cv2.Sobel', 'cv2.Sobel', (['img'], {'ddepth': 'cv2.CV_32F', 'dx': '(1)', 'dy': '(0)', 'ksize': '(-1)'}), '(img, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)\n', (1621, 1667), False, 'import cv2\n'), ((1684, 1702), 'numpy.absolute', 'np.absolute', (['gradX'], {}), '(gradX)\n', (1695, 1702), True, 'import numpy as np\n'), ((1858, 1910), 'cv2.morphologyEx', 'cv2.morphologyEx', (['gradX', 'cv2.MORPH_CLOSE', 'rectKernel'], {}), '(gradX, cv2.MORPH_CLOSE, rectKernel)\n', (1874, 1910), False, 'import cv2\n'), ((2015, 2066), 'cv2.morphologyEx', 'cv2.morphologyEx', (['thresh', 'cv2.MORPH_CLOSE', 'sqKernel'], {}), '(thresh, cv2.MORPH_CLOSE, sqKernel)\n', (2031, 2066), False, 'import cv2\n'), ((2081, 2118), 'cv2.erode', 'cv2.erode', (['thresh', 'None'], {'iterations': '(4)'}), '(thresh, None, iterations=4)\n', (2090, 2118), False, 'import cv2\n'), ((2507, 2575), 'cv2.findContours', 'cv2.findContours', (['img_binary', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(img_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (2523, 2575), False, 'import cv2\n'), ((2808, 2822), 'datavalidation.passportdata.PassportData', 'PassportData', ([], {}), '()\n', (2820, 2822), False, 'from datavalidation.passportdata import PassportData\n'), ((1732, 1745), 'numpy.min', 'np.min', (['gradX'], {}), '(gradX)\n', (1738, 1745), True, 'import numpy as np\n'), ((1747, 1760), 'numpy.max', 'np.max', (['gradX'], {}), '(gradX)\n', (1753, 1760), True, 'import numpy as np\n'), ((1929, 1994), 'cv2.threshold', 'cv2.threshold', (['gradX', '(0)', '(255)', '(cv2.THRESH_BINARY | cv2.THRESH_OTSU)'], {}), '(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n', (1942, 1994), False, 'import cv2\n'), ((4675, 4698), 'pasportrecogniotion.util.docdescription.DocDescription', 'DocDescription', (['docfile'], {}), '(docfile)\n', (4689, 4698), False, 'from pasportrecogniotion.util.docdescription import DocDescription\n')] |
import numpy as np
import pandas as pd
import das_utils
import constants as CC
import re
def testTableDefs(schema,tables):
"""
Function searches the dimensions of the tables to show cases where
the same dimension is used in multiple recodes. The output is printed,
and this function is useful for developing the table code.
Use it if you get an error about merging the same dimension when
running getTableBuilder().
"""
for table in tables.keys():
for elmnt in range(0, len(tables[table])):
# print(table)
# print(elmnt)
dims = tables[table][elmnt].split(" * ")
dims = [schema.getQuerySeed(dim).keepdims[0] for dim in dims if len(schema.getQuerySeed(dim).keepdims) >= 1]
for dim in np.unique(dims):
if dims.count(dim) > 1:
print(f"Table {table}, element{elmnt} contains rows defined by same dimension {dim} ")
print("Finished checking table dimensions.")
class TableBuilder():
def __init__(self, schema, tabledict):
self.tabledict = tabledict
self.tablenames = list(self.tabledict.keys())
self.workload_querynames = []
for queries in self.tabledict.values():
self.workload_querynames += queries
self.workload_querynames = np.unique(self.workload_querynames).tolist()
self.workload_querynames.sort(key=lambda k: len(re.split(CC.SCHEMA_CROSS_SPLIT_DELIM, k)))
self.schema = schema
#self.workload_queries = self.schema.getQueries(self.workload_querynames)
def __repr__(self):
items = [f"Tables: {self.tablenames}"]
return "\n".join(items)
def tableExists(self, tablename):
if tablename in self.tabledict:
exists = True
else:
exists = False
return exists
# def getTables(self, tablenames=None, data=None):
# if tablenames is None:
# tablenames = self.tablenames
# else:
# tablenames = das_utils.aslist(tablenames)
# tables = {}
# for name in tablenames:
# tables[name] = self.getTable(name, data)
# return tables
def getCustomTable(self, querynames, data=None):
querynames = das_utils.aslist(querynames)
if data is None:
data = np.zeros(self.schema.shape)
querynames = self.getCustomQuerynames(querynames)
return getTable(data, self.schema, querynames).toDF()
def getCustomTableTuples(self, querynames):
"""
returns a list of tuples (query, level) in the custom table shell
used for comparing rows that exist to the table shell to find all missing rows
a list of tuples has a much smaller memory footprint than using a pandas dataframe or even a numpy array
"""
tuples = []
querynames = self.getCustomQuerynames(das_utils.aslist(querynames))
for query in querynames:
tuples += [(query, level) for level in self.schema.getQueryLevel(query)]
return tuples
def getTable(self, querynames, data=None):
return self.getCustomTable(querynames, data=data)
def getTableQueries(self, tablename):
return self.schema.getQueries(self.getTableWorkload(tablename))
def getTableWorkload(self, tablename):
return self.tabledict[tablename]
# def getTable(self, tablename, data=None):
# if data is None:
# data = np.ones(self.schema.shape)
# assert tablename in self.tabledict, f"Table '{tablename}' does not exist in this workload."
# return getTable(data, self.schema, self.tabledict[tablename]).toDF()
def getWorkload(self):
return self.workload_querynames
def getWorkloadByTable(self, tablenames=None):
if tablenames is None:
tablenames = self.tablenames
else:
tablenames = das_utils.aslist(tablenames)
querynames = []
for name in tablenames:
if name in self.tabledict:
querynames += self.tabledict[name]
querynames = np.unique(querynames).tolist()
return querynames
def getCustomQuerynames(self, querynames):
queries = []
querynames = das_utils.aslist(querynames)
for name in querynames:
if name in self.tabledict:
queries += self.tabledict[name]
else:
if self.schema.isValidQuery(name):
queries += [name]
else:
print(f"'{name}' is not a valid query for this schema\nRemoving it from the list of queries.")
queries = np.unique(queries).tolist()
return queries
class Table():
def __init__(self, answerdict, leveldict):
self.answerdict = answerdict
self.queries = list(answerdict.keys())
self.shapedict = {}
self.flatdict = {}
for n,a in answerdict.items():
self.shapedict[n] = a.shape
self.flatdict[n] = a.flatten()
self.leveldict = leveldict
def __repr__(self):
namelen = [len(x) for x in self.queries]
padding = [max(namelen) - x for x in namelen]
queries = [f"{query}{' '*padding[i]} | {self.shapedict[query]}" for i,query in enumerate(self.queries)]
items = [
"Queries | Shape"
]
items += queries
return "\n".join(items)
def toDF(self):
rows = []
for query in self.queries:
ans = self.answerdict[query]
lev = self.leveldict[query]
for ind in np.ndindex(ans.shape):
if ind == ():
rows.append([query, ind, ans[ind], lev.tolist().pop()])
else:
rows.append([query, ind, ans[ind], lev[ind]])
queries, indices, answers, levels = [list(x) for x in zip(*rows)]
tab = {
"Query": queries,
#"Cell": indices,
"Answer": answers,
"Level": levels
}
return pd.DataFrame(tab)
def getTable(data, schema, querynames):
querynames = das_utils.aslist(querynames)
answerdict = {}
leveldict = {}
for name in querynames:
#print(name)
answerdict[name] = schema.getQuery(name).answerWithShape(data)
leveldict[name] = schema.getQueryLevel(name, flatten=False)
return Table(answerdict, leveldict)
| [
"pandas.DataFrame",
"numpy.ndindex",
"re.split",
"das_utils.aslist",
"numpy.zeros",
"numpy.unique"
] | [((6357, 6385), 'das_utils.aslist', 'das_utils.aslist', (['querynames'], {}), '(querynames)\n', (6373, 6385), False, 'import das_utils\n'), ((2321, 2349), 'das_utils.aslist', 'das_utils.aslist', (['querynames'], {}), '(querynames)\n', (2337, 2349), False, 'import das_utils\n'), ((4409, 4437), 'das_utils.aslist', 'das_utils.aslist', (['querynames'], {}), '(querynames)\n', (4425, 4437), False, 'import das_utils\n'), ((6279, 6296), 'pandas.DataFrame', 'pd.DataFrame', (['tab'], {}), '(tab)\n', (6291, 6296), True, 'import pandas as pd\n'), ((785, 800), 'numpy.unique', 'np.unique', (['dims'], {}), '(dims)\n', (794, 800), True, 'import numpy as np\n'), ((2394, 2421), 'numpy.zeros', 'np.zeros', (['self.schema.shape'], {}), '(self.schema.shape)\n', (2402, 2421), True, 'import numpy as np\n'), ((2981, 3009), 'das_utils.aslist', 'das_utils.aslist', (['querynames'], {}), '(querynames)\n', (2997, 3009), False, 'import das_utils\n'), ((4031, 4059), 'das_utils.aslist', 'das_utils.aslist', (['tablenames'], {}), '(tablenames)\n', (4047, 4059), False, 'import das_utils\n'), ((5819, 5840), 'numpy.ndindex', 'np.ndindex', (['ans.shape'], {}), '(ans.shape)\n', (5829, 5840), True, 'import numpy as np\n'), ((1340, 1375), 'numpy.unique', 'np.unique', (['self.workload_querynames'], {}), '(self.workload_querynames)\n', (1349, 1375), True, 'import numpy as np\n'), ((4245, 4266), 'numpy.unique', 'np.unique', (['querynames'], {}), '(querynames)\n', (4254, 4266), True, 'import numpy as np\n'), ((4828, 4846), 'numpy.unique', 'np.unique', (['queries'], {}), '(queries)\n', (4837, 4846), True, 'import numpy as np\n'), ((1441, 1481), 're.split', 're.split', (['CC.SCHEMA_CROSS_SPLIT_DELIM', 'k'], {}), '(CC.SCHEMA_CROSS_SPLIT_DELIM, k)\n', (1449, 1481), False, 'import re\n')] |
import numpy
from orangecontrib.shadow.als.widgets.gui.ow_als_generic_analyzer import ALSGenericAnalyzer
class ALSCurvedElementAnalyzer(ALSGenericAnalyzer):
name = "ALS Curved Element Analyzer"
description = "Shadow Utility: ALS Curved Element Analyzer"
icon = "icons/curved_element_analyzer.png"
priority = 1
oe_name = ""
def __init__(self):
super().__init__()
def complete_input_form(self):
shadowOui_input_beam, oe_number, shadowOui_OE_before_tracing, shadowOui_OE_after_tracing, widget_class_name = self.get_shadowOui_objects()
if "Ellipsoid" in widget_class_name:
self.oe_name = "Ellipsoid"
variables_to_change_list = ["Major Axis", "Minor Axis"]
elif "Hyperboloid" in widget_class_name:
self.oe_name = "Hyperboloid"
variables_to_change_list = ["Major Axis", "Minor Axis"]
elif "Paraboloid" in widget_class_name:
self.oe_name = "Paraboloid"
variables_to_change_list = ["Parabola Parameters"]
elif "Spheric" in widget_class_name:
self.oe_name = "Spheric"
variables_to_change_list = ["Radius"]
elif "Toroidal" in widget_class_name:
self.oe_name = "Torus"
variables_to_change_list = ["Major Radius", "Minor Radius"]
else:
raise ValueError("Input Optical Element is not Valid (only: Ellipsoid, Hyperboloid, Paraboloid, Spheric and Toruses")
self.oe_settings_box.setTitle(self.oe_name + " Setting")
self.cb_variable_to_change.clear()
for item in variables_to_change_list:
self.cb_variable_to_change.addItem(item)
self.cb_variable_to_change.setCurrentIndex(self.variable_to_change)
def get_OE_name(self):
return self.oe_name
def get_variables_to_change_list(self):
return []
def get_current_value(self, shadow_OE_before_tracing, shadow_OE_after_tracing):
if "Ellipsoid" in self.oe_name or "Hyperboloid" in self.oe_name:
if self.variable_to_change == 0:
return str(shadow_OE_after_tracing.AXMAJ) + " [" + self.workspace_units_label + "]"
elif self.variable_to_change == 1:
return str(shadow_OE_after_tracing.AXMIN) + " [" + self.workspace_units_label + "]"
elif "Paraboloid" in self.oe_name:
if self.variable_to_change == 0:
return str(shadow_OE_after_tracing.PARAM) + " [" + self.workspace_units_label + "]"
elif "Spheric" in self.oe_name:
if self.variable_to_change == 0:
return str(shadow_OE_after_tracing.RMIRR) + " [" + self.workspace_units_label + "]"
elif "Torus" in self.oe_name:
if self.variable_to_change == 0:
return str(shadow_OE_after_tracing.R_MAJ) + " [" + self.workspace_units_label + "]"
elif self.variable_to_change == 1:
return str(shadow_OE_after_tracing.R_MIN) + " [" + self.workspace_units_label + "]"
def create_auxiliary_data(self, shadow_OE_before_tracing, shadow_OE_after_tracing):
if "Ellipsoid" in self.oe_name or "Hyperboloid" in self.oe_name:
AXMIN = shadow_OE_after_tracing.AXMIN
AXMAJ = shadow_OE_after_tracing.AXMAJ
SSOUR = shadow_OE_before_tracing.SSOUR
SIMAG = shadow_OE_before_tracing.SIMAG
#### FROM SHADOW3 KERNEL
#! C Computes the mirror center position
#! C
#! C The center is computed on the basis of the object and image positions
#! C
AFOCI = numpy.sqrt(AXMAJ**2-AXMIN**2)
ECCENT = AFOCI/AXMAJ
YCEN = (SSOUR-SIMAG)*0.5/ECCENT
ZCEN = -numpy.sqrt(1-YCEN**2/AXMAJ**2)*AXMIN
# ANGLE OF AXMAJ AND POLE (CCW): NOT RETURNED BY SHADOW!
ELL_THE = numpy.degrees(numpy.arctan(numpy.abs(ZCEN/YCEN)))
return AXMIN, AXMAJ, ELL_THE
elif "Torus" in self.oe_name:
R_MIN = shadow_OE_after_tracing.R_MIN
R_MAJ = shadow_OE_after_tracing.R_MAJ
return R_MIN, R_MAJ
def modify_OE(self, shadow_OE, scanned_value, auxiliary_data=None):
#switch to external/user defined surface shape parameters
shadow_OE.F_EXT = 1
if "Ellipsoid" in self.oe_name or "Hyperboloid" in self.oe_name:
AXMIN, AXMAJ, ELL_THE = auxiliary_data
if self.variable_to_change == 0:
shadow_OE.AXMIN = AXMIN
shadow_OE.AXMAJ = scanned_value
elif self.variable_to_change == 1:
shadow_OE.AXMIN = scanned_value
shadow_OE.AXMAJ = AXMAJ
shadow_OE.ELL_THE = ELL_THE
elif "Paraboloid" in self.oe_name:
shadow_OE.PARAM = scanned_value
elif "Spheric" in self.oe_name:
shadow_OE.RMIRR = scanned_value
elif "Torus" in self.oe_name:
R_MIN, R_MAJ = auxiliary_data
if self.variable_to_change == 0:
shadow_OE.R_MIN = R_MIN
shadow_OE.R_MAJ = scanned_value
elif self.variable_to_change == 1:
shadow_OE.R_MIN = scanned_value
shadow_OE.R_MAJ = R_MAJ
| [
"numpy.abs",
"numpy.sqrt"
] | [((3632, 3667), 'numpy.sqrt', 'numpy.sqrt', (['(AXMAJ ** 2 - AXMIN ** 2)'], {}), '(AXMAJ ** 2 - AXMIN ** 2)\n', (3642, 3667), False, 'import numpy\n'), ((3764, 3802), 'numpy.sqrt', 'numpy.sqrt', (['(1 - YCEN ** 2 / AXMAJ ** 2)'], {}), '(1 - YCEN ** 2 / AXMAJ ** 2)\n', (3774, 3802), False, 'import numpy\n'), ((3920, 3942), 'numpy.abs', 'numpy.abs', (['(ZCEN / YCEN)'], {}), '(ZCEN / YCEN)\n', (3929, 3942), False, 'import numpy\n')] |
##################
# Model Training #
##################
# Imports
import os
import pandas as pd
import numpy as np
import joblib
from sklearn.ensemble import ExtraTreesClassifier
import yaml
# Parameters
params = {
'n_estimators': yaml.safe_load(open('params.yaml'))['train']['n_estimators'],
'max_leaf_nodes': yaml.safe_load(open('params.yaml'))['train']['max_leaf_nodes'],
'max_features': yaml.safe_load(open('params.yaml'))['train']['max_features']
}
# Load train sets
X_train = pd.read_parquet(os.path.join('data', 'x_train.parquet'))
y_train = pd.read_parquet(os.path.join('data', 'y_train.parquet'))
# Train
xtr_clf = ExtraTreesClassifier(random_state=42, n_jobs=-1, n_estimators=params['n_estimators'],
max_leaf_nodes=params['max_leaf_nodes'], max_features=params['max_features'])
xtr_clf = xtr_clf.fit(X_train, np.ravel(y_train))
# Pickles
os.makedirs('models/', exist_ok=True)
joblib.dump(xtr_clf, os.path.join('models', 'clf.pkl'))
| [
"sklearn.ensemble.ExtraTreesClassifier",
"os.path.join",
"os.makedirs",
"numpy.ravel"
] | [((642, 815), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(42)', 'n_jobs': '(-1)', 'n_estimators': "params['n_estimators']", 'max_leaf_nodes': "params['max_leaf_nodes']", 'max_features': "params['max_features']"}), "(random_state=42, n_jobs=-1, n_estimators=params[\n 'n_estimators'], max_leaf_nodes=params['max_leaf_nodes'], max_features=\n params['max_features'])\n", (662, 815), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((898, 935), 'os.makedirs', 'os.makedirs', (['"""models/"""'], {'exist_ok': '(True)'}), "('models/', exist_ok=True)\n", (909, 935), False, 'import os\n'), ((515, 554), 'os.path.join', 'os.path.join', (['"""data"""', '"""x_train.parquet"""'], {}), "('data', 'x_train.parquet')\n", (527, 554), False, 'import os\n'), ((582, 621), 'os.path.join', 'os.path.join', (['"""data"""', '"""y_train.parquet"""'], {}), "('data', 'y_train.parquet')\n", (594, 621), False, 'import os\n'), ((868, 885), 'numpy.ravel', 'np.ravel', (['y_train'], {}), '(y_train)\n', (876, 885), True, 'import numpy as np\n'), ((957, 990), 'os.path.join', 'os.path.join', (['"""models"""', '"""clf.pkl"""'], {}), "('models', 'clf.pkl')\n", (969, 990), False, 'import os\n')] |
import abc
import math
import numpy as np
import numpy.fft as npf
import scipy.linalg as spl
"""
Discrete to Continuous symbol mappers.
TX architecture:
discrete symbols -> [mapper] -> continuous symbols -> [modulator] -> continuous signal
RX architecture:
continuous signal -> [modulator] -> continuous symbols -> [mapper] -> discrete symbols
[ + ]
[sym_sync ]
"""
class Mapper:
"""
Map discrete symbols to continuous symbols which can be modulated by an analog channel.
"""
def __init__(self):
pass
@abc.abstractmethod
def encode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[discrete alphabet]
Returns
-------
y: np.ndarray[continuous alphabet]
"""
pass
@abc.abstractmethod
def decode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[continuous alphabet]
Returns
-------
y: np.ndarray[discrete alphabet]
"""
pass
class PAM(Mapper):
r"""
M-ary Pulse Amplitude Modulation.
A = {0, ..., M-1}
C = {c_{k}, k \in A}
c_{k} = (k - \frac{M - 1}{2}) * d
"""
def __init__(self, M: int, d: int):
"""
Parameters
----------
M: int
Codebook cardinality.
Must be even-valued.
d: float
Inter-codeword spacing.
"""
assert (M >= 2) and (M % 2 == 0)
self._M = M
assert d > 0
self._d = d
# Codeword dictionary
self._C = (np.arange(M) - (M - 1) / 2) * d
def encode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[A]
Returns
-------
y: np.ndarray[C]
"""
assert np.isin(x, np.arange(self._M)).all()
return (y := self._C[x])
def decode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[float/complex]
Returns
-------
y: np.ndarray[A]
"""
dist = np.abs(x.reshape((*x.shape, 1)) - self._C)
return (y := np.argmin(dist, axis=-1))
@property
def codebook(self) -> np.ndarray:
"""
Returns
-------
C: np.ndarray[float]
(M,) codewords.
"""
return self._C
class QAM(Mapper):
r"""
M-ary Quadrature Amplitude Modulation.
A = {0, ..., M-1}
C = {c_{k}, k \in A}
c_{k} = a_{l} + j * b_{m} \in \bC, with k <--> (l, m) a bijection.
a_{l} = (l - \frac{\sqrt{M} - 1}{2}) * d
b_{m} = (m - \frac{\sqrt{M} - 1}{2}) * d
"""
def __init__(self, M: int, d: int):
"""
Parameters
----------
M: int
Codebook cardinality.
Must be of the form (2j)**2, j >= 1.
d: float
Inter-codeword spacing (per dimension).
"""
j = math.sqrt(M) / 2
assert (j >= 1) and j.is_integer()
self._M = M
assert d > 0
self._d = d
# Codeword dictionary
C_1d = PAM(math.sqrt(M), d).codebook
self._C = np.reshape(C_1d.reshape((1, -1)) + 1j * C_1d.reshape((-1, 1)), -1)
def encode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[A]
Returns
-------
y: np.ndarray[C]
"""
assert np.isin(x, np.arange(self._M)).all()
return (y := self._C[x])
def decode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[float/complex]
Returns
-------
y: np.ndarray[A]
"""
dist = np.abs(x.reshape((*x.shape, 1)) - self._C)
return (y := np.argmin(dist, axis=-1))
class PSK(Mapper):
r"""
M-ary Phase-Shifted Key Modulation.
A = {0, ..., M-1}
C = {c_{k}, k \in A}
c_{k} = d * \exp(j 2 \pi k / M)
"""
def __init__(self, M: int, d: int):
"""
Parameters
----------
M: int
Codebook cardinality.
d: float
Codebook radius.
"""
assert M >= 2
self._M = M
assert d > 0
self._d = d
# Codeword dictionary
self._C = d * np.exp(1j * 2 * np.pi * np.arange(M) / M)
def encode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[A]
Returns
-------
y: np.ndarray[C]
"""
assert np.isin(x, np.arange(self._M)).all()
return (y := self._C[x])
def decode(self, x: np.ndarray) -> np.ndarray:
"""
Parameters
----------
x: np.ndarray[float/complex]
Returns
-------
y: np.ndarray[A]
"""
dist = np.abs(x.reshape((*x.shape, 1)) - self._C)
return (y := np.argmin(dist, axis=-1))
class OFDM(Mapper):
"""
Orthogonal Frequency Division Multiplexing Modulation.
As the notion of time is important in OFDM, encode/decode methods must specify the `axis`
parameter.
"""
def __init__(
self,
N_prefix: int,
mask_ch: np.ndarray,
x_train: np.ndarray,
):
"""
Parameters
----------
N_prefix: int
Length of the circular prefix >= 0.
mask_ch: np.ndarray[bool]
(N_channel,) channel mask. Used to turn off individual channels. (I.e.: do not transmit
data on inactive channels.)
x_train: np.ndarray[continuous alphabet]
(N_channel,) training symbols known to TX/RX. Used to estimate channel properties.
"""
assert N_prefix >= 0
self._N_prefix = N_prefix
assert (mask_ch.ndim == 1) and (mask_ch.dtype.kind == "b")
self._mask_ch = mask_ch.copy()
self._N_channel = mask_ch.size
self._N_active_ch = np.sum(mask_ch)
assert self._N_active_ch > 0
assert x_train.shape == (self._N_channel,)
self._x_train = x_train.copy()
def encode(self, x: np.ndarray, axis: int = -1) -> np.ndarray:
"""
OFDM-encode data stream(s).
Parameters
----------
x: np.ndarray[continuous alphabet]
(..., N, ...) symbols. N must be divisible by the number of active channels.
axis: int
Dimension of `x` along which lie data streams.
Returns
-------
y: np.ndarray[complex]
(..., Q, ...) symbols, where Q is a multiple of (N_channel + N_prefix).
Training symbols `x_train` are encoded at the start of `y`.
"""
assert -x.ndim <= axis < x.ndim
axis += 0 if (axis >= 0) else x.ndim
sh_x, N = x.shape, x.shape[axis]
assert N % self._N_active_ch == 0, "N must be divisible by the number of active channels."
# reshape x to (..., -1, N_active_ch, ...)
sh_xA = sh_x[:axis] + (-1, self._N_active_ch) + sh_x[(axis + 1) :]
xA = x.reshape(sh_xA)
# Add (active) training symbols. We need to do this in 2 steps due to the way np.concatenate
# works:
#
# 1: reshape x_train to have same dimensionality as xA;
sh_tr = [1] * xA.ndim
sh_tr[axis + 1] = self._N_active_ch
x_train = self._x_train[self._mask_ch].reshape(sh_tr)
# 2: broadcast x_train to have same shape as xA, except at axis-th dimension where it
# should be 1.
sh_tr = list(xA.shape)
sh_tr[axis] = 1
x_train = np.broadcast_to(x_train, sh_tr)
xAT = np.concatenate([x_train, xA], axis=axis)
# expand xA to (..., -1, N_channel, ...) by filling active channels only.
sh_xB = sh_x[:axis] + (xAT.shape[axis], self._N_channel) + sh_x[(axis + 1) :]
xB = np.zeros(sh_xB, dtype=x.dtype)
idx = [slice(None)] * xB.ndim
idx[axis + 1] = self._mask_ch
xB[tuple(idx)] = xAT
y = npf.ifft(xB, axis=axis + 1, norm="ortho")
# insert circular prefix
if self._N_prefix > 0:
idx = [slice(None)] * xB.ndim
idx[axis + 1] = slice(-self._N_prefix, None)
y = np.concatenate([y[tuple(idx)], y], axis=axis + 1)
# reshape y to (..., Q, ...)
sh_y = list(x.shape)
sh_y[axis] = -1
y = y.reshape(sh_y)
return y
def decode(self, x: np.ndarray, axis: int = -1) -> np.ndarray:
"""
OFDM-decode data-stream(s).
This method does not perform channel equalization: the responsibility is left to the user
during post-processing.
Parameters
----------
x: np.ndarray[float/complex]
(..., N, ...) symbols. N must be divisible by (N_channel + N_prefix).
axis: int
Dimension of `x` along which lie data streams.
Returns
-------
y: np.ndarray[complex]
(..., Q, N_active_ch, ...) symbols, where Q is the number of decoded OFDM
(block-)symbols.
"""
assert -x.ndim <= axis < x.ndim
axis += 0 if (axis >= 0) else x.ndim
sh_x, N = x.shape, x.shape[axis]
assert (
N % (self._N_channel + self._N_prefix) == 0
), "N must be divisible by (N_channel + N_prefix)."
# reshape x to (..., -1, N_channel + N_prefix, ...)
sh_xA = sh_x[:axis] + (-1, self._N_channel + self._N_prefix) + sh_x[(axis + 1) :]
xA = x.reshape(sh_xA)
# Drop circular prefix
idx = [slice(None)] * xA.ndim
idx[axis + 1] = slice(self._N_prefix, None)
xB = xA[tuple(idx)]
y = npf.fft(xB, axis=axis + 1, norm="ortho")
# Drop symbols in inactive channels
idx = [slice(None)] * xB.ndim
idx[axis + 1] = self._mask_ch
y = y[tuple(idx)]
return y
def channel(self, h: np.ndarray) -> np.ndarray:
"""
Compute the frequency-domain channel coefficients for a given impulse response.
Parameters
----------
h: np.ndarray[float/complex]
(N_tap,) channel impulse response.
Returns
-------
H: np.ndarray[complex]
(N_channel,) channel coefficients (frequency-domain).
Coefficients of inactive channels are set to 0.
"""
assert h.ndim == 1
assert (
self._N_prefix >= h.size - 1
), "Impulse response is incompatible with this OFDM transceiver."
H = npf.fft(h, n=self._N_channel)
H[~self._mask_ch] = 0
return H
def channel_LS(self, y_train: np.ndarray) -> np.ndarray:
"""
Least-Squares (LS) estimation of frequency-domain channel coefficients.
Parameters
----------
y_train: np.ndarray[float/complex]
(N_channel,) or (N_active_ch,) observed training symbols.
Returns
-------
H: np.ndarray[complex]
(N_channel,) channel coefficients (frequency-domain).
Coefficients of inactive channels are set to 0.
"""
assert y_train.ndim == 1
N = y_train.size
if N == self._N_channel:
y_train = y_train[self._mask_ch]
elif N == self._N_active_ch:
pass
else:
raise ValueError("Parameter[y_train]: expected (N_channel,) or (N_active_ch,) array.")
H = np.zeros((self._N_channel,), dtype=complex)
H[self._mask_ch] = y_train / self._x_train[self._mask_ch]
return H
def qamMap(M: int) -> np.ndarray:
"""
M-ary Quadrature Amplitude Modulation codebook.
Parameters
----------
M: int
Codebook cardinality.
Must be of the form (2j)**2, j >= 1.
Returns
-------
C: np.ndarray[complex]
(M,) QAM codebook.
"""
C = QAM(M=M, d=1)._C
return C
def pskMap(M: int) -> np.ndarray:
"""
M-ary Phase-Shifted Key Modulation codebook.
Parameters
----------
M: int
Codebook cardinality.
Returns
-------
C: np.ndarray[float/complex]
(M,) PSK codebook.
"""
C = PSK(M=M, d=1)._C
return C
def encoder(x: np.ndarray, C: np.ndarray) -> np.ndarray:
"""
Map integers to symbols.
Parameters
----------
x: np.ndarray[int]
(*sh_x,) values in {0, ..., M-1}.
C: np.ndarray[float/complex]
(M,) codebook.
Returns
-------
y: np.ndarray[float/complex]
(*sh_x,) codewords.
"""
M = C.size
assert np.isin(x, np.arange(M)).all()
return C[x]
def decoder(x: np.ndarray, C: np.ndarray) -> np.ndarray:
"""
Map symbols to codeword-indices via minimum-distance decoding.
Parameters
----------
x: np.ndarray[float/complex]
(*sh_x,) noisy symbols.
C: np.ndarray[float/complex]
(M,) codebook.
Returns
-------
y: np.ndarray[int]
(*sh_x,) values in {0, ..., M-1}.
"""
dist = np.abs(x.reshape((*x.shape, 1)) - C)
return (y := np.argmin(dist, axis=-1))
def ofdm_tx_frame(
N_prefix: int,
x_train: np.ndarray,
mask_ch: np.ndarray,
x: np.ndarray,
) -> np.ndarray:
"""
Generate OFDM frame(s).
Parameters
----------
N_prefix: int
Length of the circular prefix >= 0.
x_train: np.ndarray[float/complex]
(N_channel,) training symbols known to TX/RX. Used to estimate channel properties.
mask_ch: np.ndarray[bool]
(N_channel,) channel mask. Used to turn off individual channels. (I.e.: do not transmit data
on inactive channels.)
x: np.ndarray[float/complex]
(N_data,) symbols. It will be padded with zeros if not a multiple of useable carriers.
Returns
-------
y: np.ndarray[float/complex]
(Q,) serialized OFDM symbols, with the training sequence transmitted in the first OFDM
block.
"""
mapper = OFDM(N_prefix, mask_ch, x_train)
_, r = divmod(x.size, mapper._N_active_ch)
x = np.pad(x, (0, mapper._N_active_ch - r))
y = mapper.encode(x)
return y
def ofdm_rx_frame(
N_prefix: int,
mask_ch: np.ndarray,
x: np.ndarray,
) -> np.ndarray:
"""
Decode OFDM frame(s), without channel equalization.
Parameters
----------
N_prefix: int
Length of the circular prefix >= 0.
mask_ch: np.ndarray[bool]
(N_channel,) channel mask. Used to turn off individual channels. (I.e.: no data received on
inactive channels.)
x: np.ndarray[float/complex]
(N_data,) symbols. Any trailing partial OFDM frame will be discarded.
Returns
-------
y: np.ndarray[complex]
(Q, N_active_ch) symbols, where Q is the number of decoded OFDM (block-)symbols.
"""
N_channel = mask_ch.size
# x_train doesn't matter here since we don't do equalization (yet) -> choose anything.
mapper = OFDM(N_prefix, mask_ch, x_train=np.zeros(N_channel))
q, _ = divmod(x.size, N_channel + N_prefix)
x = x[: (q * (N_channel + N_prefix))]
y = mapper.decode(x)
return y
def ofdm_channel(
N_prefix: int,
mask_ch: np.ndarray,
h: np.ndarray,
) -> np.ndarray:
"""
Compute the frequency-domain channel coefficients for a given impulse response.
Parameters
----------
N_prefix: int
Length of the circular prefix >= 0. (Needed to determine if `h` is acceptable.)
mask_ch: np.ndarray[bool]
(N_channel,) channel mask. Used to turn off individual channels. (I.e.: no data on inactive
channels.)
h: np.ndarray[float/complex]
(N_tap,) channel impulse response.
Returns
-------
H: np.ndarray[complex]
(N_active_ch,) channel coefficients (frequency-domain).
"""
N_channel = mask_ch.size
# x_train doesn't matter here -> choose anything.
mapper = OFDM(N_prefix, mask_ch, x_train=np.zeros(N_channel))
H = mapper.channel(h)[mask_ch]
return H
def ofdm_channel_LS(y: np.ndarray, x_train: np.ndarray) -> np.ndarray:
"""
Least-Squares (LS) estimation of frequency-domain channel coefficients.
Parameters
----------
y: np.ndarray[float/complex]
(Q, N_active_ch) data stream, with training symbols in the leading OFDM block.
x_train: np.ndarray[float/complex]
(N_active_ch,) training symbols known to the receiver.
Returns
-------
H: np.ndarray[complex]
(N_active_ch,) channel coefficients (frequency-domain).
"""
y_train = y[0]
H = y_train / x_train
return H
def ofdm_channel_MMSE(
y: np.ndarray,
x_train: np.ndarray,
mask_ch: np.ndarray,
Ka: np.ndarray,
tau: np.ndarray,
var: float,
) -> np.ndarray:
"""
Minimum Mean Squared-Error (MMSE) estimation of frequency-domain channel coefficients.
We assume the channel delays are known. The covariance matrix of channel amplitudes is also
assumed to be known.
Parameters
----------
y: np.ndarray[float/complex]
(Q, N_active_ch) data stream, with training symbols in the leading OFDM block.
x_train: np.ndarray[float/complex]
(N_active_ch,) training symbols known to the receiver.
mask_ch: np.ndarray[bool]
(N_channel,) channel mask. Used to turn off individual channels. (I.e.: no data on inactive
channels.)
Ka: np.ndarray[float/complex]
(N_path, N_path) channel amplitude covariance matrix.
tau: np.ndarray[float]
(N_path,) delays for each path of the multi-path channel. The delays are expressed in number
of samples, i.e., tau_l/T_s.
var: float
Noise variance
Returns
-------
H: np.ndarray[complex]
(N_active_ch,) channel coefficients (frequency-domain).
"""
y_train = y[0]
N_channel = mask_ch.size
N_active_ch = x_train.size
k = npf.fftfreq(N_channel)[mask_ch].reshape((-1, 1))
A = np.exp(-1j * 2 * np.pi * k * tau)
Kd = A @ Ka @ A.conj().T
Kdy = Kd * x_train.conj()
Kz = var * np.eye(N_active_ch)
Ky = x_train.reshape((-1, 1)) * Kdy + Kz
H = Kdy @ spl.solve(Ky, y_train, assume_a="pos")
return H
| [
"numpy.pad",
"numpy.fft.ifft",
"scipy.linalg.solve",
"numpy.sum",
"math.sqrt",
"numpy.fft.fft",
"numpy.zeros",
"numpy.argmin",
"numpy.fft.fftfreq",
"numpy.arange",
"numpy.exp",
"numpy.eye",
"numpy.broadcast_to",
"numpy.concatenate"
] | [((14212, 14251), 'numpy.pad', 'np.pad', (['x', '(0, mapper._N_active_ch - r)'], {}), '(x, (0, mapper._N_active_ch - r))\n', (14218, 14251), True, 'import numpy as np\n'), ((18113, 18148), 'numpy.exp', 'np.exp', (['(-1.0j * 2 * np.pi * k * tau)'], {}), '(-1.0j * 2 * np.pi * k * tau)\n', (18119, 18148), True, 'import numpy as np\n'), ((6103, 6118), 'numpy.sum', 'np.sum', (['mask_ch'], {}), '(mask_ch)\n', (6109, 6118), True, 'import numpy as np\n'), ((7748, 7779), 'numpy.broadcast_to', 'np.broadcast_to', (['x_train', 'sh_tr'], {}), '(x_train, sh_tr)\n', (7763, 7779), True, 'import numpy as np\n'), ((7794, 7834), 'numpy.concatenate', 'np.concatenate', (['[x_train, xA]'], {'axis': 'axis'}), '([x_train, xA], axis=axis)\n', (7808, 7834), True, 'import numpy as np\n'), ((8017, 8047), 'numpy.zeros', 'np.zeros', (['sh_xB'], {'dtype': 'x.dtype'}), '(sh_xB, dtype=x.dtype)\n', (8025, 8047), True, 'import numpy as np\n'), ((8166, 8207), 'numpy.fft.ifft', 'npf.ifft', (['xB'], {'axis': '(axis + 1)', 'norm': '"""ortho"""'}), "(xB, axis=axis + 1, norm='ortho')\n", (8174, 8207), True, 'import numpy.fft as npf\n'), ((9851, 9891), 'numpy.fft.fft', 'npf.fft', (['xB'], {'axis': '(axis + 1)', 'norm': '"""ortho"""'}), "(xB, axis=axis + 1, norm='ortho')\n", (9858, 9891), True, 'import numpy.fft as npf\n'), ((10706, 10735), 'numpy.fft.fft', 'npf.fft', (['h'], {'n': 'self._N_channel'}), '(h, n=self._N_channel)\n', (10713, 10735), True, 'import numpy.fft as npf\n'), ((11608, 11651), 'numpy.zeros', 'np.zeros', (['(self._N_channel,)'], {'dtype': 'complex'}), '((self._N_channel,), dtype=complex)\n', (11616, 11651), True, 'import numpy as np\n'), ((13233, 13257), 'numpy.argmin', 'np.argmin', (['dist'], {'axis': '(-1)'}), '(dist, axis=-1)\n', (13242, 13257), True, 'import numpy as np\n'), ((18222, 18241), 'numpy.eye', 'np.eye', (['N_active_ch'], {}), '(N_active_ch)\n', (18228, 18241), True, 'import numpy as np\n'), ((18302, 18340), 'scipy.linalg.solve', 'spl.solve', (['Ky', 'y_train'], {'assume_a': '"""pos"""'}), "(Ky, y_train, assume_a='pos')\n", (18311, 18340), True, 'import scipy.linalg as spl\n'), ((2287, 2311), 'numpy.argmin', 'np.argmin', (['dist'], {'axis': '(-1)'}), '(dist, axis=-1)\n', (2296, 2311), True, 'import numpy as np\n'), ((3074, 3086), 'math.sqrt', 'math.sqrt', (['M'], {}), '(M)\n', (3083, 3086), False, 'import math\n'), ((3927, 3951), 'numpy.argmin', 'np.argmin', (['dist'], {'axis': '(-1)'}), '(dist, axis=-1)\n', (3936, 3951), True, 'import numpy as np\n'), ((5062, 5086), 'numpy.argmin', 'np.argmin', (['dist'], {'axis': '(-1)'}), '(dist, axis=-1)\n', (5071, 5086), True, 'import numpy as np\n'), ((15133, 15152), 'numpy.zeros', 'np.zeros', (['N_channel'], {}), '(N_channel)\n', (15141, 15152), True, 'import numpy as np\n'), ((16091, 16110), 'numpy.zeros', 'np.zeros', (['N_channel'], {}), '(N_channel)\n', (16099, 16110), True, 'import numpy as np\n'), ((1685, 1697), 'numpy.arange', 'np.arange', (['M'], {}), '(M)\n', (1694, 1697), True, 'import numpy as np\n'), ((3246, 3258), 'math.sqrt', 'math.sqrt', (['M'], {}), '(M)\n', (3255, 3258), False, 'import math\n'), ((12748, 12760), 'numpy.arange', 'np.arange', (['M'], {}), '(M)\n', (12757, 12760), True, 'import numpy as np\n'), ((18056, 18078), 'numpy.fft.fftfreq', 'npf.fftfreq', (['N_channel'], {}), '(N_channel)\n', (18067, 18078), True, 'import numpy.fft as npf\n'), ((1940, 1958), 'numpy.arange', 'np.arange', (['self._M'], {}), '(self._M)\n', (1949, 1958), True, 'import numpy as np\n'), ((3580, 3598), 'numpy.arange', 'np.arange', (['self._M'], {}), '(self._M)\n', (3589, 3598), True, 'import numpy as np\n'), ((4715, 4733), 'numpy.arange', 'np.arange', (['self._M'], {}), '(self._M)\n', (4724, 4733), True, 'import numpy as np\n'), ((4474, 4486), 'numpy.arange', 'np.arange', (['M'], {}), '(M)\n', (4483, 4486), True, 'import numpy as np\n')] |
'''
IKI Bangladesh (MIOASI): Plotting functions
Plotting scripts and helper functions relating to the IKI Bangladesh project.
Note: Python 3 compatible only
Author: HS
Created: 7/3/19
'''
import cartopy
import cartopy.crs as ccrs
import cartopy.geodesic as cgeo
import iris
import iris.plot as iplt
import matplotlib.pyplot as plt
import numpy as np
import user_vars
from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter
def add_gridlines(axs):
'''Add coastlines and gridlines, showing lat-lon values.
Requires: import cartopy.feature as cfeature,
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
'''
gls = axs.gridlines(draw_labels=False)
# Set cartopy Gridliner properties
gls.ylines = False
gls.xlines = False
# Add ticks at labels
axs.set_xticks(gls.xlocator.tick_values(axs.get_extent()[0], axs.get_extent()[1])[1:-1])
axs.set_yticks(gls.ylocator.tick_values(axs.get_extent()[2], axs.get_extent()[3])[1:-1])
axs.xaxis.set_major_formatter(LongitudeFormatter())
axs.yaxis.set_major_formatter(LatitudeFormatter())
axs.tick_params(axis="both", direction="in", labelsize=8, top=True, right=True)
def plotfp(cube, ax, domain='BGD', vmin=15, vmax=60):
"""Plot footprint
Args:
cube (iris.cube.Cube): cube of data
domain (str): Name of plotting domain (see user_vars)
vmin (int): Minimum gust value to plot. Values < vmin are masked.
"""
# Mask values
mcube = iris.util.mask_cube(cube, cube.data <= vmin)
land_10m = cartopy.feature.NaturalEarthFeature('physical', 'land', '10m',
edgecolor=None, facecolor='lightgrey')
border_10m = cartopy.feature.NaturalEarthFeature('cultural', 'admin_0_boundary_lines_land', '10m',
edgecolor='black', facecolor='none')
if not ax:
ax = plt.gca()
ax.add_feature(land_10m, lw=0.)
ax.coastlines(resolution='10m', lw=0.5, zorder=20)
ax.add_feature(border_10m, lw=0.5, zorder=20)
# Plot cube
levels = [15, 20, 25, 30, 35, 40, 45, 50]
cont = iplt.pcolormesh(mcube, axes=ax, cmap='hot_r', zorder=10, vmin=vmin, vmax=vmax)
# cbar_xy = [0.03, 0.05, 0.6, 0.02]
# cbar_axes = fig.add_axes(cbar_xy, 'colour_bar_axes')
# bar = fig.colorbar(cont, cbar_axes, orientation='horizontal')
# bar.set_label('10m Gust Speed (m/s)')
extent = user_vars.DOMAINS[domain]
ax.set_extent(extent)
return cont
def _axes_to_lonlat(ax, coords):
"""(lon, lat) from axes coordinates."""
display = ax.transAxes.transform(coords)
data = ax.transData.inverted().transform(display)
lonlat = ccrs.PlateCarree().transform_point(*data, ax.projection)
return lonlat
def _upper_bound(start, direction, distance, dist_func):
"""A point farther than distance from start, in the given direction.
It doesn't matter which coordinate system start is given in, as long
as dist_func takes points in that coordinate system.
Args:
start: Starting point for the line.
direction Nonzero (2, 1)-shaped array, a direction vector.
distance: Positive distance to go past.
dist_func: A two-argument function which returns distance.
Returns:
Coordinates of a point (a (2, 1)-shaped NumPy array).
"""
if distance <= 0:
raise ValueError(f"Minimum distance is not positive: {distance}")
if np.linalg.norm(direction) == 0:
raise ValueError("Direction vector must not be zero.")
# Exponential search until the distance between start and end is
# greater than the given limit.
length = 0.1
end = start + length * direction
while dist_func(start, end) < distance:
length *= 2
end = start + length * direction
return end
def _distance_along_line(start, end, distance, dist_func, tol):
"""Point at a distance from start on the segment from start to end.
It doesn't matter which coordinate system start is given in, as long
as dist_func takes points in that coordinate system.
Args:
start: Starting point for the line.
end: Outer bound on point's location.
distance: Positive distance to travel.
dist_func: Two-argument function which returns distance.
tol: Relative error in distance to allow.
Returns:
Coordinates of a point (a (2, 1)-shaped NumPy array).
"""
initial_distance = dist_func(start, end)
if initial_distance < distance:
raise ValueError(f"End is closer to start ({initial_distance}) than "
f"given distance ({distance}).")
if tol <= 0:
raise ValueError(f"Tolerance is not positive: {tol}")
# Binary search for a point at the given distance.
left = start
right = end
while not np.isclose(dist_func(start, right), distance, rtol=tol):
midpoint = (left + right) / 2
# If midpoint is too close, search in second half.
if dist_func(start, midpoint) < distance:
left = midpoint
# Otherwise the midpoint is too far, so search in first half.
else:
right = midpoint
return right
def _point_along_line(ax, start, distance, angle=0, tol=0.01):
"""Point at a given distance from start at a given angle.
Args:
ax: CartoPy axes.
start: Starting point for the line in axes coordinates.
distance: Positive physical distance to travel.
angle: Anti-clockwise angle for the bar, in radians. Default: 0
tol: Relative error in distance to allow. Default: 0.01
Returns:
Coordinates of a point (a (2, 1)-shaped NumPy array).
"""
# Direction vector of the line in axes coordinates.
direction = np.array([np.cos(angle), np.sin(angle)])
geodesic = cgeo.Geodesic()
# Physical distance between points.
def dist_func(a_axes, b_axes):
a_phys = _axes_to_lonlat(ax, a_axes)
b_phys = _axes_to_lonlat(ax, b_axes)
# Geodesic().inverse returns a NumPy MemoryView like [[distance,
# start azimuth, end azimuth]].
return geodesic.inverse(a_phys, b_phys).base[0, 0]
end = _upper_bound(start, direction, distance, dist_func)
return _distance_along_line(start, end, distance, dist_func, tol)
def scale_bar(ax, location, length, metres_per_unit=1000, unit_name='km',
tol=0.01, angle=0, color='black', linewidth=3, text_offset=0.005,
ha='center', va='bottom', plot_kwargs=None, text_kwargs=None,
**kwargs):
"""Add a scale bar to Cartopy axes.
For angles between 0 and 90 the text and line may be plotted at
slightly different angles for unknown reasons. To work around this,
override the 'rotation' keyword argument with text_kwargs.
Args:
ax: CartoPy axes.
location: Position of left-side of bar in axes coordinates.
length: Geodesic length of the scale bar.
metres_per_unit: Number of metres in the given unit. Default: 1000
unit_name: Name of the given unit. Default: 'km'
tol: Allowed relative error in length of bar. Default: 0.01
angle: Anti-clockwise rotation of the bar.
color: Color of the bar and text. Default: 'black'
linewidth: Same argument as for plot.
text_offset: Perpendicular offset for text in axes coordinates.
Default: 0.005
ha: Horizontal alignment. Default: 'center'
va: Vertical alignment. Default: 'bottom'
**plot_kwargs: Keyword arguments for plot, overridden by **kwargs.
**text_kwargs: Keyword arguments for text, overridden by **kwargs.
**kwargs: Keyword arguments for both plot and text.
"""
# Setup kwargs, update plot_kwargs and text_kwargs.
if plot_kwargs is None:
plot_kwargs = {}
if text_kwargs is None:
text_kwargs = {}
plot_kwargs = {'linewidth': linewidth, 'color': color, **plot_kwargs,
**kwargs}
text_kwargs = {'ha': ha, 'va': va, 'rotation': angle, 'color': color,
**text_kwargs, **kwargs}
# Convert all units and types.
location = np.asarray(location) # For vector addition.
length_metres = length * metres_per_unit
angle_rad = angle * np.pi / 180
# End-point of bar.
end = _point_along_line(ax, location, length_metres, angle=angle_rad,
tol=tol)
# Coordinates are currently in axes coordinates, so use transAxes to
# put into data coordinates. *zip(a, b) produces a list of x-coords,
# then a list of y-coords.
ax.plot(*zip(location, end), transform=ax.transAxes, **plot_kwargs)
# Push text away from bar in the perpendicular direction.
midpoint = (location + end) / 2
offset = text_offset * np.array([-np.sin(angle_rad), np.cos(angle_rad)])
text_location = midpoint + offset
# 'rotation' keyword argument is in text_kwargs.
ax.text(*text_location, f"{length} {unit_name}", rotation_mode='anchor',
transform=ax.transAxes, **text_kwargs)
| [
"iris.plot.pcolormesh",
"cartopy.mpl.ticker.LongitudeFormatter",
"iris.util.mask_cube",
"numpy.asarray",
"cartopy.feature.NaturalEarthFeature",
"numpy.sin",
"numpy.linalg.norm",
"cartopy.geodesic.Geodesic",
"matplotlib.pyplot.gca",
"cartopy.crs.PlateCarree",
"numpy.cos",
"cartopy.mpl.ticker.La... | [((1522, 1566), 'iris.util.mask_cube', 'iris.util.mask_cube', (['cube', '(cube.data <= vmin)'], {}), '(cube, cube.data <= vmin)\n', (1541, 1566), False, 'import iris\n'), ((1582, 1688), 'cartopy.feature.NaturalEarthFeature', 'cartopy.feature.NaturalEarthFeature', (['"""physical"""', '"""land"""', '"""10m"""'], {'edgecolor': 'None', 'facecolor': '"""lightgrey"""'}), "('physical', 'land', '10m', edgecolor=\n None, facecolor='lightgrey')\n", (1617, 1688), False, 'import cartopy\n'), ((1752, 1878), 'cartopy.feature.NaturalEarthFeature', 'cartopy.feature.NaturalEarthFeature', (['"""cultural"""', '"""admin_0_boundary_lines_land"""', '"""10m"""'], {'edgecolor': '"""black"""', 'facecolor': '"""none"""'}), "('cultural',\n 'admin_0_boundary_lines_land', '10m', edgecolor='black', facecolor='none')\n", (1787, 1878), False, 'import cartopy\n'), ((2200, 2278), 'iris.plot.pcolormesh', 'iplt.pcolormesh', (['mcube'], {'axes': 'ax', 'cmap': '"""hot_r"""', 'zorder': '(10)', 'vmin': 'vmin', 'vmax': 'vmax'}), "(mcube, axes=ax, cmap='hot_r', zorder=10, vmin=vmin, vmax=vmax)\n", (2215, 2278), True, 'import iris.plot as iplt\n'), ((6011, 6026), 'cartopy.geodesic.Geodesic', 'cgeo.Geodesic', ([], {}), '()\n', (6024, 6026), True, 'import cartopy.geodesic as cgeo\n'), ((8521, 8541), 'numpy.asarray', 'np.asarray', (['location'], {}), '(location)\n', (8531, 8541), True, 'import numpy as np\n'), ((1045, 1065), 'cartopy.mpl.ticker.LongitudeFormatter', 'LongitudeFormatter', ([], {}), '()\n', (1063, 1065), False, 'from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter\n'), ((1101, 1120), 'cartopy.mpl.ticker.LatitudeFormatter', 'LatitudeFormatter', ([], {}), '()\n', (1118, 1120), False, 'from cartopy.mpl.ticker import LatitudeFormatter, LongitudeFormatter\n'), ((1961, 1970), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1968, 1970), True, 'import matplotlib.pyplot as plt\n'), ((3545, 3570), 'numpy.linalg.norm', 'np.linalg.norm', (['direction'], {}), '(direction)\n', (3559, 3570), True, 'import numpy as np\n'), ((2767, 2785), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (2783, 2785), True, 'import cartopy.crs as ccrs\n'), ((5960, 5973), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (5966, 5973), True, 'import numpy as np\n'), ((5975, 5988), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (5981, 5988), True, 'import numpy as np\n'), ((9201, 9218), 'numpy.cos', 'np.cos', (['angle_rad'], {}), '(angle_rad)\n', (9207, 9218), True, 'import numpy as np\n'), ((9182, 9199), 'numpy.sin', 'np.sin', (['angle_rad'], {}), '(angle_rad)\n', (9188, 9199), True, 'import numpy as np\n')] |
"""
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange
from numpy import zeros, ones, array, where, pi, diag, eye, maximum
from numpy import sum as npsum
from numpy.random import random
from scipy.special import erf, erfcx
from numpy.linalg import inv, slogdet, solve, cholesky
from scipy.linalg import solve_triangular
from scipy.optimize import minimize, differential_evolution, fmin_l_bfgs_b
from itertools import product
from warnings import warn
from copy import copy
from inspect import isclass
import matplotlib.pyplot as plt
class SquaredExponential(object):
r"""
``SquaredExponential`` is a covariance-function class which can be passed to
``GpRegressor`` via the ``kernel`` keyword argument. It uses the 'squared-exponential'
covariance function given by:
.. math::
K(\underline{u}, \underline{v}) = A^2 \exp \left( -\frac{1}{2} \sum_{i=1}^{n} \left(\frac{u_i - v_i}{l_i}\right)^2 \right)
The hyper-parameter vector :math:`\underline{\theta}` used by ``SquaredExponential`` to define
the above function is structured as follows:
.. math::
\underline{\theta} = [ \ln{A}, \ln{l_1}, \ldots, \ln{l_n}]
:param hyperpar_bounds: \
By default, ``SquaredExponential`` will automatically set sensible lower and upper bounds on the value of
the hyperparameters based on the available data. However, this keyword allows the bounds to be specified
manually as a list of length-2 tuples giving the lower/upper bounds for each parameter.
"""
def __init__(self, hyperpar_bounds = None):
if hyperpar_bounds is None:
self.bounds = None
else:
self.bounds = hyperpar_bounds
def pass_data(self, x, y):
# pre-calculates hyperparameter-independent part of the
# data covariance matrix as an optimisation
dx = x[:,None,:] - x[None,:,:]
self.distances = -0.5*dx**2 # distributed outer subtraction using broadcasting
self.epsilon = 1e-12 * eye(dx.shape[0]) # small values added to the diagonal for stability
# construct sensible bounds on the hyperparameter values
if self.bounds is None:
s = log(y.std())
self.bounds = [(s-4,s+4)]
for i in range(x.shape[1]):
lwr = log(abs(dx[:,:,i]).mean())-4
upr = log(dx[:,:,i].max())+2
self.bounds.append((lwr,upr))
def __call__(self, u, v, theta):
a = exp(theta[0])
L = exp(theta[1:])
D = -0.5*(u[:,None,:] - v[None,:,:])**2
C = exp((D / L[None,None,:]**2).sum(axis=2))
return (a**2)*C
def build_covariance(self, theta):
"""
Optimized version of self.matrix() specifically for the data
covariance matrix where the vectors v1 & v2 are both self.x.
"""
a = exp(theta[0])
L = exp(theta[1:])
C = exp((self.distances / L[None,None,:]**2).sum(axis=2)) + self.epsilon
return (a**2)*C
def gradient_terms(self, v, x, theta):
"""
Calculates the covariance-function specific parts of
the expression for the predictive mean and covariance
of the gradient of the GP estimate.
"""
a = exp(theta[0])
L = exp(theta[1:])
A = (x - v[None,:]) / L[None,:]**2
return A.T, (a/L)**2
def covariance_and_gradients(self, theta):
a = exp(theta[0])
L = exp(theta[1:])
C = exp((self.distances / L[None,None,:]**2).sum(axis=2)) + self.epsilon
K = (a**2)*C
grads = [(2.*a)*C]
for i,k in enumerate(L):
grads.append( (-2./k**3)*self.distances[:,:,i]*K )
return K, grads
def get_bounds(self):
return self.bounds
class RationalQuadratic(object):
r"""
``RationalQuadratic`` is a covariance-function class which can be passed to
``GpRegressor`` via the ``kernel`` keyword argument. It uses the 'rational quadratic'
covariance function given by:
.. math::
K(\underline{u}, \underline{v}) = A^2 \left( 1 + \frac{1}{2\alpha} \sum_{i=1}^{n} \left(\frac{u_i - v_i}{l_i}\right)^2 \right)^{-\alpha}
The hyper-parameter vector :math:`\underline{\theta}` used by ``RationalQuadratic`` to define
the above function is structured as follows:
.. math::
\underline{\theta} = [ \ln{A}, \ln{\alpha}, \ln{l_1}, \ldots, \ln{l_n}]
:param hyperpar_bounds: \
By default, ``RationalQuadratic`` will automatically set sensible lower and upper bounds on the value of
the hyperparameters based on the available data. However, this keyword allows the bounds to be specified
manually as a list of length-2 tuples giving the lower/upper bounds for each parameter.
"""
def __init__(self, hyperpar_bounds = None):
if hyperpar_bounds is None:
self.bounds = None
else:
self.bounds = hyperpar_bounds
def pass_data(self, x, y):
# pre-calculates hyperparameter-independent part of the
# data covariance matrix as an optimisation
dx = x[:,None,:] - x[None,:,:]
self.distances = 0.5*dx**2 # distributed outer subtraction using broadcasting
self.epsilon = 1e-12 * eye(dx.shape[0]) # small values added to the diagonal for stability
# construct sensible bounds on the hyperparameter values
if self.bounds is None:
s = log(y.std())
self.bounds = [(s-4,s+4), (-2,6)]
for i in range(x.shape[1]):
lwr = log(abs(dx[:,:,i]).mean())-4
upr = log(dx[:,:,i].max())+2
self.bounds.append((lwr,upr))
def __call__(self, u, v, theta):
a = exp(theta[0])
k = exp(theta[1])
L = exp(theta[2:])
D = 0.5*(u[:,None,:] - v[None,:,:])**2
Z = (D / L[None,None,:]**2).sum(axis=2)
return (a**2)*(1 + Z/k)**(-k)
def build_covariance(self, theta):
a = exp(theta[0])
k = exp(theta[1])
L = exp(theta[2:])
Z = (self.distances / L[None,None,:]**2).sum(axis=2)
return (a**2)*((1 + Z/k)**(-k) + self.epsilon)
def gradient_terms(self, v, x, theta):
"""
Calculates the covariance-function specific parts of
the expression for the predictive mean and covariance
of the gradient of the GP estimate.
"""
raise ValueError("""
Gradient calculations are not yet available for the
RationalQuadratic covariance function.
""")
def covariance_and_gradients(self, theta):
a = exp(theta[0])
q = exp(theta[1])
L = exp(theta[2:])
Z = (self.distances / L[None,None,:]**2).sum(axis=2)
F = (1 + Z/q)
ln_F = log(F)
C = exp(-q*ln_F) + self.epsilon
K = (a**2)*C
grads = [(2.*a)*C]
grads.append( -K*(ln_F - (Z/q)/F) )
G = 2*K/F
for i,l in enumerate(L):
grads.append( G*(self.distances[:,:,i]/l**3) )
return K, grads
def get_bounds(self):
return self.bounds
class GpRegressor(object):
"""
A class for performing Gaussian-process regression in one or more dimensions.
Gaussian-process regression (GPR) is a non-parametric regression technique
which can fit arbitrarily spaced data in any number of dimensions. A unique
feature of GPR is its ability to account for uncertainties on the data
(which must be assumed to be Gaussian) and propagate that uncertainty to the
regression estimate by modelling the regression estimate itself as a multivariate
normal distribution.
:param x: \
The spatial coordinates of the y-data values. For the 1-dimensional case,
this should be a list or array of floats. For greater than 1 dimension,
a list of coordinate arrays or tuples should be given.
:param y: The y-data values as a list or array of floats.
:param y_err: \
The error on the y-data values supplied as a list or array of floats.
This technique explicitly assumes that errors are Gaussian, so the supplied
error values represent normal distribution standard deviations. If this
argument is not specified the errors are taken to be small but non-zero.
:param hyperpars: \
An array specifying the hyper-parameter values to be used by the
covariance function class, which by default is ``SquaredExponential``.
See the documentation for the relevant covariance function class for
a description of the required hyper-parameters. Generally this argument
should be left unspecified, in which case the hyper-parameters will be
selected automatically.
:param class kernel: \
The covariance function class which will be used to model the data. The
covariance function classes can be imported from the ``gp_tools`` module and
then passed to ``GpRegressor`` using this keyword argument.
:param bool cross_val: \
If set to ``True``, leave-one-out cross-validation is used to select the
hyper-parameters in place of the marginal likelihood.
"""
def __init__(self, x, y, y_err = None, hyperpars = None, kernel = SquaredExponential, cross_val = False):
self.N_points = len(x)
# identify the number of spatial dimensions
if hasattr(x[0], '__len__'): # multi-dimensional case
self.N_dimensions = len(x[0])
else: # 1D case
self.N_dimensions = 1
# load the spatial data into a 2D array
self.x = zeros([self.N_points,self.N_dimensions])
for i,v in enumerate(x): self.x[i,:] = v
# data to fit
self.y = array(y)
# data errors covariance matrix
self.sig = zeros([self.N_points, self.N_points])
if y_err is not None:
if len(y) == len(y_err):
for i in range(len(self.y)):
self.sig[i,i] = y_err[i]**2
else:
raise ValueError('y_err must be the same length as y')
# create an instance of the covariance function if only the class was passed
if isclass(kernel):
self.cov = kernel()
else:
self.cov = kernel
# pass the data to the kernel for pre-calculations
self.cov.pass_data(self.x, self.y)
if cross_val:
self.model_selector = self.loo_likelihood
self.model_selector_gradient = self. loo_likelihood_gradient
else:
self.model_selector = self.marginal_likelihood
self.model_selector_gradient = self.marginal_likelihood_gradient
self.hp_bounds = self.cov.get_bounds()
# if hyper-parameters are specified manually, allocate them
if hyperpars is None:
hyperpars = self.optimize_hyperparameters()
# build the covariance matrix
self.set_hyperparameters(hyperpars)
def __call__(self, points, theta = None):
"""
Calculate the mean and standard deviation of the regression estimate at a series
of specified spatial points.
:param list points: \
A list containing the spatial locations where the mean and standard deviation
of the estimate is to be calculated. In the 1D case this would be a list of
floats, or a list of coordinate tuples in the multi-dimensional case.
:return: \
Two 1D arrays, the first containing the means and the second containing the
standard deviations.
"""
if theta is not None:
self.set_hyperparameters(theta)
mu_q = []
errs = []
p = self.process_points(points)
for q in p[:,None,:]:
K_qx = self.cov(q, self.x, self.hyperpars)
K_qq = self.cov(q, q, self.hyperpars)
mu_q.append(dot(K_qx, self.alpha)[0])
v = solve_triangular(self.L, K_qx.T, lower = True)
errs.append( K_qq[0,0] - npsum(v**2) )
return array(mu_q), sqrt( abs(array(errs)) )
def set_hyperparameters(self, theta):
self.hyperpars = theta
self.K_xx = self.cov.build_covariance(theta) + self.sig
self.L = cholesky(self.K_xx)
self.alpha = solve_triangular(self.L.T, solve_triangular(self.L, self.y, lower = True))
def process_points(self, points):
if type(points) is ndarray:
x = points
else:
x = array(points)
m = len(x.shape)
if self.N_dimensions == 1:
if m == 0: # the case when given a float
x = x.reshape([1,1])
elif m == 1:
x = x.reshape([x.shape[0],1])
elif m == 2 and x.shape[1] != 1:
raise ValueError('given spatial points have an incorrect number of dimensions')
else:
if m == 0:
raise ValueError('given spatial points have an incorrect number of dimensions')
elif m == 1 and x.shape[0] == self.N_dimensions:
x = x.reshape([1, self.N_dimensions])
elif m == 2 and x.shape[1] != self.N_dimensions:
raise ValueError('given spatial points have an incorrect number of dimensions')
return x
def gradient(self, points):
"""
Calculate the mean and covariance of the gradient of the regression estimate
with respect to the spatial coordinates at a series of specified points.
:param list points: \
A list containing the spatial locations where the mean vector and and covariance
matrix of the gradient of the regression estimate are to be calculated. In the 1D
case this would be a list of floats, or a list of coordinate tuples in the
multi-dimensional case.
:return means, covariances: \
Two arrays containing the means and covariances of each given spatial point. If the
number of spatial dimensions ``N`` is greater than 1, then the covariances array is
a set of 2D covariance matrices, having shape ``(M,N,N)`` where ``M`` is the given
number of spatial points.
"""
mu_q = []
vars = []
p = self.process_points(points)
for q in p[:,None,:]:
K_qx = self.cov(q, self.x, self.hyperpars)
A, R = self.cov.gradient_terms(q[0,:], self.x, self.hyperpars)
B = (K_qx * self.alpha).T
Q = solve_triangular(self.L, (A*K_qx).T, lower = True)
# calculate the mean and covariance
mean = dot(A,B)
covariance = R - Q.T.dot(Q)
# store the results for the current point
mu_q.append(mean)
vars.append(covariance)
return array(mu_q).squeeze(), array(vars).squeeze()
def spatial_derivatives(self, points):
"""
Calculate the spatial derivatives (i.e. the gradient) of the predictive mean
and variance of the GP estimate. These quantities are useful in the analytic
calculation of the spatial derivatives of acquisition functions like the expected
improvement.
:param list points: \
A list containing the spatial locations where the gradient of the mean and
variance are to be calculated. In the 1D case this would be a list of floats,
or a list of coordinate tuples in the multi-dimensional case.
:return mean_gradients, variance_gradients: \
Two arrays containing the gradient vectors of the mean and variance at each given
spatial point.
"""
mu_gradients = []
var_gradients = []
p = self.process_points(points)
for q in p[:,None,:]:
K_qx = self.cov(q, self.x, self.hyperpars)
A, _ = self.cov.gradient_terms(q[0,:], self.x, self.hyperpars)
B = (K_qx * self.alpha).T
Q = solve_triangular(self.L.T, solve_triangular(self.L, K_qx.T, lower = True))
# calculate the mean and covariance
dmu_dx = dot(A,B)
dV_dx = -2*(A*K_qx[None,:]).dot(Q)
# store the results for the current point
mu_gradients.append(dmu_dx)
var_gradients.append(dV_dx)
return array(mu_gradients).squeeze(), array(var_gradients).squeeze()
def build_posterior(self, points):
"""
Generates the full mean vector and covariance matrix for the GP fit at
a set of specified points.
:param points: \
A list containing the spatial locations which will be used to construct
the Gaussian process. In the 1D case this would be a list of floats, or
a list of coordinate tuples in the multi-dimensional case.
:return: The mean vector as a 1D array, followed by covariance matrix as a 2D array.
"""
v = self.process_points(points)
K_qx = self.cov(v, self.x, self.hyperpars)
K_qq = self.cov(v, v, self.hyperpars)
mu = dot(K_qx, self.alpha)
sigma = K_qq - dot(K_qx, solve_triangular(self.L.T, solve_triangular(self.L, K_qx.T, lower = True)))
return mu, sigma
def loo_predictions(self):
"""
Calculates the 'leave-one out' (LOO) predictions for the data,
where each data point is removed from the training set and then
has its value predicted using the remaining data.
This implementation is based on equation (5.12) from Rasmussen &
Williams.
"""
# Use the Cholesky decomposition of the covariance to find its inverse
I = eye(len(self.x))
iK = solve_triangular(self.L.T, solve_triangular(self.L, I, lower = True))
var = 1./diag(iK)
mu = self.y - self.alpha * var
sigma = sqrt(var)
return mu, sigma
def loo_likelihood(self, theta):
"""
Calculates the 'leave-one out' (LOO) log-likelihood.
This implementation is based on equations (5.10, 5.11, 5.12) from
Rasmussen & Williams.
"""
try:
K_xx = self.cov.build_covariance(theta) + self.sig
L = cholesky(K_xx)
# Use the Cholesky decomposition of the covariance to find its inverse
I = eye(len(self.x))
iK = solve_triangular(L.T, solve_triangular(L, I, lower = True))
alpha = solve_triangular(L.T, solve_triangular(L, self.y, lower = True))
var = 1. / diag(iK)
return -0.5*(var*alpha**2 + log(var)).sum()
except:
warn('Cholesky decomposition failure in loo_likelihood')
return -1e50
def loo_likelihood_gradient(self, theta):
"""
Calculates the 'leave-one out' (LOO) log-likelihood, as well as its
gradient with respect to the hyperparameters.
This implementation is based on equations (5.10, 5.11, 5.12, 5.13, 5.14)
from Rasmussen & Williams.
"""
K_xx, grad_K = self.cov.covariance_and_gradients(theta)
K_xx += self.sig
L = cholesky(K_xx)
# Use the Cholesky decomposition of the covariance to find its inverse
I = eye(len(self.x))
iK = solve_triangular(L.T, solve_triangular(L, I, lower = True))
alpha = solve_triangular(L.T, solve_triangular(L, self.y, lower = True))
var = 1. / diag(iK)
LOO = -0.5*(var*alpha**2 + log(var)).sum()
grad = zeros(len(grad_K))
for i,dK in enumerate(grad_K):
Z = iK.dot(dK)
grad[i] = ((alpha*Z.dot(alpha) - 0.5*(1 + var*alpha**2)*diag(Z.dot(iK))) * var).sum()
return LOO, grad*exp(theta)
def marginal_likelihood(self, theta):
"""
returns the log-marginal likelihood for the supplied hyperparameter values.
This implementation is based on equation (5.8) from Rasmussen & Williams.
"""
K_xx = self.cov.build_covariance(theta) + self.sig
try: # protection against singular matrix error crash
L = cholesky(K_xx)
alpha = solve_triangular(L.T, solve_triangular(L, self.y, lower = True))
return -0.5*dot( self.y.T, alpha ) - log(diagonal(L)).sum()
except:
warn('Cholesky decomposition failure in marginal_likelihood')
return -1e50
def marginal_likelihood_gradient(self, theta):
"""
returns the log-marginal likelihood and its gradient with respect
to the hyperparameters.
This implementation is based on equations (5.8, 5.9) from Rasmussen & Williams.
"""
K_xx, grad_K = self.cov.covariance_and_gradients(theta)
K_xx += self.sig
# get the cholesky decomposition
L = cholesky(K_xx)
# calculate the log-marginal likelihood
alpha = solve_triangular(L.T, solve_triangular(L, self.y, lower = True))
LML = -0.5*dot( self.y.T, alpha ) - log(diagonal(L)).sum()
# calculate the gradients
iK = solve_triangular(L.T, solve_triangular(L, eye(L.shape[0]), lower = True))
Q = alpha[:,None]*alpha[None,:] - iK
grad = array([ 0.5*(Q*dK.T).sum() for dK in grad_K])*exp(theta)
return LML, grad
def optimize_hyperparameters(self):
# optimise the hyperparameters
opt_result = differential_evolution(lambda x : -self.model_selector(x), self.hp_bounds)
return opt_result.x
def bfgs_func(self, theta):
y, grad_y = self.model_selector_gradient(theta)
return -y, -grad_y
def multistart_bfgs(self, starts = None):
if starts is None: starts = int(2*sqrt(len(self.hp_bounds)))+1
# starting positions guesses by random sampling + one in the centre of the hypercube
lwr, upr = [array([k[i] for k in self.hp_bounds]) for i in [0,1]]
starting_positions = [ lwr + (upr-lwr)*random(size = len(self.hp_bounds)) for _ in range(starts-1) ]
starting_positions.append(0.5*(lwr+upr))
# run BFGS for each starting position
results = [ fmin_l_bfgs_b(self.bfgs_func, x0, approx_grad = False, bounds = self.hp_bounds) for x0 in starting_positions ]
# extract best solution
solution = sorted(results, key = lambda x : x[1])[0][0]
return solution
class MarginalisedGpRegressor(object):
def __init__(self, x, y, y_err = None, hyperparameter_samples = None, kernel = SquaredExponential, cross_val = False):
self.gps = [ GpRegressor(x,y,y_err=y_err, kernel=kernel, cross_val=cross_val, hyperpars=theta) for theta in hyperparameter_samples]
self.n = len(self.gps)
def __call__(self, points):
results = [ gp(points) for gp in self.gps ]
means, sigmas = [array([v[i] for v in results]) for i in [0,1]]
return means.mean(axis=0), sigmas.mean(axis=0)
def spatial_derivatives(self, points):
results = [ gp.spatial_derivatives(points) for gp in self.gps ]
grad_mu, grad_var = [array([v[i] for v in results]) for i in [0,1]]
return grad_mu.mean(axis=0), grad_var.mean(axis=0)
def gradient(self, points):
results = [ gp.gradient(points) for gp in self.gps ]
grad_mu, grad_var = [array([v[i] for v in results]) for i in [0,1]]
return grad_mu.mean(axis=0), grad_var.mean(axis=0)
class GpInverter(object):
"""
Solves linear inverse problems of the form y = Gb, using a Gaussian-process
prior which imposes spatial regularity on the solution.
The solution vector 'b' must describe the value of a quantity everywhere
on a grid, as the GP prior imposes covariance between these grid-points
based on the 'distance' between them. The grid need not be a spatial one,
only one over which regularity is desired, e.g. time, wavelength ect.
> arguments
x - array of position values/vectors for the model parameters
y - array of data values
cov - covariance matrix for the data
G - the linearisation matrix
"""
def __init__(self, x, y, cov, G, scale_length = None, mean = None, amplitude = None, selector = 'evidence'):
self.x = x # spatial location of the parameters, *not* the y data
self.y = y # data values
self.S_y = cov # data covariance matrix
self.G = G # geometry matrix
self.selector = selector
self.hyperpar_settings = (amplitude, scale_length, mean)
# check inputs for compatability
self.parse_inputs()
self.I = ones([G.shape[1],1])
self.f = dot( self.G, self.I )
self.iS_y = inv(self.S_y)
# generate square-distance matrix from self.x
if hasattr(self.x[0], '__iter__'): # multi-dimensional case
self.D = [ [ self.dist(i,j) for j in self.x] for i in self.x ]
else: # 1D case
self.D = [ [ (i-j)**2 for j in self.x] for i in self.x ]
self.D = -0.5*array(self.D)
self.A, self.L, self.mu_val = self.optimize_hyperparameters()
# now we have determined the hyperparameters, generate the prior
# mean and covariance matrices
self.mu_p = self.mu_val * ones([len(x), 1])
self.S_p = (self.A**2)*exp(self.D/(self.L**2))
# we may now also generate the posterior mean and covariance.
# To improve the numerical stability of calculating the posterior
# covariance, we use the woodbury matrix identity:
K = dot(self.G, self.S_p)
V = self.S_y + dot(K, self.G.T)
iVK = solve(V,K)
self.S_b = self.S_p - dot( K.T, iVK )
# posterior mean involves no further inversions so is stable
self.mu_b = self.mu_p + dot( self.S_b, dot( self.G.T, dot( self.iS_y, (self.y - self.mu_val*self.f) ) ) )
def parse_inputs(self):
# first check input types
if type(self.y) is not ndarray: self.y = array(self.y)
if type(self.S_y) is not ndarray: self.S_y = array(self.S_y)
if type(self.G) is not ndarray: self.G = array(self.G)
# now check shapes / sizes are compatible
if len(self.y.shape) is not 2: self.y = self.y.reshape([self.y.size,1])
if self.S_y.shape[0] != self.S_y.shape[0]:
raise ValueError('Data covariance matrix must be square')
if self.S_y.shape[0] != self.y.shape[0]:
raise ValueError('Dimensions of the data covariance matrix must equal the number of data points')
if (self.G.shape[0] != self.y.shape[0]) or (self.G.shape[1] != len(self.x)):
raise ValueError('The operator matrix must have dimensions [# data points, # spatial points]')
def dist(self, a, b):
return sum( (i-j)**2 for i, j in zip(a, b) )
def log_ev(self, h):
# extract hyperparameters
A, L, mu_p = [exp(v) for v in h]
# first make the prior covariance
S_p = (A**2)*exp(self.D/(L**2))
# now the marginal likelihood covariance
S_m = dot( self.G, dot(S_p, self.G.T) ) + self.S_y
# and the marginal likelihood mean
mu_m = mu_p * self.f
# now calculate negative log marginal likelihood
u = self.y - mu_m
iSu = solve(S_m, u)
L = dot( u.T, iSu ) + slogdet(S_m)[1]
return L[0][0]
def nn_maximum_likelihood(self, h):
A, L, mu_p = [exp(v) for v in h]
S_p = (A**2)*exp(self.D/(L**2))
K = dot(self.G, S_p)
V = self.S_y + dot(K, self.G.T)
iVK = solve(V,K)
S_b = S_p - dot( K.T, iVK )
# posterior mean involves no further inversions so is stable
mu_b = mu_p + dot( S_b, dot( self.G.T, dot( self.iS_y, (self.y - mu_p*self.f) ) ) )
mu_b[where(mu_b < 0)] = 0.
# find the residual
res = self.y - self.G.dot(mu_b)
LL = dot(res.T, self.iS_y.dot(res))
return LL[0,0]
def optimize_hyperparameters(self):
# choose the selection criterion for the hyperparameters
if self.selector is 'evidence':
criterion = self.log_ev
elif self.selector is 'NNML':
criterion = self.nn_maximum_likelihood
else:
raise ValueError('The selector keyword must be given as either `evidence` or `NNML`')
# Choose the correct inputs for the criterion based on which
# hyperparameters have been given fixed values
code = tuple([ x is None for x in self.hyperpar_settings ])
log_vals = []
for x in self.hyperpar_settings:
if x is None:
log_vals.append(None)
else:
log_vals.append(log(x))
selection_functions = {
(1,1,1) : lambda x : criterion(x),
(1,1,0) : lambda x : criterion([x[0],x[1],log_vals[2]]),
(1,0,1) : lambda x : criterion([x[0],log_vals[1],x[1]]),
(0,1,1) : lambda x : criterion([log_vals[0],x[0],x[1]]),
(1,0,0) : lambda x : criterion([x[0],log_vals[1],log_vals[2]]),
(0,1,0) : lambda x : criterion([log_vals[0],x[0],log_vals[2]]),
(0,0,1) : lambda x : criterion([log_vals[0],log_vals[1],x[0]]),
(0,0,0) : None
}
minfunc = selection_functions[code]
# if all the hyperparameters have been fixed, just return the fixed values
if minfunc is None: return self.hyperpar_settings
# make some guesses for the hyperparameters
A_guess = [-6,-4,-2, 0]
L_guess = [-6,-5,-4,-3,-2] # NOTE - should be data-determined in future
mu_guess = [-8,-6,-4,-2, 0]
# build a list of initial guesses again depending on what parameters are fixed
guess_components = []
if code[0]: guess_components.append(A_guess)
if code[1]: guess_components.append(L_guess)
if code[2]: guess_components.append(mu_guess)
guesses = [ g for g in product(*guess_components) ]
# sort the guesses by best score
guesses = sorted(guesses, key = minfunc)
LML_list = []
theta_list = []
for g in guesses[:3]: # minimize the LML for the best guesses
min_obj = minimize( minfunc, g, method = 'L-BFGS-B' )
LML_list.append( min_obj['fun'] )
theta_list.append( min_obj['x'] )
# pick the solution the best score
opt_params = theta_list[ argmin(array(LML_list)) ]
paras = []
k = 0
for i in range(3):
if code[i]:
paras.append(opt_params[k])
k += 1
else:
paras.append(log_vals[i])
return [exp(v) for v in paras]
class ExpectedImprovement(object):
r"""
``ExpectedImprovement`` is an acquisition-function class which can be passed to
``GpOptimiser`` via the ``acquisition`` keyword argument. It implements the
expected-improvement acquisition function given by
.. math::
\mathrm{EI}(\underline{x}) = \left( z F(z) + P(z) \right) \sigma(\underline{x})
where
.. math::
z = \frac{\mu(\underline{x}) - y_{\mathrm{max}}}{\sigma(\underline{x})},
\qquad P(z) = \frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{1}{2}z^2 \right)},
\qquad F(z) = \frac{1}{2}\left[ 1 + \mathrm{erf}\left(\frac{z}{\sqrt{2}}\right) \right],
:math:`\mu(\underline{x}),\,\sigma(\underline{x})` are the predictive mean and standard
deviation of the Gaussian-process regression model at position :math:`\underline{x}`,
and :math:`y_{\mathrm{max}}` is the current maximum observed value of the objective function.
"""
def __init__(self):
self.ir2pi = 1 / sqrt(2*pi)
self.ir2 = 1. / sqrt(2)
self.rpi2 = sqrt(0.5*pi)
self.ln2pi = log(2*pi)
self.name = 'Expected improvement'
self.convergence_description = '$\mathrm{EI}_{\mathrm{max}} \; / \; (y_{\mathrm{max}} - y_{\mathrm{min}})$'
def update_gp(self, gp):
self.gp = gp
self.mu_max = gp.y.max()
def __call__(self, x):
mu, sig = self.gp(x)
Z = (mu[0] - self.mu_max) / sig[0]
if Z < -3:
ln_EI = log(1+Z*self.cdf_pdf_ratio(Z)) + self.ln_pdf(Z) + log(sig[0])
EI = exp(ln_EI)
else:
pdf = self.normal_pdf(Z)
cdf = self.normal_cdf(Z)
EI = sig[0] * (Z*cdf + pdf)
return EI
def opt_func(self, x):
mu, sig = self.gp(x)
Z = (mu[0] - self.mu_max) / sig[0]
if Z < -3:
ln_EI = log(1+Z*self.cdf_pdf_ratio(Z)) + self.ln_pdf(Z) + log(sig[0])
else:
pdf = self.normal_pdf(Z)
cdf = self.normal_cdf(Z)
ln_EI = log(sig[0] * (Z*cdf + pdf))
return -ln_EI
def opt_func_gradient(self, x):
mu, sig = self.gp(x)
dmu, dvar = self.gp.spatial_derivatives(x)
Z = (mu[0] - self.mu_max) / sig[0]
if Z < -3:
R = self.cdf_pdf_ratio(Z)
H = 1+Z*R
ln_EI = log(H) + self.ln_pdf(Z) + log(sig[0])
grad_ln_EI = (0.5*dvar/sig[0] + R*dmu) / (H*sig[0])
else:
pdf = self.normal_pdf(Z)
cdf = self.normal_cdf(Z)
EI = sig[0]*(Z*cdf + pdf)
ln_EI = log(EI)
grad_ln_EI = (0.5*pdf*dvar/sig[0] + dmu*cdf) / EI
return -ln_EI, -grad_ln_EI.squeeze()
def normal_pdf(self, z):
return exp(-0.5*z**2)*self.ir2pi
def normal_cdf(self, z):
return 0.5*(1. + erf(z*self.ir2))
def cdf_pdf_ratio(self, z):
return self.rpi2*erfcx(-z*self.ir2)
def ln_pdf(self,z):
return -0.5*(z**2 + self.ln2pi)
def starting_positions(self, bounds):
lwr, upr = [array([k[i] for k in bounds]) for i in [0,1]]
widths = upr-lwr
starts = []
for x0 in self.gp.x:
# get the gradient at the current point
y0, g0 = self.opt_func_gradient(x0)
for i in range(20):
step = 2e-3 / (abs(g0) / widths).max()
x1 = x0-step*g0
y1, g1 = self.opt_func_gradient(x1)
if (y1 < y0) and ((x1 >= lwr)&(x1 <= upr)).all():
x0 = x1.copy()
g0 = g1.copy()
y0 = copy(y1)
else:
break
starts.append(x0)
return starts
def convergence_metric(self, x):
return self.__call__(x) / (self.mu_max - self.gp.y.min())
class UpperConfidenceBound(object):
r"""
``UpperConfidenceBound`` is an acquisition-function class which can be passed to
``GpOptimiser`` via the ``acquisition`` keyword argument. It implements the
upper-confidence-bound acquisition function given by
.. math::
\mathrm{UCB}(\underline{x}) = \mu(\underline{x}) + \kappa \sigma(\underline{x})
where :math:`\mu(\underline{x}),\,\sigma(\underline{x})` are the predictive mean and
standard deviation of the Gaussian-process regression model at position :math:`\underline{x}`.
:param float kappa: Value of the coefficient :math:`\kappa` which scales the contribution
of the predictive standard deviation to the acquisition function. ``kappa`` should be
set so that :math:`\kappa \ge 0`.
"""
def __init__(self, kappa = 2):
self.kappa = kappa
self.name = 'Upper confidence bound'
self.convergence_description = '$\mathrm{UCB}_{\mathrm{max}} - y_{\mathrm{max}}$'
def update_gp(self, gp):
self.gp = gp
self.mu_max = gp.y.max()
def __call__(self, x):
mu, sig = self.gp(x)
return mu[0] + self.kappa*sig[0]
def opt_func(self, x):
mu, sig = self.gp(x)
return -mu[0] - self.kappa*sig[0]
def opt_func_gradient(self, x):
mu, sig = self.gp(x)
dmu, dvar = self.gp.spatial_derivatives(x)
ucb = mu[0] + self.kappa*sig[0]
grad_ucb = dmu + 0.5*self.kappa*dvar/sig[0]
return -ucb, -grad_ucb.squeeze()
def starting_positions(self, bounds):
starts = [v for v in self.gp.x]
return starts
def convergence_metric(self, x):
return self.__call__(x) - self.mu_max
class MaxVariance(object):
r"""
``MaxVariance`` is a acquisition-function class which can be passed to
``GpOptimiser`` via the ``acquisition`` keyword argument. It selects new
evaluations of the objective function by finding the spatial position
:math:`\underline{x}` with the largest variance :math:`\sigma^2(\underline{x})`
as predicted by the Gaussian-process regression model.
This is a `pure learning' acquisition function which does not seek to find the
maxima of the objective function, but only to minimize uncertainty in the
prediction of the function.
"""
def __init__(self):
pass
def update_gp(self, gp):
self.gp = gp
self.mu_max = gp.y.max()
def __call__(self, x):
_, sig = self.gp(x)
return sig[0]**2
def opt_func(self, x):
_, sig = self.gp(x)
return -sig[0]**2
def opt_func_gradient(self, x):
_, sig = self.gp(x)
_, dvar = self.gp.spatial_derivatives(x)
return -sig[0]**2, -dvar.squeeze()
def starting_positions(self, bounds):
lwr, upr = [array([k[i] for k in bounds]) for i in [0,1]]
starts = [lwr + (upr - lwr)*random(size=len(bounds)) for _ in range(len(self.gp.y))]
return starts
def get_name(self):
return 'Max variance'
class GpOptimiser(object):
"""
A class for performing Gaussian-process optimisation in one or more dimensions.
GpOptimiser extends the functionality of GpRegressor to perform Gaussian-process
optimisation, often also referred to as 'Bayesian optimisation'. This technique
is suited to problems for which a single evaluation of the function being explored
is expensive, such that the total number of function evaluations must be made as
small as possible.
In order to construct the Gaussian-process regression estimate which is used to
search for the global maximum, on initialisation GpOptimiser must be provided with
at least two evaluations of the function which is to be maximised.
:param x: \
The spatial coordinates of the y-data values. For the 1-dimensional case,
this should be a list or array of floats. For greater than 1 dimension,
a list of coordinate arrays or tuples should be given.
:param y: The y-data values as a list or array of floats.
:keyword y_err: \
The error on the y-data values supplied as a list or array of floats.
This technique explicitly assumes that errors are Gaussian, so the supplied
error values represent normal distribution standard deviations. If this
argument is not specified the errors are taken to be small but non-zero.
:keyword bounds: \
A iterable containing tuples which specify the upper and lower bounds
for the optimisation in each dimension in the format (lower_bound, upper_bound).
:param hyperpars: \
An array specifying the hyper-parameter values to be used by the
covariance function class, which by default is ``SquaredExponential``.
See the documentation for the relevant covariance function class for
a description of the required hyper-parameters. Generally this argument
should be left unspecified, in which case the hyper-parameters will be
selected automatically.
:param class kernel: \
The covariance-function class which will be used to model the data. The
covariance-function classes can be imported from the gp_tools module and
then passed to ``GpOptimiser`` using this keyword argument.
:param bool cross_val: \
If set to ``True``, leave-one-out cross-validation is used to select the
hyper-parameters in place of the marginal likelihood.
:param class acquisition: \
The acquisition-function class which is used to select new points at which
the objective function is evaluated. The acquisition-function classes can be
imported from the ``gp_tools`` module and then passed as arguments - see their
documentation for the list of available acquisition functions. If left unspecified,
the ``ExpectedImprovement`` acquisition function is used by default.
"""
def __init__(self, x, y, y_err = None, bounds = None, hyperpars = None, kernel = SquaredExponential,
cross_val = False, acquisition = ExpectedImprovement):
self.x = list(x)
self.y = list(y)
self.y_err = y_err
if y_err is not None: self.y_err = list(self.y_err)
if bounds is None:
ValueError('The bounds keyword argument must be specified')
else:
self.bounds = bounds
self.kernel = kernel
self.cross_val = cross_val
self.gp = GpRegressor(x, y, y_err=y_err, hyperpars=hyperpars, kernel=kernel, cross_val=cross_val)
# if the class has been passed instead of an instance, create an instance
if isclass(acquisition):
self.acquisition = acquisition()
else:
self.acquisition = acquisition
self.acquisition.update_gp(self.gp)
# create storage for tracking
self.acquisition_max_history = []
self.convergence_metric_history = []
self.iteration_history = []
def __call__(self, x):
return self.gp(x)
def add_evaluation(self, new_x, new_y, new_y_err=None):
"""
Add the latest evaluation to the data set and re-build the
Gaussian process so a new proposed evaluation can be made.
:param new_x: location of the new evaluation
:param new_y: function value of the new evaluation
:param new_y_err: Error of the new evaluation.
"""
# store the acquisition function value of the new point
self.acquisition_max_history.append( self.acquisition(new_x) )
self.convergence_metric_history.append( self.acquisition.convergence_metric(new_x) )
self.iteration_history.append( len(self.y)+1 )
# update the data arrays
self.x.append(new_x)
self.y.append(new_y)
if self.y_err is not None:
if new_y_err is not None:
self.y_err.append(new_y_err)
else:
raise ValueError('y_err must be specified for new evaluations if y_err was specified during __init__')
# re-train the GP
self.gp = GpRegressor(self.x, self.y, y_err=self.y_err, kernel = self.kernel, cross_val = self.cross_val)
self.mu_max = max(self.y)
# update the acquisition function info
self.acquisition.update_gp(self.gp)
def diff_evo(self):
opt_result = differential_evolution(self.acquisition.opt_func, self.bounds, popsize = 30)
solution = opt_result.x
funcval = opt_result.fun
if hasattr(funcval, '__len__'): funcval = funcval[0]
return solution, funcval
def multistart_bfgs(self):
starting_positions = self.acquisition.starting_positions(self.bounds)
# run BFGS for each starting position
results = [ fmin_l_bfgs_b(self.acquisition.opt_func_gradient, x0, approx_grad = False, bounds = self.bounds, pgtol=1e-10) for x0 in starting_positions ]
# extract best solution
solution, funcval = sorted(results, key = lambda x : x[1])[0][:2]
if hasattr(funcval, '__len__'): funcval = funcval[0]
return solution, funcval
def propose_evaluation(self, bfgs = False):
"""
Request a proposed location for the next evaluation. This proposal is
selected by maximising the chosen acquisition function.
:param bool bfgs: \
If set as ``True``, multi-start BFGS is used to maximise used to maximise
the acquisition function. Otherwise, ``scipy.optimize.differential_evolution``
is used to maximise the acquisition function instead.
:return: location of the next proposed evaluation.
"""
if bfgs:
# find the evaluation point which maximises the acquisition function
proposed_ev, max_acq = self.multistart_bfgs()
else:
proposed_ev, max_acq = self.diff_evo()
# if the problem is 1D, but the result is returned as a length-1 array,
# extract the result from the array
if hasattr(proposed_ev, '__len__') and len(proposed_ev) == 1:
proposed_ev = proposed_ev[0]
return proposed_ev
def plot_results(self, filename = None, show_plot = True):
fig = plt.figure( figsize=(10,4) )
ax1 = fig.add_subplot(121)
maxvals = maximum.accumulate(self.y)
pad = maxvals.ptp()*0.1
iterations = arange(len(self.y))+1
ax1.plot( iterations, maxvals, c = 'red', alpha = 0.6, label = 'max observed value')
ax1.plot( iterations, self.y, '.', label='function evaluations', markersize=10)
ax1.set_xlabel('iteration')
ax1.set_ylabel('function value')
ax1.set_ylim([maxvals.min()-pad, maxvals.max()+pad])
ax1.legend(loc=4)
ax1.grid()
ax2 = fig.add_subplot(122)
ax2.plot(self.iteration_history, self.convergence_metric_history, c = 'C0', alpha = 0.35)
ax2.plot(self.iteration_history, self.convergence_metric_history, '.', c = 'C0', label = self.acquisition.convergence_description, markersize = 10)
ax2.set_yscale('log')
ax2.set_xlabel('iteration')
ax2.set_ylabel('acquisition function value')
ax2.set_xlim([0,None])
ax2.set_title('Convergence summary')
ax2.legend()
ax2.grid()
fig.tight_layout()
if filename is not None: plt.savefig(filename)
if show_plot:
plt.show()
else:
plt.close() | [
"numpy.sum",
"scipy.linalg.solve_triangular",
"numpy.abs",
"scipy.special.erfcx",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.exp",
"numpy.diag",
"numpy.linalg.solve",
"scipy.optimize.minimize",
"inspect.isclass",
"matplotlib.pyplot.close",
"itertools.product",
"numpy.linalg.cholesky"... | [((2534, 2547), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (2537, 2547), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((2560, 2574), 'numpy.exp', 'exp', (['theta[1:]'], {}), '(theta[1:])\n', (2563, 2574), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((2914, 2927), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (2917, 2927), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((2940, 2954), 'numpy.exp', 'exp', (['theta[1:]'], {}), '(theta[1:])\n', (2943, 2954), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((3307, 3320), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (3310, 3320), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((3333, 3347), 'numpy.exp', 'exp', (['theta[1:]'], {}), '(theta[1:])\n', (3336, 3347), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((3480, 3493), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (3483, 3493), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((3506, 3520), 'numpy.exp', 'exp', (['theta[1:]'], {}), '(theta[1:])\n', (3509, 3520), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((5789, 5802), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (5792, 5802), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((5815, 5828), 'numpy.exp', 'exp', (['theta[1]'], {}), '(theta[1])\n', (5818, 5828), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((5841, 5855), 'numpy.exp', 'exp', (['theta[2:]'], {}), '(theta[2:])\n', (5844, 5855), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6041, 6054), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (6044, 6054), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6067, 6080), 'numpy.exp', 'exp', (['theta[1]'], {}), '(theta[1])\n', (6070, 6080), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6093, 6107), 'numpy.exp', 'exp', (['theta[2:]'], {}), '(theta[2:])\n', (6096, 6107), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6668, 6681), 'numpy.exp', 'exp', (['theta[0]'], {}), '(theta[0])\n', (6671, 6681), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6694, 6707), 'numpy.exp', 'exp', (['theta[1]'], {}), '(theta[1])\n', (6697, 6707), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6720, 6734), 'numpy.exp', 'exp', (['theta[2:]'], {}), '(theta[2:])\n', (6723, 6734), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((6834, 6840), 'numpy.log', 'log', (['F'], {}), '(F)\n', (6837, 6840), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((9672, 9713), 'numpy.zeros', 'zeros', (['[self.N_points, self.N_dimensions]'], {}), '([self.N_points, self.N_dimensions])\n', (9677, 9713), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((9802, 9810), 'numpy.array', 'array', (['y'], {}), '(y)\n', (9807, 9810), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((9871, 9908), 'numpy.zeros', 'zeros', (['[self.N_points, self.N_points]'], {}), '([self.N_points, self.N_points])\n', (9876, 9908), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((10255, 10270), 'inspect.isclass', 'isclass', (['kernel'], {}), '(kernel)\n', (10262, 10270), False, 'from inspect import isclass\n'), ((12326, 12345), 'numpy.linalg.cholesky', 'cholesky', (['self.K_xx'], {}), '(self.K_xx)\n', (12334, 12345), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((17151, 17172), 'numpy.dot', 'dot', (['K_qx', 'self.alpha'], {}), '(K_qx, self.alpha)\n', (17154, 17172), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((17929, 17938), 'numpy.sqrt', 'sqrt', (['var'], {}), '(var)\n', (17933, 17938), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((19195, 19209), 'numpy.linalg.cholesky', 'cholesky', (['K_xx'], {}), '(K_xx)\n', (19203, 19209), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((20861, 20875), 'numpy.linalg.cholesky', 'cholesky', (['K_xx'], {}), '(K_xx)\n', (20869, 20875), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((24624, 24645), 'numpy.ones', 'ones', (['[G.shape[1], 1]'], {}), '([G.shape[1], 1])\n', (24628, 24645), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((24662, 24681), 'numpy.dot', 'dot', (['self.G', 'self.I'], {}), '(self.G, self.I)\n', (24665, 24681), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((24704, 24717), 'numpy.linalg.inv', 'inv', (['self.S_y'], {}), '(self.S_y)\n', (24707, 24717), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((25552, 25573), 'numpy.dot', 'dot', (['self.G', 'self.S_p'], {}), '(self.G, self.S_p)\n', (25555, 25573), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((25629, 25640), 'numpy.linalg.solve', 'solve', (['V', 'K'], {}), '(V, K)\n', (25634, 25640), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((27272, 27285), 'numpy.linalg.solve', 'solve', (['S_m', 'u'], {}), '(S_m, u)\n', (27277, 27285), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((27491, 27507), 'numpy.dot', 'dot', (['self.G', 'S_p'], {}), '(self.G, S_p)\n', (27494, 27507), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27562, 27573), 'numpy.linalg.solve', 'solve', (['V', 'K'], {}), '(V, K)\n', (27567, 27573), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((31761, 31775), 'numpy.sqrt', 'sqrt', (['(0.5 * pi)'], {}), '(0.5 * pi)\n', (31765, 31775), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((31795, 31806), 'numpy.log', 'log', (['(2 * pi)'], {}), '(2 * pi)\n', (31798, 31806), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((41216, 41236), 'inspect.isclass', 'isclass', (['acquisition'], {}), '(acquisition)\n', (41223, 41236), False, 'from inspect import isclass\n'), ((42930, 43004), 'scipy.optimize.differential_evolution', 'differential_evolution', (['self.acquisition.opt_func', 'self.bounds'], {'popsize': '(30)'}), '(self.acquisition.opt_func, self.bounds, popsize=30)\n', (42952, 43004), False, 'from scipy.optimize import minimize, differential_evolution, fmin_l_bfgs_b\n'), ((44791, 44818), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (44801, 44818), True, 'import matplotlib.pyplot as plt\n'), ((44873, 44899), 'numpy.maximum.accumulate', 'maximum.accumulate', (['self.y'], {}), '(self.y)\n', (44891, 44899), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((2068, 2084), 'numpy.eye', 'eye', (['dx.shape[0]'], {}), '(dx.shape[0])\n', (2071, 2084), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((5315, 5331), 'numpy.eye', 'eye', (['dx.shape[0]'], {}), '(dx.shape[0])\n', (5318, 5331), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((6853, 6867), 'numpy.exp', 'exp', (['(-q * ln_F)'], {}), '(-q * ln_F)\n', (6856, 6867), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((12019, 12063), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', 'K_qx.T'], {'lower': '(True)'}), '(self.L, K_qx.T, lower=True)\n', (12035, 12063), False, 'from scipy.linalg import solve_triangular\n'), ((12133, 12144), 'numpy.array', 'array', (['mu_q'], {}), '(mu_q)\n', (12138, 12144), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((12394, 12438), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', 'self.y'], {'lower': '(True)'}), '(self.L, self.y, lower=True)\n', (12410, 12438), False, 'from scipy.linalg import solve_triangular\n'), ((12570, 12583), 'numpy.array', 'array', (['points'], {}), '(points)\n', (12575, 12583), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((14588, 14638), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', '(A * K_qx).T'], {'lower': '(True)'}), '(self.L, (A * K_qx).T, lower=True)\n', (14604, 14638), False, 'from scipy.linalg import solve_triangular\n'), ((14707, 14716), 'numpy.dot', 'dot', (['A', 'B'], {}), '(A, B)\n', (14710, 14716), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((16196, 16205), 'numpy.dot', 'dot', (['A', 'B'], {}), '(A, B)\n', (16199, 16205), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((17804, 17843), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', 'I'], {'lower': '(True)'}), '(self.L, I, lower=True)\n', (17820, 17843), False, 'from scipy.linalg import solve_triangular\n'), ((17864, 17872), 'numpy.diag', 'diag', (['iK'], {}), '(iK)\n', (17868, 17872), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((18284, 18298), 'numpy.linalg.cholesky', 'cholesky', (['K_xx'], {}), '(K_xx)\n', (18292, 18298), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((19354, 19388), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'I'], {'lower': '(True)'}), '(L, I, lower=True)\n', (19370, 19388), False, 'from scipy.linalg import solve_triangular\n'), ((19430, 19469), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'self.y'], {'lower': '(True)'}), '(L, self.y, lower=True)\n', (19446, 19469), False, 'from scipy.linalg import solve_triangular\n'), ((19492, 19500), 'numpy.diag', 'diag', (['iK'], {}), '(iK)\n', (19496, 19500), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((20160, 20174), 'numpy.linalg.cholesky', 'cholesky', (['K_xx'], {}), '(K_xx)\n', (20168, 20174), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((20962, 21001), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'self.y'], {'lower': '(True)'}), '(L, self.y, lower=True)\n', (20978, 21001), False, 'from scipy.linalg import solve_triangular\n'), ((21299, 21309), 'numpy.exp', 'exp', (['theta'], {}), '(theta)\n', (21302, 21309), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((21886, 21923), 'numpy.array', 'array', (['[k[i] for k in self.hp_bounds]'], {}), '([k[i] for k in self.hp_bounds])\n', (21891, 21923), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((22164, 22239), 'scipy.optimize.fmin_l_bfgs_b', 'fmin_l_bfgs_b', (['self.bfgs_func', 'x0'], {'approx_grad': '(False)', 'bounds': 'self.hp_bounds'}), '(self.bfgs_func, x0, approx_grad=False, bounds=self.hp_bounds)\n', (22177, 22239), False, 'from scipy.optimize import minimize, differential_evolution, fmin_l_bfgs_b\n'), ((22844, 22874), 'numpy.array', 'array', (['[v[i] for v in results]'], {}), '([v[i] for v in results])\n', (22849, 22874), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((23091, 23121), 'numpy.array', 'array', (['[v[i] for v in results]'], {}), '([v[i] for v in results])\n', (23096, 23121), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((23320, 23350), 'numpy.array', 'array', (['[v[i] for v in results]'], {}), '([v[i] for v in results])\n', (23325, 23350), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((25031, 25044), 'numpy.array', 'array', (['self.D'], {}), '(self.D)\n', (25036, 25044), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((25312, 25337), 'numpy.exp', 'exp', (['(self.D / self.L ** 2)'], {}), '(self.D / self.L ** 2)\n', (25315, 25337), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((25598, 25614), 'numpy.dot', 'dot', (['K', 'self.G.T'], {}), '(K, self.G.T)\n', (25601, 25614), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((25670, 25683), 'numpy.dot', 'dot', (['K.T', 'iVK'], {}), '(K.T, iVK)\n', (25673, 25683), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((25982, 25995), 'numpy.array', 'array', (['self.y'], {}), '(self.y)\n', (25987, 25995), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((26049, 26064), 'numpy.array', 'array', (['self.S_y'], {}), '(self.S_y)\n', (26054, 26064), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((26114, 26127), 'numpy.array', 'array', (['self.G'], {}), '(self.G)\n', (26119, 26127), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((26894, 26900), 'numpy.exp', 'exp', (['v'], {}), '(v)\n', (26897, 26900), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((26976, 26996), 'numpy.exp', 'exp', (['(self.D / L ** 2)'], {}), '(self.D / L ** 2)\n', (26979, 26996), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27298, 27311), 'numpy.dot', 'dot', (['u.T', 'iSu'], {}), '(u.T, iSu)\n', (27301, 27311), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27418, 27424), 'numpy.exp', 'exp', (['v'], {}), '(v)\n', (27421, 27424), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27459, 27479), 'numpy.exp', 'exp', (['(self.D / L ** 2)'], {}), '(self.D / L ** 2)\n', (27462, 27479), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27531, 27547), 'numpy.dot', 'dot', (['K', 'self.G.T'], {}), '(K, self.G.T)\n', (27534, 27547), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27593, 27606), 'numpy.dot', 'dot', (['K.T', 'iVK'], {}), '(K.T, iVK)\n', (27596, 27606), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27784, 27799), 'numpy.where', 'where', (['(mu_b < 0)'], {}), '(mu_b < 0)\n', (27789, 27799), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((30216, 30255), 'scipy.optimize.minimize', 'minimize', (['minfunc', 'g'], {'method': '"""L-BFGS-B"""'}), "(minfunc, g, method='L-BFGS-B')\n", (30224, 30255), False, 'from scipy.optimize import minimize, differential_evolution, fmin_l_bfgs_b\n'), ((30683, 30689), 'numpy.exp', 'exp', (['v'], {}), '(v)\n', (30686, 30689), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((31698, 31710), 'numpy.sqrt', 'sqrt', (['(2 * pi)'], {}), '(2 * pi)\n', (31702, 31710), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((31733, 31740), 'numpy.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (31737, 31740), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((32267, 32277), 'numpy.exp', 'exp', (['ln_EI'], {}), '(ln_EI)\n', (32270, 32277), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((32733, 32762), 'numpy.log', 'log', (['(sig[0] * (Z * cdf + pdf))'], {}), '(sig[0] * (Z * cdf + pdf))\n', (32736, 32762), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33291, 33298), 'numpy.log', 'log', (['EI'], {}), '(EI)\n', (33294, 33298), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33452, 33470), 'numpy.exp', 'exp', (['(-0.5 * z ** 2)'], {}), '(-0.5 * z ** 2)\n', (33455, 33470), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33608, 33628), 'scipy.special.erfcx', 'erfcx', (['(-z * self.ir2)'], {}), '(-z * self.ir2)\n', (33613, 33628), False, 'from scipy.special import erf, erfcx\n'), ((33755, 33784), 'numpy.array', 'array', (['[k[i] for k in bounds]'], {}), '([k[i] for k in bounds])\n', (33760, 33784), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((37359, 37388), 'numpy.array', 'array', (['[k[i] for k in bounds]'], {}), '([k[i] for k in bounds])\n', (37364, 37388), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((43342, 43451), 'scipy.optimize.fmin_l_bfgs_b', 'fmin_l_bfgs_b', (['self.acquisition.opt_func_gradient', 'x0'], {'approx_grad': '(False)', 'bounds': 'self.bounds', 'pgtol': '(1e-10)'}), '(self.acquisition.opt_func_gradient, x0, approx_grad=False,\n bounds=self.bounds, pgtol=1e-10)\n', (43355, 43451), False, 'from scipy.optimize import minimize, differential_evolution, fmin_l_bfgs_b\n'), ((45926, 45947), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (45937, 45947), True, 'import matplotlib.pyplot as plt\n'), ((45982, 45992), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (45990, 45992), True, 'import matplotlib.pyplot as plt\n'), ((46019, 46030), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (46028, 46030), True, 'import matplotlib.pyplot as plt\n'), ((16078, 16122), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', 'K_qx.T'], {'lower': '(True)'}), '(self.L, K_qx.T, lower=True)\n', (16094, 16122), False, 'from scipy.linalg import solve_triangular\n'), ((18455, 18489), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'I'], {'lower': '(True)'}), '(L, I, lower=True)\n', (18471, 18489), False, 'from scipy.linalg import solve_triangular\n'), ((18535, 18574), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'self.y'], {'lower': '(True)'}), '(L, self.y, lower=True)\n', (18551, 18574), False, 'from scipy.linalg import solve_triangular\n'), ((18601, 18609), 'numpy.diag', 'diag', (['iK'], {}), '(iK)\n', (18605, 18609), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((18694, 18750), 'warnings.warn', 'warn', (['"""Cholesky decomposition failure in loo_likelihood"""'], {}), "('Cholesky decomposition failure in loo_likelihood')\n", (18698, 18750), False, 'from warnings import warn\n'), ((19777, 19787), 'numpy.exp', 'exp', (['theta'], {}), '(theta)\n', (19780, 19787), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((20217, 20256), 'scipy.linalg.solve_triangular', 'solve_triangular', (['L', 'self.y'], {'lower': '(True)'}), '(L, self.y, lower=True)\n', (20233, 20256), False, 'from scipy.linalg import solve_triangular\n'), ((20360, 20421), 'warnings.warn', 'warn', (['"""Cholesky decomposition failure in marginal_likelihood"""'], {}), "('Cholesky decomposition failure in marginal_likelihood')\n", (20364, 20421), False, 'from warnings import warn\n'), ((21024, 21044), 'numpy.dot', 'dot', (['self.y.T', 'alpha'], {}), '(self.y.T, alpha)\n', (21027, 21044), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((21161, 21176), 'numpy.eye', 'eye', (['L.shape[0]'], {}), '(L.shape[0])\n', (21164, 21176), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((27071, 27089), 'numpy.dot', 'dot', (['S_p', 'self.G.T'], {}), '(S_p, self.G.T)\n', (27074, 27089), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27316, 27328), 'numpy.linalg.slogdet', 'slogdet', (['S_m'], {}), '(S_m)\n', (27323, 27328), False, 'from numpy.linalg import inv, slogdet, solve, cholesky\n'), ((29954, 29980), 'itertools.product', 'product', (['*guess_components'], {}), '(*guess_components)\n', (29961, 29980), False, 'from itertools import product\n'), ((30436, 30451), 'numpy.array', 'array', (['LML_list'], {}), '(LML_list)\n', (30441, 30451), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((32238, 32249), 'numpy.log', 'log', (['sig[0]'], {}), '(sig[0])\n', (32241, 32249), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((32613, 32624), 'numpy.log', 'log', (['sig[0]'], {}), '(sig[0])\n', (32616, 32624), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33069, 33080), 'numpy.log', 'log', (['sig[0]'], {}), '(sig[0])\n', (33072, 33080), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33533, 33550), 'scipy.special.erf', 'erf', (['(z * self.ir2)'], {}), '(z * self.ir2)\n', (33536, 33550), False, 'from scipy.special import erf, erfcx\n'), ((11977, 11998), 'numpy.dot', 'dot', (['K_qx', 'self.alpha'], {}), '(K_qx, self.alpha)\n', (11980, 11998), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((12103, 12116), 'numpy.sum', 'npsum', (['(v ** 2)'], {}), '(v ** 2)\n', (12108, 12116), True, 'from numpy import sum as npsum\n'), ((12156, 12167), 'numpy.array', 'array', (['errs'], {}), '(errs)\n', (12161, 12167), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((14892, 14903), 'numpy.array', 'array', (['mu_q'], {}), '(mu_q)\n', (14897, 14903), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((14915, 14926), 'numpy.array', 'array', (['vars'], {}), '(vars)\n', (14920, 14926), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((16402, 16421), 'numpy.array', 'array', (['mu_gradients'], {}), '(mu_gradients)\n', (16407, 16421), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((16433, 16453), 'numpy.array', 'array', (['var_gradients'], {}), '(var_gradients)\n', (16438, 16453), False, 'from numpy import zeros, ones, array, where, pi, diag, eye, maximum\n'), ((17233, 17277), 'scipy.linalg.solve_triangular', 'solve_triangular', (['self.L', 'K_qx.T'], {'lower': '(True)'}), '(self.L, K_qx.T, lower=True)\n', (17249, 17277), False, 'from scipy.linalg import solve_triangular\n'), ((20284, 20304), 'numpy.dot', 'dot', (['self.y.T', 'alpha'], {}), '(self.y.T, alpha)\n', (20287, 20304), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((25818, 25863), 'numpy.dot', 'dot', (['self.iS_y', '(self.y - self.mu_val * self.f)'], {}), '(self.iS_y, self.y - self.mu_val * self.f)\n', (25821, 25863), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((27726, 27764), 'numpy.dot', 'dot', (['self.iS_y', '(self.y - mu_p * self.f)'], {}), '(self.iS_y, self.y - mu_p * self.f)\n', (27729, 27764), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((28694, 28700), 'numpy.log', 'log', (['x'], {}), '(x)\n', (28697, 28700), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((33043, 33049), 'numpy.log', 'log', (['H'], {}), '(H)\n', (33046, 33049), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((34308, 34316), 'copy.copy', 'copy', (['y1'], {}), '(y1)\n', (34312, 34316), False, 'from copy import copy\n'), ((19536, 19544), 'numpy.log', 'log', (['var'], {}), '(var)\n', (19539, 19544), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((21053, 21064), 'numpy.diagonal', 'diagonal', (['L'], {}), '(L)\n', (21061, 21064), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((18650, 18658), 'numpy.log', 'log', (['var'], {}), '(var)\n', (18653, 18658), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((20313, 20324), 'numpy.diagonal', 'diagonal', (['L'], {}), '(L)\n', (20321, 20324), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((2368, 2384), 'numpy.abs', 'abs', (['dx[:, :, i]'], {}), '(dx[:, :, i])\n', (2371, 2384), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((5623, 5639), 'numpy.abs', 'abs', (['dx[:, :, i]'], {}), '(dx[:, :, i])\n', (5626, 5639), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n'), ((34038, 34045), 'numpy.abs', 'abs', (['g0'], {}), '(g0)\n', (34041, 34045), False, 'from numpy import abs, exp, log, dot, sqrt, argmin, diagonal, ndarray, arange\n')] |
# coding:utf-8
'''
Created on 2017/12/19
@author: sunyihuan
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.model_selection import train_test_split
import scipy.io as scio
def one_hot(y, classes):
# m, _ = y.reshape(-1, 1).shape
return np.eye(classes)[y]
def get_center_loss(features, labels, alpha, num_classes):
"""获取center loss及center的更新op
features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length].
labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size].
alpha: 0-1之间的数字,控制样本类别中心的学习率,细节参考原文.
num_classes: 整数,表明总共有多少个类别,网络分类输出有多少个神经元这里就取多少.
Return:
loss: Tensor,可与softmax loss相加作为总的loss进行优化.
centers_update_op: op,用于更新样本中心的op,在训练时需要同时运行该op,否则样本中心不会更新
"""
# 获取特征的维数,例如256维
len_features = features.get_shape()[1]
# 建立一个Variable,shape为[num_classes, len_features],用于存储整个网络的样本中心,
# 设置trainable=False是因为样本中心不是由梯度进行更新的
centers = tf.get_variable('centers', [num_classes, len_features], dtype=tf.float32,
initializer=tf.constant_initializer(0), trainable=False)
# 将label展开为一维的,输入如果已经是一维的,则该动作其实无必要
labels = tf.reshape(labels, [-1])
# 根据样本label,获取mini-batch中每一个样本对应的中心值
centers_batch = tf.gather(centers, labels)
# 计算loss
loss = tf.div(tf.nn.l2_loss(features - centers_batch), int(len_features))
# 当前mini-batch的特征值与它们对应的中心值之间的差
diff = centers_batch - features
# 获取mini-batch中同一类别样本出现的次数,了解原理请参考原文公式(4)
unique_label, unique_idx, unique_count = tf.unique_with_counts(labels)
appear_times = tf.gather(unique_count, unique_idx)
appear_times = tf.reshape(appear_times, [-1, 1])
diff = diff / tf.cast((1 + appear_times), tf.float32)
diff = alpha * diff
centers_update_op = tf.scatter_sub(centers, labels, diff)
return loss, centers_update_op
def model(lr=0.01, epoches=200, minibatch_size=64, drop_prob=.2):
X = tf.placeholder(tf.float32, shape=[None, 96, 96])
XX = tf.reshape(X, shape=[-1, 96, 96, 1])
Y = tf.placeholder(tf.int32, shape=[None, ])
YY = tf.one_hot(Y, 3755, on_value=1, off_value=None, axis=1)
dp = tf.placeholder(tf.float32)
global_step = tf.Variable(0, trainable=False)
reg1 = tf.contrib.layers.l2_regularizer(scale=0.1)
conv1 = tf.layers.conv2d(XX, 32, 5, padding='same', activation=tf.nn.relu, kernel_regularizer=reg1)
conv1 = tf.layers.max_pooling2d(conv1, 2, 2, padding='same')
conv2 = tf.layers.conv2d(conv1, 64, 3, padding='same', activation=tf.nn.relu)
conv2 = tf.layers.max_pooling2d(conv2, 2, 2, padding='same')
# conv3 = tf.layers.conv2d(conv2, 128, 3, padding='same', activation=tf.nn.relu)
# conv3 = tf.layers.average_pooling2d(conv3, 2, 2, padding='same')
# convZ = tf.layers.flatten(pool3)
convZ = tf.contrib.layers.flatten(conv2)
fc1 = tf.layers.dense(convZ, 256, activation=tf.nn.relu)
# fc1 = tf.layers.batch_normalization(fc1)
# fc1 = tf.layers.dropout(fc1, rate=dp, training=True)
#
fc2 = tf.layers.dense(fc1, 512, activation=tf.nn.relu)
# fc2 = tf.layers.batch_normalization(fc2)
# fc2 = tf.layers.dropout(fc2, rate=dp, training=True)
# fc3 = tf.layers.dense(fc2, 2, activation=None, name='fc3')
# fc3_out = tf.nn.relu(fc3)
# fc3 = tf.layers.batch_normalization(fc3)
# fc3 = tf.layers.dropout(fc3, rate=dp, training=True)
ZL = tf.layers.dense(fc2, 3755, activation=None)
# loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=ZL, labels=Y))
learning_rate = tf.train.exponential_decay(lr,
global_step=global_step,
decay_steps=10, decay_rate=0.9)
learning_rate = tf.maximum(learning_rate, .001)
# with tf.variable_scope('loss_scope'):
# centerloss, centers_update_op = get_center_loss(fc2, Y, 0.5, 10)
# # self.loss = tf.losses.softmax_cross_entropy(onehot_labels=util.makeonehot(self.y, self.CLASSNUM), logits=self.score)
# # lambda则0.1-0.0001之间不等
loss = tf.losses.sparse_softmax_cross_entropy(labels=Y, logits=ZL)
# with tf.control_dependencies([]):
# train_op = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(loss)
# train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
train_op = tf.train.AdamOptimizer(learning_rate).minimize(loss)
predict_op = tf.argmax(ZL, 1, name='predict')
correct_prediction = tf.equal(predict_op, tf.argmax(YY, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
add_global = global_step.assign_add(1)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for epoch in range(epoches):
image_batch_now, label_batch_now = sess.run([img, label])
__, _loss, _ = sess.run([add_global, loss, train_op],
feed_dict={X: image_batch_now, Y: label_batch_now, dp: drop_prob})
print(_loss)
coord.request_stop()
coord.join(threads)
print(1)
# if epoch % 5 == 0:
# train_accuracy = accuracy.eval({X: trX[:2000], Y: trY[:2000], dp: 0.0})
# test_accuracy = accuracy.eval({X: teX[:2000], Y: teY[:2000], dp: 0.0})
# print("Cost after epoch %i: %f tr-acc: %f te-acc: %f" % (epoch, _loss, train_accuracy, test_accuracy))
# train_accuracy = accuracy.eval({X: trX[:2000], Y: trY[:2000], dp: 0.0})
# test_accuracy = accuracy.eval({X: teX[:2000], Y: teY[:2000], dp: 0.0})
#
# # 修改网络倒数层为2,然后输出特征
# # _fc3 = fc3.eval({X: teX[:2000], Y: teY[:2000], dp: 0.0})
# # plt.scatter(_fc3[:, 0], _fc3[:, 1], c=teY[:2000])
# # plt.show()
# print("Train Accuracy:", train_accuracy)
# print("Test Accuracy:", test_accuracy)
# saver.save(sess, "save/model.ckpt")
def read(path):
batch_size = 64
image_size = 96
filename_queue = tf.train.string_input_producer([path], shuffle=True)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
img_features = tf.parse_single_example(
serialized_example,
features={
'label': tf.FixedLenFeature([], tf.int64),
'image_raw': tf.FixedLenFeature([], tf.string),
})
image = tf.decode_raw(img_features['image_raw'], tf.float32)
min_after_dequeue = 10000
image = tf.reshape(image, [image_size, image_size])
label = tf.cast(img_features['label'], tf.int32)
capacity = min_after_dequeue + 3 * batch_size
image_batch, label_batch = tf.train.shuffle_batch([image, label],
batch_size=batch_size,
num_threads=3,
capacity=capacity,
# allow_smaller_final_batch=True,
min_after_dequeue=min_after_dequeue
)
return image_batch, label_batch
tfrecord_file = 'F:/dataSets/CASIA/HWDB1/train.tfrecord'
img, label = read(tfrecord_file)
model()
| [
"tensorflow.train.Coordinator",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.train.shuffle_batch",
"tensorflow.contrib.layers.flatten",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.constant_initializer",
"tensorflow.decode_raw",
"tensorflow.Variable",
"tensorflow.layers.max_p... | [((1212, 1236), 'tensorflow.reshape', 'tf.reshape', (['labels', '[-1]'], {}), '(labels, [-1])\n', (1222, 1236), True, 'import tensorflow as tf\n'), ((1299, 1325), 'tensorflow.gather', 'tf.gather', (['centers', 'labels'], {}), '(centers, labels)\n', (1308, 1325), True, 'import tensorflow as tf\n'), ((1580, 1609), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['labels'], {}), '(labels)\n', (1601, 1609), True, 'import tensorflow as tf\n'), ((1629, 1664), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (1638, 1664), True, 'import tensorflow as tf\n'), ((1684, 1717), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (1694, 1717), True, 'import tensorflow as tf\n'), ((1826, 1863), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['centers', 'labels', 'diff'], {}), '(centers, labels, diff)\n', (1840, 1863), True, 'import tensorflow as tf\n'), ((1975, 2023), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 96, 96]'}), '(tf.float32, shape=[None, 96, 96])\n', (1989, 2023), True, 'import tensorflow as tf\n'), ((2033, 2069), 'tensorflow.reshape', 'tf.reshape', (['X'], {'shape': '[-1, 96, 96, 1]'}), '(X, shape=[-1, 96, 96, 1])\n', (2043, 2069), True, 'import tensorflow as tf\n'), ((2078, 2116), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), '(tf.int32, shape=[None])\n', (2092, 2116), True, 'import tensorflow as tf\n'), ((2128, 2183), 'tensorflow.one_hot', 'tf.one_hot', (['Y', '(3755)'], {'on_value': '(1)', 'off_value': 'None', 'axis': '(1)'}), '(Y, 3755, on_value=1, off_value=None, axis=1)\n', (2138, 2183), True, 'import tensorflow as tf\n'), ((2194, 2220), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (2208, 2220), True, 'import tensorflow as tf\n'), ((2239, 2270), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (2250, 2270), True, 'import tensorflow as tf\n'), ((2283, 2326), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', ([], {'scale': '(0.1)'}), '(scale=0.1)\n', (2315, 2326), True, 'import tensorflow as tf\n'), ((2339, 2434), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['XX', '(32)', '(5)'], {'padding': '"""same"""', 'activation': 'tf.nn.relu', 'kernel_regularizer': 'reg1'}), "(XX, 32, 5, padding='same', activation=tf.nn.relu,\n kernel_regularizer=reg1)\n", (2355, 2434), True, 'import tensorflow as tf\n'), ((2443, 2495), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['conv1', '(2)', '(2)'], {'padding': '"""same"""'}), "(conv1, 2, 2, padding='same')\n", (2466, 2495), True, 'import tensorflow as tf\n'), ((2509, 2578), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['conv1', '(64)', '(3)'], {'padding': '"""same"""', 'activation': 'tf.nn.relu'}), "(conv1, 64, 3, padding='same', activation=tf.nn.relu)\n", (2525, 2578), True, 'import tensorflow as tf\n'), ((2591, 2643), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['conv2', '(2)', '(2)'], {'padding': '"""same"""'}), "(conv2, 2, 2, padding='same')\n", (2614, 2643), True, 'import tensorflow as tf\n'), ((2853, 2885), 'tensorflow.contrib.layers.flatten', 'tf.contrib.layers.flatten', (['conv2'], {}), '(conv2)\n', (2878, 2885), True, 'import tensorflow as tf\n'), ((2897, 2947), 'tensorflow.layers.dense', 'tf.layers.dense', (['convZ', '(256)'], {'activation': 'tf.nn.relu'}), '(convZ, 256, activation=tf.nn.relu)\n', (2912, 2947), True, 'import tensorflow as tf\n'), ((3070, 3118), 'tensorflow.layers.dense', 'tf.layers.dense', (['fc1', '(512)'], {'activation': 'tf.nn.relu'}), '(fc1, 512, activation=tf.nn.relu)\n', (3085, 3118), True, 'import tensorflow as tf\n'), ((3439, 3482), 'tensorflow.layers.dense', 'tf.layers.dense', (['fc2', '(3755)'], {'activation': 'None'}), '(fc2, 3755, activation=None)\n', (3454, 3482), True, 'import tensorflow as tf\n'), ((3595, 3686), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['lr'], {'global_step': 'global_step', 'decay_steps': '(10)', 'decay_rate': '(0.9)'}), '(lr, global_step=global_step, decay_steps=10,\n decay_rate=0.9)\n', (3621, 3686), True, 'import tensorflow as tf\n'), ((3797, 3829), 'tensorflow.maximum', 'tf.maximum', (['learning_rate', '(0.001)'], {}), '(learning_rate, 0.001)\n', (3807, 3829), True, 'import tensorflow as tf\n'), ((4123, 4182), 'tensorflow.losses.sparse_softmax_cross_entropy', 'tf.losses.sparse_softmax_cross_entropy', ([], {'labels': 'Y', 'logits': 'ZL'}), '(labels=Y, logits=ZL)\n', (4161, 4182), True, 'import tensorflow as tf\n'), ((4493, 4525), 'tensorflow.argmax', 'tf.argmax', (['ZL', '(1)'], {'name': '"""predict"""'}), "(ZL, 1, name='predict')\n", (4502, 4525), True, 'import tensorflow as tf\n'), ((4717, 4750), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4748, 4750), True, 'import tensorflow as tf\n'), ((4763, 4779), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4777, 4779), True, 'import tensorflow as tf\n'), ((6175, 6227), 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['[path]'], {'shuffle': '(True)'}), '([path], shuffle=True)\n', (6205, 6227), True, 'import tensorflow as tf\n'), ((6241, 6260), 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), '()\n', (6258, 6260), True, 'import tensorflow as tf\n'), ((6546, 6598), 'tensorflow.decode_raw', 'tf.decode_raw', (["img_features['image_raw']", 'tf.float32'], {}), "(img_features['image_raw'], tf.float32)\n", (6559, 6598), True, 'import tensorflow as tf\n'), ((6642, 6685), 'tensorflow.reshape', 'tf.reshape', (['image', '[image_size, image_size]'], {}), '(image, [image_size, image_size])\n', (6652, 6685), True, 'import tensorflow as tf\n'), ((6698, 6738), 'tensorflow.cast', 'tf.cast', (["img_features['label']", 'tf.int32'], {}), "(img_features['label'], tf.int32)\n", (6705, 6738), True, 'import tensorflow as tf\n'), ((6820, 6956), 'tensorflow.train.shuffle_batch', 'tf.train.shuffle_batch', (['[image, label]'], {'batch_size': 'batch_size', 'num_threads': '(3)', 'capacity': 'capacity', 'min_after_dequeue': 'min_after_dequeue'}), '([image, label], batch_size=batch_size, num_threads=3,\n capacity=capacity, min_after_dequeue=min_after_dequeue)\n', (6842, 6956), True, 'import tensorflow as tf\n'), ((311, 326), 'numpy.eye', 'np.eye', (['classes'], {}), '(classes)\n', (317, 326), True, 'import numpy as np\n'), ((1357, 1396), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(features - centers_batch)'], {}), '(features - centers_batch)\n', (1370, 1396), True, 'import tensorflow as tf\n'), ((1737, 1774), 'tensorflow.cast', 'tf.cast', (['(1 + appear_times)', 'tf.float32'], {}), '(1 + appear_times, tf.float32)\n', (1744, 1774), True, 'import tensorflow as tf\n'), ((4573, 4589), 'tensorflow.argmax', 'tf.argmax', (['YY', '(1)'], {}), '(YY, 1)\n', (4582, 4589), True, 'import tensorflow as tf\n'), ((4621, 4660), 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), '(correct_prediction, tf.float32)\n', (4628, 4660), True, 'import tensorflow as tf\n'), ((4789, 4801), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (4799, 4801), True, 'import tensorflow as tf\n'), ((4850, 4872), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (4870, 4872), True, 'import tensorflow as tf\n'), ((4891, 4943), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'sess': 'sess', 'coord': 'coord'}), '(sess=sess, coord=coord)\n', (4919, 4943), True, 'import tensorflow as tf\n'), ((1114, 1140), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), '(0)\n', (1137, 1140), True, 'import tensorflow as tf\n'), ((4423, 4460), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), '(learning_rate)\n', (4445, 4460), True, 'import tensorflow as tf\n'), ((6429, 6461), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (6447, 6461), True, 'import tensorflow as tf\n'), ((6488, 6521), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (6506, 6521), True, 'import tensorflow as tf\n')] |
import os
import numpy as np
import sympy
from matplotlib import pyplot as plt
import scipy
from datastorage import DataStorage as ds
import datastorage
from .. import undulator
#from .abcd import
from .optics import hard_aperture
from .optics import lens
from .useful_beams import id18h
from ..crl import LensBlock, Transfocator
transfocator = Transfocator([LensBlock(2 ** i, radius=500e-6) for i in range(8)])
def size_at_dist(beam, f, dist):
# print(f"{f:12.2f}", end="\r")
op = lens(f)
b = beam.apply(op)
b = b.propagate(dist)
return float(b.rms_size * 2.35)
def find_fl_to_focus(beam, dist, verbose=True):
def tominimize(f):
if f<0.001: f=0.001
return abs(1/beam.lens(f).propagate(dist).radius)
x0 = find_fl_to_get_size(beam, dist, 0, verbose=verbose)
bracket = x0-1,x0
res = scipy.optimize.minimize_scalar(
tominimize, bracket=bracket, method="golden", tol=1e-3,options=dict(maxiter=30)
)
if verbose:
print(
f"find f to focus@dist: found FL of {res.x:.3f}m after {res.nit} iterations"
)
return res.x
def find_fl_to_get_size(beam, dist, size, verbose=True, retry=False):
def tominimize(f):
return abs(size_at_dist(beam, f, dist) - size)
if beam.radius > 0:
bracket = float(beam.radius * 0.9), float(beam.radius * 1.1)
else:
bracket = (35, 45)
res = scipy.optimize.minimize_scalar(
tominimize, bracket=bracket, method="golden", tol=1e-3, options=dict(maxiter=30)
)
size_with_best_fl = size_at_dist(beam, res.x, dist)
size_without_optics = float(beam.propagate(dist).rms_size * 2.35)
if abs(size_without_optics - size) < abs(size_with_best_fl - size):
fl = np.inf
if verbose:
print(f"Looked for best FL, found best match without optics")
else:
fl = res.x
if verbose:
print(
f"size@dist: found FL of {res.x:.1f}m after {res.nit} iteration, asked for {size*1e6:.1f}μm, got {size_at_dist(beam, res.x, dist)*1e6:.1f}μm"
)
return fl
F = np.arange(5, 50.5, 0.5)
s = [size_at_dist(beam, f, dist) for f in F]
s = np.asarray(s)
idx = np.argmin(np.abs(s - size))
if verbose:
for fi, si in zip(F, s):
print(f"{fi:.1f} {abs(si-size)*1e6:.0f}")
print(
f"Will be using focus length of {F[idx]:.1f}; it gives a size of {s[idx]*1e6:.0f} um (objective was {size*1e6:.0f}"
)
return F[idx]
def find_fl(beam, dist, verbose=True):
return find_fl_to_get_size(beam, dist, 0, verbose=verbose)
def propagate(
beam=id18h,
optics=[[40, "x1", "coll"], [150, "x1", "focus@200"]],
z=np.arange(0, 230, 0.5),
use_transfocator=True,
transfocator=transfocator,
fixed_f = None,
fname=None,
force=False,
):
"""
beam is a GSM or a GSM_Numeric beam
optics = [
[ pos1, aperture1, coll|flat|focus@dist|sizeUM@dist,None ],
[ pos2, aperture2, coll|flat|focus@dist|sizeUM@dism,None ],
[ .................................... ],
]
sizeUM@dist means that FL to get as close as possible to UM um at a certain
distance will be calculated (and used)
if optics element starts with 'crl_', a CRL lens set will be used.
The use of lenses can be 'forced' using use_transfocator=True
transfocator is either an istance of crl.Transfocator or a dictionary of
transfocator instances (key is the distance from source)
fixed_f is to take into account constrains in one direction (e.g. h)
imposed by having fixed focal length or lenses in v direction
It should be a dictionary of focal length or CRL lenset (key is distance)
aperture can be an:
- absolute value, "x1.2" is 1.2 times the FWHM CL, coherence length, None
"""
print("WARNING: hard apertures are implemented as shown in Vartanyans 2013 JSR paper")
print(" They are an approximations (valid in the far field?)")
if not force and fname is not None and os.path.isfile(fname):
data = datastorage.read(fname)
return data
info = ds()
energy = 12.398 / (beam.wavelen * 1e10)
positions = [0]
apertures = [None]
focal_lengths = [None]
desired_focal_lengths = [None]
lenses = [None]
beams_before_aperture_before_optics = [beam]
beams_after_aperture_before_optics = [beam]
beams_after_aperture_after_optics = [beam]
log = ["source"]
for i, o in enumerate(optics, start=1):
_log = []
_log.append(f"Working on optics element {i}")
_pos, _aperture, _element = o
if isinstance(_element, (int, float)):
fl = _element
_element = "" # to make if statements below happy
_log.append(f"Explicitly asked to use {fl:.3f} focal_length")
if _element is not None and _element.startswith("crl_"):
_use_transfocator = True
_element = _element[:4]
_log.append(
"Will use CRL for this element because element name starts with crl_"
)
else:
_use_transfocator = False
_use_transfocator = _use_transfocator or use_transfocator
positions.append(_pos)
dpos = _pos - positions[i - 1]
# babo = before aperture, before optics
babo = beams_after_aperture_after_optics[-1].propagate(dpos)
### WORK ON APERTURE ###
# aabo = after aperture, before optics
if _aperture is None:
aabo = babo
apertures.append(None)
_log.append("no aperture for this element")
else:
if isinstance(_aperture, str):
# "x1.2"
aperture_as_fraction_of_cl = float(_aperture[1:])
_aperture = aperture_as_fraction_of_cl * babo.rms_cl * 2.35
_log.append(
f"aperture defined as {aperture_as_fraction_of_cl:.2f} of FWHM CL {babo.rms_cl * 2.35:.2e} m"
)
_log.append(f"aperture of {_aperture:.2e} m")
apertures.append(_aperture)
_aperture = hard_aperture(_aperture)
aabo = babo.apply(_aperture)
### WORK ON FOCUSING OPTICS ###
# aaao = after aperture, after optics
if _element is None:
aaao = aabo
focal_lengths.append(None)
desired_focal_lengths.append(None)
lenses.append(None)
_log.append(f"No focusing optics for this element")
else:
if fixed_f is not None and _pos in fixed_f:
c = fixed_f[_pos]
_log.append("Adding constrain from other direction:"+str(c))
if isinstance(c,(float,int)):
c = lens(c)
aabo = aabo.apply(c)
if _element[:4].lower() == "coll":
fl = aabo.radius
_log.append(
f"Asked for collimating, will try to use focal length = radius of curvature {fl:.3e} m"
)
if _element[:5].lower() == "focus":
where_to_focus = float(_element.split("@")[1])
dist_to_focus = where_to_focus - _pos
_log.append(
f"Asked for focusing at {where_to_focus:.3f} m from source (meaning {dist_to_focus:.3f} m from optical element)"
)
fl = find_fl(aabo, dist_to_focus)
_log.append(f"Found the FL needed: {fl:.3f} m")
if _element[:4].lower() == "size":
size, where = _element[4:].split("@")
size = float(size) * 1e-6
dist = float(where) - _pos
_log.append(
f"Asked for imaging beam to a size of {size:.3e} m at a distance of {float(where):.3f} m (meaning {float(dist):.3f} m from optical element)"
)
fl = find_fl_to_get_size(aabo, dist, size)
_log.append(f"Found the FL needed: {fl:.3f} m")
desired_focal_lengths.append(fl)
if _use_transfocator:
_log.append(
f"Using transfocator, finding best combination for FL {fl:.3f} m"
)
if not isinstance(transfocator,Transfocator):
_transfocator = transfocator[_pos]
else:
_transfocator = transfocator
ret_transf = _transfocator.find_best_set_for_focal_length(
energy=energy, focal_length=fl,
accuracy_needed=min(fl / 1000, 0.1),
beam_fwhm=None,
)
fl = ret_transf.focal_length
_log.append(f"Using transfocator, found set with FL of {fl:.2f} m")
_log.append(
f"Using transfocator, using set {str(ret_transf.best_lens_set)}"
)
fl_obj = ret_transf.best_lens_set
_log.append(fl_obj)
lenses.append(fl_obj)
else:
lenses.append(fl)
fl_obj = lens(fl)
focal_lengths.append(fl)
if fl == np.inf:
aaao = aabo
else:
aaao = aabo.apply(fl_obj)
beams_before_aperture_before_optics.append(babo)
beams_after_aperture_before_optics.append(aabo)
beams_after_aperture_after_optics.append(aaao)
log.append(_log)
print("\n".join([l for l in _log if isinstance(l, str)]))
positions = np.asarray(positions)
info = ds(
log=log,
inputs=optics,
optics_positions=positions,
apertures=apertures,
focal_lengths=focal_lengths,
desired_focal_lengths=desired_focal_lengths,
beams_before_aperture_before_optics=beams_before_aperture_before_optics,
beams_after_aperture_before_optics=beams_after_aperture_before_optics,
beams_after_aperture_after_optics=beams_after_aperture_after_optics,
lenses=lenses
)
size = np.zeros_like(z)
cl = np.zeros_like(z)
gdc = np.zeros_like(z)
radius = np.zeros_like(z)
for i, zi in enumerate(z):
print(f"calculating {i}/{len(z)}", end="\r")
# calc which beam to use
div = np.floor_divide(positions, zi)
temp_idx = np.ravel(np.argwhere(div == 0))
if len(temp_idx) == 0:
idx = 0
else:
idx = temp_idx[-1]
beam = beams_after_aperture_after_optics[idx]
dpos = zi - positions[idx]
b = beam.propagate(dpos)
size[i] = b.rms_size * 2.35 * 1e6
cl[i] = b.rms_cl * 2.35 * 1e6
gdc[i] = b.global_degree_of_coherence
radius[i] = b.radius
divergence = np.gradient(size, z)
ret = ds(
z=z,
divergence=divergence,
fwhm_size=size,
fwhm_cl=cl,
global_degree_of_coherence=gdc,
radius=radius,
info=info,
)
if fname is not None:
ret.save(fname)
return ret
| [
"numpy.zeros_like",
"numpy.abs",
"numpy.floor_divide",
"numpy.asarray",
"datastorage.read",
"os.path.isfile",
"numpy.arange",
"numpy.argwhere",
"datastorage.DataStorage",
"numpy.gradient"
] | [((2103, 2126), 'numpy.arange', 'np.arange', (['(5)', '(50.5)', '(0.5)'], {}), '(5, 50.5, 0.5)\n', (2112, 2126), True, 'import numpy as np\n'), ((2184, 2197), 'numpy.asarray', 'np.asarray', (['s'], {}), '(s)\n', (2194, 2197), True, 'import numpy as np\n'), ((2712, 2734), 'numpy.arange', 'np.arange', (['(0)', '(230)', '(0.5)'], {}), '(0, 230, 0.5)\n', (2721, 2734), True, 'import numpy as np\n'), ((4154, 4158), 'datastorage.DataStorage', 'ds', ([], {}), '()\n', (4156, 4158), True, 'from datastorage import DataStorage as ds\n'), ((9600, 9621), 'numpy.asarray', 'np.asarray', (['positions'], {}), '(positions)\n', (9610, 9621), True, 'import numpy as np\n'), ((9633, 10034), 'datastorage.DataStorage', 'ds', ([], {'log': 'log', 'inputs': 'optics', 'optics_positions': 'positions', 'apertures': 'apertures', 'focal_lengths': 'focal_lengths', 'desired_focal_lengths': 'desired_focal_lengths', 'beams_before_aperture_before_optics': 'beams_before_aperture_before_optics', 'beams_after_aperture_before_optics': 'beams_after_aperture_before_optics', 'beams_after_aperture_after_optics': 'beams_after_aperture_after_optics', 'lenses': 'lenses'}), '(log=log, inputs=optics, optics_positions=positions, apertures=apertures,\n focal_lengths=focal_lengths, desired_focal_lengths=\n desired_focal_lengths, beams_before_aperture_before_optics=\n beams_before_aperture_before_optics, beams_after_aperture_before_optics\n =beams_after_aperture_before_optics, beams_after_aperture_after_optics=\n beams_after_aperture_after_optics, lenses=lenses)\n', (9635, 10034), True, 'from datastorage import DataStorage as ds\n'), ((10109, 10125), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (10122, 10125), True, 'import numpy as np\n'), ((10135, 10151), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (10148, 10151), True, 'import numpy as np\n'), ((10162, 10178), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (10175, 10178), True, 'import numpy as np\n'), ((10192, 10208), 'numpy.zeros_like', 'np.zeros_like', (['z'], {}), '(z)\n', (10205, 10208), True, 'import numpy as np\n'), ((10813, 10833), 'numpy.gradient', 'np.gradient', (['size', 'z'], {}), '(size, z)\n', (10824, 10833), True, 'import numpy as np\n'), ((10844, 10964), 'datastorage.DataStorage', 'ds', ([], {'z': 'z', 'divergence': 'divergence', 'fwhm_size': 'size', 'fwhm_cl': 'cl', 'global_degree_of_coherence': 'gdc', 'radius': 'radius', 'info': 'info'}), '(z=z, divergence=divergence, fwhm_size=size, fwhm_cl=cl,\n global_degree_of_coherence=gdc, radius=radius, info=info)\n', (10846, 10964), True, 'from datastorage import DataStorage as ds\n'), ((2218, 2234), 'numpy.abs', 'np.abs', (['(s - size)'], {}), '(s - size)\n', (2224, 2234), True, 'import numpy as np\n'), ((4060, 4081), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (4074, 4081), False, 'import os\n'), ((4098, 4121), 'datastorage.read', 'datastorage.read', (['fname'], {}), '(fname)\n', (4114, 4121), False, 'import datastorage\n'), ((10341, 10371), 'numpy.floor_divide', 'np.floor_divide', (['positions', 'zi'], {}), '(positions, zi)\n', (10356, 10371), True, 'import numpy as np\n'), ((10400, 10421), 'numpy.argwhere', 'np.argwhere', (['(div == 0)'], {}), '(div == 0)\n', (10411, 10421), True, 'import numpy as np\n')] |
#T# relational operators are used to do relational operations, i.e. operations in which there is testing of the values of numbers, by comparing them against each other
#T# the equality == operator compares if two numbers are equal
a = 5; b = 3
bool1 = a == b # False
a = 4; b = 4
bool1 = a == b # True
#T# the not equal != operator compares if two number are not equal
a = 5; b = 3
bool1 = a != b # True
a = 4; b = 4
bool1 = a != b # False
#T# the greater than > operator compares if the first number is greater than the second
a = 5; b = 3
bool1 = a > b # True
a = 4; b = 4
bool1 = a > b # False
#T# the less than < operator compares if the first number is less than the second
a = 3; b = 5
bool1 = a < b # True
a = 4; b = 4
bool1 = a < b # False
#T# the greater than or equal to >= operator compares if the first number is greater than or equal to the second
a = 5; b = 3
bool1 = a >= b # True
a = 4; b = 4
bool1 = a >= b # True
a = 3; b = 5
bool1 = a >= b # False
#T# the less than or equal to <= operator compares if the first number is less than or equal to the second
a = 3; b = 5
bool1 = a <= b # True
a = 4; b = 4
bool1 = a <= b # True
a = 5; b = 3
bool1 = a <= b # False
#T# to do relational operations with lists or arrays element-wise, the numpy package is used
import numpy as np
#T# the array_equal function from the numpy package, compares if two arrays are equal, with the same shape and the same elements
arr1 = np.array([[6, 9, 4, 4], [8, 1, 9, 10]])
arr2 = np.array([[6, 9, 4, 4], [8, 1, 9, 10]])
bool1 = np.array_equal(arr1, arr2) # True
#T# the equal function from the numpy package, compares if two arrays are equal element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.equal(arr1, arr2)
# array([[False, False, True, False], [False, False, False, True]])
#T# the equality operator == can be used to compare if two numpy arrays are equal element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 == arr2
# array([[False, False, True, False], [False, False, False, True]])
#T# the not_equal function from the numpy package, compares if two arrays are not equal element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.not_equal(arr1, arr2)
# array([[ True, True, False, True], [ True, True, True, False]])
#T# the not equal != operator can be used to compare if two numpy arrays are not equal element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 != arr2
# array([[ True, True, False, True], [ True, True, True, False]])
#T# the greater function from the numpy package, compares if the first array is greater than the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.greater(arr1, arr2)
# array([[False, True, False, False], [ True, False, True, False]])
#T# the greater than > operator can be used to compare if the first numpy array is greater than the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 > arr2
# array([[False, True, False, False], [ True, False, True, False]])
#T# the less function from the numpy package, compares if the first array is less than the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.less(arr1, arr2)
# array([[ True, False, False, True], [False, True, False, False]])
#T# the less than < operator can be used to compare if the first numpy array is less than the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 < arr2
# array([[ True, False, False, True], [False, True, False, False]])
#T# the greater_equal function from the numpy package, compares if the first array is greater than or equal to the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.greater_equal(arr1, arr2)
# array([[False, True, True, False], [ True, False, True, True]])
#T# the greater than or equal to >= operator can be used to compare if the first numpy array is greater than or equal to the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 >= arr2
# array([[False, True, True, False], [ True, False, True, True]])
#T# the less_equal function from the numpy package, compares if the first array is less than or equal to the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = np.less_equal(arr1, arr2)
# array([[ True, False, True, True], [False, True, False, True]])
#T# the less than or equal to <= operator can be used to compare if the first numpy array is less than or equal to the second element-wise, it supports array broadcasting
arr1 = np.array([[6, 9, 4, 4], [8, 1, 10, 8]])
arr2 = np.array([7, 3, 4, 8])
arr3 = arr1 <= arr2
# array([[ True, False, True, True], [False, True, False, True]]) | [
"numpy.less_equal",
"numpy.less",
"numpy.greater",
"numpy.not_equal",
"numpy.equal",
"numpy.array",
"numpy.array_equal",
"numpy.greater_equal"
] | [((1436, 1475), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 9, 10]]'], {}), '([[6, 9, 4, 4], [8, 1, 9, 10]])\n', (1444, 1475), True, 'import numpy as np\n'), ((1483, 1522), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 9, 10]]'], {}), '([[6, 9, 4, 4], [8, 1, 9, 10]])\n', (1491, 1522), True, 'import numpy as np\n'), ((1531, 1557), 'numpy.array_equal', 'np.array_equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (1545, 1557), True, 'import numpy as np\n'), ((1698, 1737), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (1706, 1737), True, 'import numpy as np\n'), ((1745, 1767), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (1753, 1767), True, 'import numpy as np\n'), ((1775, 1795), 'numpy.equal', 'np.equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (1783, 1795), True, 'import numpy as np\n'), ((2001, 2040), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (2009, 2040), True, 'import numpy as np\n'), ((2048, 2070), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (2056, 2070), True, 'import numpy as np\n'), ((2302, 2341), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (2310, 2341), True, 'import numpy as np\n'), ((2349, 2371), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (2357, 2371), True, 'import numpy as np\n'), ((2379, 2403), 'numpy.not_equal', 'np.not_equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (2391, 2403), True, 'import numpy as np\n'), ((2614, 2653), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (2622, 2653), True, 'import numpy as np\n'), ((2661, 2683), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (2669, 2683), True, 'import numpy as np\n'), ((2931, 2970), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (2939, 2970), True, 'import numpy as np\n'), ((2978, 3000), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (2986, 3000), True, 'import numpy as np\n'), ((3008, 3030), 'numpy.greater', 'np.greater', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (3018, 3030), True, 'import numpy as np\n'), ((3261, 3300), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (3269, 3300), True, 'import numpy as np\n'), ((3308, 3330), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (3316, 3330), True, 'import numpy as np\n'), ((3571, 3610), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (3579, 3610), True, 'import numpy as np\n'), ((3618, 3640), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (3626, 3640), True, 'import numpy as np\n'), ((3648, 3667), 'numpy.less', 'np.less', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (3655, 3667), True, 'import numpy as np\n'), ((3892, 3931), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (3900, 3931), True, 'import numpy as np\n'), ((3939, 3961), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (3947, 3961), True, 'import numpy as np\n'), ((4226, 4265), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (4234, 4265), True, 'import numpy as np\n'), ((4273, 4295), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (4281, 4295), True, 'import numpy as np\n'), ((4303, 4331), 'numpy.greater_equal', 'np.greater_equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (4319, 4331), True, 'import numpy as np\n'), ((4587, 4626), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (4595, 4626), True, 'import numpy as np\n'), ((4634, 4656), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (4642, 4656), True, 'import numpy as np\n'), ((4916, 4955), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (4924, 4955), True, 'import numpy as np\n'), ((4963, 4985), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (4971, 4985), True, 'import numpy as np\n'), ((4993, 5018), 'numpy.less_equal', 'np.less_equal', (['arr1', 'arr2'], {}), '(arr1, arr2)\n', (5006, 5018), True, 'import numpy as np\n'), ((5268, 5307), 'numpy.array', 'np.array', (['[[6, 9, 4, 4], [8, 1, 10, 8]]'], {}), '([[6, 9, 4, 4], [8, 1, 10, 8]])\n', (5276, 5307), True, 'import numpy as np\n'), ((5315, 5337), 'numpy.array', 'np.array', (['[7, 3, 4, 8]'], {}), '([7, 3, 4, 8])\n', (5323, 5337), True, 'import numpy as np\n')] |
import os
import glob
import math
from functools import partial
from multiprocessing import Pool
from typing import Union, Optional, List, Tuple, Dict
import xarray as xr
import numpy as np
from tqdm import tqdm
from climart.data_wrangling.constants import INPUT_RAW_SUBDIR, DATA_CREATION_SEED
from climart.data_wrangling.data_variables import get_all_vars, input_variables_to_drop_for_exp, \
output_variables_to_drop_for_exp, EXP_TYPES, _ALL_INPUT_VARS
from climart.data_wrangling.h5_dataset_writer import ClimART_GeneralHdF5_Writer
from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, \
get_logger, compute_temperature_diff
log = get_logger(__name__)
CACHE = {}
def get_single_var_complete_xarray(input_filepaths: List[str],
variable: str,
exp_type: str = 'pristine'
) -> xr.DataArray:
var_type = 'input' if variable in _ALL_INPUT_VARS else 'output'
if var_type == 'output':
input_filepaths = [f.replace('input_raw', f'output_{exp_type.lower()}') for f in input_filepaths]
vars_to_drop = ['iseed'] + get_all_vars(var_type=var_type, exp_type='all')
if variable == 'layer_pressure':
vars_to_keep = ['shj', 'pressg']
elif variable == 'level_pressure':
vars_to_keep = ['shtj', 'pressg']
elif variable == 'layer_thickness':
vars_to_keep = ['dshj', 'pressg']
elif variable == 'temp_diff':
vars_to_keep = ['tfrow']
elif variable == 'height':
vars_to_keep = ['dz']
else:
vars_to_keep = [variable]
for var_to_keep in vars_to_keep:
vars_to_drop.remove(var_to_keep)
open_dset_kwargs = dict(
paths=input_filepaths,
preprocess=lambda d: d.stack(columns=['latitude', 'longitude']),
concat_dim='columns',
combine="nested",
data_vars=vars_to_keep,
drop_variables=vars_to_drop,
)
dset = xr.open_mfdataset(**open_dset_kwargs)[vars_to_keep]
if variable == 'layer_pressure':
dset = dset['shj'] * dset['pressg']
elif variable == 'level_pressure':
dset = dset['shtj'] * dset['pressg']
elif variable == 'layer_thickness':
dset = dset['dshj'] * dset['pressg']
elif variable == 'temp_diff':
dset = compute_temperature_diff(dset['tfrow'])
elif variable == 'height':
dset = compute_absolute_level_height(dset['dz'])
else:
dset = dset[variable]
return dset
def get_single_dataset(input_filename: str,
add_pressure: bool = True,
add_temp_diff: bool = True,
add_layer_thickness: bool = True,
add_absolute_level_height: bool = True,
add_coords: bool = True,
use_cache_for_coords: bool = True,
verbose=False, **kwargs) -> (xr.Dataset, xr.Dataset):
remove_vars_in = input_variables_to_drop_for_exp['clear_sky']
input_dset = xr.open_dataset(input_filename,
drop_variables=remove_vars_in,
chunks={"longitude": 10, "latitude": 10})
output_dsets = dict()
for exp_type in EXP_TYPES:
output_filename = input_filename.replace(INPUT_RAW_SUBDIR, f"output_{exp_type}")
remove_vars_out = output_variables_to_drop_for_exp[exp_type]
output_dset = xr.open_dataset(output_filename,
drop_variables=remove_vars_out,
chunks={"longitude": 10, "latitude": 10})
output_dsets[exp_type] = output_dset
if add_coords:
# Convert lat/lon to points on a unit sphere: https://datascience.stackexchange.com/a/13575
if use_cache_for_coords and 'x_cord' in CACHE.keys():
input_dset['x_cord'] = CACHE['x_cord']
input_dset['y_cord'] = CACHE['y_cord']
input_dset['z_cord'] = CACHE['z_cord']
else:
lat = list(input_dset.get_index('latitude'))
lon = list(input_dset.get_index('longitude'))
x_cord, y_cord, z_cord = [], [], []
for i in lat:
for j in lon:
x = math.cos(i) * math.cos(j)
y = math.cos(i) * math.sin(j)
z = math.sin(i)
x_cord.append(x)
y_cord.append(y)
z_cord.append(z)
x_cord, y_cord, z_cord = np.array(x_cord), np.array(y_cord), np.array(z_cord)
x_cord = x_cord.reshape((len(lat), len(lon)))
y_cord = y_cord.reshape((len(lat), len(lon)))
z_cord = z_cord.reshape((len(lat), len(lon)))
dim_and_coords = dict(dims=('latitude', 'longitude'),
coords={"latitude": lat, 'longitude': lon})
input_dset['x_cord'] = xr.DataArray(data=x_cord, **dim_and_coords)
input_dset['y_cord'] = xr.DataArray(data=y_cord, **dim_and_coords)
input_dset['z_cord'] = xr.DataArray(data=z_cord, **dim_and_coords)
if use_cache_for_coords:
CACHE['x_cord'] = input_dset['x_cord']
CACHE['y_cord'] = input_dset['y_cord']
CACHE['z_cord'] = input_dset['z_cord']
# Flatten spatial dimensions:
input_dset = input_dset.stack(columns=['latitude', 'longitude'])
for k, output_dset in output_dsets.items():
output_dsets[k] = output_dset.stack(columns=['latitude', 'longitude'])
if add_pressure:
# pressure is of shape #levels x (lat x lon), shtj too, and pressg of shape (lat x lon)
input_dset['layer_pressure'] = input_dset['shj'] * input_dset['pressg']
input_dset['level_pressure'] = input_dset['shtj'] * input_dset['pressg']
if add_layer_thickness:
input_dset['layer_thickness'] = input_dset['dshj'] * input_dset['pressg']
if add_temp_diff:
input_dset['temp_diff'] = compute_temperature_diff(input_dset['tfrow'])
if add_absolute_level_height:
input_dset['height'] = compute_absolute_level_height(input_dset['dz'])
if verbose:
print(input_dset)
print('---' * 25)
print(output_dsets)
print('*+*' * 40, '\n')
return input_dset, output_dsets
def get_ML_dataset(input_files, split: str = "", **kwargs) -> (xr.DataArray, Dict[str, xr.DataArray]):
print(f"{split}: there are {len(input_files)} files to be loaded")
X = None
out_dsets = dict()
for input_filepath in input_files:
X_temp, Y_temp_dict = get_single_dataset(input_filepath, **kwargs)
X = X_temp if X is None else xr.concat([X, X_temp], dim='columns')
for k, out_dset in Y_temp_dict.items():
if k not in out_dsets.keys():
out_dsets[k] = out_dset
else:
out_dsets[k] = xr.concat([out_dsets[k], out_dset], dim='columns')
return X, out_dsets
def create_ML_dataset_and_h5(
x: Tuple[int, Tuple[int, List[str]]],
):
save_dir = '/miniscratch/salva.ruhling-cachay/ECC_data/snapshots/1979-2014/hdf5'
i, (year, fnames) = x
X_year, Y_dict_year = get_ML_dataset(
input_files=fnames,
split=str(year),
add_pressure=True,
add_temp_diff=True,
add_layer_thickness=True,
add_absolute_level_height=True,
add_coords=True,
use_cache_for_coords=True
)
h5_dset = ClimART_GeneralHdF5_Writer(
input_data=X_year,
output_data=Y_dict_year,
save_name=str(year),
save_dir=save_dir
)
def create_yearly_h5_files(
raw_data_dir: str,
val_year_start: int = 2005,
test_year_start: int = 2007,
test_pinatubo: bool = True,
train_files_per_year: Union[str, int] = 'all',
val_files_per_year: Union[str, int] = 'all',
test_files_per_year: Union[str, int] = 15,
which_years: Union[str, List[int]] = 'all',
multiprocessing_cpus: Optional[int] = 0
):
""" If h5_dir is None, a directory will be automatically created."""
all_input_files = glob.glob(raw_data_dir + f'/{INPUT_RAW_SUBDIR}/**/*.nc', recursive=True)
rng = np.random.default_rng(seed=DATA_CREATION_SEED)
year_to_all_fnames = get_year_to_canam_files_dict(all_input_files)
year_to_fnames = dict()
for year, fnames in year_to_all_fnames.items():
if isinstance(which_years, list) and year not in which_years:
log.info(f"Skipping year {year} as requested by `which_years` arg.")
continue
elif test_pinatubo and 1991 <= year <= 1993:
to_add = fnames
elif 1979 <= year < val_year_start:
to_add = fnames if train_files_per_year in ['all', -1] else rng.choice(fnames, size=train_files_per_year)
elif val_year_start <= year < test_year_start:
to_add = fnames if val_files_per_year in ['all', -1] else rng.choice(fnames, size=val_files_per_year)
elif test_year_start <= year < 2015:
to_add = fnames if test_files_per_year in ['all', -1] else rng.choice(fnames, size=test_files_per_year)
else:
to_add = fnames
log.info(f'Using all snapshots for year {year} for h5 creation.')
# raise ValueError()
year_to_fnames[year] = to_add
del year_to_all_fnames
iterable_years = enumerate(year_to_fnames.items())
if multiprocessing_cpus <= 0:
log.info(f"Using a single GPU/CPU")
for x in iterable_years:
create_ML_dataset_and_h5(x)
else:
log.info(f"Using multiprocessing on {multiprocessing_cpus} CPUs")
pool = Pool(multiprocessing_cpus)
total = len(year_to_fnames.keys())
for _ in tqdm(pool.imap_unordered(
create_ML_dataset_and_h5,
iterable_years), total=total
):
pass
| [
"climart.utils.utils.get_year_to_canam_files_dict",
"climart.utils.utils.get_logger",
"climart.utils.utils.compute_absolute_level_height",
"xarray.open_dataset",
"math.sin",
"xarray.concat",
"numpy.random.default_rng",
"multiprocessing.Pool",
"climart.utils.utils.compute_temperature_diff",
"numpy.... | [((684, 704), 'climart.utils.utils.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (694, 704), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((3066, 3175), 'xarray.open_dataset', 'xr.open_dataset', (['input_filename'], {'drop_variables': 'remove_vars_in', 'chunks': "{'longitude': 10, 'latitude': 10}"}), "(input_filename, drop_variables=remove_vars_in, chunks={\n 'longitude': 10, 'latitude': 10})\n", (3081, 3175), True, 'import xarray as xr\n'), ((8189, 8261), 'glob.glob', 'glob.glob', (["(raw_data_dir + f'/{INPUT_RAW_SUBDIR}/**/*.nc')"], {'recursive': '(True)'}), "(raw_data_dir + f'/{INPUT_RAW_SUBDIR}/**/*.nc', recursive=True)\n", (8198, 8261), False, 'import glob\n'), ((8272, 8318), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'DATA_CREATION_SEED'}), '(seed=DATA_CREATION_SEED)\n', (8293, 8318), True, 'import numpy as np\n'), ((8345, 8390), 'climart.utils.utils.get_year_to_canam_files_dict', 'get_year_to_canam_files_dict', (['all_input_files'], {}), '(all_input_files)\n', (8373, 8390), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((1181, 1228), 'climart.data_wrangling.data_variables.get_all_vars', 'get_all_vars', ([], {'var_type': 'var_type', 'exp_type': '"""all"""'}), "(var_type=var_type, exp_type='all')\n", (1193, 1228), False, 'from climart.data_wrangling.data_variables import get_all_vars, input_variables_to_drop_for_exp, output_variables_to_drop_for_exp, EXP_TYPES, _ALL_INPUT_VARS\n'), ((1997, 2034), 'xarray.open_mfdataset', 'xr.open_mfdataset', ([], {}), '(**open_dset_kwargs)\n', (2014, 2034), True, 'import xarray as xr\n'), ((3474, 3585), 'xarray.open_dataset', 'xr.open_dataset', (['output_filename'], {'drop_variables': 'remove_vars_out', 'chunks': "{'longitude': 10, 'latitude': 10}"}), "(output_filename, drop_variables=remove_vars_out, chunks={\n 'longitude': 10, 'latitude': 10})\n", (3489, 3585), True, 'import xarray as xr\n'), ((6042, 6087), 'climart.utils.utils.compute_temperature_diff', 'compute_temperature_diff', (["input_dset['tfrow']"], {}), "(input_dset['tfrow'])\n", (6066, 6087), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((6153, 6200), 'climart.utils.utils.compute_absolute_level_height', 'compute_absolute_level_height', (["input_dset['dz']"], {}), "(input_dset['dz'])\n", (6182, 6200), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((9741, 9767), 'multiprocessing.Pool', 'Pool', (['multiprocessing_cpus'], {}), '(multiprocessing_cpus)\n', (9745, 9767), False, 'from multiprocessing import Pool\n'), ((4962, 5005), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'x_cord'}), '(data=x_cord, **dim_and_coords)\n', (4974, 5005), True, 'import xarray as xr\n'), ((5041, 5084), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'y_cord'}), '(data=y_cord, **dim_and_coords)\n', (5053, 5084), True, 'import xarray as xr\n'), ((5120, 5163), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'z_cord'}), '(data=z_cord, **dim_and_coords)\n', (5132, 5163), True, 'import xarray as xr\n'), ((6729, 6766), 'xarray.concat', 'xr.concat', (['[X, X_temp]'], {'dim': '"""columns"""'}), "([X, X_temp], dim='columns')\n", (6738, 6766), True, 'import xarray as xr\n'), ((4555, 4571), 'numpy.array', 'np.array', (['x_cord'], {}), '(x_cord)\n', (4563, 4571), True, 'import numpy as np\n'), ((4573, 4589), 'numpy.array', 'np.array', (['y_cord'], {}), '(y_cord)\n', (4581, 4589), True, 'import numpy as np\n'), ((4591, 4607), 'numpy.array', 'np.array', (['z_cord'], {}), '(z_cord)\n', (4599, 4607), True, 'import numpy as np\n'), ((6946, 6996), 'xarray.concat', 'xr.concat', (['[out_dsets[k], out_dset]'], {'dim': '"""columns"""'}), "([out_dsets[k], out_dset], dim='columns')\n", (6955, 6996), True, 'import xarray as xr\n'), ((2349, 2388), 'climart.utils.utils.compute_temperature_diff', 'compute_temperature_diff', (["dset['tfrow']"], {}), "(dset['tfrow'])\n", (2373, 2388), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((4395, 4406), 'math.sin', 'math.sin', (['i'], {}), '(i)\n', (4403, 4406), False, 'import math\n'), ((2435, 2476), 'climart.utils.utils.compute_absolute_level_height', 'compute_absolute_level_height', (["dset['dz']"], {}), "(dset['dz'])\n", (2464, 2476), False, 'from climart.utils.utils import compute_absolute_level_height, get_year_to_canam_files_dict, get_logger, compute_temperature_diff\n'), ((4295, 4306), 'math.cos', 'math.cos', (['i'], {}), '(i)\n', (4303, 4306), False, 'import math\n'), ((4309, 4320), 'math.cos', 'math.cos', (['j'], {}), '(j)\n', (4317, 4320), False, 'import math\n'), ((4345, 4356), 'math.cos', 'math.cos', (['i'], {}), '(i)\n', (4353, 4356), False, 'import math\n'), ((4359, 4370), 'math.sin', 'math.sin', (['j'], {}), '(j)\n', (4367, 4370), False, 'import math\n')] |
from config import paths
import re
import sys
import os
import tokens
import numpy as np
TOKEN_SPECIFICATION = {} # (token id, regex)
# 0: TokenInfo('root', 1, 0, '\\sqrt{{{}}}'),
TOKEN_SPECIFICATION[0] = r'sqrt'
# 1: TokenInfo('fac', 1, 1, '{}!'),
TOKEN_SPECIFICATION[1] = r'!'
# 2: TokenInfo('max', 1, 2, 'max {}'),
TOKEN_SPECIFICATION[2] = r'max'
# 3: TokenInfo('min', 1, 3, 'min {}'),
TOKEN_SPECIFICATION[3] = r'min'
# 4: TokenInfo('argmax', 1, 4, 'argmax {}'),
TOKEN_SPECIFICATION[4] = r'arg(\b)*max'
# 5: TokenInfo('argmin', 1, 5, 'argmin {}'),
TOKEN_SPECIFICATION[5] = r'arg(\b)*min'
# 6: TokenInfo('inverse', 1, 6, '{}^{{-1}}'),
TOKEN_SPECIFICATION[6] = r'^{-1}'
# 7: TokenInfo('sin', 1, 7, 'sin {}'),
TOKEN_SPECIFICATION[7] = r'sin'
# 8: TokenInfo('cos', 1, 8, 'cos {}'),
TOKEN_SPECIFICATION[8] = r'cos'
# 9: TokenInfo('tan', 1, 9, 'tan {}'),
TOKEN_SPECIFICATION[9] = r'tan'
# 10: TokenInfo('sinh', 1, 10, 'sinh {}'),
TOKEN_SPECIFICATION[10] = r'sinh'
# 11: TokenInfo('cosh', 1, 11, 'cosh {}'),
TOKEN_SPECIFICATION[11] = r'cosh'
# 12: TokenInfo('tanh', 1, 12, 'tanh {}'),
TOKEN_SPECIFICATION[12] = r'tanh'
# 13: TokenInfo('sigmoid', 1, 13, '\\sigma({})'),
TOKEN_SPECIFICATION[13] = r'sigma\('
# 14: TokenInfo('transpose', 1, 14, '{}^T'),
TOKEN_SPECIFICATION[14] = r'\^T'
# 15: TokenInfo('prime', 1, 15, '{}\''),
TOKEN_SPECIFICATION[15] = r"\^'"
# 16: TokenInfo('absolute', 1, 16, '|{}|'),
TOKEN_SPECIFICATION[16] = r'\|(\b)*\|'
# 17: TokenInfo('norm', 1, 17, '||{}||'),
TOKEN_SPECIFICATION[17] = r'\|\|(\b)*\|\|'
# 18: TokenInfo('mathbbe', 1, 18, '\\mathbb{{E}}[{}]'),
TOKEN_SPECIFICATION[18] = r'mathbb\{E\}'
# 19: TokenInfo('mathbbp', 1, 19, '\\mathbb{{P}}[{}]'),
TOKEN_SPECIFICATION[19] = r'mathbb\{P\}'
# 20: TokenInfo('maxsub', 2, 20, 'max_{{{}}} {}'),
TOKEN_SPECIFICATION[20] = r'max_'
# 21: TokenInfo('minsub', 2, 21, 'min_{{{}}} {}'),
TOKEN_SPECIFICATION[21] = r'min_'
# 22: TokenInfo('argmaxsub', 2, 22, 'argmax_{{{}}} {}'),
TOKEN_SPECIFICATION[22] = r'arg(\b)*max_'
# 23: TokenInfo('argminsub', 2, 23, 'argmin_{{{}}} {}'),
TOKEN_SPECIFICATION[23] = r'arg(\b)*min_'
# 24: TokenInfo('mathbbesub', 2, 24, '\\mathbb{{E}}_{{{}}}[{}]'),
TOKEN_SPECIFICATION[24] = r'mathbb\{E\}_'
# 25: TokenInfo('mathbbpsub', 2, 25, '\\mathbb{{P}}_{{{}}}[{}]'),
TOKEN_SPECIFICATION[25] = r'mathbb\{E\}_'
# 26: TokenInfo('add', 2, 26, '{} + {}'),
TOKEN_SPECIFICATION[26] = r'\+'
# 27: TokenInfo('sub', 2, 27, '{} - {}'),
TOKEN_SPECIFICATION[27] = r'-'
# 28: TokenInfo('dot', 2, 28, '{} \\cdot {}'),
TOKEN_SPECIFICATION[28] = r'cdot'
# 29: TokenInfo('cross', 2, 29, '{} \\times {}'),
TOKEN_SPECIFICATION[29] = r'times'
# 30: TokenInfo('fract', 2, 30, '\\frac{{{}}}{{{}}}'),
TOKEN_SPECIFICATION[30] = r'frac'
# 31: TokenInfo('mod', 2, 31, '{} mod {}'),
TOKEN_SPECIFICATION[31] = r'mod'
# 32: TokenInfo('power', 2, 32, '{}^{{{}}}'),
TOKEN_SPECIFICATION[32] = r'\^'
# 33: TokenInfo('derive', 2, None, '\\frac{{\\delta{}}}{{\\delta {}}}'),
TOKEN_SPECIFICATION[33] = r'frac(\b)*delta'
# 34: TokenInfo('sum', 3, 33, '\\sum\\nolimits_{{{}}}^{{{}}} {}'),
TOKEN_SPECIFICATION[34] = r'sum'
# 35: TokenInfo('product', 3, 34, '\\prod\\nolimits_{{{}}}^{{{}}} {}'),
TOKEN_SPECIFICATION[35] = r'prod'
# 36: TokenInfo('integral', 3, 35, '\\int\\nolimits_{{{}}}^{{{}}} {}'),
TOKEN_SPECIFICATION[36] = r'int'
# 37: TokenInfo('equals', 2, 36, '{} = {}'),
TOKEN_SPECIFICATION[37] = r'='
# 38: TokenInfo('lesser', 2, 37, '{} < {}'),
TOKEN_SPECIFICATION[38] = r'le'
# 39: TokenInfo('greater', 2, 38, '{} > {}'),
TOKEN_SPECIFICATION[39] = r'ge'
# 40: TokenInfo('lessereq', 2, 39, '{} \\leq {}'),
TOKEN_SPECIFICATION[40] = r'leq'
# 41: TokenInfo('greatereq', 2, 40, '{} \\geq {}'),
TOKEN_SPECIFICATION[41] = r'geq'
# 42: TokenInfo('subset', 2, 41, '{} \\subset {}'),
TOKEN_SPECIFICATION[42] = r'subset'
# 43: TokenInfo('subseteq', 2, 42, '{} \\subseteq {}'),
TOKEN_SPECIFICATION[43] = r'subseteq'
# 44: TokenInfo('union', 2, 43, '{} \\cup {}'),
TOKEN_SPECIFICATION[44] = r'cup'
# 45: TokenInfo('difference', 2, 44, '{} \\cap {}'),
TOKEN_SPECIFICATION[45] = r'cap'
# 46: TokenInfo('elementof', 2, 45, '{} \\in {}'),
TOKEN_SPECIFICATION[46] = r'in'
# 47: TokenInfo('apply', 2, 46, '{}({})'),
TOKEN_SPECIFICATION[47] = r'\w\((\d)*\)'
# 48: TokenInfo('brackets', 1, 47, '({})'),
TOKEN_SPECIFICATION[48] = r'\((\d)*\)'
# 49: TokenInfo(u'\u0393', 0, 50, '\\Gamma'),
TOKEN_SPECIFICATION[49] = r'Gamma'
# 50: TokenInfo(u'\u0394', 0, 51, '\\Delta'),
TOKEN_SPECIFICATION[50] = r'Delta'
# 51: TokenInfo(u'\u0398', 0, 55, '\\Theta'),
TOKEN_SPECIFICATION[51] = r'Theta'
# 52: TokenInfo(u'\u039B', 0, 58, '\\Lambda'),
TOKEN_SPECIFICATION[52] = r'Lambda'
# 53: TokenInfo(u'\u039E', 0, 61, '\\Xi'),
TOKEN_SPECIFICATION[53] = r'Xi'
# 54: TokenInfo(u'\u03A0', 0, 63, '\\Pi'),
TOKEN_SPECIFICATION[54] = r'Pi'
# 55: TokenInfo(u'\u03A3', 0, 65, '\\Sigma'),
TOKEN_SPECIFICATION[55] = r'Sigma'
# 56: TokenInfo(u'\u03A5', 0, 67, '\\Upsilon'),
TOKEN_SPECIFICATION[56] = r'Upsilon'
# 57: TokenInfo(u'\u03A6', 0, 68, '\\Phi'),
TOKEN_SPECIFICATION[57] = r'Phi'
# 58: TokenInfo(u'\u03A8', 0, 70, '\\Psi'),
TOKEN_SPECIFICATION[58] = r'Psi'
# 59: TokenInfo(u'\u03A9', 0, 71, '\\Omega'),
TOKEN_SPECIFICATION[59] = r'Omega'
# 60: TokenInfo(u'\u03B1', 0, 72, '\\alpha'),
TOKEN_SPECIFICATION[60] = r'alpha'
# 61: TokenInfo(u'\u03B2', 0, 73, '\\beta'),
TOKEN_SPECIFICATION[61] = r'beta'
# 62: TokenInfo(u'\u03B3', 0, 74, '\\gamma'),
TOKEN_SPECIFICATION[62] = r'gamma'
# 63: TokenInfo(u'\u03B4', 0, 75, '\\delta'),
TOKEN_SPECIFICATION[63] = r'delta'
# 64: TokenInfo(u'\u03B5', 0, 76, '\\epsilon'),
TOKEN_SPECIFICATION[64] = r'epsilon'
# 65: TokenInfo(u'\u03B6', 0, 77, '\\zeta'),
TOKEN_SPECIFICATION[65] = r'zeta'
# 66: TokenInfo(u'\u03B7', 0, 78, '\\eta'),
TOKEN_SPECIFICATION[66] = r'eta'
# 67: TokenInfo(u'\u03B8', 0, 79, '\\theta'),
TOKEN_SPECIFICATION[67] = r'theta'
# 68: TokenInfo(u'\u03B9', 0, 80, '\\iota'),
TOKEN_SPECIFICATION[68] = r'iota'
# 69: TokenInfo(u'\u03BA', 0, 81, '\\kappa'),
TOKEN_SPECIFICATION[69] = r'kappa'
# 70: TokenInfo(u'\u03BB', 0, 82, '\\lambda'),
TOKEN_SPECIFICATION[70] = r'lambda'
# 71: TokenInfo(u'\u03BC', 0, 83, '\\mu'),
TOKEN_SPECIFICATION[71] = r'mu'
# 72: TokenInfo(u'\u03BD', 0, 84, '\\nu'),
TOKEN_SPECIFICATION[72] = r'nu'
# 73: TokenInfo(u'\u03BE', 0, 85, '\\xi'),
TOKEN_SPECIFICATION[73] = r'xi'
# 74: TokenInfo(u'\u03C0', 0, 87, '\\pi'),
TOKEN_SPECIFICATION[74] = r'pi'
# 75: TokenInfo(u'\u03C1', 0, 88, '\\rho'),
TOKEN_SPECIFICATION[75] = r'rho'
# 76: TokenInfo(u'\u03C3', 0, 89, '\\sigma'),
TOKEN_SPECIFICATION[76] = r'sigma'
# 77: TokenInfo(u'\u03C4', 0, 90, '\\tau'),
TOKEN_SPECIFICATION[77] = r'tau'
# 78: TokenInfo(u'\u03C5', 0, 91, '\\upsilon'),
TOKEN_SPECIFICATION[78] = r'upsilon'
# 79: TokenInfo(u'\u03C6', 0, 92, '\\phi'),
TOKEN_SPECIFICATION[79] = r'phi'
# 80: TokenInfo(u'\u03C7', 0, 93, '\\chi'),
TOKEN_SPECIFICATION[80] = r'chi'
# 81: TokenInfo(u'\u03C8', 0, 94, '\\psi'),
TOKEN_SPECIFICATION[81] = r'psi'
# 82: TokenInfo(u'\u03C9', 0, 95, '\\omega'),
TOKEN_SPECIFICATION[82] = r'omega'
# 83: TokenInfo('A', 0, 96, 'A'),
TOKEN_SPECIFICATION[83] = r'A'
# 84: TokenInfo('B', 0, 97, 'B'),
TOKEN_SPECIFICATION[84] = r'B'
# 85: TokenInfo('C', 0, 98, 'C'),
TOKEN_SPECIFICATION[85] = r'C'
# 86: TokenInfo('D', 0, 99, 'D'),
TOKEN_SPECIFICATION[86] = r'D'
# 87: TokenInfo('E', 0, 100, 'E'),
TOKEN_SPECIFICATION[87] = r'E'
# 88: TokenInfo('F', 0, 101, 'F'),
TOKEN_SPECIFICATION[88] = r'F'
# 89: TokenInfo('G', 0, 102, 'G'),
TOKEN_SPECIFICATION[89] = r'G'
# 90: TokenInfo('H', 0, 103, 'H'),
TOKEN_SPECIFICATION[90] = r'H'
# 91: TokenInfo('I', 0, 104, 'I'),
TOKEN_SPECIFICATION[91] = r'I'
# 92: TokenInfo('J', 0, 105, 'J'),
TOKEN_SPECIFICATION[92] = r'J'
# 93: TokenInfo('K', 0, 106, 'K'),
TOKEN_SPECIFICATION[93] = r'K'
# 94: TokenInfo('L', 0, 107, 'L'),
TOKEN_SPECIFICATION[94] = r'L'
# 95: TokenInfo('M', 0, 108, 'M'),
TOKEN_SPECIFICATION[95] = r'M'
# 96: TokenInfo('N', 0, 109, 'N'),
TOKEN_SPECIFICATION[96] = r'N'
# 97: TokenInfo('O', 0, 110, 'O'),
TOKEN_SPECIFICATION[97] = r'O'
# 98: TokenInfo('P', 0, 111, 'P'),
TOKEN_SPECIFICATION[98] = r'P'
# 99: TokenInfo('Q', 0, 112, 'Q'),
TOKEN_SPECIFICATION[99] = r'Q'
# 100: TokenInfo('R', 0, 113, 'R'),
TOKEN_SPECIFICATION[100] = r'R'
# 101: TokenInfo('S', 0, 114, 'S'),
TOKEN_SPECIFICATION[101] = r'S'
# 102: TokenInfo('T', 0, 115, 'T'),
TOKEN_SPECIFICATION[102] = r'T'
# 103: TokenInfo('U', 0, 116, 'U'),
TOKEN_SPECIFICATION[103] = r'U'
# 104: TokenInfo('V', 0, 117, 'V'),
TOKEN_SPECIFICATION[104] = r'V'
# 105: TokenInfo('W', 0, 118, 'W'),
TOKEN_SPECIFICATION[105] = r'W'
# 106: TokenInfo('X', 0, 119, 'X'),
TOKEN_SPECIFICATION[106] = r'X'
# 107: TokenInfo('Y', 0, 120, 'Y'),
TOKEN_SPECIFICATION[107] = r'Y'
# 108: TokenInfo('Z', 0, 121, 'Z'),
TOKEN_SPECIFICATION[108] = r'Z'
# 109: TokenInfo('a', 0, 122, 'a'),
TOKEN_SPECIFICATION[109] = r'a'
# 110: TokenInfo('b', 0, 123, 'b'),
TOKEN_SPECIFICATION[110] = r'b'
# 111: TokenInfo('c', 0, 124, 'c'),
TOKEN_SPECIFICATION[111] = r'c'
# 112: TokenInfo('d', 0, 125, 'd'),
TOKEN_SPECIFICATION[112] = r'd'
# 113: TokenInfo('e', 0, 126, 'e'),
TOKEN_SPECIFICATION[113] = r'e'
# 114: TokenInfo('f', 0, 127, 'f'),
TOKEN_SPECIFICATION[114] = r'f'
# 115: TokenInfo('g', 0, 128, 'g'),
TOKEN_SPECIFICATION[115] = r'g'
# 116: TokenInfo('h', 0, 129, 'h'),
TOKEN_SPECIFICATION[116] = r'h'
# 117: TokenInfo('i', 0, 130, 'i'),
TOKEN_SPECIFICATION[117] = r'i'
# 118: TokenInfo('j', 0, 131, 'j'),
TOKEN_SPECIFICATION[118] = r'j'
# 119: TokenInfo('k', 0, 132, 'k'),
TOKEN_SPECIFICATION[119] = r'k'
# 120: TokenInfo('l', 0, 133, 'l'),
TOKEN_SPECIFICATION[120] = r'l'
# 121: TokenInfo('m', 0, 134, 'm'),
TOKEN_SPECIFICATION[121] = r'm'
# 122: TokenInfo('n', 0, 135, 'n'),
TOKEN_SPECIFICATION[122] = r'n'
# 123: TokenInfo('o', 0, 136, 'o'),
TOKEN_SPECIFICATION[123] = r'o'
# 124: TokenInfo('p', 0, 137, 'p'),
TOKEN_SPECIFICATION[124] = r'p'
# 125: TokenInfo('q', 0, 138, 'q'),
TOKEN_SPECIFICATION[125] = r'q'
# 126: TokenInfo('r', 0, 139, 'r'),
TOKEN_SPECIFICATION[126] = r'r'
# 127: TokenInfo('s', 0, 140, 's'),
TOKEN_SPECIFICATION[127] = r's'
# 128: TokenInfo('t', 0, 141, 't'),
TOKEN_SPECIFICATION[128] = r't'
# 129: TokenInfo('u', 0, 142, 'u'),
TOKEN_SPECIFICATION[129] = r'u'
# 130: TokenInfo('v', 0, 143, 'v'),
TOKEN_SPECIFICATION[130] = r'v'
# 131: TokenInfo('w', 0, 144, 'w'),
TOKEN_SPECIFICATION[131] = r'w'
# 132: TokenInfo('x', 0, 145, 'x'),
TOKEN_SPECIFICATION[132] = r'x'
# 133: TokenInfo('y', 0, 146, 'y'),
TOKEN_SPECIFICATION[133] = r'y'
# 134: TokenInfo('z', 0, 147, 'z'),
TOKEN_SPECIFICATION[134] = r'z'
# 135: TokenInfo('1', 0, 148, '1'),
TOKEN_SPECIFICATION[135] = r'1'
# 136: TokenInfo('2', 0, 149, '2'),
TOKEN_SPECIFICATION[136] = r'2'
# 137: TokenInfo('3', 0, 150, '3'),
TOKEN_SPECIFICATION[137] = r'3'
# 138: TokenInfo('4', 0, 151, '4'),
TOKEN_SPECIFICATION[138] = r'4'
# 139: TokenInfo('5', 0, 152, '5'),
TOKEN_SPECIFICATION[139] = r'5'
# 140: TokenInfo('6', 0, 153, '6'),
TOKEN_SPECIFICATION[140] = r'6'
# 141: TokenInfo('7', 0, 154, '7'),
TOKEN_SPECIFICATION[141] = r'7'
# 142: TokenInfo('8', 0, 155, '8'),
TOKEN_SPECIFICATION[142] = r'8'
# 143: TokenInfo('9', 0, 156, '9'),
TOKEN_SPECIFICATION[143] = r'9'
# 144: TokenInfo('0', 0, 157, '0')
TOKEN_SPECIFICATION[144] = r'0'
# 145: TokenInfo('infty', 0, 0, '\\infty'),
TOKEN_SPECIFICATION[145] = r'infty'
# 146: TokenInfo('propto', 0, 0, '\\propto'),
TOKEN_SPECIFICATION[146] = r'propto'
# 147: TokenInfo('negate', 0, 0, '-{}')
TOKEN_SPECIFICATION[147] = r'-\w'
TOKEN_REGEX = r'|'.join('(?P<%s>%s)' % ('g' + str(id), reg) for (id, reg) in TOKEN_SPECIFICATION.items())
OCCURENCES = [0] * len(TOKEN_SPECIFICATION.keys())
assert len(TOKEN_SPECIFICATION) == len(tokens.possibilities())
def find_all(string):
for match in re.finditer(TOKEN_REGEX, string): # matches first matching regex, atoms last in TOKEN_REGEX
group = match.lastgroup
group_num = int(group[1:]) # delete g, group names starting with a number are not allowed
OCCURENCES[group_num] += 1
def scan(directory, constrictions):
iterator = os.scandir(directory)
total = len(constrictions)
count = 1
for entry in iterator:
if entry.is_file():
if entry.name.endswith('txt') or entry.name.endswith('tex'):
with open(directory + '/' + entry.name, 'r') as file:
string = file.read()
find_all(string)
if entry.is_dir() and not constrictions:
scan(directory + '/' + entry.name, constrictions)
if entry.is_dir() and entry.name in constrictions:
scan(directory + '/' + entry.name, constrictions)
print('Directory {} of {} finished..'.format(count, min(total, 2000)))
count += 1
if count > 2000:
break
save(paths.distribution_bias)
def save(path):
with open(path, "w") as file:
string = ''
for count in OCCURENCES:
string += str(count) + ','
string = string[:-1]
file.write(string)
def load(path):
if not os.path.exists(path):
return None
with open(path, 'r') as file:
data = file.read()
ls = data.split(',')
occurrences = [int(o)/100000 for o in ls] # arbitrary value to prevent overflow
# total = sum(occurrences)
# distribution = [o / total for o in occurrences]
for i in range(len(occurrences)):
occurrences[i] += 1
def softmax(w, t = 1.0):
e = np.exp(np.array(w) / t)
dist = e / np.sum(e)
return dist
distribution = softmax(occurrences)
return distribution
def read_file_names():
iterator = os.scandir(paths.arxiv_data)
filenames = []
for entry in iterator:
if entry.is_dir():
filenames.append(entry.name)
return filenames
if __name__ == '__main__':
if len(sys.argv) == 1:
raise ValueError('Please specify a directory to scan for latex documents.')
path = sys.argv[1]
if not os.path.exists(path):
raise ValueError('Path does not exist.')
# take only those folders which we actually train on
constrictions = read_file_names()
scan(sys.argv[1], constrictions)
| [
"numpy.sum",
"re.finditer",
"os.path.exists",
"tokens.possibilities",
"numpy.array",
"os.scandir"
] | [((11807, 11839), 're.finditer', 're.finditer', (['TOKEN_REGEX', 'string'], {}), '(TOKEN_REGEX, string)\n', (11818, 11839), False, 'import re\n'), ((12119, 12140), 'os.scandir', 'os.scandir', (['directory'], {}), '(directory)\n', (12129, 12140), False, 'import os\n'), ((13696, 13724), 'os.scandir', 'os.scandir', (['paths.arxiv_data'], {}), '(paths.arxiv_data)\n', (13706, 13724), False, 'import os\n'), ((11742, 11764), 'tokens.possibilities', 'tokens.possibilities', ([], {}), '()\n', (11762, 11764), False, 'import tokens\n'), ((13104, 13124), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (13118, 13124), False, 'import os\n'), ((14036, 14056), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (14050, 14056), False, 'import os\n'), ((13560, 13569), 'numpy.sum', 'np.sum', (['e'], {}), '(e)\n', (13566, 13569), True, 'import numpy as np\n'), ((13524, 13535), 'numpy.array', 'np.array', (['w'], {}), '(w)\n', (13532, 13535), True, 'import numpy as np\n')] |
# Copyright 2018 <NAME>
# 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.
"""Command line hooks for feature-related activities"""
import logging
import sys
from typing import Optional, Sequence
import numpy as np
from pydrobert.kaldi.io import open as kaldi_open
from pydrobert.kaldi.io.argparse import KaldiParser
from pydrobert.kaldi.logging import kaldi_logger_decorator
from pydrobert.kaldi.logging import kaldi_vlog_level_cmd_decorator
from pydrobert.kaldi.logging import register_logger_for_kaldi
__all__ = [
"normalize_feat_lens",
]
def _normalize_feat_lens_parse_args(args, logger):
parser = KaldiParser(
description=normalize_feat_lens.__doc__, add_verbose=True, logger=logger,
)
parser.add_argument(
"feats_in_rspecifier",
type="kaldi_rspecifier",
help="The features to be normalized",
)
parser.add_argument(
"len_in_rspecifier",
type="kaldi_rspecifier",
help="The reference lengths (int32 table)",
)
parser.add_argument(
"feats_out_wspecifier", type="kaldi_wspecifier", help="The output features",
)
parser.add_argument(
"--type",
type="kaldi_dtype",
default="bm",
help="The kaldi type of the input/output features",
)
parser.add_argument(
"--tolerance",
type=int,
default=float("inf"),
help="""\
How many frames deviation from reference to tolerate before error. The default
is to be infinitely tolerant (a feat I'm sure we all desire)
""",
)
parser.add_argument(
"--strict",
type="kaldi_bool",
default=False,
help="""\
Whether missing keys in len_in and lengths beyond the threshold cause
an error (true) or are skipped with a warning (false)
""",
)
parser.add_argument(
"--pad-mode",
default="edge",
choices=("zero", "constant", "edge", "symmetric", "mean"),
help="""\
If frames are being padded to the features, specify how they should be padded.
zero=zero pad, edge=pad with rightmost frame, symmetric=pad with reverse of
frame edges, mean=pad with mean feature values
""",
)
parser.add_argument(
"--side",
default="right",
choices=("left", "right", "center"),
help="""\
If an utterance needs to be padded or truncated, specify what side of the
utterance to do this on. left=beginning, right=end, center=distribute
evenly on either side
""",
)
return parser.parse_args(args)
@kaldi_vlog_level_cmd_decorator
@kaldi_logger_decorator
def normalize_feat_lens(args: Optional[Sequence[str]] = None) -> None:
"""Ensure features match some reference lengths
Incoming features are either clipped or padded to match
reference lengths (stored as an int32 table), if they are within
tolerance.
"""
logger = logging.getLogger(sys.argv[0])
if not logger.handlers:
logger.addHandler(logging.StreamHandler())
register_logger_for_kaldi(sys.argv[0])
options = _normalize_feat_lens_parse_args(args, logger)
if options.pad_mode == "zero":
options.pad_mode = "constant"
feats_in = kaldi_open(options.feats_in_rspecifier, options.type, mode="r")
len_in = kaldi_open(options.len_in_rspecifier, "i", mode="r+")
feats_out = kaldi_open(options.feats_out_wspecifier, options.type, mode="w")
total_utts = 0
processed_utts = 0
for utt_id, feats in list(feats_in.items()):
total_utts += 1
if utt_id not in len_in:
msg = "Utterance '{}' absent in '{}'".format(
utt_id, options.len_in_rspecifier
)
if options.strict:
logger.error(msg)
return 1
else:
logger.warning(msg)
continue
exp_feat_len = len_in[utt_id]
act_feat_len = len(feats)
logger.debug(
"{} exp len: {} act len: {}".format(utt_id, exp_feat_len, act_feat_len)
)
if act_feat_len < exp_feat_len:
if act_feat_len < exp_feat_len - options.tolerance:
msg = "{} has feature length {}, which is below the "
msg += "tolerance ({}) of the expected length {}"
msg = msg.format(utt_id, act_feat_len, options.tolerance, exp_feat_len)
if options.strict:
logger.error(msg)
return 1
else:
logger.warning(msg)
continue
# for matrices or vectors, this cast shouldn't be necessary.
# If the user tries some special type like token vectors,
# however, this *might* work as intended
feats = np.array(feats, copy=False)
pad_list = [(0, 0)] * len(feats.shape)
if options.side == "right":
pad_list[0] = (0, exp_feat_len - act_feat_len)
elif options.side == "left":
pad_list[0] = (exp_feat_len - act_feat_len, 0)
else:
pad_list[0] = (
(exp_feat_len - act_feat_len) // 2,
(exp_feat_len - act_feat_len + 1) // 2,
)
feats = np.pad(feats, pad_list, options.pad_mode)
elif act_feat_len > exp_feat_len:
if act_feat_len > exp_feat_len + options.tolerance:
msg = "{} has feature length {}, which is above the "
msg += "tolerance ({}) of the expected length {}"
msg = msg.format(utt_id, act_feat_len, options.tolerance, exp_feat_len)
if options.strict:
logger.error(msg)
return 1
else:
logger.warning(msg)
continue
if options.side == "right":
feats = feats[: exp_feat_len - act_feat_len]
elif options.side == "left":
feats = feats[exp_feat_len - act_feat_len :]
else:
feats = feats[
(exp_feat_len - act_feat_len)
// 2 : (exp_feat_len - act_feat_len + 1)
// 2
]
feats_out.write(utt_id, feats)
processed_utts += 1
logger.info("Processed {}/{} utterances".format(processed_utts, total_utts))
return 0
| [
"numpy.pad",
"pydrobert.kaldi.logging.register_logger_for_kaldi",
"logging.StreamHandler",
"pydrobert.kaldi.io.argparse.KaldiParser",
"numpy.array",
"pydrobert.kaldi.io.open",
"logging.getLogger"
] | [((1108, 1197), 'pydrobert.kaldi.io.argparse.KaldiParser', 'KaldiParser', ([], {'description': 'normalize_feat_lens.__doc__', 'add_verbose': '(True)', 'logger': 'logger'}), '(description=normalize_feat_lens.__doc__, add_verbose=True,\n logger=logger)\n', (1119, 1197), False, 'from pydrobert.kaldi.io.argparse import KaldiParser\n'), ((3342, 3372), 'logging.getLogger', 'logging.getLogger', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (3359, 3372), False, 'import logging\n'), ((3456, 3494), 'pydrobert.kaldi.logging.register_logger_for_kaldi', 'register_logger_for_kaldi', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (3481, 3494), False, 'from pydrobert.kaldi.logging import register_logger_for_kaldi\n'), ((3643, 3706), 'pydrobert.kaldi.io.open', 'kaldi_open', (['options.feats_in_rspecifier', 'options.type'], {'mode': '"""r"""'}), "(options.feats_in_rspecifier, options.type, mode='r')\n", (3653, 3706), True, 'from pydrobert.kaldi.io import open as kaldi_open\n'), ((3720, 3773), 'pydrobert.kaldi.io.open', 'kaldi_open', (['options.len_in_rspecifier', '"""i"""'], {'mode': '"""r+"""'}), "(options.len_in_rspecifier, 'i', mode='r+')\n", (3730, 3773), True, 'from pydrobert.kaldi.io import open as kaldi_open\n'), ((3790, 3854), 'pydrobert.kaldi.io.open', 'kaldi_open', (['options.feats_out_wspecifier', 'options.type'], {'mode': '"""w"""'}), "(options.feats_out_wspecifier, options.type, mode='w')\n", (3800, 3854), True, 'from pydrobert.kaldi.io import open as kaldi_open\n'), ((3427, 3450), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (3448, 3450), False, 'import logging\n'), ((5219, 5246), 'numpy.array', 'np.array', (['feats'], {'copy': '(False)'}), '(feats, copy=False)\n', (5227, 5246), True, 'import numpy as np\n'), ((5709, 5750), 'numpy.pad', 'np.pad', (['feats', 'pad_list', 'options.pad_mode'], {}), '(feats, pad_list, options.pad_mode)\n', (5715, 5750), True, 'import numpy as np\n')] |
# Main script to run the PLAN tool
import argparse
import math
import numpy as np
import operator
import os
import pickle as pk
import re
import subprocess
import sys
import time
from datetime import datetime
from itertools import combinations
from scipy.stats.stats import pearsonr
from tqdm import tqdm
from Verilog_VCD import Verilog_VCD as v
################################################################################
# Functions to be modified by user as per the design being analysed.
# Please refer to PLAN.md for the corresponding functions for different designs.
################################################################################
# To read the input values generated during simulation
def loadData():
a = []
with open('txtfile', 'r') as f:
buff = f.read().split('\n')
for d in buff[:-1]:
a.append(d)
return np.array(a,dtype='int')
# To compute the oracle trace from the the input trace generated and the secret key used during simulation
def computeOracle(k):
ip1 = loadData()
y = np.bitwise_xor(ip1, k)
return y
################################################################################
################################################################################
# global variables
vcdpath = 'vcd/'
filepath = 'pkl/'
pairs = []
sigArray1 = {} # stores the value carried by each signal for each run
sigGroup = {}
sigMatrix = {}
cipher = {}
O = {}
togglingSigs = set()
def createClkList(clkList, sname, tv):
for x in tv:
if x[0] not in clkList: # if clock is not there in the dict
clkList[x[0]]=[[],[]]
clkList[x[0]][0].append(sname)
clkList[x[0]][1].append(x[1])
else:
clkList[x[0]][0].append(sname)
clkList[x[0]][1].append(x[1])
return clkList
def readVCD(num_iterations):
rng = range(1, num_iterations+1)
for name, i in zip([' '+str(x)+'.vcd' for x in rng], rng):
data = {}
clockList = {}
data = v.parse_vcd(vcdpath + name, use_stdout=0)
for x in data:
signame = data[x]['nets'][0].get('hier') + '.' + data[x]['nets'][0].get('name')
clockList = createClkList(clockList, signame, list(data[x]['tv']))
with open(filepath + str(i) + '.pkl', 'wb') as f:
for x in sorted(clockList):
pk.dump([x, clockList[x]], f)
print('Pickle files have been created successfully...')
def alphaNumOrder(string):
return ''.join([format(int(x), '05d') if x.isdigit()
else x for x in re.split(r'(\d+)', string)])
def initSigArray(rfiles):
vcdname = ' 1.vcd'
data = v.parse_vcd(vcdpath + vcdname, use_stdout=0)
for f, n in zip(rfiles, range(1, len(rfiles) + 1)):
fname = str(n)
sigArray1[fname] = {}
for s in data:
sigArray1[fname][data[s]['nets'][0].get('hier') + '.' + data[s]['nets'][0].get('name')] = '0'
with open('sigArray.pkl', 'wb') as f:
for x in sigArray1:
pk.dump([x, sigArray1[x]], f)
print("SigArray has been created successfully")
def initpairs(num_iterations):
return list(combinations(np.linspace(1, num_iterations, num_iterations).astype(int), 2));
def loadSigArray():
with open('sigArray.pkl', 'rb') as f:
try:
while True:
temp = []
temp = pk.load(f)
sigArray1.update({temp[0]:temp[1]})
except EOFError:
pass
def init(num_iterations):
global pairs, sigs;
loadSigArray()
pairs = initpairs(num_iterations)
sigs = [x for x in sigArray1['1']] # All signal names
def updateSigArray(k1, k2, v):
tempdict = {};
for k, v in zip(k2, v):
sigArray1[k1][k] = v
tempdict[k] = v
return tempdict
# compute Hamming distance between every pair of values for each signal
def HammingDistanceSignalWise(sig):
tempfile = {}
for p in pairs:
temp = []
p1 = str(p[0])
p2 = str(p[1])
s1 = sigArray1[p1]
s2 = sigArray1[p2]
temp.append(bin(int(s1[sig], 2) ^ int(s2[sig], 2)).count('1'))
tempfile[p] = int(np.sum(temp))
return tempfile
def processSignals(sigs):
for sig in tqdm(sigs, "Processing signals"):
try:
ham = (sig, HammingDistanceSignalWise(sig))
temp = []
for pair in pairs:
temp.append(ham[1][pair])
with open('modules/' + ham[0] + '.pkl', 'ab') as f:
pk.dump(temp, f)
except Exception as e:
print("{}:{}".format(sig, e))
print()
def transformData(signal):
data = []
with open('modules/' + signal + '.pkl', 'rb') as f:
try:
while True:
data.append(pk.load(f))
except EOFError:
pass
return np.transpose(data)
def computeAndSaveLeakageScores(leaks_file_path, num_iterations, key_value):
leaks = {}
O = {}
mx = {}
O[1] = []
init(num_iterations)
y = computeOracle(key_value)
for p in pairs:
O[1].append(bin(y[p[0]-1] ^ y[p[1]-1]).count('1')) # HD b/w two temp values
counter = 0
for sig in togglingSigs:
data = transformData(sig)
temp = []
for sc in data.transpose():
score = pearsonr(O[1], sc)[0]
if (math.isnan(score)):
temp.append(0)
else:
temp.append(np.abs(score))
leaks[sig] = temp
counter += 1
for m in leaks: # calculate max leakage in each signal
mx[m] = max(leaks[m])
leaks_x = []
leaks_y = []
sorted_sigwise = dict(sorted(mx.items(), key=operator.itemgetter(1), reverse=True))
for x in sorted(mx):
leaks_x.append(x)
leaks_y.append(mx[x])
with open(leaks_file_path, "w") as f:
f.write("Signal,Leakage\n")
for x in sorted_sigwise:
f.write("%s,%.4f\n" %(x, sorted_sigwise[x]))
f.write("\n")
return len(sorted_sigwise)
def main(input_file_path, simulation_script, num_iterations, key_value, leaks_file_path, time_file_path):
start_time = time.time()
# simulation
subprocess.run(['./' + simulation_script, input_file_path, str(num_iterations)])
# analysis
nc2 = ((num_iterations * (num_iterations - 1)) / 2)
readVCD(num_iterations)
rfiles = os.listdir(filepath)
rfiles.sort(key = alphaNumOrder)
initSigArray(rfiles)
debug = 0 # flag for debugging
init(num_iterations) # mandatory intialisations
signals = [x for x in sigGroup] # signals present
for x in signals:
sigMatrix[x] = []
for y in range(len(sigGroup[x])):
temp = []
sigMatrix[x].append(temp)
result = []
for fn in range(1, num_iterations + 1):
fname = str(fn)
with open(filepath + rfiles[fn - 1], 'rb') as file:
temp = pk.load(file)
tempsigs = temp[1][0]
tempvals = temp[1][1]
togglingSigs.update(tempsigs)
tempdict = updateSigArray(fname, tempsigs, tempvals)
processSignals(togglingSigs)
numSigs = computeAndSaveLeakageScores(leaks_file_path, num_iterations, key_value)
end_time = time.time()
print("Completed!")
with open(time_file_path, "w") as sf:
sf.write("Number of signals: {}\n".format(numSigs))
sf.write("Total time taken: {:.4f}s\n".format(end_time - start_time))
if __name__ == '__main__':
# creating the argument parser
my_parser = argparse.ArgumentParser(description='Pre-silicon power side-channel analysis using PLAN')
# adding the arguments
my_parser.add_argument('InputFilePath',
metavar='input_file_path',
type=str,
help='path to the input Verilog file to be analyzed')
my_parser.add_argument('KeyValue',
metavar='key_value',
type=int,
help='secret value in input Verilog file')
my_parser.add_argument('SimulationScript',
metavar='simulation_script',
type=str,
help='path to script used for behavioral simulation')
my_parser.add_argument('Design',
metavar='design',
type=str,
help='name of the design being analysed')
my_parser.add_argument('-n',
'--num-iterations',
type=int,
action='store',
help='number of iterations in behavioral simulation, default value = 1000')
my_parser.add_argument('-r',
'--results-path',
type=str,
action='store',
help='name of directory within results/ directory to store results, default value = current timestamp')
# parsing the arguments
args = my_parser.parse_args()
input_file_path = args.InputFilePath
key_value = args.KeyValue
simulation_script = args.SimulationScript
design = args.Design
num_iterations = args.num_iterations
if not num_iterations:
num_iterations = 1000
results_path = args.results_path
if results_path:
results_path = 'results/' + results_path + '/' + design + '/'
else:
results_path = 'results/' + datetime.today().strftime('%Y-%m-%d-%H:%M:%S') + '/' + design + '/'
if not os.path.isdir(results_path):
os.makedirs(results_path)
leaks_file_path = results_path + "leaks.txt"
time_file_path = results_path + "time.txt"
if not os.path.isdir('vcd/'):
os.makedirs('vcd/')
if not os.path.isdir('pkl/'):
os.makedirs('pkl/')
if not os.path.isdir('modules/'):
os.makedirs('modules/')
print("Note: Please check that:")
print("1. the simulation script ({}) given as argument has the correct line numbers, variable names, max range to generate random values".format(simulation_script))
print("2. the secret key ({}) given as argument is same as that in the input Verilog file ({}) - please refer to PLAN.md for guidance".format(key_value, input_file_path))
print("3. this script (run_plan.py) has the correct functions to load data and compute oracle (in the first few lines) - please refer to PLAN.md for guidance")
print()
print("If you are sure that the above details are correct, and wish to continue, press Y/y (and enter)")
print("To stop, press any other key (and enter)")
user_input = input()
if user_input == 'y' or user_input == 'Y':
main(input_file_path, simulation_script, num_iterations, key_value, leaks_file_path, time_file_path)
| [
"pickle.dump",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.abs",
"scipy.stats.stats.pearsonr",
"numpy.bitwise_xor",
"pickle.load",
"numpy.transpose",
"numpy.linspace",
"tqdm.tqdm",
"math.isnan",
"re.split",
"datetime.datetime.today",
"os.listdir",
"Verilog_VCD.Verilog_VCD.parse_vcd",
... | [((865, 889), 'numpy.array', 'np.array', (['a'], {'dtype': '"""int"""'}), "(a, dtype='int')\n", (873, 889), True, 'import numpy as np\n'), ((1048, 1070), 'numpy.bitwise_xor', 'np.bitwise_xor', (['ip1', 'k'], {}), '(ip1, k)\n', (1062, 1070), True, 'import numpy as np\n'), ((2649, 2693), 'Verilog_VCD.Verilog_VCD.parse_vcd', 'v.parse_vcd', (['(vcdpath + vcdname)'], {'use_stdout': '(0)'}), '(vcdpath + vcdname, use_stdout=0)\n', (2660, 2693), True, 'from Verilog_VCD import Verilog_VCD as v\n'), ((4232, 4264), 'tqdm.tqdm', 'tqdm', (['sigs', '"""Processing signals"""'], {}), "(sigs, 'Processing signals')\n", (4236, 4264), False, 'from tqdm import tqdm\n'), ((4848, 4866), 'numpy.transpose', 'np.transpose', (['data'], {}), '(data)\n', (4860, 4866), True, 'import numpy as np\n'), ((6152, 6163), 'time.time', 'time.time', ([], {}), '()\n', (6161, 6163), False, 'import time\n'), ((6380, 6400), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (6390, 6400), False, 'import os\n'), ((7244, 7255), 'time.time', 'time.time', ([], {}), '()\n', (7253, 7255), False, 'import time\n'), ((7541, 7635), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Pre-silicon power side-channel analysis using PLAN"""'}), "(description=\n 'Pre-silicon power side-channel analysis using PLAN')\n", (7564, 7635), False, 'import argparse\n'), ((2000, 2041), 'Verilog_VCD.Verilog_VCD.parse_vcd', 'v.parse_vcd', (['(vcdpath + name)'], {'use_stdout': '(0)'}), '(vcdpath + name, use_stdout=0)\n', (2011, 2041), True, 'from Verilog_VCD import Verilog_VCD as v\n'), ((9590, 9617), 'os.path.isdir', 'os.path.isdir', (['results_path'], {}), '(results_path)\n', (9603, 9617), False, 'import os\n'), ((9627, 9652), 'os.makedirs', 'os.makedirs', (['results_path'], {}), '(results_path)\n', (9638, 9652), False, 'import os\n'), ((9762, 9783), 'os.path.isdir', 'os.path.isdir', (['"""vcd/"""'], {}), "('vcd/')\n", (9775, 9783), False, 'import os\n'), ((9793, 9812), 'os.makedirs', 'os.makedirs', (['"""vcd/"""'], {}), "('vcd/')\n", (9804, 9812), False, 'import os\n'), ((9825, 9846), 'os.path.isdir', 'os.path.isdir', (['"""pkl/"""'], {}), "('pkl/')\n", (9838, 9846), False, 'import os\n'), ((9856, 9875), 'os.makedirs', 'os.makedirs', (['"""pkl/"""'], {}), "('pkl/')\n", (9867, 9875), False, 'import os\n'), ((9888, 9913), 'os.path.isdir', 'os.path.isdir', (['"""modules/"""'], {}), "('modules/')\n", (9901, 9913), False, 'import os\n'), ((9923, 9946), 'os.makedirs', 'os.makedirs', (['"""modules/"""'], {}), "('modules/')\n", (9934, 9946), False, 'import os\n'), ((3014, 3043), 'pickle.dump', 'pk.dump', (['[x, sigArray1[x]]', 'f'], {}), '([x, sigArray1[x]], f)\n', (3021, 3043), True, 'import pickle as pk\n'), ((4156, 4168), 'numpy.sum', 'np.sum', (['temp'], {}), '(temp)\n', (4162, 4168), True, 'import numpy as np\n'), ((5351, 5368), 'math.isnan', 'math.isnan', (['score'], {}), '(score)\n', (5361, 5368), False, 'import math\n'), ((6919, 6932), 'pickle.load', 'pk.load', (['file'], {}), '(file)\n', (6926, 6932), True, 'import pickle as pk\n'), ((2350, 2379), 'pickle.dump', 'pk.dump', (['[x, clockList[x]]', 'f'], {}), '([x, clockList[x]], f)\n', (2357, 2379), True, 'import pickle as pk\n'), ((2559, 2585), 're.split', 're.split', (['"""(\\\\d+)"""', 'string'], {}), "('(\\\\d+)', string)\n", (2567, 2585), False, 'import re\n'), ((3371, 3381), 'pickle.load', 'pk.load', (['f'], {}), '(f)\n', (3378, 3381), True, 'import pickle as pk\n'), ((4510, 4526), 'pickle.dump', 'pk.dump', (['temp', 'f'], {}), '(temp, f)\n', (4517, 4526), True, 'import pickle as pk\n'), ((5313, 5331), 'scipy.stats.stats.pearsonr', 'pearsonr', (['O[1]', 'sc'], {}), '(O[1], sc)\n', (5321, 5331), False, 'from scipy.stats.stats import pearsonr\n'), ((5684, 5706), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (5703, 5706), False, 'import operator\n'), ((3157, 3203), 'numpy.linspace', 'np.linspace', (['(1)', 'num_iterations', 'num_iterations'], {}), '(1, num_iterations, num_iterations)\n', (3168, 3203), True, 'import numpy as np\n'), ((4783, 4793), 'pickle.load', 'pk.load', (['f'], {}), '(f)\n', (4790, 4793), True, 'import pickle as pk\n'), ((5448, 5461), 'numpy.abs', 'np.abs', (['score'], {}), '(score)\n', (5454, 5461), True, 'import numpy as np\n'), ((9510, 9526), 'datetime.datetime.today', 'datetime.today', ([], {}), '()\n', (9524, 9526), False, 'from datetime import datetime\n')] |
import numpy as np
import os
import pickle
from scipy import linalg
from distutils.util import strtobool
from inception import InceptionV3
import torchvision.transforms as transforms
from transform import TranformDynamicRange
import torch
from dataset import TrainDataset
from base_layer import BaseLayer
import argparse
from generator import Generator
from tensorboard_logger import TensorboardLogger
from datasource import get_dataloader
class FrechetInceptionDistance(BaseLayer):
def __init__(self, generator, dataloader, opt):
super(FrechetInceptionDistance, self).__init__()
self.generator = generator
# self.generator.eval()
self.batch_size = opt.batch_size
self.latent_dim = opt.latent_dim
self.data_path = opt.data_path
self.dataloader = dataloader
self.all_data_num = len(self.dataloader.dataset)
self.inception = InceptionV3([3], normalize_input=False)
self.cache_dir = opt.cache_path
self.cache_filename = '{}_real_image_mean_cov.pkl'.format(self.data_path.split('/')[-1])
self.cache_file_path = os.path.join(self.cache_dir, self.cache_filename)
def get_score(self):
print('---- calculate fid score ----')
if os.path.isfile(self.cache_file_path):
print('reading real mean and cov from cache file')
real_features, real_mean, real_cov = self.load_pkl(self.cache_file_path)
else:
if not os.path.isdir(self.cache_dir):
os.makedirs(self.cache_dir, exist_ok=True)
feature_list = []
print('extract features from real image')
for index, imgs in enumerate(self.dataloader):
feature = self.inception(imgs)[0].view(imgs.shape[0], -1)
feature_list.append(feature)
if index % 16 == 0:
print('{} was done'.format(index))
real_features = torch.cat(feature_list, 0).to('cpu').detach().numpy()
real_mean = np.mean(real_features, axis=0)
print('calculating real images mean was done')
real_cov = np.cov(real_features, rowvar=False)
print('calculating real images coveriance was done')
self.save_pkl((real_features, real_mean, real_cov), self.cache_file_path)
batch_loop_num = len(self.dataloader)
fake_feature_list = []
print('extract features from fake image')
for index in range(batch_loop_num):
latent = self.Tensor(np.random.normal(loc=0, scale=1, size=(self.batch_size, self.latent_dim)))
fake_imgs, _ = self.generator(latent)
fake_imgs = fake_imgs.to('cpu').detach()
fake_feature = self.inception(fake_imgs)[0].view(fake_imgs.shape[0], -1)
fake_feature_list.append(fake_feature)
if index % 16 == 0:
print('{} was done'.format(index))
fake_features = torch.cat(fake_feature_list, 0).to('cpu').detach().numpy()
if self.all_data_num < fake_features.shape[0]:
fake_features = fake_features[:self.all_data_num]
TensorboardLogger.writer.add_histogram('{}/fid/real_features'.format(TensorboardLogger.now), real_features, TensorboardLogger.global_step)
TensorboardLogger.writer.add_histogram('{}/fid/fake_features'.format(TensorboardLogger.now), fake_features, TensorboardLogger.global_step)
fake_mean = np.mean(fake_features, axis=0)
print('calculating fake images mean was done')
fake_cov = np.cov(fake_features, rowvar=False)
print('calculating fake images coveriance was done')
score = self.calc_fid(fake_mean, fake_cov, real_mean, real_cov)
print('=====> fid score: {}'.format(score))
return score
def calc_fid(self, fake_mean, fake_cov, real_mean, real_cov, eps=1e-6):
cov_sqrt, _ = linalg.sqrtm(fake_cov @ real_cov, disp=False)
print('calculating cov_sqrt was done')
if not np.isfinite(cov_sqrt).all():
print('product of cov matrices is singular')
offset = np.eye(fake_cov.shape[0]) * eps
cov_sqrt = linalg.sqrtm((fake_cov + offset) @ (real_cov + offset))
if np.iscomplexobj(cov_sqrt):
if not np.allclose(np.diagonal(cov_sqrt).imag, 0, atol=1e-3):
m = np.max(np.abs(cov_sqrt.imag))
raise ValueError(f'Imaginary component {m}')
cov_sqrt = cov_sqrt.real
mean_diff = fake_mean - real_mean
mean_norm = mean_diff @ mean_diff
trace = np.trace(fake_cov) + np.trace(real_cov) - 2 * np.trace(cov_sqrt)
result = mean_norm + trace
return result
def load_pkl(self, filename):
with open(filename, 'rb') as file:
return pickle.load(file, encoding='latin1')
def save_pkl(self, obj, filename):
with open(filename, 'wb') as file:
pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--n_epochs", type=int, default=500, help="number of epochs of training")
parser.add_argument("--data_path", type=str, default='../dataset/endless_summer', help="学習に使用するデータセットのディレクトリを指定します")
parser.add_argument("--batch_size", type=int, default=16, help="size of the batches")
parser.add_argument("--latent_dim", type=int, default=512, help="")
parser.add_argument("--learning_rate", type=float, default=0.002, help="adam: learning rate")
parser.add_argument("--beta1", type=float, default=0.0, help="adam: decay of first order momentum of gradient")
parser.add_argument("--beta2", type=float, default=0.99, help="adam: decay of first order momentum of gradient")
parser.add_argument("--resolution", type=int, default=32, help="size of each image dimension")
parser.add_argument("--pl_minibatch_shrink", type=int, default=1, help="pl_minibatch_shrink")
parser.add_argument("--g_reg_interval", type=int, default=4, help="g_reg_interval")
parser.add_argument("--d_reg_interval", type=int, default=16, help="d_reg_interval")
parser.add_argument("--model_path", type=str, default='./model', help="model_path")
parser.add_argument("--results", type=str, default='./results', help="results")
parser.add_argument("--is_restore_model", type=strtobool, default=True, help="is_restore_model")
parser.add_argument("--cache_path", type=str, default='./cache', help="cache")
parser.add_argument("--tensorboard_path", type=str, default='./logs', help="tensorboard_path")
opt = parser.parse_args()
dataloader = get_dataloader(opt.data_path, opt.resolution, opt.batch_size)
# dataset = BoxDataset(
# file_path=os.path.join(opt.data_path, '*.png'),
# transform=transforms.Compose(
# [
# transforms.Resize(32),
# transforms.ToTensor(),
# TranformDynamicRange([0, 255], [-1, 1])
# ]
# ),
# )
#
# dataloader = torch.utils.data.DataLoader(
# dataset=dataset,
# batch_size=8,
# shuffle=True,
# )
generator = Generator(opt)
# if opt.is_restore_model:
# generator.restore()
models = BaseLayer.restore_model(opt.model_path)
if models is not None:
generator, generator_predict, discriminator = models
fid = FrechetInceptionDistance(generator, dataloader=dataloader, opt=opt)
fid_score = fid.get_score()
print(fid_score)
| [
"pickle.dump",
"numpy.trace",
"numpy.abs",
"argparse.ArgumentParser",
"torch.cat",
"os.path.isfile",
"numpy.mean",
"pickle.load",
"numpy.random.normal",
"os.path.join",
"datasource.get_dataloader",
"numpy.isfinite",
"numpy.cov",
"numpy.diagonal",
"base_layer.BaseLayer.restore_model",
"... | [((5021, 5046), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5044, 5046), False, 'import argparse\n'), ((6636, 6697), 'datasource.get_dataloader', 'get_dataloader', (['opt.data_path', 'opt.resolution', 'opt.batch_size'], {}), '(opt.data_path, opt.resolution, opt.batch_size)\n', (6650, 6697), False, 'from datasource import get_dataloader\n'), ((7172, 7186), 'generator.Generator', 'Generator', (['opt'], {}), '(opt)\n', (7181, 7186), False, 'from generator import Generator\n'), ((7262, 7301), 'base_layer.BaseLayer.restore_model', 'BaseLayer.restore_model', (['opt.model_path'], {}), '(opt.model_path)\n', (7285, 7301), False, 'from base_layer import BaseLayer\n'), ((901, 940), 'inception.InceptionV3', 'InceptionV3', (['[3]'], {'normalize_input': '(False)'}), '([3], normalize_input=False)\n', (912, 940), False, 'from inception import InceptionV3\n'), ((1109, 1158), 'os.path.join', 'os.path.join', (['self.cache_dir', 'self.cache_filename'], {}), '(self.cache_dir, self.cache_filename)\n', (1121, 1158), False, 'import os\n'), ((1243, 1279), 'os.path.isfile', 'os.path.isfile', (['self.cache_file_path'], {}), '(self.cache_file_path)\n', (1257, 1279), False, 'import os\n'), ((3433, 3463), 'numpy.mean', 'np.mean', (['fake_features'], {'axis': '(0)'}), '(fake_features, axis=0)\n', (3440, 3463), True, 'import numpy as np\n'), ((3539, 3574), 'numpy.cov', 'np.cov', (['fake_features'], {'rowvar': '(False)'}), '(fake_features, rowvar=False)\n', (3545, 3574), True, 'import numpy as np\n'), ((3880, 3925), 'scipy.linalg.sqrtm', 'linalg.sqrtm', (['(fake_cov @ real_cov)'], {'disp': '(False)'}), '(fake_cov @ real_cov, disp=False)\n', (3892, 3925), False, 'from scipy import linalg\n'), ((4219, 4244), 'numpy.iscomplexobj', 'np.iscomplexobj', (['cov_sqrt'], {}), '(cov_sqrt)\n', (4234, 4244), True, 'import numpy as np\n'), ((2013, 2043), 'numpy.mean', 'np.mean', (['real_features'], {'axis': '(0)'}), '(real_features, axis=0)\n', (2020, 2043), True, 'import numpy as np\n'), ((2127, 2162), 'numpy.cov', 'np.cov', (['real_features'], {'rowvar': '(False)'}), '(real_features, rowvar=False)\n', (2133, 2162), True, 'import numpy as np\n'), ((4151, 4206), 'scipy.linalg.sqrtm', 'linalg.sqrtm', (['((fake_cov + offset) @ (real_cov + offset))'], {}), '((fake_cov + offset) @ (real_cov + offset))\n', (4163, 4206), False, 'from scipy import linalg\n'), ((4790, 4826), 'pickle.load', 'pickle.load', (['file'], {'encoding': '"""latin1"""'}), "(file, encoding='latin1')\n", (4801, 4826), False, 'import pickle\n'), ((4922, 4978), 'pickle.dump', 'pickle.dump', (['obj', 'file'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(obj, file, protocol=pickle.HIGHEST_PROTOCOL)\n', (4933, 4978), False, 'import pickle\n'), ((1462, 1491), 'os.path.isdir', 'os.path.isdir', (['self.cache_dir'], {}), '(self.cache_dir)\n', (1475, 1491), False, 'import os\n'), ((1509, 1551), 'os.makedirs', 'os.makedirs', (['self.cache_dir'], {'exist_ok': '(True)'}), '(self.cache_dir, exist_ok=True)\n', (1520, 1551), False, 'import os\n'), ((2519, 2592), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': '(1)', 'size': '(self.batch_size, self.latent_dim)'}), '(loc=0, scale=1, size=(self.batch_size, self.latent_dim))\n', (2535, 2592), True, 'import numpy as np\n'), ((4096, 4121), 'numpy.eye', 'np.eye', (['fake_cov.shape[0]'], {}), '(fake_cov.shape[0])\n', (4102, 4121), True, 'import numpy as np\n'), ((4571, 4589), 'numpy.trace', 'np.trace', (['fake_cov'], {}), '(fake_cov)\n', (4579, 4589), True, 'import numpy as np\n'), ((4592, 4610), 'numpy.trace', 'np.trace', (['real_cov'], {}), '(real_cov)\n', (4600, 4610), True, 'import numpy as np\n'), ((4617, 4635), 'numpy.trace', 'np.trace', (['cov_sqrt'], {}), '(cov_sqrt)\n', (4625, 4635), True, 'import numpy as np\n'), ((3989, 4010), 'numpy.isfinite', 'np.isfinite', (['cov_sqrt'], {}), '(cov_sqrt)\n', (4000, 4010), True, 'import numpy as np\n'), ((4347, 4368), 'numpy.abs', 'np.abs', (['cov_sqrt.imag'], {}), '(cov_sqrt.imag)\n', (4353, 4368), True, 'import numpy as np\n'), ((4277, 4298), 'numpy.diagonal', 'np.diagonal', (['cov_sqrt'], {}), '(cov_sqrt)\n', (4288, 4298), True, 'import numpy as np\n'), ((2941, 2972), 'torch.cat', 'torch.cat', (['fake_feature_list', '(0)'], {}), '(fake_feature_list, 0)\n', (2950, 2972), False, 'import torch\n'), ((1935, 1961), 'torch.cat', 'torch.cat', (['feature_list', '(0)'], {}), '(feature_list, 0)\n', (1944, 1961), False, 'import torch\n')] |
# %tensorflow_version 2.x
from tensorflow.python.client import device_lib
# print(device_lib.list_local_devices())
# <codecell>
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import binary_net
seed = 0
batch_size = 100
momentum = .9
units = 4096
# units = 2048
# units = 128
hidden_layers = 3
epochs = 1000
dropout_in = .2
dropout_hidden = .5
# w_lr_scale = 1
w_lr_scale = "Glorot"
lr_initial = .003
lr_final = .0000003
lr_decay = (lr_final / lr_initial) ** (1 / epochs)
save_path = "checkpoints/mnist_parameters"
np.random.seed(seed)
tf.random.set_seed(seed)
# <codecell>
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
path="mnist.npz")
# Convert to [-1, 1].
x_train = (2 * (x_train.reshape(-1, 784) / 255) - 1).astype(np.float32)
x_test = (2 * (x_test.reshape(-1, 784) / 255) - 1).astype(np.float32)
# Convert to {-1, 1}.
y_train = (2 * tf.one_hot(y_train, 10) - 1).numpy()
y_test = (2 * tf.one_hot(y_test, 10) - 1).numpy()
x_val, x_train = x_train[50000:], x_train[:50000]
y_val, y_train = y_train[50000:], y_train[:50000]
# <codecell>
inputs = tf.keras.Input(shape=(784,))
x = layers.Dropout(dropout_in)(inputs)
for i in range(hidden_layers):
x = binary_net.Dense(units, w_lr_scale=w_lr_scale)(x)
x = layers.BatchNormalization(momentum=momentum, epsilon=1e-4)(x)
x = layers.Activation(binary_net.sign_d_clipped)(x)
x = layers.Dropout(dropout_hidden)(x)
x = binary_net.Dense(10, w_lr_scale=w_lr_scale)(x)
outputs = layers.BatchNormalization(momentum=momentum, epsilon=1e-4)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
def schedule(epoch, lr):
return lr * lr_decay
callback = tf.keras.callbacks.LearningRateScheduler(schedule)
callback.set_model(model)
opt = tf.keras.optimizers.Adam(lr_initial / lr_decay, epsilon=1e-8)
model.compile(optimizer=opt,
loss=tf.keras.losses.squared_hinge,
metrics=[tf.keras.losses.squared_hinge,
tf.keras.metrics.CategoricalAccuracy()])
# <codecell>
# model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, callbacks=[callback], validation_data=(x_val, y_val))
binary_net.train(model, x_train, y_train, batch_size, epochs, callback, x_val, y_val, save_path)
model.evaluate(x_test, y_test, batch_size=batch_size)
| [
"tensorflow.random.set_seed",
"binary_net.Dense",
"tensorflow.one_hot",
"numpy.random.seed",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.metrics.CategoricalAccuracy",
"tensorflow.keras.Input",
"tensorflow.keras.datasets.mnist.load_data",
"tens... | [((550, 570), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (564, 570), True, 'import numpy as np\n'), ((571, 595), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (589, 595), True, 'import tensorflow as tf\n'), ((650, 701), 'tensorflow.keras.datasets.mnist.load_data', 'tf.keras.datasets.mnist.load_data', ([], {'path': '"""mnist.npz"""'}), "(path='mnist.npz')\n", (683, 701), True, 'import tensorflow as tf\n'), ((1122, 1150), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': '(784,)'}), '(shape=(784,))\n', (1136, 1150), True, 'import tensorflow as tf\n'), ((1578, 1624), 'tensorflow.keras.Model', 'tf.keras.Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (1592, 1624), True, 'import tensorflow as tf\n'), ((1687, 1737), 'tensorflow.keras.callbacks.LearningRateScheduler', 'tf.keras.callbacks.LearningRateScheduler', (['schedule'], {}), '(schedule)\n', (1727, 1737), True, 'import tensorflow as tf\n'), ((1770, 1832), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(lr_initial / lr_decay)'], {'epsilon': '(1e-08)'}), '(lr_initial / lr_decay, epsilon=1e-08)\n', (1794, 1832), True, 'import tensorflow as tf\n'), ((2167, 2267), 'binary_net.train', 'binary_net.train', (['model', 'x_train', 'y_train', 'batch_size', 'epochs', 'callback', 'x_val', 'y_val', 'save_path'], {}), '(model, x_train, y_train, batch_size, epochs, callback,\n x_val, y_val, save_path)\n', (2183, 2267), False, 'import binary_net\n'), ((1155, 1181), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['dropout_in'], {}), '(dropout_in)\n', (1169, 1181), False, 'from tensorflow.keras import layers\n'), ((1451, 1494), 'binary_net.Dense', 'binary_net.Dense', (['(10)'], {'w_lr_scale': 'w_lr_scale'}), '(10, w_lr_scale=w_lr_scale)\n', (1467, 1494), False, 'import binary_net\n'), ((1508, 1568), 'tensorflow.keras.layers.BatchNormalization', 'layers.BatchNormalization', ([], {'momentum': 'momentum', 'epsilon': '(0.0001)'}), '(momentum=momentum, epsilon=0.0001)\n', (1533, 1568), False, 'from tensorflow.keras import layers\n'), ((1229, 1275), 'binary_net.Dense', 'binary_net.Dense', (['units'], {'w_lr_scale': 'w_lr_scale'}), '(units, w_lr_scale=w_lr_scale)\n', (1245, 1275), False, 'import binary_net\n'), ((1287, 1347), 'tensorflow.keras.layers.BatchNormalization', 'layers.BatchNormalization', ([], {'momentum': 'momentum', 'epsilon': '(0.0001)'}), '(momentum=momentum, epsilon=0.0001)\n', (1312, 1347), False, 'from tensorflow.keras import layers\n'), ((1357, 1401), 'tensorflow.keras.layers.Activation', 'layers.Activation', (['binary_net.sign_d_clipped'], {}), '(binary_net.sign_d_clipped)\n', (1374, 1401), False, 'from tensorflow.keras import layers\n'), ((1413, 1443), 'tensorflow.keras.layers.Dropout', 'layers.Dropout', (['dropout_hidden'], {}), '(dropout_hidden)\n', (1427, 1443), False, 'from tensorflow.keras import layers\n'), ((1989, 2027), 'tensorflow.keras.metrics.CategoricalAccuracy', 'tf.keras.metrics.CategoricalAccuracy', ([], {}), '()\n', (2025, 2027), True, 'import tensorflow as tf\n'), ((910, 933), 'tensorflow.one_hot', 'tf.one_hot', (['y_train', '(10)'], {}), '(y_train, 10)\n', (920, 933), True, 'import tensorflow as tf\n'), ((961, 983), 'tensorflow.one_hot', 'tf.one_hot', (['y_test', '(10)'], {}), '(y_test, 10)\n', (971, 983), True, 'import tensorflow as tf\n')] |
#implemnet Logistic Regression via Numpy
import numpy as np
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- number of features in a given example
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""
w = np.zeros([dim,1]) # dimx1
b = 0
assert(w.shape == (dim, 1))
assert(isinstance(b, float) or isinstance(b, int))
return w, b
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
s = 1/(1+np.exp(-z))
return s
def propagate(w, b, X, Y):
"""
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (features, #examples)
Y -- true "label" vector of size (1, #examples)
Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b
"""
m = X.shape[1]
A = sigmoid(np.dot(w.T, X)+b) # compute activation
cost = - 1/m * np.sum(Y*np.log(A) + (1-Y)*np.log(1-A)) #compute cost
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = 1/m * np.dot(X,(A-Y).T)
db = 1/m * np.sum(A-Y)
assert(dw.shape == w.shape)
assert(db.dtype == float)
cost = np.squeeze(cost)
assert(cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
"""
This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of shape (features, #examples)
Y -- true "label" vector of shape (1, #examples)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- True to print the loss every 100 steps
Returns:
params -- dictionary containing the weights w and bias b
grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
"""
costs = []
for i in range(num_iterations):
# Run propagation
grads, cost = propagate(w,b,X,Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w - learning_rate * dw
b = b - learning_rate * db
# Record the costs
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training iterations
if print_cost and i % 100 == 0:
print ("Cost after iteration %i: %f" %(i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
def predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (features, #examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
m = X.shape[1]
Y_prediction = np.zeros((1,m))
w = w.reshape(X.shape[0], 1)
# Compute vector "A" predicting the probabilities of a cat being present in the picture
A = sigmoid(np.dot(w.T,X)+b)
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
if (A[0][i] > 0.5):
Y_prediction[0][i] = 1
else:
Y_prediction[0][i] = 0
assert(Y_prediction.shape == (1, m))
return Y_prediction
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations
Returns:
d -- dictionary containing information about the model.
"""
#1. initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
#2. Gradient descent
parameters, grads, costs = optimize(w,b,X_train,Y_train,num_iterations, learning_rate, print_cost)
#3. Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
#4. Predict test/train set examples
Y_prediction_test = predict(w,b,X_test)
Y_prediction_train = predict(w,b,X_train)
#5. Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train" : Y_prediction_train,
"w" : w,
"b" : b,
"learning_rate" : learning_rate,
"num_iterations": num_iterations}
return d
#Run the following cell to train your model.
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True) | [
"numpy.sum",
"numpy.log",
"numpy.abs",
"numpy.zeros",
"numpy.exp",
"numpy.squeeze",
"numpy.dot"
] | [((396, 414), 'numpy.zeros', 'np.zeros', (['[dim, 1]'], {}), '([dim, 1])\n', (404, 414), True, 'import numpy as np\n'), ((1522, 1538), 'numpy.squeeze', 'np.squeeze', (['cost'], {}), '(cost)\n', (1532, 1538), True, 'import numpy as np\n'), ((3656, 3672), 'numpy.zeros', 'np.zeros', (['(1, m)'], {}), '((1, m))\n', (3664, 3672), True, 'import numpy as np\n'), ((1403, 1423), 'numpy.dot', 'np.dot', (['X', '(A - Y).T'], {}), '(X, (A - Y).T)\n', (1409, 1423), True, 'import numpy as np\n'), ((1436, 1449), 'numpy.sum', 'np.sum', (['(A - Y)'], {}), '(A - Y)\n', (1442, 1449), True, 'import numpy as np\n'), ((708, 718), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (714, 718), True, 'import numpy as np\n'), ((1233, 1247), 'numpy.dot', 'np.dot', (['w.T', 'X'], {}), '(w.T, X)\n', (1239, 1247), True, 'import numpy as np\n'), ((3813, 3827), 'numpy.dot', 'np.dot', (['w.T', 'X'], {}), '(w.T, X)\n', (3819, 3827), True, 'import numpy as np\n'), ((1300, 1309), 'numpy.log', 'np.log', (['A'], {}), '(A)\n', (1306, 1309), True, 'import numpy as np\n'), ((1318, 1331), 'numpy.log', 'np.log', (['(1 - A)'], {}), '(1 - A)\n', (1324, 1331), True, 'import numpy as np\n'), ((5631, 5667), 'numpy.abs', 'np.abs', (['(Y_prediction_train - Y_train)'], {}), '(Y_prediction_train - Y_train)\n', (5637, 5667), True, 'import numpy as np\n'), ((5730, 5764), 'numpy.abs', 'np.abs', (['(Y_prediction_test - Y_test)'], {}), '(Y_prediction_test - Y_test)\n', (5736, 5764), True, 'import numpy as np\n')] |
"""
This is an attempt to recreate the deepmind DDQN algorithm to beat atari games:
https://arxiv.org/pdf/1509.06461.pdf
article and code that guided this attempt:
https://towardsdatascience.com/tutorial-double-deep-q-learning-with-dueling-network-architectures-4c1b3fb7f756
https://github.com/fg91/Deep-Q-Learning/blob/master/DQN.ipynb
"""
from datetime import datetime
from resource import getrusage, RUSAGE_SELF
import tensorflow as tf
import numpy as np
import gym, os, argparse, sys, time
parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if parent_dir not in sys.path:
sys.path.insert(1, parent_dir)
from utils.ExperienceBuffer import ExpBuf
from utils.BaseReplayQnet import BaseReplayQnet
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type=str, help='train, show')
# TODO: The epsilon process here doesn't match that of the example.
# TODO: consider having a 2 step anneal. Here we stop at 10% but that may
# make long terms planning hard for the network since the further into
# the future we go, the more likely its planning is to get messed up
# by a forced random action. Perhaps do 100% -> 10% over X steps, then
# hold random action at 10% for X steps, then anneal from 10% -> 1%
# over another X steps.
parser.add_argument('--e_i', type=float, default=1,
help="Initial chance of selecting a random action.")
parser.add_argument('--e_f', type=float, default=.05,
help="Final chance of selecting a random action.")
parser.add_argument(
'--e_anneal', type=int, default=int(8e6),
help='Number of transition replays over which to linearly anneal from e_i '
'to e_f.')
parser.add_argument(
'--ckpt_dir', type=str,
help='Folder to save checkpoints to.')
parser.add_argument('--restore_ckpt', type=str,
help='path to restore a ckpt from')
# TODO: the capacity from deepmind/example is 1M, but I don't have room for that on this computer
parser.add_argument(
'--exp_capacity', type=int, default=int(4e5),
help='Number of past experiences to hold for replay. (400k ~ 11GB)')
parser.add_argument(
'--begin_updates', type=int, default=int(5e4),
help='Number of experiences before begin to training begins.')
parser.add_argument(
'--batch_size', type=int, default=32,
help='Batch size for each update to the network (multiple of 8)')
parser.add_argument(
'--output_period', type=int, default=int(2e6),
help='Number of transition updates between outputs (print, checkpoint)')
parser.add_argument(
'--learning_rate', type=float, default=1e-5,
help="learning rate for the network. passed to the optimizer.")
parser.add_argument('--adam_epsilon', type=float, default=1e-8,
help='Constant used by AdamOptimizer')
parser.add_argument(
'--future_discount', type=float, default=0.99,
help="Rate at which to discount future rewards.")
parser.add_argument('--train_record_fname', type=str,
default="training-record-DDQNBreakout.txt",
help="Absolute path to file to save progress to (same as what is"
" printed to cmd line.")
parser.add_argument('--train_steps', type=int, default=int(100e6),
help="Number of transition replays to experience "
"(will update train_steps // batch_size times)")
parser.add_argument(
'--update_target_net_period', type=int, default=int(8e4),
help='Number of transition updates between copying main_net to target_net')
parser.add_argument(
'--show_random', type=bool, default=False,
help="Use random actions when mode=show at a rate of e_f")
parser.add_argument(
'--random_starts', type=int, default=30,
help='randomly perform stand still at beginning of episode.')
def preprocess_img(img):
"""
Images are converted from RGB to grayscale and downsampled by a factor of
2. Deepmind actually used a final 84x84 image by cropping since their GPU
wanted a square input for convolutions. We do not preprocess, rather we
store as uint8 for the sake of memory.
:param img: Atari image (210, 160, 3)
:return: Grayscale downsample version (85, 80)
"""
return np.mean(img[::2, ::2], axis=2).astype(np.uint8)[15:100, :]
class DDQNBreakoutQnet(BaseReplayQnet):
"""
Class to perform basic Q learning
"""
def __init__(self, input_shape, n_actions, batch_size, optimizer,
exp_buf_capacity, discount, update_target_net_period,
is_training):
"""
:param input_shape:
:param n_actions:
:param batch_size:
:param optimizer:
:param exp_buf_capacity:
:param discount:
:param update_target_net: Number of updates between copying main_net to target_net.
"""
self.is_training = is_training
BaseReplayQnet.__init__(
self, input_shape, n_actions, batch_size, optimizer,
ExpBuf(exp_buf_capacity), discount)
self.target_net = self.make_nn('target_net')
self.transition_updates = 0
self.update_target_net_period = update_target_net_period
main_vars = tf.trainable_variables("main_net")
target_vars = tf.trainable_variables("target_net")
self.update_target_net_ops = [t_var.assign(m_var.value())
for m_var, t_var
in zip(main_vars, target_vars)]
def _create_inputs(self):
"""
Create tensors to take batches of inputs
- state = 4 (105, 80) images stacked together.
- action = used to replay an action taken before.
- target_vals = "true" Q value for calculating loss.
"""
self.state_input = tf.placeholder(shape=(None, *self.input_shape),
dtype=tf.uint8)
self.action_input = tf.placeholder(shape=None, dtype=tf.int32)
self.target_vals_input = tf.placeholder(shape=None, dtype=tf.float32)
def make_nn_impl(self):
"""
Make a NN to take in a batch of states (3 preprocessed images) with
an output of size 3 (stay, left, right). No activation function is
applied to the final output.
:return:
"""
# TODO: think about putting the normalization here so don't need to
# worry about it everywhere we use the NN.
normalized_input = tf.to_float(self.state_input) / 128. - 1
print('normalized_input', normalized_input)
init = tf.variance_scaling_initializer(scale=2)
conv1 = tf.layers.conv2d(
normalized_input, filters=32, kernel_size=(8, 8), strides=4,
activation=tf.nn.relu, kernel_initializer=init, use_bias=False,
name="conv1")
print('conv1', conv1)
conv2 = tf.layers.conv2d(
conv1, filters=64, kernel_size=(4, 4), strides=2, use_bias=False,
activation=tf.nn.relu, kernel_initializer=init, name="conv2")
print('conv2', conv2)
conv3 = tf.layers.conv2d(
conv2, filters=64, kernel_size=(3, 3), strides=1, use_bias=False,
activation=tf.nn.relu, kernel_initializer=init, name="conv3")
print('conv3', conv3)
# TODO: example uses 1024 filters, but I don't have a GPU so trying with a smaller network
conv4 = tf.layers.conv2d(
conv3, filters=512, kernel_size=(7, 6), strides=1, use_bias=False,
activation=tf.nn.relu, kernel_initializer=init, name="conv4")
print('conv4', conv4)
# Deuling networks - split now into value network, which should learn
# the value of being in a given state, and advantage network, which
# should learn the relative advantage of each possible action.
vstream, astream = tf.split(conv4, 2, 3)
vstream = tf.layers.dropout(tf.layers.flatten(vstream), rate=.2,
training=self.is_training)
print('vstream', vstream)
astream = tf.layers.dropout(tf.layers.flatten(astream), rate=.2,
training=self.is_training)
print('astream', astream)
value = tf.layers.dense(
vstream, units=1, kernel_initializer=init, name="value")
print('value', value)
advantage = tf.layers.dense(
astream, units=self.n_actions, kernel_initializer=init,
name="advantage")
print('advantage', advantage)
print() # Add empty line after finishing a network.
# Subtract the average advantage since advantage should only be used to
# differentiate between actions, not change the net value of the we
# expect to get from this state.
avg_advantage = tf.reduce_mean(advantage, axis=1, keepdims=True)
return value + advantage - avg_advantage
def loss_fn(self, expected, actual):
"""
A function for calculating the loss of the neural network. Common
examples include RootMeanSquare or HuberLoss.
:param expected: a batch of target_vals
:param actual: a batch of ouputs from the network
:return: a batch of losses.
"""
return tf.losses.huber_loss(labels=expected, predictions=actual,
reduction=tf.losses.Reduction.NONE)
def update(self, sess):
"""
Perform a basic Q learning update by taking a batch of experiences from
memory and replaying them.
:param sess: tf.Session()
"""
# Every T updates, copy the main_net, which is the one being updated,
# to target_net so that the Q value predictions are up to date. Done
# before frame_update+= so that on the first update main_net is copied
# to target_net.
self.update_target_net(sess)
self.transition_updates += self.batch_size
# Get a batch of past experiences.
states, actions, rewards, next_states, not_terminals = \
self.exp_buf.sample(self.batch_size)
# Double DQN - To predict the 'true' Q value, we use main_net to predict
# the action we should take in the next state, and use target_net to
# predict the value we expect to get from taking that action.
next_actions = self.predict(sess, next_states)
fullQ = sess.run(self.target_net,
feed_dict={self.state_input: next_states})
nextQ = fullQ[range(self.batch_size), next_actions]
# Discounted future value:
# trueQ = r + discount * Q_target(next_state, next_action)
# If this is a terminal term, trueQ = r
target_vals = rewards + not_terminals * self.discount * nextQ
# Calculate the value of being back in state and performing action. Then
# compare that the the expected value just calculated. This is used to
# compute the error for feedback. Then backpropogate the loss so that
# the network can update.
_ = sess.run(self.train_op,
feed_dict={
self.state_input: states,
self.action_input: actions,
self.target_vals_input: target_vals})
def update_target_net(self, sess):
if self.transition_updates % self.update_target_net_period == 0:
for copy_op in self.update_target_net_ops:
sess.run(copy_op)
def get_qnet(args, scope=''):
"""
Wrapper for getting the Breakout network so don't have to copy and paste
the same params each time.
"""
assert args.batch_size % 8 == 0, "batch_size must be a multiple of 8"
optimizer=tf.train.AdamOptimizer(learning_rate=args.learning_rate,
epsilon=args.adam_epsilon)
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
return DDQNBreakoutQnet(
input_shape = (85, 80, 4), n_actions=4, batch_size=args.batch_size,
optimizer=optimizer, exp_buf_capacity=args.exp_capacity,
update_target_net_period=args.update_target_net_period,
discount=args.future_discount, is_training=(args.mode=='train'))
def play_episode(args, sess, env, qnet, e):
"""
Actually plays a single game and performs updates once we have enough
experiences.
:param args: parser.parse_args
:param sess: tf.Session()
:param env: gym.make()
:param qnet: class which holds the NN to play and update.
:param e: chance of a random action selection.
:return: reward earned in the game, update value of e, transitions updated
against.
"""
done = False
_ = env.reset()
reward = 0 # total reward for this episode
turn = 0
transitions = 0 # updates * batch_size
terminal = True # Anytime we lose a life, and beginning of episode.
while not done:
if terminal:
terminal = False
# To make sure that the agent doesn't just learn to set up well for
# the way the game starts, begin the game by not doing anything and
# letting the ball move.
for _ in range(np.random.randint(1, args.random_starts)):
# Perform random actions at the beginning so the network doesn't
# just learn a sequence of steps to always take.
img, _, done, info = env.step(env.action_space.sample())
img = preprocess_img(img)
state = np.stack((img, img, img, img), axis=2)
lives = info['ale.lives']
if done:
# If lost our last life during random_start, nothing left to play
break
# Perform an action
action = qnet.predict(sess, np.array([state]))[0]
if np.random.rand(1) < e:
action = qnet.rand_action()
img, r, done, info = env.step(action)
# Store as an experience
img = np.reshape(preprocess_img(img), (85, 80, 1))
next_state = np.concatenate((state[:, :, 1:], img), axis=2)
if info['ale.lives'] < lives:
terminal = True
qnet.add_experience(state, action, r, next_state, terminal)
# Updates
if qnet.exp_buf_size() > args.begin_updates and\
turn % (qnet.batch_size // 8) == 0:
# Once we have enough experiences in the buffer we can
# start learning. We want to use each experience on average 8 times
# so that's why for a batch size of 8 we would update every turn.
qnet.update(sess)
transitions += qnet.batch_size
if e > args.e_f:
# Reduce once for every update on 8 states. This makes e
# not dependent on the batch_size.
e -= (qnet.batch_size*(args.e_i - args.e_f)) / args.e_anneal
# Prep for the next turn
state = next_state
reward += r
turn += 1
return reward, e, transitions
def write_output(args, sess, saver, last_output_ep, e, rewards,
transitions):
"""
Periodically we want to create some sort of output (printing, saving, etc...).
This function does that.
:param args: parser.parse_args
:param sess: tf.Session()
:param saver: tf.train.Saver()
:param last_output_ep: number of episodes played at last output
:param e: chance of random action
:param rewards: list of rewards for each episode played.
:param transitions: Number of transitions replayed.
:param qnet: NN being trained
:return:
"""
num_eps = len(rewards) - last_output_ep
time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
mem_usg_str = \
'mem_usage={:0.2f}GB'.format(getrusage(RUSAGE_SELF).ru_maxrss / 2**20)
episode_str = 'episode=' + str(len(rewards))
reward_str = 'avg_reward_last_' + str(num_eps) + '_games=' + \
str(sum(rewards[-num_eps:]) // num_eps)
e_str = 'e={:0.2f}'.format(e)
transitions_str ='training_step=' + str(transitions)
output_str = ' '.join((time_str, mem_usg_str, episode_str, reward_str,
e_str, transitions_str))
print(output_str)
with open(os.path.join(args.ckpt_dir, args.train_record_fname), 'a') as f:
f.write(output_str + '\n')
# save the model
model_name = 'model-DDQNBreakout-' + str(transitions) + '.ckpt'
saver.save(sess, os.path.join(args.ckpt_dir, model_name))
def train(args):
"""
This function trains a Neural Network on how to play brickbreaker. Is
meant to be identical to how Deepminds paper "Playing Atari with Deep
Reinforcement Learning" works. I use 3 images to make the state instead
of 4 since when using 4 I only had enough for 400k states in the buffer,
but now I can fit 600k and it still does well.
:param args: parser.parse_args
:return:
"""
with open(os.path.join(args.ckpt_dir, args.train_record_fname), 'a') as f:
f.write("DDQNBreakout -- begin training -- " + str(args) + "\n")
# TODO: Figure out a way to only hold each img once and then reconstruct
# the states from pointers to them. Would probs point to the last and grab
# most_recent[-3:] and repeat an initial state 4x in the buffer like we
# do to create the initial state now.
tf.reset_default_graph()
env = gym.make('BreakoutDeterministic-v4')
qnet = get_qnet(args)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
# Don't want to change the graph once we begin playing the game.
tf.get_default_graph().finalize()
with tf.Session() as sess:
sess.run(init)
e = args.e_i
last_output_ep = 0
rewards = []
transitions = 0 # number of transitions updated against
next_output = args.output_period
while transitions < args.train_steps:
r, e, t = play_episode(args, sess, env, qnet, e)
if transitions == 0 and t > 0:
# Output status from before training starts.
write_output(args, sess, saver, last_output_ep, e, rewards,
transitions)
last_output_ep = len(rewards)
transitions += t
rewards.append(r)
if transitions > next_output:
# Regular output during training.
write_output(args, sess, saver, last_output_ep, e, rewards,
transitions)
next_output += args.output_period
last_output_ep = len(rewards)
with open(os.path.join(args.ckpt_dir, args.train_record_fname), 'a') as f:
f.write('\n\n')
def show_game(args):
env = gym.make('BreakoutDeterministic-v4')
tf.reset_default_graph()
qnet = get_qnet(args)
saver = tf.train.Saver()
tf.get_default_graph().finalize()
with tf.Session() as sess:
saver.restore(sess, args.restore_ckpt)
done = False
img = env.reset()
_ = env.render()
img = preprocess_img(img)
state = np.stack((img, img, img, img), axis=2)
reward, turns = 0, 0
while not done:
t1 = time.time()
action = qnet.predict(sess, np.array([state]))[0]
if args.show_random and np.random.rand(1) < args.e_f:
action = 1 # Doesn't seem to like restarting
img, r, done, _ = env.step(action)
_ = env.render()
img = np.reshape(preprocess_img(img), (85, 80, 1))
state = np.concatenate((state[:, :, 1:], img), axis=2)
reward += r
turns += 1
time.sleep(max(0, .025 - (time.time() - t1)))
print('turns =', turns, ' reward =', reward)
def main():
args = parser.parse_args(sys.argv[1:])
if args.mode == 'show':
assert args.restore_ckpt != '', 'Must provide a checkpoint to show.'
args.exp_capacity = 0
show_game(args)
elif args.mode == 'train':
assert args.ckpt_dir != '', \
'Must provide a directory to save checkpoints to.'
train(args)
else:
assert False, "Must provide a mode to run in: train, show."
if __name__ == '__main__':
main()
| [
"argparse.ArgumentParser",
"tensorflow.trainable_variables",
"tensorflow.reset_default_graph",
"numpy.mean",
"numpy.random.randint",
"utils.ExperienceBuffer.ExpBuf",
"tensorflow.get_default_graph",
"tensorflow.split",
"os.path.join",
"resource.getrusage",
"tensorflow.variable_scope",
"tensorfl... | [((738, 763), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (761, 763), False, 'import gym, os, argparse, sys, time\n'), ((607, 637), 'sys.path.insert', 'sys.path.insert', (['(1)', 'parent_dir'], {}), '(1, parent_dir)\n', (622, 637), False, 'import gym, os, argparse, sys, time\n'), ((11690, 11778), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'args.learning_rate', 'epsilon': 'args.adam_epsilon'}), '(learning_rate=args.learning_rate, epsilon=args.\n adam_epsilon)\n', (11712, 11778), True, 'import tensorflow as tf\n'), ((17303, 17327), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (17325, 17327), True, 'import tensorflow as tf\n'), ((17338, 17374), 'gym.make', 'gym.make', (['"""BreakoutDeterministic-v4"""'], {}), "('BreakoutDeterministic-v4')\n", (17346, 17374), False, 'import gym, os, argparse, sys, time\n'), ((17413, 17446), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (17444, 17446), True, 'import tensorflow as tf\n'), ((17459, 17475), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (17473, 17475), True, 'import tensorflow as tf\n'), ((18691, 18727), 'gym.make', 'gym.make', (['"""BreakoutDeterministic-v4"""'], {}), "('BreakoutDeterministic-v4')\n", (18699, 18727), False, 'import gym, os, argparse, sys, time\n'), ((18732, 18756), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (18754, 18756), True, 'import tensorflow as tf\n'), ((18796, 18812), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (18810, 18812), True, 'import tensorflow as tf\n'), ((543, 569), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (559, 569), False, 'import gym, os, argparse, sys, time\n'), ((5175, 5209), 'tensorflow.trainable_variables', 'tf.trainable_variables', (['"""main_net"""'], {}), "('main_net')\n", (5197, 5209), True, 'import tensorflow as tf\n'), ((5232, 5268), 'tensorflow.trainable_variables', 'tf.trainable_variables', (['"""target_net"""'], {}), "('target_net')\n", (5254, 5268), True, 'import tensorflow as tf\n'), ((5765, 5828), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '(None, *self.input_shape)', 'dtype': 'tf.uint8'}), '(shape=(None, *self.input_shape), dtype=tf.uint8)\n', (5779, 5828), True, 'import tensorflow as tf\n'), ((5899, 5941), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': 'None', 'dtype': 'tf.int32'}), '(shape=None, dtype=tf.int32)\n', (5913, 5941), True, 'import tensorflow as tf\n'), ((5975, 6019), 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': 'None', 'dtype': 'tf.float32'}), '(shape=None, dtype=tf.float32)\n', (5989, 6019), True, 'import tensorflow as tf\n'), ((6541, 6581), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {'scale': '(2)'}), '(scale=2)\n', (6572, 6581), True, 'import tensorflow as tf\n'), ((6598, 6763), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['normalized_input'], {'filters': '(32)', 'kernel_size': '(8, 8)', 'strides': '(4)', 'activation': 'tf.nn.relu', 'kernel_initializer': 'init', 'use_bias': '(False)', 'name': '"""conv1"""'}), "(normalized_input, filters=32, kernel_size=(8, 8), strides=\n 4, activation=tf.nn.relu, kernel_initializer=init, use_bias=False, name\n ='conv1')\n", (6614, 6763), True, 'import tensorflow as tf\n'), ((6837, 6986), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['conv1'], {'filters': '(64)', 'kernel_size': '(4, 4)', 'strides': '(2)', 'use_bias': '(False)', 'activation': 'tf.nn.relu', 'kernel_initializer': 'init', 'name': '"""conv2"""'}), "(conv1, filters=64, kernel_size=(4, 4), strides=2, use_bias\n =False, activation=tf.nn.relu, kernel_initializer=init, name='conv2')\n", (6853, 6986), True, 'import tensorflow as tf\n'), ((7053, 7202), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['conv2'], {'filters': '(64)', 'kernel_size': '(3, 3)', 'strides': '(1)', 'use_bias': '(False)', 'activation': 'tf.nn.relu', 'kernel_initializer': 'init', 'name': '"""conv3"""'}), "(conv2, filters=64, kernel_size=(3, 3), strides=1, use_bias\n =False, activation=tf.nn.relu, kernel_initializer=init, name='conv3')\n", (7069, 7202), True, 'import tensorflow as tf\n'), ((7368, 7522), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['conv3'], {'filters': '(512)', 'kernel_size': '(7, 6)', 'strides': '(1)', 'use_bias': '(False)', 'activation': 'tf.nn.relu', 'kernel_initializer': 'init', 'name': '"""conv4"""'}), "(conv3, filters=512, kernel_size=(7, 6), strides=1,\n use_bias=False, activation=tf.nn.relu, kernel_initializer=init, name=\n 'conv4')\n", (7384, 7522), True, 'import tensorflow as tf\n'), ((7822, 7843), 'tensorflow.split', 'tf.split', (['conv4', '(2)', '(3)'], {}), '(conv4, 2, 3)\n', (7830, 7843), True, 'import tensorflow as tf\n'), ((8200, 8272), 'tensorflow.layers.dense', 'tf.layers.dense', (['vstream'], {'units': '(1)', 'kernel_initializer': 'init', 'name': '"""value"""'}), "(vstream, units=1, kernel_initializer=init, name='value')\n", (8215, 8272), True, 'import tensorflow as tf\n'), ((8336, 8429), 'tensorflow.layers.dense', 'tf.layers.dense', (['astream'], {'units': 'self.n_actions', 'kernel_initializer': 'init', 'name': '"""advantage"""'}), "(astream, units=self.n_actions, kernel_initializer=init,\n name='advantage')\n", (8351, 8429), True, 'import tensorflow as tf\n'), ((8772, 8820), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['advantage'], {'axis': '(1)', 'keepdims': '(True)'}), '(advantage, axis=1, keepdims=True)\n', (8786, 8820), True, 'import tensorflow as tf\n'), ((9221, 9319), 'tensorflow.losses.huber_loss', 'tf.losses.huber_loss', ([], {'labels': 'expected', 'predictions': 'actual', 'reduction': 'tf.losses.Reduction.NONE'}), '(labels=expected, predictions=actual, reduction=tf.\n losses.Reduction.NONE)\n', (9241, 9319), True, 'import tensorflow as tf\n'), ((11820, 11865), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'tf.AUTO_REUSE'}), '(scope, reuse=tf.AUTO_REUSE)\n', (11837, 11865), True, 'import tensorflow as tf\n'), ((13988, 14034), 'numpy.concatenate', 'np.concatenate', (['(state[:, :, 1:], img)'], {'axis': '(2)'}), '((state[:, :, 1:], img), axis=2)\n', (14002, 14034), True, 'import numpy as np\n'), ((16398, 16437), 'os.path.join', 'os.path.join', (['args.ckpt_dir', 'model_name'], {}), '(args.ckpt_dir, model_name)\n', (16410, 16437), False, 'import gym, os, argparse, sys, time\n'), ((17592, 17604), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (17602, 17604), True, 'import tensorflow as tf\n'), ((18860, 18872), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (18870, 18872), True, 'import tensorflow as tf\n'), ((19051, 19089), 'numpy.stack', 'np.stack', (['(img, img, img, img)'], {'axis': '(2)'}), '((img, img, img, img), axis=2)\n', (19059, 19089), True, 'import numpy as np\n'), ((4964, 4988), 'utils.ExperienceBuffer.ExpBuf', 'ExpBuf', (['exp_buf_capacity'], {}), '(exp_buf_capacity)\n', (4970, 4988), False, 'from utils.ExperienceBuffer import ExpBuf\n'), ((7880, 7906), 'tensorflow.layers.flatten', 'tf.layers.flatten', (['vstream'], {}), '(vstream)\n', (7897, 7906), True, 'import tensorflow as tf\n'), ((8050, 8076), 'tensorflow.layers.flatten', 'tf.layers.flatten', (['astream'], {}), '(astream)\n', (8067, 8076), True, 'import tensorflow as tf\n'), ((13477, 13515), 'numpy.stack', 'np.stack', (['(img, img, img, img)'], {'axis': '(2)'}), '((img, img, img, img), axis=2)\n', (13485, 13515), True, 'import numpy as np\n'), ((13765, 13782), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (13779, 13782), True, 'import numpy as np\n'), ((15613, 15627), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (15625, 15627), False, 'from datetime import datetime\n'), ((16187, 16239), 'os.path.join', 'os.path.join', (['args.ckpt_dir', 'args.train_record_fname'], {}), '(args.ckpt_dir, args.train_record_fname)\n', (16199, 16239), False, 'import gym, os, argparse, sys, time\n'), ((16887, 16939), 'os.path.join', 'os.path.join', (['args.ckpt_dir', 'args.train_record_fname'], {}), '(args.ckpt_dir, args.train_record_fname)\n', (16899, 16939), False, 'import gym, os, argparse, sys, time\n'), ((17549, 17571), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (17569, 17571), True, 'import tensorflow as tf\n'), ((18570, 18622), 'os.path.join', 'os.path.join', (['args.ckpt_dir', 'args.train_record_fname'], {}), '(args.ckpt_dir, args.train_record_fname)\n', (18582, 18622), False, 'import gym, os, argparse, sys, time\n'), ((18817, 18839), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (18837, 18839), True, 'import tensorflow as tf\n'), ((19161, 19172), 'time.time', 'time.time', ([], {}), '()\n', (19170, 19172), False, 'import gym, os, argparse, sys, time\n'), ((19522, 19568), 'numpy.concatenate', 'np.concatenate', (['(state[:, :, 1:], img)'], {'axis': '(2)'}), '((state[:, :, 1:], img), axis=2)\n', (19536, 19568), True, 'import numpy as np\n'), ((4206, 4236), 'numpy.mean', 'np.mean', (['img[::2, ::2]'], {'axis': '(2)'}), '(img[::2, ::2], axis=2)\n', (4213, 4236), True, 'import numpy as np\n'), ((6432, 6461), 'tensorflow.to_float', 'tf.to_float', (['self.state_input'], {}), '(self.state_input)\n', (6443, 6461), True, 'import tensorflow as tf\n'), ((13157, 13197), 'numpy.random.randint', 'np.random.randint', (['(1)', 'args.random_starts'], {}), '(1, args.random_starts)\n', (13174, 13197), True, 'import numpy as np\n'), ((13732, 13749), 'numpy.array', 'np.array', (['[state]'], {}), '([state])\n', (13740, 13749), True, 'import numpy as np\n'), ((15715, 15737), 'resource.getrusage', 'getrusage', (['RUSAGE_SELF'], {}), '(RUSAGE_SELF)\n', (15724, 15737), False, 'from resource import getrusage, RUSAGE_SELF\n'), ((19213, 19230), 'numpy.array', 'np.array', (['[state]'], {}), '([state])\n', (19221, 19230), True, 'import numpy as np\n'), ((19271, 19288), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (19285, 19288), True, 'import numpy as np\n'), ((19654, 19665), 'time.time', 'time.time', ([], {}), '()\n', (19663, 19665), False, 'import gym, os, argparse, sys, time\n')] |
"""
HeurOSPF proposed in
<NAME> and <NAME>. Internet traffic engineering by optimizing OSPF weights.
In Proc. IEEE INFOCOM, volume 2, pages 519–528. IEEE, 2000. doi:10.1109/INFCOM.2000.
832225.
"""
import random
import time
import networkit as nk
import numpy as np
from algorithm.generic_sr import GenericSR
from algorithm.segment_routing.sr_utility import SRUtility
from utility import utility
class HeurOSPFWeights(GenericSR):
BIG_M = 10 ** 9
def __init__(self, nodes: list, links: list, demands: list, weights: dict = None, waypoints: dict = None,
hashtable_size: int = 16, sec_hashtable_size_multiplier: int = 20, max_weight: int = 20,
iterations: int = 5000, perturb_it: int = 300, seed: float = 0, time_out: int = None,
limit_not_improved=2500, **kwargs):
super().__init__(nodes, links, demands, weights, waypoints)
self.__seed = seed
np.random.seed(self.__seed)
# topology info
self.__capacities = self.__extract_capacity_dict(links) # dict with {(u,v):c, ..}
self.__links = list(self.__capacities.keys()) # list with [(u,v), ..]
self.__n = len(nodes)
self.__max_weight = max_weight # possible values in the weights vector are in [0, 1,..., max_weight]
# demand segmentation and aggregate to matrix
# store all target nodes for Some pairs shortest path algorithm
self.__waypoints = waypoints
self.__demands, self.__targets = self.__preprocess_demand_segmentation(waypoints, demands)
# initial weights
self.__init_weights = weights
# neighborhood search
self.__iterations = iterations
self.__perturb_it = perturb_it
# hashtable
self.__hash_collision_counter = 0
self.__hash_misses = 0
self.__l = hashtable_size
self.__l2 = int(np.log2(len(links) * sec_hashtable_size_multiplier))
self.__hashtable1 = None
self.__hashtable2 = None
# networKit graph and some pairs shortest path (SPSP) algorithm
self.__g = None
self.__spsp = None
# for exit criteria (1) timeout; (2) # iterations of no improvement
self.__start_time = None
self.__timeout = time_out if time_out else utility.TIME_LIMIT - 10
self.__limit_not_improved = limit_not_improved
self.__init_global_hashtable()
self.__init_secondary_hashtable()
self.__init_graph()
return
@staticmethod
def __preprocess_demand_segmentation(segments, demands):
""" Prepares input (compatibility reasons) """
targets = set()
demands_prepared = demands
demand_matrix = dict()
if segments is not None:
demands_prepared = SRUtility.get_segmented_demands(segments, demands)
demands_prepared = [(s, t, d) for s, t, d in demands_prepared]
for s, t, d in demands_prepared:
targets.add(t)
if (s, t) not in demand_matrix:
demand_matrix[s, t] = 0
demand_matrix[s, t] += d
return demand_matrix, list(targets)
@staticmethod
def __extract_capacity_dict(links):
""" Converts the list of link/capacities into a capacity dict (compatibility reasons)"""
return {(u, v): c for u, v, c in links}
@staticmethod
def __get_link_cost(link_load):
""" Return cost value of a single link load """
if link_load >= 2:
return int(50000 * link_load)
if link_load >= 11 / 10:
return int(5000 * link_load)
if link_load >= 1:
return int(500 * link_load)
if link_load >= 9 / 10:
return int(70 * link_load)
if link_load >= 2 / 3:
return int(10 * link_load)
if link_load >= 1 / 3:
return int(3 * link_load)
else:
return int(1 * link_load)
def __hash(self, weights: tuple):
""" Computes hashvalues of a weights vector """
hash_val = hash(weights)
h1 = hash_val % 2 ** self.__l
h2 = hash_val % 2 ** self.__l2
return h1, h2
def __init_global_hashtable(self):
""" Initializes global hash table used to avoid cycling and recomputation of known results """
self.__hashtable1 = np.zeros((2 ** self.__l), dtype=bool)
return
def __init_secondary_hashtable(self):
""" Initializes secondary hash table to (1) speed up and (2) diversify neighborhood search """
self.__hashtable2 = np.zeros((2 ** self.__l2), dtype=bool)
return
def __get_random_weights(self):
""" Maps links to randomly chosen weights in the range of [1/4 * max_weight, 3/4 * max_weight] """
rnd_weights = np.random.randint(
low=self.__max_weight / 4, high=self.__max_weight * 3 / 4, size=(len(self.__links),))
random_weights_dict = dict(zip(self.__links, rnd_weights))
return random_weights_dict
def __init_graph(self):
""" Create networKit graph, add weighted edges and create spsp (some pairs shortest path) object """
self.__g = nk.Graph(weighted=True, directed=True, n=self.__n)
for u, v in self.__links:
self.__g.addEdge(u, v, 1)
self.__spsp = nk.distance.SPSP(self.__g, sources=self.__targets)
def __update_nkit_graph_weights(self, weights):
""" Updates weight in networKit graph """
for u, v, w in self.__g.iterEdgesWeights():
# Note: the weights are reversed since we need the distance from all sources to a specific target
if w != weights[v, u]:
self.__g.setWeight(u, v, weights[v, u])
return
def __reset_secondary_hashtable(self):
""" Sets all values in the hashtable to False; called after each successful iteration """
self.__hashtable2[self.__hashtable2] = False
return
def __get_distances(self):
""" Recomputes the shortest path for 'some' pairs """
self.__spsp.run()
return self.__spsp.getDistances()
def __perturb(self, weights):
""" Perturbs current solution to escape local minima """
new_weights = weights.copy()
n_samples = max(3, int(len(self.__links) * 0.1))
inds = np.random.choice(len(self.__links), n_samples)
rand_links = [self.__links[ind] for ind in inds]
for u, v in rand_links:
w_diff = self.__max_weight
while new_weights[u, v] + w_diff > self.__max_weight or new_weights[u, v] + w_diff < 1:
w_diff = random.randint(-2, 2)
new_weights[u, v] += w_diff
return new_weights
def __get_neighbor(self, x: int, t_idx: int, distances: dict, weights: dict, loads: dict):
""" Chooses random neighbor vector w_a' """
weights = weights.copy()
# choose theta (load threshold) at random
theta = np.random.uniform(low=0.25, high=1)
# retrieve neighbors of x
neighbors = list(self.__g.iterNeighbors(x))
# retrieve min w(Pi)
min_w_pi = self.BIG_M
for x_i in neighbors:
distance_x_i = distances[t_idx][x_i]
min_w_pi = min(min_w_pi, distance_x_i)
# filter overloaded adjacent arcs
candidates = list()
min_rhs = self.__max_weight - 1
for x_i in neighbors:
if distances[t_idx][x_i] - min_w_pi > self.__max_weight:
min_rhs = min(min_rhs, distances[t_idx][x_i] + weights[x, x_i])
continue
candidates.append(x_i)
# compute w_star
subset_b = candidates.copy()
w_star = self.BIG_M
while w_star > min_rhs:
for x_i in subset_b:
if 1 + distances[t_idx][x_i] > min_rhs:
subset_b.remove(x_i)
if len(subset_b) == 0:
return weights
w_star = max(1 + distances[t_idx][x_i] for x_i in subset_b)
# compute new neighbor weight vector
for x_i in subset_b:
new_weight = w_star - distances[t_idx][x_i]
if loads[x, x_i] <= theta:
weights[x, x_i] = new_weight
else:
# if link is overloaded link weight can only be increased
weights[x, x_i] = max(weights[x, x_i], new_weight)
return weights
def __add_loads_for(self, t_idx, weights, demands, acc_flows, distances):
""" Computes flow path from all sources to node t and returns the updated acc_flows dict"""
current_flows = np.zeros((self.__n, self.__n), np.float)
t = self.__targets[t_idx]
A_out = {y: list() for y in range(self.__n)}
A_in = {y: list() for y in range(self.__n)}
reverse_indices = range(self.__n - 1, -1, -1)
for x, y in weights:
if weights[(x, y)] == distances[t_idx][x] - distances[t_idx][y]:
A_out[x].append(y)
A_in[y].append(x)
y_map = dict(zip(reverse_indices, np.array(distances[t_idx]).argsort()))
for y_idx in range(self.__n - 1):
y = y_map[y_idx]
d_yt = demands[y, t] if (y, t) in demands else 0
acc_demand_to_t = d_yt + np.sum(current_flows[y])
if acc_demand_to_t <= 0:
continue
l = acc_demand_to_t / len(A_out[y])
for z in A_out[y]:
current_flows[z][y] = l
acc_flows[y, z] += l
return acc_flows
def __evaluate_cost(self, weights):
"""
evaluates cost of weight setting
:return: max link utilization, distances, link loads
"""
acc_flows = {(i, j): 0 for i, j in self.__links}
self.__update_nkit_graph_weights(weights)
distances = self.__get_distances()
for t_idx in range(len(self.__targets)):
acc_flows = self.__add_loads_for(t_idx, weights, self.__demands, acc_flows, distances)
loads = dict()
cost = 0
for u, v in self.__links:
loads[u, v] = acc_flows[u, v] / self.__capacities[u, v]
cost += self.__get_link_cost(loads[u, v])
return cost, distances, loads
def __explore_neighborhood(self, sample_size: int, c_weights, c_distances, c_loads):
""" for a given weights vector find the best neighbor weights vector"""
best_weights, best_cost, best_loads, best_distances = c_weights, self.BIG_M, c_loads, c_distances
h1 = None
for _ in range(sample_size):
# choose src and destination
t_idx = np.random.randint(len(self.__targets))
x = self.__targets[t_idx]
while x == self.__targets[t_idx]:
x = np.random.randint(self.__n)
# retrieve neighbor weights vector
n_weights = self.__get_neighbor(x, t_idx, c_distances, c_weights, c_loads)
# hash solution
h1, h2 = self.__hash(tuple(n_weights.values()))
if self.__hashtable1[h1]:
self.__hash_collision_counter += 1
continue
if self.__hashtable2[h2]:
self.__hash_collision_counter += 1
continue
self.__hash_misses += 1
self.__hashtable2[h2] = True
# evaluate cost and compare
n_cost, n_distances, n_loads = self.__evaluate_cost(n_weights)
if best_cost >= n_cost:
best_weights, best_cost, best_loads, best_distances = n_weights, n_cost, n_loads, n_distances
self.__hashtable1[h1] = True
return best_weights, best_cost, best_loads, best_distances
def __ospf_heuristic(self):
""" main procedure """
# evaluate initial weights
weights = self.__init_weights if self.__init_weights else self.__get_random_weights()
cost, distances, loads = self.__evaluate_cost(weights)
# bc_ := best cost
# bu_ := best (= lowest) max link utilization
bc_cost = bu_cost = cost
bc_util = bu_util = self.BIG_M
bc_weights = bu_weights = weights
bc_loads = bu_loads = loads
# pr_cost/pr_max_util stores results from last neighborhood search iteration
pr_cost = pr_util = self.BIG_M
# initially 20% of the neighborhood size gets evaluated
neighborhood_size = len(self.__targets) * (self.__n - 1)
sample_factor = 0.2
count_not_better_as_pr = 0 # counts worse than previous
count_not_improved_best = 0 # counts worse than best
it = 0
exit_reason = "max iterations reached"
for it in range(self.__iterations):
# explore neighborhood
sample_size = max(int(neighborhood_size * sample_factor), 5) # max(..,5) is for too small topologies
weights, cost, loads, distances = self.__explore_neighborhood(sample_size, weights, distances, loads)
util = max(loads.values())
# exit criteria (1) timeout
if self.__timeout < time.time() - self.__start_time:
exit_reason = "time out"
break
# exit criteria (2) not improved best for a very long time
if not (bc_cost > cost or bu_util > util):
count_not_improved_best += 1
if count_not_improved_best > self.__limit_not_improved:
exit_reason = f"LIMIT NOT IMPROVED exceeded {self.__limit_not_improved}"
break
else:
count_not_improved_best = 0
# keep best solution data
if bc_cost >= cost and bu_util >= util:
bc_weights, bc_cost, bc_loads, bc_util, bc_distances = weights, cost, loads, util, distances
bu_weights, bu_cost, bu_loads, bu_util, bu_distances = weights, cost, loads, util, distances
elif bc_cost >= cost:
bc_weights, bc_cost, bc_loads, bc_util, bc_distances = weights, cost, loads, util, distances
elif bu_util >= util:
bu_weights, bu_cost, bu_loads, bu_util, bu_distances = weights, cost, loads, util, distances
# better than previous solution?
if pr_cost > cost or pr_util > util:
sample_factor = max(0.01, sample_factor / 3)
count_not_better_as_pr = 0
self.__reset_secondary_hashtable()
else:
sample_factor = min(1, sample_factor * 10)
count_not_better_as_pr += 1
if count_not_better_as_pr >= self.__perturb_it:
weights = self.__perturb(weights)
count_not_better_as_pr = 0
self.__reset_secondary_hashtable()
pr_cost, pr_util = cost, util
return bc_weights, bc_cost, bc_loads, bc_util, bu_weights, bu_cost, bu_loads, bu_util, it, exit_reason
def solve(self) -> dict:
""" compute solution """
self.__start_time = t_start = time.time() # sys wide time
pt_start = time.process_time() # count process time (e.g. sleep excluded and count per core)
bc_weights, bc_cost, bc_loads, bc_util, bu_weights, bu_cost, bu_loads, bu_util, number_iterations, exit_reason = self.__ospf_heuristic()
pt_duration = time.process_time() - pt_start
t_duration = time.time() - t_start
solution = dict()
# best max utilization result
solution["objective"] = bu_util
solution["execution_time"] = t_duration
solution["process_time"] = pt_duration
solution["waypoints"] = self.__waypoints
solution["weights"] = bu_weights
solution["loads"] = bu_loads
solution["cost"] = bu_cost
# bc := best cost result
solution["bc_objective"] = bc_util
solution["bc_weights"] = bc_weights
solution["bc_cost"] = bc_cost
solution["bc_loads"] = bc_loads
solution["used_iterations"] = number_iterations
solution["exit_reason"] = exit_reason
# parameters
solution["max_iterations"] = self.__iterations
solution["max_weight"] = self.__max_weight
solution["perturb_it"] = self.__perturb_it
solution["seed"] = self.__seed
solution["hash_table_l1"] = self.__l
solution["hash_table_l2"] = self.__l2
return solution
def get_name(self):
""" returns name of algorithm """
return f"heur_ospf_weights"
| [
"networkit.Graph",
"numpy.random.uniform",
"numpy.random.seed",
"random.randint",
"numpy.sum",
"time.process_time",
"numpy.zeros",
"time.time",
"numpy.random.randint",
"numpy.array",
"algorithm.segment_routing.sr_utility.SRUtility.get_segmented_demands",
"networkit.distance.SPSP"
] | [((960, 987), 'numpy.random.seed', 'np.random.seed', (['self.__seed'], {}), '(self.__seed)\n', (974, 987), True, 'import numpy as np\n'), ((4353, 4388), 'numpy.zeros', 'np.zeros', (['(2 ** self.__l)'], {'dtype': 'bool'}), '(2 ** self.__l, dtype=bool)\n', (4361, 4388), True, 'import numpy as np\n'), ((4580, 4616), 'numpy.zeros', 'np.zeros', (['(2 ** self.__l2)'], {'dtype': 'bool'}), '(2 ** self.__l2, dtype=bool)\n', (4588, 4616), True, 'import numpy as np\n'), ((5176, 5226), 'networkit.Graph', 'nk.Graph', ([], {'weighted': '(True)', 'directed': '(True)', 'n': 'self.__n'}), '(weighted=True, directed=True, n=self.__n)\n', (5184, 5226), True, 'import networkit as nk\n'), ((5321, 5371), 'networkit.distance.SPSP', 'nk.distance.SPSP', (['self.__g'], {'sources': 'self.__targets'}), '(self.__g, sources=self.__targets)\n', (5337, 5371), True, 'import networkit as nk\n'), ((6960, 6995), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.25)', 'high': '(1)'}), '(low=0.25, high=1)\n', (6977, 6995), True, 'import numpy as np\n'), ((8617, 8657), 'numpy.zeros', 'np.zeros', (['(self.__n, self.__n)', 'np.float'], {}), '((self.__n, self.__n), np.float)\n', (8625, 8657), True, 'import numpy as np\n'), ((15046, 15057), 'time.time', 'time.time', ([], {}), '()\n', (15055, 15057), False, 'import time\n'), ((15094, 15113), 'time.process_time', 'time.process_time', ([], {}), '()\n', (15111, 15113), False, 'import time\n'), ((2809, 2859), 'algorithm.segment_routing.sr_utility.SRUtility.get_segmented_demands', 'SRUtility.get_segmented_demands', (['segments', 'demands'], {}), '(segments, demands)\n', (2840, 2859), False, 'from algorithm.segment_routing.sr_utility import SRUtility\n'), ((15344, 15363), 'time.process_time', 'time.process_time', ([], {}), '()\n', (15361, 15363), False, 'import time\n'), ((15396, 15407), 'time.time', 'time.time', ([], {}), '()\n', (15405, 15407), False, 'import time\n'), ((6624, 6645), 'random.randint', 'random.randint', (['(-2)', '(2)'], {}), '(-2, 2)\n', (6638, 6645), False, 'import random\n'), ((9277, 9301), 'numpy.sum', 'np.sum', (['current_flows[y]'], {}), '(current_flows[y])\n', (9283, 9301), True, 'import numpy as np\n'), ((10780, 10807), 'numpy.random.randint', 'np.random.randint', (['self.__n'], {}), '(self.__n)\n', (10797, 10807), True, 'import numpy as np\n'), ((13084, 13095), 'time.time', 'time.time', ([], {}), '()\n', (13093, 13095), False, 'import time\n'), ((9069, 9095), 'numpy.array', 'np.array', (['distances[t_idx]'], {}), '(distances[t_idx])\n', (9077, 9095), True, 'import numpy as np\n')] |
"""A package for processing and analysis of non-hierarchical gate-level VLSI designs.
The kyupy package itself contains a logger and other simple utility functions.
In addition, it defines a ``numba`` and a ``cuda`` objects that point to the actual packages
if they are available and otherwise point to mocks.
"""
import time
import importlib.util
import gzip
import numpy as np
_pop_count_lut = np.asarray([bin(x).count('1') for x in range(256)])
def popcount(a):
"""Returns the number of 1-bits in a given packed numpy array."""
return np.sum(_pop_count_lut[a])
def readtext(file):
"""Reads and returns the text in a given file. Transparently decompresses \\*.gz files."""
if hasattr(file, 'read'):
return file.read()
if str(file).endswith('.gz'):
with gzip.open(file, 'rt') as f:
return f.read()
else:
with open(file, 'rt') as f:
return f.read()
def hr_sci(value):
"""Formats a value in a human-readible scientific notation."""
multiplier = 0
while abs(value) >= 1000:
value /= 1000
multiplier += 1
while abs(value) < 1:
value *= 1000
multiplier -= 1
return f'{value:.3f}{" kMGTPEafpnµm"[multiplier]}'
def hr_bytes(nbytes):
"""Formats a given number of bytes for human readability."""
multiplier = 0
while abs(nbytes) >= 1000:
nbytes /= 1024
multiplier += 1
return f'{nbytes:.1f}{["", "ki", "Mi", "Gi", "Ti", "Pi"][multiplier]}B'
def hr_time(seconds):
"""Formats a given time interval for human readability."""
s = ''
if seconds >= 86400:
d = seconds // 86400
seconds -= d * 86400
s += f'{int(d)}d'
if seconds >= 3600:
h = seconds // 3600
seconds -= h * 3600
s += f'{int(h)}h'
if seconds >= 60:
m = seconds // 60
seconds -= m * 60
if 'd' not in s:
s += f'{int(m)}m'
if 'h' not in s and 'd' not in s:
s += f'{int(seconds)}s'
return s
class Log:
"""A very simple logger that formats the messages with the number of seconds since
program start.
"""
def __init__(self):
self.start = time.perf_counter()
self.logfile = None
"""When set to a file handle, log messages are written to it instead to standard output.
After each write, ``flush()`` is called as well.
"""
def log(self, level, message):
t = time.perf_counter() - self.start
if self.logfile is None:
print(f'{t:011.3f} {level} {message}')
else:
self.logfile.write(f'{t:011.3f} {level} {message}\n')
self.logfile.flush()
def info(self, message):
"""Log an informational message."""
self.log('-', message)
def warn(self, message):
"""Log a warning message."""
self.log('W', message)
def error(self, message):
"""Log an error message."""
self.log('E', message)
def range(self, *args):
"""A generator that operates just like the ``range()`` built-in, and also occasionally logs the progress
and compute time estimates."""
elems = len(range(*args))
start_time = time.perf_counter()
lastlog_time = start_time
log_interval = 5
for elem, i in enumerate(range(*args)):
yield i
current_time = time.perf_counter()
if current_time > lastlog_time + log_interval:
done = (elem + 1) / elems
elapsed_time = current_time - start_time
total_time = elapsed_time / done
rem_time = total_time - elapsed_time
self.log(':', f'{done*100:.0f}% done {hr_time(elapsed_time)} elapsed {hr_time(rem_time)} remaining')
log_interval = min(600, int(log_interval*1.5))
lastlog_time = current_time
log = Log()
"""The standard logger instance."""
#
# Code below mocks basic numba and cuda functions for pure-python fallback.
#
class MockNumba:
@staticmethod
def njit(func):
def inner(*args, **kwargs):
return func(*args, **kwargs)
return inner
class MockCuda:
def __init__(self):
self.x = 0
self.y = 0
def jit(self, device=False):
_ = device # silence "not used" warning
outer = self
def make_launcher(func):
class Launcher:
def __init__(self, funcc):
self.func = funcc
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __getitem__(self, item):
grid_dim, block_dim = item
def inner(*args, **kwargs):
for grid_x in range(grid_dim[0]):
for grid_y in range(grid_dim[1]):
for block_x in range(block_dim[0]):
for block_y in range(block_dim[1]):
outer.x = grid_x * block_dim[0] + block_x
outer.y = grid_y * block_dim[1] + block_y
self.func(*args, **kwargs)
return inner
return Launcher(func)
return make_launcher
@staticmethod
def to_device(array, to=None):
if to is not None:
to[...] = array
return to
return array.copy()
def synchronize(self):
pass
def grid(self, dims):
_ = dims # silence "not used" warning
return self.x, self.y
if importlib.util.find_spec('numba') is not None:
import numba
import numba.cuda
from numba.cuda.cudadrv.error import CudaSupportError
try:
list(numba.cuda.gpus)
from numba import cuda
except CudaSupportError:
log.warn('Cuda unavailable. Falling back to pure Python.')
cuda = MockCuda()
else:
numba = MockNumba()
"""If Numba is available on the system, it is the actual ``numba`` package.
Otherwise, it simply defines an ``njit`` decorator that does nothing.
"""
cuda = MockCuda()
"""If Numba is installed and Cuda GPUs are available, it is the actual ``numba.cuda`` package.
Otherwise, it is an object that defines basic methods and decorators so that cuda-code can still
run in the Python interpreter.
"""
log.warn('Numba unavailable. Falling back to pure Python.')
| [
"numpy.sum",
"time.perf_counter",
"gzip.open"
] | [((553, 578), 'numpy.sum', 'np.sum', (['_pop_count_lut[a]'], {}), '(_pop_count_lut[a])\n', (559, 578), True, 'import numpy as np\n'), ((2199, 2218), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2216, 2218), False, 'import time\n'), ((3228, 3247), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3245, 3247), False, 'import time\n'), ((800, 821), 'gzip.open', 'gzip.open', (['file', '"""rt"""'], {}), "(file, 'rt')\n", (809, 821), False, 'import gzip\n'), ((2461, 2480), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2478, 2480), False, 'import time\n'), ((3402, 3421), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3419, 3421), False, 'import time\n')] |
import numpy as np
def iou(box_group1, box_group2):
""" Calculates the intersection over union (aka. Jaccard Index) between two boxes.
Boxes are assumed to be in corners format (xmin, ymin, xmax, ymax)
Args:
- box_group1: boxes in group 1
- box_group2: boxes in group 2
Returns:
- A numpy array of shape (len(box_group1), len(box_group2)) where each value represents the iou between a box in box_group1 to a box in box_group2
Raises:
- The shape of box_group1 and box_group2 are not the same.
Code References:
- https://stackoverflow.com/questions/28723670/intersection-over-union-between-two-detections/41660682
"""
assert box_group1.shape == box_group2.shape, "The two boxes array must be the same shape."
xmin_intersect = np.maximum(box_group1[..., 0], box_group2[..., 0])
ymin_intersect = np.maximum(box_group1[..., 1], box_group2[..., 1])
xmax_intersect = np.minimum(box_group1[..., 2], box_group2[..., 2])
ymax_intersect = np.minimum(box_group1[..., 3], box_group2[..., 3])
intersect = (xmax_intersect - xmin_intersect) * (ymax_intersect - ymin_intersect)
box_group1_area = (box_group1[..., 2] - box_group1[..., 0]) * (box_group1[..., 3] - box_group1[..., 1])
box_group2_area = (box_group2[..., 2] - box_group2[..., 0]) * (box_group2[..., 3] - box_group2[..., 1])
union = box_group1_area + box_group2_area - intersect
res = intersect / union
# set invalid ious to zeros
res[xmax_intersect < xmin_intersect] = 0
res[ymax_intersect < ymin_intersect] = 0
res[res < 0] = 0
res[res > 1] = 0
return res
| [
"numpy.minimum",
"numpy.maximum"
] | [((787, 837), 'numpy.maximum', 'np.maximum', (['box_group1[..., 0]', 'box_group2[..., 0]'], {}), '(box_group1[..., 0], box_group2[..., 0])\n', (797, 837), True, 'import numpy as np\n'), ((859, 909), 'numpy.maximum', 'np.maximum', (['box_group1[..., 1]', 'box_group2[..., 1]'], {}), '(box_group1[..., 1], box_group2[..., 1])\n', (869, 909), True, 'import numpy as np\n'), ((931, 981), 'numpy.minimum', 'np.minimum', (['box_group1[..., 2]', 'box_group2[..., 2]'], {}), '(box_group1[..., 2], box_group2[..., 2])\n', (941, 981), True, 'import numpy as np\n'), ((1003, 1053), 'numpy.minimum', 'np.minimum', (['box_group1[..., 3]', 'box_group2[..., 3]'], {}), '(box_group1[..., 3], box_group2[..., 3])\n', (1013, 1053), True, 'import numpy as np\n')] |
"""
First run this 'extractEmbeddings.py' for extract embeddings
Second run this 'trainModel.py' for traine classification mode
Third run this file along with image path to recognize facess in image
Note:
1) We are using state of the art Face Detection Model called Retina-Face to detect facess acuuretly
2) This Face Recognition model detects only trained facess
3) We also give some thresholds to identify facess that are not in Traing Set as 'None'
4) We give 'None' to those facess
"""
import numpy as np
import pickle
import cv2
import os
import model as embedding
import imutils
import argparse
import torch
# we save 'RetinaFace' model at 'models/retinaface'
# we load retinaface model to detect facess
import torch.backends.cudnn as cudnn
from models.retinaface.config import cfg
from models.retinaface.prior_box import PriorBox
from models.retinaface.py_cpu_nms import py_cpu_nms
from retina_face import RetinaFace
from models.retinaface.box_utils import decode , decode_landm
import torchvision.transforms.functional as F
import matplotlib.pyplot as plt
from PIL import Image
import time
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
currentDir = os.getcwd()
# paths to embedding pickle file
embeddingPickle = os.path.join(currentDir, "output/FinalEmbeddings.pickle")
# path to save recognizer pickle file
recognizerPickle = os.path.join(currentDir, "output/FinalRecognizer.pickle")
# path to save labels pickle file
labelPickle = os.path.join(currentDir, "output/FinalLabel.pickle")
# path to save prdictedImages
predictedImg = os.path.join(currentDir, "predictedImg")
if not os.path.exists(predictedImg):
os.mkdir(predictedImg)
# Use argparse to get image path on commend line
# loading 'RetinaFace' weights to detect facess
trained_model_path = "models/retinaface/weights/Final_Retinaface.pth"
cpu = True
confidence_threshold = 0.05
top_k = 5000
nms_threshold = 0.3
keep_top_k = 750
save_image_path = "predictedImg"
vis_threshold = 0.6
### check_keys
def check_keys(model, pretrained_state_dict):
ckpt_keys = set(pretrained_state_dict.keys())
model_keys = set(model.state_dict().keys())
used_pretrained_keys = model_keys & ckpt_keys
unused_pretrained_keys = ckpt_keys - model_keys
missing_keys = model_keys - ckpt_keys
#print('Missing keys:{}'.format(len(missing_keys)))
#print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))
#print('Used keys:{}'.format(len(used_pretrained_keys)))
assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'
return True
### remove_prefix
def remove_prefix(state_dict, prefix):
''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
#print('remove prefix \'{}\''.format(prefix))
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()}
### load_model
def load_model(model, pretrained_path, load_to_cpu):
#print('Loading pretrained model from {}'.format(pretrained_path))
if load_to_cpu:
pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)
else:
device = torch.cuda.current_device()
pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))
if "state_dict" in pretrained_dict.keys():
pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')
else:
pretrained_dict = remove_prefix(pretrained_dict, 'module.')
check_keys(model, pretrained_dict)
model.load_state_dict(pretrained_dict, strict=False)
return model
torch.set_grad_enabled(False)
#net and model
net = RetinaFace(phase="test")
net = load_model(net , trained_model_path, cpu)
net.eval()
print("Finished loading model!")
cudnn.benchmark = True
device = torch.device("cpu" if cpu else "cuda")
net = net.to(device)
resize = 1
# load embedding model
embedder = embedding.InceptionResnetV1(pretrained="vggface2").eval()
# load the actual face recognition model along with the label encoder
recognizer = pickle.loads(open(recognizerPickle, "rb").read())
label = pickle.loads(open(labelPickle, "rb").read())
# loading embeddings pickle
data = pickle.loads(open(embeddingPickle, "rb").read())
COLORS = np.random.randint(0, 255, size=(len(label.classes_), 3), dtype="uint8")
Embeddings = np.array(data["embeddings"])
names = np.array(data["names"])
print("Embeddings ", Embeddings.shape)
print("Names ", names.shape)
#print("Labels ", labels.shape)
def distance(emb1, emb2):
return np.sum(np.square(emb1 - emb2))
video = cv2.VideoCapture(0)
while True:
ret,frame = video.read()
img = np.float32(frame)
im_height,im_width,_ = img.shape
scale = torch.Tensor([img.shape[1],img.shape[0],img.shape[1],img.shape[0]])
img -= (104,117,123)
img = img.transpose(2,0,1)
img = torch.from_numpy(img).unsqueeze(0)
img = img.to(device)
scale = scale.to(device)
tic = time.time()
loc,conf,landms = net(img) #forward pass
print('net forward time: {:.4f}'.format(time.time() - tic))
priorbox = PriorBox(cfg,image_size=(im_height,im_width))
priors = priorbox.forward()
priors = priors.to(device)
prior_data = priors.data
boxes = decode(loc.data.squeeze(0),prior_data,cfg['variance'])
boxes = boxes * scale / resize
boxes = boxes.cpu().numpy()
scores = conf.squeeze(0).data.cpu().numpy()[:,1]
landms = decode_landm(landms.data.squeeze(0),prior_data,cfg['variance'])
scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],
img.shape[3], img.shape[2], img.shape[3], img.shape[2],
img.shape[3], img.shape[2]])
scale1 = scale1.to(device)
landms = landms * scale1 / resize
landms = landms.cpu().numpy()
# ignore low scores
inds = np.where(scores > confidence_threshold)[0]
boxes = boxes[inds]
landms = landms[inds]
scores = scores[inds]
# keep top-K befor NMS
order = scores.argsort()[::-1][:top_k]
boxes = boxes[order]
landms = landms[order]
scores = scores[order]
# do NMS
dets = np.hstack((boxes,scores[:,np.newaxis])).astype(np.float32,copy=False)
keep = py_cpu_nms(dets,nms_threshold)
# keep = nms(dets,args.nms_threshold,force_cpu = args.cpu)
dets = dets[keep,:]
landms = landms[keep]
# keep top-K faster NMS
dets = dets[:keep_top_k,:]
landms = landms[:keep_top_k,:]
dets = np.concatenate((dets, landms), axis=1)
for b in dets:
if b[4] < vis_threshold:
continue
boxes = np.array(b[0:4])
boxes = boxes.astype('int')
(startX,startY,endX,endY) = boxes
face = frame[startY:endY,startX:endX]
try:
# print("yes-1")
faceRead = Image.fromarray(face)
faceRead = faceRead.resize((160,160),Image.ANTIALIAS)
faceRead = F.to_tensor(faceRead)
# print("yes-2")
except:
print("[Error] - resizing face " )
continue
# print(faceRead.shape)
# getting embeddings for cropped faces
faceEmbed = embedder(faceRead.unsqueeze(0))
flattenEmbed = faceEmbed.squeeze(0).detach().numpy()
# print(flattenEmbed.shape)
# predecting class
array = np.array(flattenEmbed).reshape(1,-1)
# perform classification to recognize the face
preds = recognizer.predict_proba(array)[0]
j = np.argmax(preds)
proba = preds[j]
name = label.classes_[j]
# print(name)
result = np.where(names == name)
resultEmbeddings = Embeddings[result]
dists = []
for emb in resultEmbeddings:
d = distance(emb,flattenEmbed)
dists.append(d)
# print(dists)
distarray = np.array(dists)
# print(distarray)
min_dist = np.min(distarray)
max_dist = np.max(distarray)
#print("Name : ",name)
#print("min dist : ",min_dist)
#print("max dist : ", max_dist)
if proba >= 0.5:
if (min_dist < 0.75 and max_dist < 1.4) or (min_dist < 0.5) or (proba ==1 and min_dist <= 0.5):
print("dist name ", name)
print("min dist :",min_dist)
print("max dist :",max_dist)
color = [int(c) for c in COLORS[j]]
cv2.rectangle(frame,(startX,startY),(endX,endY),color,2)
text = "{}: {:.2f}".format(name,proba)
cv2.putText(frame,text,(startX,startY - 5),cv2.FONT_HERSHEY_SIMPLEX,0.5,color,2)
else:
print("___________missing__________")
print("dist name",name)
print("min dist : ",min_dist)
print("max dist : ", max_dist)
print("probability : ",proba)
name = "NONE"
color = (255,255,0)
cv2.rectangle(frame,(startX,startY),(endX,endY),color,2)
text = "{}".format(name)
cv2.putText(frame,text,(startX,startY - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5,color,2)
else:
name = "NONE"
color = (255,255,0)
cv2.rectangle(frame,(startX,startY),(endX,endY),color,2)
text = "{}".format(name)
cv2.putText(frame,text,(startX,startY - 5),cv2.FONT_HERSHEY_SIMPLEX,0.5,color,2)
cv2.imshow("Capture",frame)
key = cv2.waitKey(2)
if key == ord('q'):
break
video.release()
cv2.destroyAllWindows()
# def detectFacess(path):
# image_path = path
# img_raw = cv2.imread(image_path, cv2.IMREAD_COLOR)
# #print(img_raw)
# img_raw_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
# imageName = image_path.split('/')[-1].split('.')[-2]
# img = np.float32(img_raw)
# im_height, im_width, _ = img.shape
# scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
# img -= (104, 117, 123)
# img = img.transpose(2, 0, 1)
# img = torch.from_numpy(img).unsqueeze(0)
# img = img.to(device)
# scale = scale.to(device)
# tic = time.time()
# loc, conf, landms = net(img) # forward pass
# print('net forward time: {:.4f}'.format(time.time() - tic))
# priorbox = PriorBox(cfg, image_size=(im_height, im_width))
# priors = priorbox.forward()
# priors = priors.to(device)
# prior_data = priors.data
# boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])
# boxes = boxes * scale / resize
# boxes = boxes.cpu().numpy()
# scores = conf.squeeze(0).data.cpu().numpy()[:, 1]
# landms = decode_landm(landms.data.squeeze(0), prior_data, cfg['variance'])
# scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],
# img.shape[3], img.shape[2], img.shape[3], img.shape[2],
# img.shape[3], img.shape[2]])
# scale1 = scale1.to(device)
# landms = landms * scale1 / resize
# landms = landms.cpu().numpy()
# # ignore low scores
# inds = np.where(scores > confidence_threshold)[0]
# boxes = boxes[inds]
# landms = landms[inds]
# scores = scores[inds]
# # keep top-K before NMS
# order = scores.argsort()[::-1][:top_k]
# boxes = boxes[order]
# landms = landms[order]
# scores = scores[order]
# # do NMS
# dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)
# keep = py_cpu_nms(dets, nms_threshold)
# # keep = nms(dets, args.nms_threshold,force_cpu=args.cpu)
# dets = dets[keep, :]
# landms = landms[keep]
# # keep top-K faster NMS
# dets = dets[:keep_top_k, :]
# landms = landms[:keep_top_k, :]
# dets = np.concatenate((dets, landms), axis=1)
# for b in dets:
# if b[4] < vis_threshold:
# continue
# boxes = np.array(b[0:4])
# boxes = boxes.astype('int')
# (startX , startY, endX, endY) = boxes
# face = img_raw_rgb[startY:endY , startX:endX]
# try:
# #print("yes-1")
# faceRead = Image.fromarray(face)
# faceRead = faceRead.resize((160, 160), Image.ANTIALIAS)
# faceRead = F.to_tensor(faceRead)
# #print("yes-2")
# except:
# print("[Error] - resizing face ")
# continue
# #print(faceRead.shape)
# # getting embeddings for croped faces
# faceEmbed = embedder(faceRead.unsqueeze(0))
# flattenEmbed = faceEmbed.squeeze(0).detach().numpy()
# #print(flattenEmbed.shape)
# # predectiong class
# array = np.array(flattenEmbed).reshape(1,-1)
# # perform classification to recognize the face
# preds = recognizer.predict_proba(array)[0]
# j = np.argmax(preds)
# proba = preds[j]
# name = label.classes_[j]
# #print(name)
# result = np.where(names == name)
# resultEmbeddings = Embeddings[result]
# dists = []
# for emb in resultEmbeddings:
# d = distance(emb, flattenEmbed)
# dists.append(d)
# #print(dists)
# distarray = np.array(dists)
# #print(distarray)
# min_dist = np.min(distarray)
# max_dist = np.max(distarray)
# #print("Name : ",name)
# #print("min dist : ",min_dist)
# #print("max dist : ", max_dist)
# if proba >= 0.5:
# if (min_dist < 0.75 and max_dist < 1.4) or (min_dist < 0.5) or (proba == 1 and min_dist <= 0.5):
# print("dist name ", name)
# print("min dist : ",min_dist)
# print("max dist : ", max_dist)
# color = [int(c) for c in COLORS[j]]
# cv2.rectangle(img_raw, (startX, startY), (endX, endY), color, 2)
# text = "{}: {:.2f}".format(name, proba)
# cv2.putText(img_raw,text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# else:
# print("________________missing______________")
# print("dist name ", name)
# print("min dist : ",min_dist)
# print("max dist : ", max_dist)
# print("probability :",proba)
# name = "NONE"
# color = (255, 255, 255)
# cv2.rectangle(img_raw, (startX, startY), (endX, endY), color, 2)
# text = "{}".format(name)
# cv2.putText(img_raw,text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# else:
# name = "NONE"
# color = (255, 255, 255)
# cv2.rectangle(img_raw, (startX, startY), (endX, endY), color, 2)
# text = "{}".format(name)
# cv2.putText(img_raw,text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# # save image predicte foler
# cv2.imwrite("{}/{}.png".format(predictedImg, imageName), img_raw)
# #im = Image.open("{}/{}.png".format(predictedImg,imageName))
# #return im
# cv2.imshow(imageName, img_raw)
# cv2.waitKey(0)
# if __name__ == '__main__':
# ap = argparse.ArgumentParser()
# ap.add_argument("-i", "--imagePath", required=True, help="Image path to recognize facess")
# args = vars(ap.parse_args())
# imagePath = args["imagePath"]
# currentDirImage = os.getcwd()
# print(currentDirImage)
# ImageDir = os.path.join(currentDirImage,imagePath)
# print(ImageDir)
# if not os.path.exists(ImageDir):
# print("Image not exists")
# #print("image path: ",ImageDir)
# readImg = plt.imread(ImageDir)
# #print("shape :", readImg.shape)
# detectFacess(imagePath)
| [
"os.mkdir",
"torchvision.transforms.functional.to_tensor",
"numpy.argmax",
"torch.device",
"cv2.rectangle",
"torch.cuda.current_device",
"cv2.imshow",
"os.path.join",
"retina_face.RetinaFace",
"torch.load",
"os.path.exists",
"numpy.max",
"torch.Tensor",
"cv2.destroyAllWindows",
"cv2.wait... | [((1193, 1204), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1202, 1204), False, 'import os\n'), ((1257, 1314), 'os.path.join', 'os.path.join', (['currentDir', '"""output/FinalEmbeddings.pickle"""'], {}), "(currentDir, 'output/FinalEmbeddings.pickle')\n", (1269, 1314), False, 'import os\n'), ((1373, 1430), 'os.path.join', 'os.path.join', (['currentDir', '"""output/FinalRecognizer.pickle"""'], {}), "(currentDir, 'output/FinalRecognizer.pickle')\n", (1385, 1430), False, 'import os\n'), ((1480, 1532), 'os.path.join', 'os.path.join', (['currentDir', '"""output/FinalLabel.pickle"""'], {}), "(currentDir, 'output/FinalLabel.pickle')\n", (1492, 1532), False, 'import os\n'), ((1579, 1619), 'os.path.join', 'os.path.join', (['currentDir', '"""predictedImg"""'], {}), "(currentDir, 'predictedImg')\n", (1591, 1619), False, 'import os\n'), ((3679, 3708), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (3701, 3708), False, 'import torch\n'), ((3731, 3755), 'retina_face.RetinaFace', 'RetinaFace', ([], {'phase': '"""test"""'}), "(phase='test')\n", (3741, 3755), False, 'from retina_face import RetinaFace\n'), ((3880, 3918), 'torch.device', 'torch.device', (["('cpu' if cpu else 'cuda')"], {}), "('cpu' if cpu else 'cuda')\n", (3892, 3918), False, 'import torch\n'), ((4412, 4440), 'numpy.array', 'np.array', (["data['embeddings']"], {}), "(data['embeddings'])\n", (4420, 4440), True, 'import numpy as np\n'), ((4449, 4472), 'numpy.array', 'np.array', (["data['names']"], {}), "(data['names'])\n", (4457, 4472), True, 'import numpy as np\n'), ((4651, 4670), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (4667, 4670), False, 'import cv2\n'), ((9649, 9672), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (9670, 9672), False, 'import cv2\n'), ((1627, 1655), 'os.path.exists', 'os.path.exists', (['predictedImg'], {}), '(predictedImg)\n', (1641, 1655), False, 'import os\n'), ((1661, 1683), 'os.mkdir', 'os.mkdir', (['predictedImg'], {}), '(predictedImg)\n', (1669, 1683), False, 'import os\n'), ((4722, 4739), 'numpy.float32', 'np.float32', (['frame'], {}), '(frame)\n', (4732, 4739), True, 'import numpy as np\n'), ((4789, 4859), 'torch.Tensor', 'torch.Tensor', (['[img.shape[1], img.shape[0], img.shape[1], img.shape[0]]'], {}), '([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])\n', (4801, 4859), False, 'import torch\n'), ((5023, 5034), 'time.time', 'time.time', ([], {}), '()\n', (5032, 5034), False, 'import time\n'), ((5160, 5207), 'models.retinaface.prior_box.PriorBox', 'PriorBox', (['cfg'], {'image_size': '(im_height, im_width)'}), '(cfg, image_size=(im_height, im_width))\n', (5168, 5207), False, 'from models.retinaface.prior_box import PriorBox\n'), ((5575, 5739), 'torch.Tensor', 'torch.Tensor', (['[img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.\n shape[2], img.shape[3], img.shape[2], img.shape[3], img.shape[2]]'], {}), '([img.shape[3], img.shape[2], img.shape[3], img.shape[2], img.\n shape[3], img.shape[2], img.shape[3], img.shape[2], img.shape[3], img.\n shape[2]])\n', (5587, 5739), False, 'import torch\n'), ((6314, 6345), 'models.retinaface.py_cpu_nms.py_cpu_nms', 'py_cpu_nms', (['dets', 'nms_threshold'], {}), '(dets, nms_threshold)\n', (6324, 6345), False, 'from models.retinaface.py_cpu_nms import py_cpu_nms\n'), ((6565, 6603), 'numpy.concatenate', 'np.concatenate', (['(dets, landms)'], {'axis': '(1)'}), '((dets, landms), axis=1)\n', (6579, 6603), True, 'import numpy as np\n'), ((9542, 9570), 'cv2.imshow', 'cv2.imshow', (['"""Capture"""', 'frame'], {}), "('Capture', frame)\n", (9552, 9570), False, 'import cv2\n'), ((9580, 9594), 'cv2.waitKey', 'cv2.waitKey', (['(2)'], {}), '(2)\n', (9591, 9594), False, 'import cv2\n'), ((1141, 1166), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1164, 1166), False, 'import torch\n'), ((3122, 3192), 'torch.load', 'torch.load', (['pretrained_path'], {'map_location': '(lambda storage, loc: storage)'}), '(pretrained_path, map_location=lambda storage, loc: storage)\n', (3132, 3192), False, 'import torch\n'), ((3220, 3247), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (3245, 3247), False, 'import torch\n'), ((3987, 4037), 'model.InceptionResnetV1', 'embedding.InceptionResnetV1', ([], {'pretrained': '"""vggface2"""'}), "(pretrained='vggface2')\n", (4014, 4037), True, 'import model as embedding\n'), ((4618, 4640), 'numpy.square', 'np.square', (['(emb1 - emb2)'], {}), '(emb1 - emb2)\n', (4627, 4640), True, 'import numpy as np\n'), ((5939, 5978), 'numpy.where', 'np.where', (['(scores > confidence_threshold)'], {}), '(scores > confidence_threshold)\n', (5947, 5978), True, 'import numpy as np\n'), ((6694, 6710), 'numpy.array', 'np.array', (['b[0:4]'], {}), '(b[0:4])\n', (6702, 6710), True, 'import numpy as np\n'), ((7578, 7594), 'numpy.argmax', 'np.argmax', (['preds'], {}), '(preds)\n', (7587, 7594), True, 'import numpy as np\n'), ((7694, 7717), 'numpy.where', 'np.where', (['(names == name)'], {}), '(names == name)\n', (7702, 7717), True, 'import numpy as np\n'), ((7935, 7950), 'numpy.array', 'np.array', (['dists'], {}), '(dists)\n', (7943, 7950), True, 'import numpy as np\n'), ((7997, 8014), 'numpy.min', 'np.min', (['distarray'], {}), '(distarray)\n', (8003, 8014), True, 'import numpy as np\n'), ((8034, 8051), 'numpy.max', 'np.max', (['distarray'], {}), '(distarray)\n', (8040, 8051), True, 'import numpy as np\n'), ((4923, 4944), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (4939, 4944), False, 'import torch\n'), ((6233, 6274), 'numpy.hstack', 'np.hstack', (['(boxes, scores[:, np.newaxis])'], {}), '((boxes, scores[:, np.newaxis]))\n', (6242, 6274), True, 'import numpy as np\n'), ((6903, 6924), 'PIL.Image.fromarray', 'Image.fromarray', (['face'], {}), '(face)\n', (6918, 6924), False, 'from PIL import Image\n'), ((7014, 7035), 'torchvision.transforms.functional.to_tensor', 'F.to_tensor', (['faceRead'], {}), '(faceRead)\n', (7025, 7035), True, 'import torchvision.transforms.functional as F\n'), ((9349, 9411), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(startX, startY)', '(endX, endY)', 'color', '(2)'], {}), '(frame, (startX, startY), (endX, endY), color, 2)\n', (9362, 9411), False, 'import cv2\n'), ((9456, 9548), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(startX, startY - 5)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'color', '(2)'], {}), '(frame, text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, color, 2)\n', (9467, 9548), False, 'import cv2\n'), ((5124, 5135), 'time.time', 'time.time', ([], {}), '()\n', (5133, 5135), False, 'import time\n'), ((7422, 7444), 'numpy.array', 'np.array', (['flattenEmbed'], {}), '(flattenEmbed)\n', (7430, 7444), True, 'import numpy as np\n'), ((8506, 8568), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(startX, startY)', '(endX, endY)', 'color', '(2)'], {}), '(frame, (startX, startY), (endX, endY), color, 2)\n', (8519, 8568), False, 'import cv2\n'), ((8635, 8727), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(startX, startY - 5)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'color', '(2)'], {}), '(frame, text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, color, 2)\n', (8646, 8727), False, 'import cv2\n'), ((9053, 9115), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(startX, startY)', '(endX, endY)', 'color', '(2)'], {}), '(frame, (startX, startY), (endX, endY), color, 2)\n', (9066, 9115), False, 'import cv2\n'), ((9168, 9260), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(startX, startY - 5)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', 'color', '(2)'], {}), '(frame, text, (startX, startY - 5), cv2.FONT_HERSHEY_SIMPLEX, \n 0.5, color, 2)\n', (9179, 9260), False, 'import cv2\n')] |
#!/usr/bin/env python
import os
import re
import cv2
import sys
import logging
import argparse
import subprocess
import numpy as np
from utils import *
def read(path):
"""
Unpack the .LJPEG image using the jpegdir library.
Sample output:
GW:1979 GH:4349 R:0
C:1 N:xx.ljpeg.1 W:1979 H:4349 hf:1 vf:1
Code borrowed from: https://github.com/nicholaslocascio/ljpeg-ddsm
"""
PATTERN = re.compile('\sC:(\d+)\s+N:(\S+)\s+W:(\d+)\s+H:(\d+)\s')
cmd = '%s -d -s %s' % (BIN, path)
l = subprocess.check_output(cmd, shell=True)
ll = l.decode()
m = PATTERN.search(ll)
C = int(m.group(1)) # I suppose this is # channels
F = m.group(2)
W = int(m.group(3))
H = int(m.group(4))
assert C == 1
im = np.fromfile(F, dtype='uint16').reshape(H, W)
L = im >> 8
H = im & 0xFF
im = (H << 8) | L
os.remove(F)
return im
if __name__ == '__main__':
BIN = os.path.join(os.path.dirname(__file__), "jpegdir", "jpeg")
if not os.path.exists(BIN):
print("jpeg library is not built yet; use 'cd jpegdir; make' first")
sys.exit(0)
parser = argparse.ArgumentParser()
parser.add_argument("ljpeg", nargs=1)
parser.add_argument("output", nargs=1)
parser.add_argument("--ics", type=str)
parser.add_argument("--normalize", action="store_true")
parser.add_argument("--correction",action="store_true")
args = parser.parse_args()
input_path = args.ljpeg[0]
output_path = args.output[0]
assert 'LJPEG' in input_path
root = os.path.dirname(input_path)
stem = os.path.splitext(input_path)[0]
fname = os.path.basename(input_path)
case_id,sequence,ext = fname.split('.')
# read ICS
ics_file_path = args.ics
ics_dict = get_ics_info(ics_file_path)
img_height = ics_dict[sequence]['height']
img_width = ics_dict[sequence]['width']
img_bpp = ics_dict[sequence]['bpp']
resolution = ics_dict[sequence]['resolution']
scanner_type = ics_dict['scanner_type']
scan_institution = ics_dict['scan_institution']
try:
raw_image = read(input_path)
except:
print("Cant open %s ... exiting" %fname)
sys.exit(0)
if img_width != raw_image.shape[1]:
logging.warn('reshape: %s' %fname)
raw_image = raw_image.reshape((img_height, img_width))
if args.normalize:
logging.warn("normalizing color, will lose information")
image = cv2.normalize(raw_image, None, 0, 255, cv2.NORM_MINMAX)
image = np.uint8(image)
if args.correction:
logging.warn("od correction: %s" %fname)
image = optical_density_correction(raw_image,scan_institution,scanner_type)
image = np.interp(image,(0.0,4.0),(255,0))
norm_img = cv2.normalize(image,None,0,1,cv2.NORM_MINMAX,dtype=cv2.CV_32F)
norm_img *= 255
image = np.uint8(norm_img)
cv2.imwrite(output_path, image)
| [
"os.remove",
"numpy.uint8",
"argparse.ArgumentParser",
"os.path.basename",
"logging.warn",
"cv2.imwrite",
"subprocess.check_output",
"os.path.dirname",
"os.path.exists",
"numpy.interp",
"numpy.fromfile",
"os.path.splitext",
"cv2.normalize",
"sys.exit",
"re.compile"
] | [((449, 513), 're.compile', 're.compile', (['"""\\\\sC:(\\\\d+)\\\\s+N:(\\\\S+)\\\\s+W:(\\\\d+)\\\\s+H:(\\\\d+)\\\\s"""'], {}), "('\\\\sC:(\\\\d+)\\\\s+N:(\\\\S+)\\\\s+W:(\\\\d+)\\\\s+H:(\\\\d+)\\\\s')\n", (459, 513), False, 'import re\n'), ((551, 591), 'subprocess.check_output', 'subprocess.check_output', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (574, 591), False, 'import subprocess\n'), ((893, 905), 'os.remove', 'os.remove', (['F'], {}), '(F)\n', (902, 905), False, 'import os\n'), ((1160, 1185), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1183, 1185), False, 'import argparse\n'), ((1578, 1605), 'os.path.dirname', 'os.path.dirname', (['input_path'], {}), '(input_path)\n', (1593, 1605), False, 'import os\n'), ((1661, 1689), 'os.path.basename', 'os.path.basename', (['input_path'], {}), '(input_path)\n', (1677, 1689), False, 'import os\n'), ((2933, 2964), 'cv2.imwrite', 'cv2.imwrite', (['output_path', 'image'], {}), '(output_path, image)\n', (2944, 2964), False, 'import cv2\n'), ((971, 996), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (986, 996), False, 'import os\n'), ((1028, 1047), 'os.path.exists', 'os.path.exists', (['BIN'], {}), '(BIN)\n', (1042, 1047), False, 'import os\n'), ((1134, 1145), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1142, 1145), False, 'import sys\n'), ((1617, 1645), 'os.path.splitext', 'os.path.splitext', (['input_path'], {}), '(input_path)\n', (1633, 1645), False, 'import os\n'), ((2282, 2317), 'logging.warn', 'logging.warn', (["('reshape: %s' % fname)"], {}), "('reshape: %s' % fname)\n", (2294, 2317), False, 'import logging\n'), ((2411, 2467), 'logging.warn', 'logging.warn', (['"""normalizing color, will lose information"""'], {}), "('normalizing color, will lose information')\n", (2423, 2467), False, 'import logging\n'), ((2484, 2539), 'cv2.normalize', 'cv2.normalize', (['raw_image', 'None', '(0)', '(255)', 'cv2.NORM_MINMAX'], {}), '(raw_image, None, 0, 255, cv2.NORM_MINMAX)\n', (2497, 2539), False, 'import cv2\n'), ((2556, 2571), 'numpy.uint8', 'np.uint8', (['image'], {}), '(image)\n', (2564, 2571), True, 'import numpy as np\n'), ((2604, 2645), 'logging.warn', 'logging.warn', (["('od correction: %s' % fname)"], {}), "('od correction: %s' % fname)\n", (2616, 2645), False, 'import logging\n'), ((2745, 2783), 'numpy.interp', 'np.interp', (['image', '(0.0, 4.0)', '(255, 0)'], {}), '(image, (0.0, 4.0), (255, 0))\n', (2754, 2783), True, 'import numpy as np\n'), ((2799, 2866), 'cv2.normalize', 'cv2.normalize', (['image', 'None', '(0)', '(1)', 'cv2.NORM_MINMAX'], {'dtype': 'cv2.CV_32F'}), '(image, None, 0, 1, cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n', (2812, 2866), False, 'import cv2\n'), ((2902, 2920), 'numpy.uint8', 'np.uint8', (['norm_img'], {}), '(norm_img)\n', (2910, 2920), True, 'import numpy as np\n'), ((788, 818), 'numpy.fromfile', 'np.fromfile', (['F'], {'dtype': '"""uint16"""'}), "(F, dtype='uint16')\n", (799, 818), True, 'import numpy as np\n'), ((2222, 2233), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2230, 2233), False, 'import sys\n')] |
#-*- coding: UTF-8 -*-
import copy
import numpy
from keras.preprocessing.sequence import pad_sequences
def genBatch(data):
m = 820
maxsentencenum = len(data[0])
for doc in data:
for sentence in doc:
if len(sentence) > m:
m = len(sentence)
for i in xrange(maxsentencenum - len(doc)):
doc.append([-1])
tmp = map(lambda doc: numpy.asarray(map(lambda sentence : sentence + [-1]*(m - len(sentence)), doc), dtype = numpy.int32), data)
tmp = map(lambda t : t+1, tmp)
return numpy.asarray(tmp)
def genLenBatch(lengths,maxsentencenum):
lengths = map(lambda length : numpy.asarray(length + [1.0]*(maxsentencenum-len(length)), dtype = numpy.float32)+numpy.float32(1e-4),lengths)
return reduce(lambda x,y : numpy.concatenate((x,y),axis = 0),lengths)
def genwordmask(docsbatch):
mask = copy.deepcopy(docsbatch)
mask = map(lambda x : map(lambda y : [1.0 ,0.0][y == -1],x), mask)
mask = numpy.asarray(mask,dtype=numpy.float32)
return mask
def gensentencemask(sentencenum):
maxnum = sentencenum[0]
mask = numpy.asarray(map(lambda num : [1.0]*num + [0.0]*(maxnum - num),sentencenum), dtype = numpy.float32)
return mask.T
class Dataset(object):
def __init__(self, filename, emb,maxbatch = 32,maxword = 500):
lines = map(lambda x: x.split('\t\t'), open(filename).readlines())
label = numpy.asarray(
map(lambda x: int(x[2])-1, lines),
dtype = numpy.int32
)
docs = map(lambda x: x[3][0:len(x[3])-1], lines)
docs = map(lambda x: x.split('<sssss>'), docs)
docs = map(lambda doc: map(lambda sentence: sentence.split(' '),doc),docs)
docs = map(lambda doc: map(lambda sentence: filter(lambda wordid: wordid !=-1,map(lambda word: emb.getID(word),sentence)),doc),docs)
tmp = zip(docs, label)
#random.shuffle(tmp)
tmp.sort(lambda x, y: len(y[0]) - len(x[0]))
docs, label = zip(*tmp)
# sentencenum = map(lambda x : len(x),docs)
# length = map(lambda doc : map(lambda sentence : len(sentence), doc), docs)
self.epoch = len(docs) / maxbatch
if len(docs) % maxbatch != 0:
self.epoch += 1
self.docs = []
self.label = []
self.length = []
for i in xrange(self.epoch):
docsbatch = genBatch(docs[i*maxbatch:(i+1)*maxbatch])
self.docs.append(docsbatch)
self.label.append(numpy.asarray(label[i*maxbatch:(i+1)*maxbatch], dtype = numpy.int32))
class Wordlist(object):
def __init__(self, filename, maxn = 100000):
lines = map(lambda x: x.split(), open(filename).readlines()[:maxn])
self.size = len(lines)
self.voc = [(item[0][0], item[1]) for item in zip(lines, xrange(self.size))]
self.voc = dict(self.voc)
def getID(self, word):
try:
return self.voc[word]
except:
return -1
def padDocs(dataset):
for indx in range(dataset.epoch):
docs = []
for doc in dataset.docs[indx]:
doc_pad = pad_sequences(doc,maxlen=130, truncating='post')
docs.append(doc_pad)
dataset.docs[indx] = numpy.asarray(docs)
return dataset
# dataname = "IMDB"
# classes = 10
# voc = Wordlist('../data/'+dataname+'/wordlist.txt')
#
# print 'data loadeding....'
# trainset = Dataset('../data/'+dataname+'/test.txt', voc)
# trainset = padDocs(trainset)
# print trainset.docs[3].shape
# print trainset.docs
# f = open('../data/IMDB/testset.save','wb')
# cPickle.dump(trainset, f, protocol=cPickle.HIGHEST_PROTOCOL)
# f.close()
# print 'data load finish...'
'''
lines = map(lambda x: x.split('\t\t'), open('../data/IMDB/test.txt').readlines())
label = numpy.asarray(
map(lambda x: int(x[2]) - 1, lines),
dtype=numpy.int32
)
docs = map(lambda x: x[3][0:len(x[3]) - 1], lines)
docs = map(lambda x: x.split('<sssss>'), docs)
docs = map(lambda doc: map(lambda sentence: sentence.split(' '), doc), docs)
length = map(lambda doc: map(lambda sentence: len(sentence), doc), docs)
maxsentencelen = max(map(lambda doc: max(doc), length))
import nltk
fdist = nltk.FreqDist()
fdist_sent = nltk.FreqDist()
totalsentlen = 0
for doc in length:
doclen = len(doc)
fdist_sent[doclen] += 1
# for senlen in doc:
# totalsentlen += senlen
# fdist[senlen] += 1
print fdist_sent.keys()
print len(fdist_sent.keys())
print sum(fdist_sent.values())
print fdist_sent.plot(74, cumulative=True)
'''
# print len(fdist.keys())
# items = sorted(fdist.items(), lambda a,b: a[1] - b[1])
# print sum(fdist.values())
# print items
# # print fdist.items()
# print maxsentencelen
# print totalsentlen //sum(fdist.values())
# fdist.plot(225, cumulative=True)
| [
"copy.deepcopy",
"keras.preprocessing.sequence.pad_sequences",
"numpy.asarray",
"numpy.float32",
"numpy.concatenate"
] | [((552, 570), 'numpy.asarray', 'numpy.asarray', (['tmp'], {}), '(tmp)\n', (565, 570), False, 'import numpy\n'), ((884, 908), 'copy.deepcopy', 'copy.deepcopy', (['docsbatch'], {}), '(docsbatch)\n', (897, 908), False, 'import copy\n'), ((991, 1031), 'numpy.asarray', 'numpy.asarray', (['mask'], {'dtype': 'numpy.float32'}), '(mask, dtype=numpy.float32)\n', (1004, 1031), False, 'import numpy\n'), ((3259, 3278), 'numpy.asarray', 'numpy.asarray', (['docs'], {}), '(docs)\n', (3272, 3278), False, 'import numpy\n'), ((801, 834), 'numpy.concatenate', 'numpy.concatenate', (['(x, y)'], {'axis': '(0)'}), '((x, y), axis=0)\n', (818, 834), False, 'import numpy\n'), ((3148, 3197), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['doc'], {'maxlen': '(130)', 'truncating': '"""post"""'}), "(doc, maxlen=130, truncating='post')\n", (3161, 3197), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((741, 762), 'numpy.float32', 'numpy.float32', (['(0.0001)'], {}), '(0.0001)\n', (754, 762), False, 'import numpy\n'), ((2523, 2595), 'numpy.asarray', 'numpy.asarray', (['label[i * maxbatch:(i + 1) * maxbatch]'], {'dtype': 'numpy.int32'}), '(label[i * maxbatch:(i + 1) * maxbatch], dtype=numpy.int32)\n', (2536, 2595), False, 'import numpy\n')] |
datapath = '../d/'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from itertools import product as iterp
from skimage.transform import warp_polar
from skimage.io import imread as rdtif
train = pd.read_csv(f'{datapath}train-unique.csv')
etrain = pd.read_csv(f'{datapath}extra_train.csv')
trainall = pd.concat([train, etrain], ignore_index=True)
psz = trainall.PlotSize_acres
x, y = trainall.x, trainall.y
d = np.sqrt(x*x + y*y)
fs = 13
fig, ax = plt.subplots(tight_layout=True)
ax.hist(d, density=True, color='steelblue', alpha=0.5, bins=30)
ax.set_xlabel('distance [km]', fontsize=fs)
ax.set_ylabel('PDF', fontsize=fs)
ax.set_xlim(-0.02,1.98)
plt.savefig('dist_hist.png')
adeg = np.rad2deg(np.arctan2(y, x))
arad = np.arctan2(y, x)
plt.figure()
plt.scatter(adeg+180, d, c=psz, s=psz*50, cmap='tab10', alpha=0.75)
plt.xlabel('angle [deg]', fontsize=fs)
plt.ylabel('distance [km]', fontsize=fs)
plt.ylim(0,1.79)
plt.xlim(0, 360)
cb = plt.colorbar()
cb.set_label(label='Area [acres]', fontsize=fs)
plt.tight_layout()
plt.savefig('bubbles.png')
fig = plt.figure()
ax = fig.add_subplot(projection='polar')
c = ax.scatter(arad, d, c=psz, s=psz*20, cmap='tab10', alpha=0.75)
plt.tight_layout()
plt.savefig('polar.png')
| [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.tight_layout",
"numpy.arctan2",
"matplotlib.pyplot.ylim",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
... | [((222, 264), 'pandas.read_csv', 'pd.read_csv', (['f"""{datapath}train-unique.csv"""'], {}), "(f'{datapath}train-unique.csv')\n", (233, 264), True, 'import pandas as pd\n'), ((274, 315), 'pandas.read_csv', 'pd.read_csv', (['f"""{datapath}extra_train.csv"""'], {}), "(f'{datapath}extra_train.csv')\n", (285, 315), True, 'import pandas as pd\n'), ((327, 372), 'pandas.concat', 'pd.concat', (['[train, etrain]'], {'ignore_index': '(True)'}), '([train, etrain], ignore_index=True)\n', (336, 372), True, 'import pandas as pd\n'), ((440, 462), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y)'], {}), '(x * x + y * y)\n', (447, 462), True, 'import numpy as np\n'), ((479, 510), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'tight_layout': '(True)'}), '(tight_layout=True)\n', (491, 510), True, 'import matplotlib.pyplot as plt\n'), ((677, 705), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""dist_hist.png"""'], {}), "('dist_hist.png')\n", (688, 705), True, 'import matplotlib.pyplot as plt\n'), ((750, 766), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (760, 766), True, 'import numpy as np\n'), ((768, 780), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (778, 780), True, 'import matplotlib.pyplot as plt\n'), ((781, 852), 'matplotlib.pyplot.scatter', 'plt.scatter', (['(adeg + 180)', 'd'], {'c': 'psz', 's': '(psz * 50)', 'cmap': '"""tab10"""', 'alpha': '(0.75)'}), "(adeg + 180, d, c=psz, s=psz * 50, cmap='tab10', alpha=0.75)\n", (792, 852), True, 'import matplotlib.pyplot as plt\n'), ((849, 887), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""angle [deg]"""'], {'fontsize': 'fs'}), "('angle [deg]', fontsize=fs)\n", (859, 887), True, 'import matplotlib.pyplot as plt\n'), ((888, 928), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""distance [km]"""'], {'fontsize': 'fs'}), "('distance [km]', fontsize=fs)\n", (898, 928), True, 'import matplotlib.pyplot as plt\n'), ((929, 946), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1.79)'], {}), '(0, 1.79)\n', (937, 946), True, 'import matplotlib.pyplot as plt\n'), ((946, 962), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(360)'], {}), '(0, 360)\n', (954, 962), True, 'import matplotlib.pyplot as plt\n'), ((968, 982), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (980, 982), True, 'import matplotlib.pyplot as plt\n'), ((1031, 1049), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1047, 1049), True, 'import matplotlib.pyplot as plt\n'), ((1050, 1076), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""bubbles.png"""'], {}), "('bubbles.png')\n", (1061, 1076), True, 'import matplotlib.pyplot as plt\n'), ((1084, 1096), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1094, 1096), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1226), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1224, 1226), True, 'import matplotlib.pyplot as plt\n'), ((1227, 1251), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""polar.png"""'], {}), "('polar.png')\n", (1238, 1251), True, 'import matplotlib.pyplot as plt\n'), ((725, 741), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (735, 741), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
@author: sreimond
"""
import pytest
from picasso.utils.analysis import special_functions
import numpy as np
def test_legendre1_degree2_order1_x02():
"""
Test if the fully normalized associated Legendre function of the first
kind of degree 2 and order 1 for the argument x = 0.2 is equal to the
analytical expression (within 12 digits accuracy).
Reference: Hofmann-Wellenhof, Moritz 2006 (ISBN 978-3-211-33545-1)
"""
p = special_functions.legendre1(2,0.2)
p21_test = p[0,4]
p21_true = np.sqrt(15.0) * np.sin(0.2) * np.cos(0.2)
assert p21_test == pytest.approx(p21_true,1e-12)
| [
"picasso.utils.analysis.special_functions.legendre1",
"numpy.sin",
"numpy.cos",
"pytest.approx",
"numpy.sqrt"
] | [((461, 496), 'picasso.utils.analysis.special_functions.legendre1', 'special_functions.legendre1', (['(2)', '(0.2)'], {}), '(2, 0.2)\n', (488, 496), False, 'from picasso.utils.analysis import special_functions\n'), ((557, 568), 'numpy.cos', 'np.cos', (['(0.2)'], {}), '(0.2)\n', (563, 568), True, 'import numpy as np\n'), ((589, 619), 'pytest.approx', 'pytest.approx', (['p21_true', '(1e-12)'], {}), '(p21_true, 1e-12)\n', (602, 619), False, 'import pytest\n'), ((527, 540), 'numpy.sqrt', 'np.sqrt', (['(15.0)'], {}), '(15.0)\n', (534, 540), True, 'import numpy as np\n'), ((543, 554), 'numpy.sin', 'np.sin', (['(0.2)'], {}), '(0.2)\n', (549, 554), True, 'import numpy as np\n')] |
import sys
import os
from glob import glob
import random
import tempfile
import numpy as np
import pandas as pd
from scipy import stats
import pyBigWig
import click
from rpy2 import robjects as robj
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
pandas2ri.activate()
derfinder = importr('derfinder')
robj.r['options'](species='arabidopsis_thaliana')
robj.r['options'](chrsStyle=robj.r("NULL"))
def get_chroms_list(bw_fn):
with pyBigWig.open(bw_fn) as bw:
chroms = list(bw.chroms().keys())
return chroms
def load_data(file_names, sample_names, conditions,
chroms=None, cutoff=10, **fullcov_kws):
chroms = robj.StrVector(chroms)
fn = robj.StrVector(file_names)
sn = robj.StrVector(sample_names)
cn = robj.StrVector(conditions)
cond_data = robj.DataFrame({'row.names': sn, 'cond': cn}, stringsasfactor=True)
fn.names = sn
full_cov = derfinder.fullCoverage(
files=fn, chrs=chroms,
cutoff=cutoff, **fullcov_kws
)
return full_cov, cond_data
def make_models(full_cov, cond_data):
sample_depths = derfinder.sampleDepth(
derfinder.collapseFullCoverage(full_cov), 1)
models = derfinder.makeModels(sample_depths, testvars=cond_data.rx('cond')[0])
return models
def run_base_level_derfinder(full_cov, cond_data, models, chrom, n_permutations, seed):
seeds = robj.IntVector([seed + i for i in range(n_permutations)])
tmpdir = tempfile.mkdtemp(dir='.')
res = derfinder.analyzeChr(
chr=robj.StrVector([chrom]), coverageInfo=full_cov.rx(chrom)[0],
models=models, groupInfo=cond_data.rx('cond')[0], writeOutput=False,
cutoffFstat=5e-02, nPermute=n_permutations, seeds=seeds,
returnOutput=True, runAnnotation=False, lowMemDir=os.path.join(tmpdir, chrom, 'chunksDir')
)
res = res.rx('regions')[0].rx('regions')[0]
res = robj.r['as.data.frame'](res)
res = robj.r['type.convert'](res, **{'as.is':True})
res = pandas2ri.ri2py(res)
return res
def run_derfinder(cntrl_bws, treat_bws,
cntrl_name, treat_name,
chroms=None, expression_cutoff=10,
n_permutations=50, seed=10123):
assert cntrl_name != treat_name
sample_names = ['{}_{}'.format(cntrl_name, i) for i in range(len(cntrl_bws))] + \
['{}_{}'.format(treat_name, i) for i in range(len(treat_bws))]
conds = [s.split('_')[0] for s in sample_names]
bws = cntrl_bws + treat_bws
if chroms is None:
# find ALL the chroms:
chroms = get_chroms_list(bws[0])
elif isinstance(chroms, str):
chroms = [chroms,]
all_chrom_results = []
full_cov, cond_data = load_data(
bws, sample_names, conds,
chroms=chroms,
cutoff=expression_cutoff
)
models = make_models(full_cov, cond_data)
for chrom in chroms:
chrom_res = run_base_level_derfinder(
full_cov, cond_data, models, chrom, n_permutations, seed
)
all_chrom_results.append(chrom_res)
results = pd.concat(all_chrom_results, axis=0)
return results
def write_bed_of_sig_res(results, output_file, cntrl_name, treat_name, effect_size_threshold=1):
name = '{}_vs_{}'.format(cntrl_name, treat_name)
fch_col = results.columns[results.columns.str.startswith('log2FoldChange')][0]
results_filt = results.copy()
results_filt['name'] = name
results_filt = results_filt.loc[
results.significantQval.astype(bool) & (np.abs(results[fch_col]) > effect_size_threshold),
['seqnames', 'start', 'end', 'name', fch_col, 'strand', 'meanCoverage',
f'mean{cntrl_name}', f'mean{treat_name}', 'pvalues', 'qvalues']
]
results_filt = results_filt.sort_values(['seqnames', 'start'])
results_filt['pvalues'] = -np.log10(results_filt.pvalues)
results_filt['qvalues'] = -np.log10(results_filt.qvalues)
results_filt.to_csv(output_file, sep='\t', header=False, index=False, float_format='%5g')
@click.command()
@click.option('-cb', '--cntrl-bws', multiple=True, required=True)
@click.option('-tb', '--treat-bws', multiple=True, required=True)
@click.option('-cn', '--cntrl-name', required=True)
@click.option('-tn', '--treat-name', required=True)
@click.option('-o', '--output-fn', required=True)
@click.option('-b', '--bed-output-fn', required=True)
@click.option('-s', '--strand', required=False, type=click.Choice(['+', '-', '.']))
@click.option('-est', '--effect-size-threshold', required=False, default=1, type=float)
@click.option('-c', '--expression-cutoff', required=False, default=10, type=float)
@click.option('-np', '--n-permutations', required=False, default=50, type=int)
def cli(cntrl_bws, treat_bws,
cntrl_name, treat_name,
output_fn, bed_output_fn, strand,
effect_size_threshold,
expression_cutoff,
n_permutations):
res = run_derfinder(
cntrl_bws, treat_bws,
cntrl_name, treat_name,
n_permutations=n_permutations,
expression_cutoff=expression_cutoff
)
res['strand'] = strand
res.to_csv(output_fn, sep='\t')
write_bed_of_sig_res(res, bed_output_fn,
cntrl_name, treat_name,
effect_size_threshold)
if __name__ == '__main__':
cli() | [
"rpy2.robjects.pandas2ri.ri2py",
"rpy2.robjects.packages.importr",
"numpy.abs",
"rpy2.robjects.pandas2ri.activate",
"click.option",
"rpy2.robjects.r",
"click.command",
"click.Choice",
"tempfile.mkdtemp",
"pyBigWig.open",
"rpy2.robjects.DataFrame",
"numpy.log10",
"os.path.join",
"pandas.con... | [((283, 303), 'rpy2.robjects.pandas2ri.activate', 'pandas2ri.activate', ([], {}), '()\n', (301, 303), False, 'from rpy2.robjects import pandas2ri\n'), ((318, 338), 'rpy2.robjects.packages.importr', 'importr', (['"""derfinder"""'], {}), "('derfinder')\n", (325, 338), False, 'from rpy2.robjects.packages import importr\n'), ((4023, 4038), 'click.command', 'click.command', ([], {}), '()\n', (4036, 4038), False, 'import click\n'), ((4040, 4104), 'click.option', 'click.option', (['"""-cb"""', '"""--cntrl-bws"""'], {'multiple': '(True)', 'required': '(True)'}), "('-cb', '--cntrl-bws', multiple=True, required=True)\n", (4052, 4104), False, 'import click\n'), ((4106, 4170), 'click.option', 'click.option', (['"""-tb"""', '"""--treat-bws"""'], {'multiple': '(True)', 'required': '(True)'}), "('-tb', '--treat-bws', multiple=True, required=True)\n", (4118, 4170), False, 'import click\n'), ((4172, 4222), 'click.option', 'click.option', (['"""-cn"""', '"""--cntrl-name"""'], {'required': '(True)'}), "('-cn', '--cntrl-name', required=True)\n", (4184, 4222), False, 'import click\n'), ((4224, 4274), 'click.option', 'click.option', (['"""-tn"""', '"""--treat-name"""'], {'required': '(True)'}), "('-tn', '--treat-name', required=True)\n", (4236, 4274), False, 'import click\n'), ((4276, 4324), 'click.option', 'click.option', (['"""-o"""', '"""--output-fn"""'], {'required': '(True)'}), "('-o', '--output-fn', required=True)\n", (4288, 4324), False, 'import click\n'), ((4326, 4378), 'click.option', 'click.option', (['"""-b"""', '"""--bed-output-fn"""'], {'required': '(True)'}), "('-b', '--bed-output-fn', required=True)\n", (4338, 4378), False, 'import click\n'), ((4464, 4554), 'click.option', 'click.option', (['"""-est"""', '"""--effect-size-threshold"""'], {'required': '(False)', 'default': '(1)', 'type': 'float'}), "('-est', '--effect-size-threshold', required=False, default=1,\n type=float)\n", (4476, 4554), False, 'import click\n'), ((4552, 4638), 'click.option', 'click.option', (['"""-c"""', '"""--expression-cutoff"""'], {'required': '(False)', 'default': '(10)', 'type': 'float'}), "('-c', '--expression-cutoff', required=False, default=10, type=\n float)\n", (4564, 4638), False, 'import click\n'), ((4635, 4712), 'click.option', 'click.option', (['"""-np"""', '"""--n-permutations"""'], {'required': '(False)', 'default': '(50)', 'type': 'int'}), "('-np', '--n-permutations', required=False, default=50, type=int)\n", (4647, 4712), False, 'import click\n'), ((681, 703), 'rpy2.robjects.StrVector', 'robj.StrVector', (['chroms'], {}), '(chroms)\n', (695, 703), True, 'from rpy2 import robjects as robj\n'), ((713, 739), 'rpy2.robjects.StrVector', 'robj.StrVector', (['file_names'], {}), '(file_names)\n', (727, 739), True, 'from rpy2 import robjects as robj\n'), ((749, 777), 'rpy2.robjects.StrVector', 'robj.StrVector', (['sample_names'], {}), '(sample_names)\n', (763, 777), True, 'from rpy2 import robjects as robj\n'), ((787, 813), 'rpy2.robjects.StrVector', 'robj.StrVector', (['conditions'], {}), '(conditions)\n', (801, 813), True, 'from rpy2 import robjects as robj\n'), ((830, 897), 'rpy2.robjects.DataFrame', 'robj.DataFrame', (["{'row.names': sn, 'cond': cn}"], {'stringsasfactor': '(True)'}), "({'row.names': sn, 'cond': cn}, stringsasfactor=True)\n", (844, 897), True, 'from rpy2 import robjects as robj\n'), ((1470, 1495), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'dir': '"""."""'}), "(dir='.')\n", (1486, 1495), False, 'import tempfile\n'), ((2001, 2021), 'rpy2.robjects.pandas2ri.ri2py', 'pandas2ri.ri2py', (['res'], {}), '(res)\n', (2016, 2021), False, 'from rpy2.robjects import pandas2ri\n'), ((3083, 3119), 'pandas.concat', 'pd.concat', (['all_chrom_results'], {'axis': '(0)'}), '(all_chrom_results, axis=0)\n', (3092, 3119), True, 'import pandas as pd\n'), ((417, 431), 'rpy2.robjects.r', 'robj.r', (['"""NULL"""'], {}), "('NULL')\n", (423, 431), True, 'from rpy2 import robjects as robj\n'), ((472, 492), 'pyBigWig.open', 'pyBigWig.open', (['bw_fn'], {}), '(bw_fn)\n', (485, 492), False, 'import pyBigWig\n'), ((3833, 3863), 'numpy.log10', 'np.log10', (['results_filt.pvalues'], {}), '(results_filt.pvalues)\n', (3841, 3863), True, 'import numpy as np\n'), ((3895, 3925), 'numpy.log10', 'np.log10', (['results_filt.qvalues'], {}), '(results_filt.qvalues)\n', (3903, 3925), True, 'import numpy as np\n'), ((4432, 4461), 'click.Choice', 'click.Choice', (["['+', '-', '.']"], {}), "(['+', '-', '.'])\n", (4444, 4461), False, 'import click\n'), ((1540, 1563), 'rpy2.robjects.StrVector', 'robj.StrVector', (['[chrom]'], {}), '([chrom])\n', (1554, 1563), True, 'from rpy2 import robjects as robj\n'), ((1801, 1841), 'os.path.join', 'os.path.join', (['tmpdir', 'chrom', '"""chunksDir"""'], {}), "(tmpdir, chrom, 'chunksDir')\n", (1813, 1841), False, 'import os\n'), ((3525, 3549), 'numpy.abs', 'np.abs', (['results[fch_col]'], {}), '(results[fch_col])\n', (3531, 3549), True, 'import numpy as np\n')] |
import numpy as np
import pickle
import numpy as np
import pickle
from itertools import chain
from collections import OrderedDict
from sklearn.model_selection import train_test_split
import matplotlib.pylab as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
import pandas as pd
pd.options.display.max_columns = 50
from IPython.display import display, HTML
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from AI_scientist.prepare_dataset import Dataset_Gen
from AI_scientist.util import plot_matrices, make_dir, get_struct_str, get_args, Early_Stopping, record_data, manifold_embedding, get_args, make_dir, sort_two_lists
from AI_scientist.settings.filepath import variational_model_PATH, dataset_PATH
from AI_scientist.pytorch.model import Model, load_model
from AI_scientist.pytorch.net import Net
from AI_scientist.variational.variational_meta_learning import Master_Model, Statistics_Net, Generative_Net, load_model_dict
from AI_scientist.variational.variational_meta_learning import VAE_Loss, sample_Gaussian, clone_net, get_nets, get_tasks, evaluate, get_reg, load_trained_models, get_relevance
from AI_scientist.variational.variational_meta_learning import plot_task_ensembles, plot_individual_tasks, plot_statistics_vs_z, plot_data_record
from AI_scientist.variational.variational_meta_learning import get_latent_model_data, get_polynomial_class, get_Legendre_class, get_master_function
import torch
import torch.nn as nn
from torch.autograd import Variable
if __name__ == "__main__":
exp_id = "exp1.1" # Standard
filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_8_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_1e-05_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.1_" # Best
filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.1_" # second best
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.1_"
filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_1e-05_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.1_"
exp_id = "exp1.2" # Standard
filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_0.0001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_1e-05_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_0.0001_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_1e-05_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_2e-06_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_2e-06_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_1e-05_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_True_0.2_lr_0.0001_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.2_lr_2e-06_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_50_backward_1_VAE_True_0.2_lr_1e-05_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_exp1.2_"
# exp_id = "exp1.3" # Gaussian standard
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_50_backward_1_VAE_False_1.0_lr_0.001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_3_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_lr_0.001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.3_"
# exp_id = "exp1.32" # Gaussian VAE
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_mean_context_0_batch_50_backward_1_VAE_True_0.2_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_50_backward_1_VAE_True_0.05_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.05_lr_0.001_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_True_0.05_lr_0.0001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_3_batch_100_backward_1_VAE_True_0.05_lr_0.0001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_mean_context_3_batch_100_backward_1_VAE_True_0.05_lr_1e-05_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_50_backward_1_VAE_True_0.05_lr_0.001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_mean_context_3_batch_50_backward_1_VAE_True_0.05_lr_0.0001_reg_1e-06_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_True_0.05_lr_0.001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# filename = "Net_['master_Gaussian']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_True_0.05_lr_0.0001_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.32_"
# exp_id = "exp1.4" # Standard, testing optim_type
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_50_backward_1_VAE_False_1.0_lr_0.001_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_0.0_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_lr_0.001_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_False_1.0_lr_0.001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_50_backward_1_VAE_False_1.0_lr_0.001_reg_1e-07_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# filename = "Net_['master_tanh']_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_50_backward_1_VAE_False_1.0_lr_0.0001_reg_1e-06_actgen_elu_actmodel_leakyRelu_struct_60Si-60Si-60Si_sum_exp1.4"
# exp_id = "exp2.0"
# filename_list = [
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0001_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0001_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0001_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0005_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0005_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0005_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_100_pooling_max_context_0_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0005_reg_1e-07_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# "Net_('master_tanh',)_input_1_(100,100)_statistics-neurons_4_pre_50_pooling_max_context_3_batch_100_backward_1_VAE_False_1.0_uncertainty_True_lr_0.0005_reg_0.0_actgen_leakyRelu_actmodel_leakyRelu_struct_60Si-60Si-60Si_individual_exp2.0_",
# ]
# filename = filename_list[0]
is_model_dict = True
print(filename)
filename = variational_model_PATH + "/trained_models/{0}_good/".format(exp_id) + filename
if is_model_dict:
info_dict = pickle.load(open(filename + ".p", "rb"))
master_model = load_model_dict(info_dict["model_dict"][-1])
statistics_Net = master_model.statistics_Net
generative_Net = master_model.generative_Net
data_record = info_dict["data_record"]
else:
statistics_Net, generative_Net, data_record = load_trained_models(filename)
filename_split = filename.split("_")
task_id_list = eval("_".join(filename_split[filename_split.index('good/Net') + 1: filename_split.index("input")]))
task_settings = data_record["task_settings"][0]
print("task_settings:\n", task_settings)
is_VAE = eval(filename_split[filename_split.index("VAE") + 1])
is_uncertainty_net = eval(filename_split[filename_split.index("uncertainty") + 1]) if "uncertainty" in filename_split else False
num_test_tasks = 1000
task_settings["num_examples"] = 2000
task_settings["test_size"] = 0.95
tasks_train, tasks_test = get_tasks(task_id_list, 1, num_test_tasks, task_settings = task_settings)
plot_types = ["standard"]
# plot_types = ["gradient"]
plot_types = ["slider"]
for plot_type in plot_types:
if plot_type == "standard":
plot_data_record(data_record, is_VAE = is_VAE)
statistics_list_test, z_list_test = plot_task_ensembles(tasks_test, statistics_Net, generative_Net, is_VAE = is_VAE, title = "y_pred_test vs. y_test")
print("test statistics vs. z:")
plot_statistics_vs_z(z_list_test, statistics_list_test)
_ = plot_individual_tasks(tasks_test, statistics_Net, generative_Net, is_VAE = is_VAE, xlim = task_settings["xlim"])
elif plot_type == "gradient":
batch_size = 256
sample_task_id = task_id_list[0] + "_{0}".format(np.random.randint(num_test_tasks))
print("sample_task_id: {0}".format(sample_task_id))
((X_train, y_train), (X_test, y_test)), _ = tasks_test[sample_task_id]
epochs_statistics = 50
lr_statistics = 5e-3
optim_type_statistics = "LBFGS"
# epochs = 50
# lr = 1e-3
# optimizer = "adam"
epochs = 50
lr = 5e-3
optim_type = "LBFGS"
master_model.get_statistics(X_train, y_train)
y_pred = master_model(X_test)
loss_list_0 = master_model.latent_param_quick_learn(X_train, y_train, validation_data = (X_test, y_test), batch_size = batch_size,
epochs = epochs_statistics, lr = lr_statistics, optim_type = optim_type_statistics)
y_pred_new = master_model(X_test)
plt.plot(X_test.data.numpy(), y_test.data.numpy(), ".b", label = "target", markersize = 2, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred.data.numpy(), ".r", label = "initial", markersize = 2, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred_new.data.numpy(), ".y", label = "optimized", markersize = 2, alpha = 0.6)
plt.plot(X_train.data.numpy(), y_train.data.numpy(), ".k", markersize = 5, label = "training points")
plt.title("Only optimizing latent variable, validation")
plt.legend()
plt.show()
master_model.get_statistics(X_train, y_train)
master_model.use_clone_net(clone_parameters = True)
y_pred = master_model(X_test)
loss_list_1 = master_model.clone_net_quick_learn(X_train, y_train, validation_data = (X_test, y_test), batch_size = batch_size,
epochs = epochs, lr = lr, optim_type = optim_type)
y_pred_new = master_model(X_test)
plt.plot(X_test.data.numpy(), y_test.data.numpy(), ".b", label = "target", markersize = 2, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred.data.numpy(), ".r", label = "initial", markersize = 2, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred_new.data.numpy(), ".y", label = "optimized", markersize = 2, alpha = 0.6)
plt.plot(X_train.data.numpy(), y_train.data.numpy(), ".k", markersize = 5, label = "training points")
plt.legend()
plt.title("Optimizing cloned net, validation")
plt.show()
master_model.get_statistics(X_train, y_train)
master_model.use_clone_net(clone_parameters = False)
W_core, _ = master_model.cloned_net.get_weights_bias(W_source = "core")
y_pred = master_model(X_test)
loss_list_2 = master_model.clone_net_quick_learn(X_train, y_train, validation_data = (X_test, y_test), batch_size = batch_size,
epochs = epochs, lr = lr, optim_type = optim_type)
y_pred_new = master_model(X_test)
plt.plot(X_test.data.numpy(), y_test.data.numpy(), ".b", label = "target", markersize = 3, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred.data.numpy(), ".r", label = "initial", markersize = 3, alpha = 0.6)
plt.plot(X_test.data.numpy(), y_pred_new.data.numpy(), ".y", label = "optimized", markersize = 3, alpha = 0.6)
plt.plot(X_train.data.numpy(), y_train.data.numpy(), ".k", markersize = 5, label = "training points")
plt.xlabel("epochs")
plt.ylabel("mse loss")
plt.legend()
plt.title("Optimizing from_scratch, validation")
plt.show()
plt.plot(range(len(loss_list_0)), loss_list_0, label = "loss_optim_latent_param")
plt.plot(range(len(loss_list_1)), loss_list_1, label = "loss_clone")
plt.plot(range(len(loss_list_2)), loss_list_2, label = "loss_scratch")
plt.legend()
plt.show()
plt.semilogy(range(len(loss_list_0)), loss_list_0, label = "loss_optim_latent_param")
plt.semilogy(range(len(loss_list_1)), loss_list_1, label = "loss_clone")
plt.semilogy(range(len(loss_list_2)), loss_list_2, label = "loss_scratch")
plt.legend()
plt.show()
elif plot_type == "slider":
from matplotlib.widgets import Slider, Button, RadioButtons
import matplotlib
num_tasks_sampled = 10
rand_id = sorted(np.random.randint(num_test_tasks, size = num_tasks_sampled))
task_dict = {}
sample_task_ids = []
for i, idx in enumerate(rand_id):
sample_task_id = task_id_list[0] + "_{0}".format(idx)
sample_task_ids.append(sample_task_id)
((X_train, y_train), (X_test, y_test)), _ = tasks_test[sample_task_id]
if i == 0:
X_test_0, y_test_0 = X_test, y_test
X_train_0, y_train_0 = X_train, y_train
task_dict[sample_task_id] = [[X_train, y_train], [X_test, y_test]]
X_train, y_train = X_train_0, y_train_0
X_test, y_test = X_test_0, y_test_0
if is_VAE:
statistics = statistics_Net(torch.cat([X_train, y_train], 1))[0][0]
else:
statistics = statistics_Net(torch.cat([X_train, y_train], 1))[0]
statistics_numpy = statistics.data.numpy()
relevance = get_relevance(X_train, y_train, statistics_Net)
pred = generative_Net(X_test, statistics)
W_core, _ = generative_Net.get_weights_bias(W_source = "core")
num_layers = len(W_core)
fig, ax = plt.subplots(figsize = (9, 7.5))
plt.subplots_adjust(left=0.25, bottom=0.27)
ss0, ss1, ss2, ss3 = statistics_numpy.squeeze().tolist()
subplt1 = plt.subplot2grid((3, num_layers), (0,0), rowspan = 2, colspan = num_layers)
l_button_test, = subplt1.plot(X_test.data.numpy(), y_test.data.numpy(), ".r", markersize = 2, alpha = 0.6, label = "testing target")
l_button, = subplt1.plot(X_train.data.numpy(), y_train.data.numpy(), ".k", markersize = 4, alpha = 0.6, label = "training point")
# subplt1.scatter(X_train.data.numpy(), y_train.data.numpy(), s = relevance * 5 + 1, c = "k", alpha = 0.6)
if is_uncertainty_net:
statistics_logvar = statistics_Net(torch.cat([X_train, y_train], 1))[1]
pred_std = torch.exp(master_model.generative_Net_logstd(X_test, statistics_logvar))
l_errormean, _, l_errorbar = subplt1.errorbar(X_test.data.numpy().squeeze(), pred.data.numpy().squeeze(), yerr = pred_std.data.numpy().squeeze(), color = "b", fmt = ".", markersize = 1, alpha = 0.2)
else:
l, = subplt1.plot(X_test.data.numpy(), pred.data.numpy(),'.b', markersize = 2, alpha = 0.6, label = "predicted")
subplt1.axis([task_settings["xlim"][0], task_settings["xlim"][1], -5, 5])
subplt1.legend()
subplt2s = []
for i in range(num_layers):
subplt2 = plt.subplot2grid((3, num_layers), (2, i))
scale_min = np.floor(np.min(W_core[i]))
scale_max = np.ceil(np.max(W_core[i]))
subplt2.matshow(W_core[i], cmap = matplotlib.cm.binary, vmin = scale_min, vmax = scale_max)
subplt2.set_xticks(np.array([]))
subplt2.set_yticks(np.array([]))
subplt2.set_xlabel("({0:.3f}, {1:.3f})".format(scale_min, scale_max), fontsize = 10)
axcolor = 'lightgoldenrodyellow'
ax0 = plt.axes([0.25, 0.08, 0.65, 0.025], facecolor=axcolor)
ax1 = plt.axes([0.25, 0.12, 0.65, 0.025], facecolor=axcolor)
ax2 = plt.axes([0.25, 0.16, 0.65, 0.025], facecolor=axcolor)
ax3 = plt.axes([0.25, 0.2, 0.65, 0.025], facecolor=axcolor)
s0 = Slider(ax0, 'Statistics[0]', -3, 3, valinit=ss0)
s1 = Slider(ax1, 'Statistics[1]', -3, 3, valinit=ss1)
s2 = Slider(ax2, 'Statistics[2]', -3, 3, valinit=ss2)
s3 = Slider(ax3, 'Statistics[3]', -3, 3, valinit=ss3)
def update(val):
(X_train, y_train), (X_test, y_test) = task_dict[radio.value_selected]
statistics_numpy = np.array([[s0.val, s1.val, s2.val, s3.val]])
statistics = Variable(torch.FloatTensor(statistics_numpy))
pred = generative_Net(X_test, statistics)
l.set_ydata(pred.data.numpy())
l.set_xdata(X_test.data.numpy())
W_core, _ = generative_Net.get_weights_bias(W_source = "core")
for i in range(num_layers):
subplt2 = plt.subplot2grid((3, num_layers), (2, i))
scale_min = np.floor(np.min(W_core[i]))
scale_max = np.ceil(np.max(W_core[i]))
subplt2.matshow(W_core[i], cmap = matplotlib.cm.binary, vmin = scale_min, vmax = scale_max)
subplt2.set_xticks(np.array([]))
subplt2.set_yticks(np.array([]))
subplt2.set_xlabel("({0:.3f}, {1:.3f})".format(scale_min, scale_max), fontsize = 10)
fig.canvas.draw_idle()
s0.on_changed(update)
s1.on_changed(update)
s2.on_changed(update)
s3.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
button.label.set_fontsize(8)
def reset(event):
s0.reset()
s1.reset()
s2.reset()
s3.reset()
button.on_clicked(reset)
rax = plt.axes([0.025, 0.5 - 0.01 * num_tasks_sampled, 0.18, 0.03 * num_tasks_sampled], facecolor = axcolor)
radio = RadioButtons(rax, sample_task_ids, active=0)
def update_y_test(label):
# Update the target_data:
(X_train, y_train), (X_test, y_test) = task_dict[label]
l_button.set_ydata(y_train.data.numpy())
l_button.set_xdata(X_train.data.numpy())
l_button_test.set_ydata(y_test.data.numpy())
l_button_test.set_xdata(X_test.data.numpy())
# Update the fitted data:
if is_VAE:
statistics = statistics_Net(torch.cat([X_train, y_train], 1))[0][0]
else:
statistics = statistics_Net(torch.cat([X_train, y_train], 1))[0]
pred = generative_Net(X_test, statistics)
if is_uncertainty_net:
statistics_logvar = statistics_Net(torch.cat([X_test, y_test], 1))[1]
pred_std = torch.exp(master_model.generative_Net_logstd(X_test, statistics_logvar))
l_errormean.set_xdata(X_test.data.numpy())
l_errormean.set_ydata(pred.data.numpy())
print(torch.cat([pred-pred_std, pred+pred_std], 1).data.numpy().shape)
l_errorbar[0].set_verts(torch.cat([pred-pred_std, pred+pred_std], 1).data.numpy())
else:
l.set_xdata(X_test.data.numpy())
l.set_ydata(pred.data.numpy())
# Update the slider
ss0, ss1, ss2, ss3 = statistics.data.numpy().squeeze().tolist()
s0.set_val(ss0)
s1.set_val(ss1)
s2.set_val(ss2)
s3.set_val(ss3)
fig.canvas.draw_idle()
radio.on_clicked(update_y_test)
plt.show()
| [
"matplotlib.pyplot.title",
"AI_scientist.variational.variational_meta_learning.load_model_dict",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.subplot2grid",
"matplotlib.widgets.Slider",
"torch.cat",
"AI_scientist.variational.variational_meta_learning.plot_task_ensembles",
"numpy.random.randint",
"ma... | [((15737, 15808), 'AI_scientist.variational.variational_meta_learning.get_tasks', 'get_tasks', (['task_id_list', '(1)', 'num_test_tasks'], {'task_settings': 'task_settings'}), '(task_id_list, 1, num_test_tasks, task_settings=task_settings)\n', (15746, 15808), False, 'from AI_scientist.variational.variational_meta_learning import VAE_Loss, sample_Gaussian, clone_net, get_nets, get_tasks, evaluate, get_reg, load_trained_models, get_relevance\n'), ((487, 514), 'os.path.dirname', 'os.path.dirname', (['"""__file__"""'], {}), "('__file__')\n", (502, 514), False, 'import sys, os\n'), ((14852, 14896), 'AI_scientist.variational.variational_meta_learning.load_model_dict', 'load_model_dict', (["info_dict['model_dict'][-1]"], {}), "(info_dict['model_dict'][-1])\n", (14867, 14896), False, 'from AI_scientist.variational.variational_meta_learning import Master_Model, Statistics_Net, Generative_Net, load_model_dict\n'), ((15114, 15143), 'AI_scientist.variational.variational_meta_learning.load_trained_models', 'load_trained_models', (['filename'], {}), '(filename)\n', (15133, 15143), False, 'from AI_scientist.variational.variational_meta_learning import VAE_Loss, sample_Gaussian, clone_net, get_nets, get_tasks, evaluate, get_reg, load_trained_models, get_relevance\n'), ((15983, 16027), 'AI_scientist.variational.variational_meta_learning.plot_data_record', 'plot_data_record', (['data_record'], {'is_VAE': 'is_VAE'}), '(data_record, is_VAE=is_VAE)\n', (15999, 16027), False, 'from AI_scientist.variational.variational_meta_learning import plot_task_ensembles, plot_individual_tasks, plot_statistics_vs_z, plot_data_record\n'), ((16079, 16194), 'AI_scientist.variational.variational_meta_learning.plot_task_ensembles', 'plot_task_ensembles', (['tasks_test', 'statistics_Net', 'generative_Net'], {'is_VAE': 'is_VAE', 'title': '"""y_pred_test vs. y_test"""'}), "(tasks_test, statistics_Net, generative_Net, is_VAE=\n is_VAE, title='y_pred_test vs. y_test')\n", (16098, 16194), False, 'from AI_scientist.variational.variational_meta_learning import plot_task_ensembles, plot_individual_tasks, plot_statistics_vs_z, plot_data_record\n'), ((16250, 16305), 'AI_scientist.variational.variational_meta_learning.plot_statistics_vs_z', 'plot_statistics_vs_z', (['z_list_test', 'statistics_list_test'], {}), '(z_list_test, statistics_list_test)\n', (16270, 16305), False, 'from AI_scientist.variational.variational_meta_learning import plot_task_ensembles, plot_individual_tasks, plot_statistics_vs_z, plot_data_record\n'), ((16322, 16435), 'AI_scientist.variational.variational_meta_learning.plot_individual_tasks', 'plot_individual_tasks', (['tasks_test', 'statistics_Net', 'generative_Net'], {'is_VAE': 'is_VAE', 'xlim': "task_settings['xlim']"}), "(tasks_test, statistics_Net, generative_Net, is_VAE=\n is_VAE, xlim=task_settings['xlim'])\n", (16343, 16435), False, 'from AI_scientist.variational.variational_meta_learning import plot_task_ensembles, plot_individual_tasks, plot_statistics_vs_z, plot_data_record\n'), ((17943, 17999), 'matplotlib.pyplot.title', 'plt.title', (['"""Only optimizing latent variable, validation"""'], {}), "('Only optimizing latent variable, validation')\n", (17952, 17999), True, 'import matplotlib.pyplot as plt\n'), ((18012, 18024), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (18022, 18024), True, 'import matplotlib.pyplot as plt\n'), ((18037, 18047), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18045, 18047), True, 'import matplotlib.pyplot as plt\n'), ((18994, 19006), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (19004, 19006), True, 'import matplotlib.pyplot as plt\n'), ((19019, 19065), 'matplotlib.pyplot.title', 'plt.title', (['"""Optimizing cloned net, validation"""'], {}), "('Optimizing cloned net, validation')\n", (19028, 19065), True, 'import matplotlib.pyplot as plt\n'), ((19078, 19088), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19086, 19088), True, 'import matplotlib.pyplot as plt\n'), ((20120, 20140), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (20130, 20140), True, 'import matplotlib.pyplot as plt\n'), ((20153, 20175), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""mse loss"""'], {}), "('mse loss')\n", (20163, 20175), True, 'import matplotlib.pyplot as plt\n'), ((20188, 20200), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20198, 20200), True, 'import matplotlib.pyplot as plt\n'), ((20213, 20261), 'matplotlib.pyplot.title', 'plt.title', (['"""Optimizing from_scratch, validation"""'], {}), "('Optimizing from_scratch, validation')\n", (20222, 20261), True, 'import matplotlib.pyplot as plt\n'), ((20274, 20284), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20282, 20284), True, 'import matplotlib.pyplot as plt\n'), ((20556, 20568), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20566, 20568), True, 'import matplotlib.pyplot as plt\n'), ((20581, 20591), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20589, 20591), True, 'import matplotlib.pyplot as plt\n'), ((20875, 20887), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (20885, 20887), True, 'import matplotlib.pyplot as plt\n'), ((20900, 20910), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20908, 20910), True, 'import matplotlib.pyplot as plt\n'), ((22105, 22152), 'AI_scientist.variational.variational_meta_learning.get_relevance', 'get_relevance', (['X_train', 'y_train', 'statistics_Net'], {}), '(X_train, y_train, statistics_Net)\n', (22118, 22152), False, 'from AI_scientist.variational.variational_meta_learning import VAE_Loss, sample_Gaussian, clone_net, get_nets, get_tasks, evaluate, get_reg, load_trained_models, get_relevance\n'), ((22342, 22372), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(9, 7.5)'}), '(figsize=(9, 7.5))\n', (22354, 22372), True, 'import matplotlib.pyplot as plt\n'), ((22387, 22430), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.25)', 'bottom': '(0.27)'}), '(left=0.25, bottom=0.27)\n', (22406, 22430), True, 'import matplotlib.pyplot as plt\n'), ((22522, 22594), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, num_layers)', '(0, 0)'], {'rowspan': '(2)', 'colspan': 'num_layers'}), '((3, num_layers), (0, 0), rowspan=2, colspan=num_layers)\n', (22538, 22594), True, 'import matplotlib.pyplot as plt\n'), ((24322, 24376), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.08, 0.65, 0.025]'], {'facecolor': 'axcolor'}), '([0.25, 0.08, 0.65, 0.025], facecolor=axcolor)\n', (24330, 24376), True, 'import matplotlib.pyplot as plt\n'), ((24395, 24449), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.12, 0.65, 0.025]'], {'facecolor': 'axcolor'}), '([0.25, 0.12, 0.65, 0.025], facecolor=axcolor)\n', (24403, 24449), True, 'import matplotlib.pyplot as plt\n'), ((24468, 24522), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.16, 0.65, 0.025]'], {'facecolor': 'axcolor'}), '([0.25, 0.16, 0.65, 0.025], facecolor=axcolor)\n', (24476, 24522), True, 'import matplotlib.pyplot as plt\n'), ((24541, 24594), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.25, 0.2, 0.65, 0.025]'], {'facecolor': 'axcolor'}), '([0.25, 0.2, 0.65, 0.025], facecolor=axcolor)\n', (24549, 24594), True, 'import matplotlib.pyplot as plt\n'), ((24613, 24661), 'matplotlib.widgets.Slider', 'Slider', (['ax0', '"""Statistics[0]"""', '(-3)', '(3)'], {'valinit': 'ss0'}), "(ax0, 'Statistics[0]', -3, 3, valinit=ss0)\n", (24619, 24661), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((24679, 24727), 'matplotlib.widgets.Slider', 'Slider', (['ax1', '"""Statistics[1]"""', '(-3)', '(3)'], {'valinit': 'ss1'}), "(ax1, 'Statistics[1]', -3, 3, valinit=ss1)\n", (24685, 24727), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((24745, 24793), 'matplotlib.widgets.Slider', 'Slider', (['ax2', '"""Statistics[2]"""', '(-3)', '(3)'], {'valinit': 'ss2'}), "(ax2, 'Statistics[2]', -3, 3, valinit=ss2)\n", (24751, 24793), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((24811, 24859), 'matplotlib.widgets.Slider', 'Slider', (['ax3', '"""Statistics[3]"""', '(-3)', '(3)'], {'valinit': 'ss3'}), "(ax3, 'Statistics[3]', -3, 3, valinit=ss3)\n", (24817, 24859), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((26121, 26154), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.8, 0.025, 0.1, 0.04]'], {}), '([0.8, 0.025, 0.1, 0.04])\n', (26129, 26154), True, 'import matplotlib.pyplot as plt\n'), ((26176, 26235), 'matplotlib.widgets.Button', 'Button', (['resetax', '"""Reset"""'], {'color': 'axcolor', 'hovercolor': '"""0.975"""'}), "(resetax, 'Reset', color=axcolor, hovercolor='0.975')\n", (26182, 26235), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((26472, 26576), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.025, 0.5 - 0.01 * num_tasks_sampled, 0.18, 0.03 * num_tasks_sampled]'], {'facecolor': 'axcolor'}), '([0.025, 0.5 - 0.01 * num_tasks_sampled, 0.18, 0.03 *\n num_tasks_sampled], facecolor=axcolor)\n', (26480, 26576), True, 'import matplotlib.pyplot as plt\n'), ((26595, 26639), 'matplotlib.widgets.RadioButtons', 'RadioButtons', (['rax', 'sample_task_ids'], {'active': '(0)'}), '(rax, sample_task_ids, active=0)\n', (26607, 26639), False, 'from matplotlib.widgets import Slider, Button, RadioButtons\n'), ((28392, 28402), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (28400, 28402), True, 'import matplotlib.pyplot as plt\n'), ((16564, 16597), 'numpy.random.randint', 'np.random.randint', (['num_test_tasks'], {}), '(num_test_tasks)\n', (16581, 16597), True, 'import numpy as np\n'), ((21114, 21171), 'numpy.random.randint', 'np.random.randint', (['num_test_tasks'], {'size': 'num_tasks_sampled'}), '(num_test_tasks, size=num_tasks_sampled)\n', (21131, 21171), True, 'import numpy as np\n'), ((23798, 23839), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, num_layers)', '(2, i)'], {}), '((3, num_layers), (2, i))\n', (23814, 23839), True, 'import matplotlib.pyplot as plt\n'), ((25012, 25056), 'numpy.array', 'np.array', (['[[s0.val, s1.val, s2.val, s3.val]]'], {}), '([[s0.val, s1.val, s2.val, s3.val]])\n', (25020, 25056), True, 'import numpy as np\n'), ((23877, 23894), 'numpy.min', 'np.min', (['W_core[i]'], {}), '(W_core[i])\n', (23883, 23894), True, 'import numpy as np\n'), ((23932, 23949), 'numpy.max', 'np.max', (['W_core[i]'], {}), '(W_core[i])\n', (23938, 23949), True, 'import numpy as np\n'), ((24094, 24106), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (24102, 24106), True, 'import numpy as np\n'), ((24143, 24155), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (24151, 24155), True, 'import numpy as np\n'), ((25095, 25130), 'torch.FloatTensor', 'torch.FloatTensor', (['statistics_numpy'], {}), '(statistics_numpy)\n', (25112, 25130), False, 'import torch\n'), ((25439, 25480), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(3, num_layers)', '(2, i)'], {}), '((3, num_layers), (2, i))\n', (25455, 25480), True, 'import matplotlib.pyplot as plt\n'), ((21989, 22021), 'torch.cat', 'torch.cat', (['[X_train, y_train]', '(1)'], {}), '([X_train, y_train], 1)\n', (21998, 22021), False, 'import torch\n'), ((23091, 23123), 'torch.cat', 'torch.cat', (['[X_train, y_train]', '(1)'], {}), '([X_train, y_train], 1)\n', (23100, 23123), False, 'import torch\n'), ((25522, 25539), 'numpy.min', 'np.min', (['W_core[i]'], {}), '(W_core[i])\n', (25528, 25539), True, 'import numpy as np\n'), ((25581, 25598), 'numpy.max', 'np.max', (['W_core[i]'], {}), '(W_core[i])\n', (25587, 25598), True, 'import numpy as np\n'), ((25751, 25763), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (25759, 25763), True, 'import numpy as np\n'), ((25804, 25816), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (25812, 25816), True, 'import numpy as np\n'), ((21887, 21919), 'torch.cat', 'torch.cat', (['[X_train, y_train]', '(1)'], {}), '([X_train, y_train], 1)\n', (21896, 21919), False, 'import torch\n'), ((27257, 27289), 'torch.cat', 'torch.cat', (['[X_train, y_train]', '(1)'], {}), '([X_train, y_train], 1)\n', (27266, 27289), False, 'import torch\n'), ((27446, 27476), 'torch.cat', 'torch.cat', (['[X_test, y_test]', '(1)'], {}), '([X_test, y_test], 1)\n', (27455, 27476), False, 'import torch\n'), ((27147, 27179), 'torch.cat', 'torch.cat', (['[X_train, y_train]', '(1)'], {}), '([X_train, y_train], 1)\n', (27156, 27179), False, 'import torch\n'), ((27844, 27892), 'torch.cat', 'torch.cat', (['[pred - pred_std, pred + pred_std]', '(1)'], {}), '([pred - pred_std, pred + pred_std], 1)\n', (27853, 27892), False, 'import torch\n'), ((27735, 27783), 'torch.cat', 'torch.cat', (['[pred - pred_std, pred + pred_std]', '(1)'], {}), '([pred - pred_std, pred + pred_std], 1)\n', (27744, 27783), False, 'import torch\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 08:58:18 2020
@author: jasonsteffener
"""
import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np
BaseDir = '/Users/jasonsteffener/Documents/GitHub/PowerMediationResults'
FileName = 'SummaryDataFile.csv'
df = pd.read_csv(os.path.join(BaseDir, FileName))
df.head()
# fig1, ((ax1, ax2, ax3, ax4, a), (ax3, ax4)) = plt.subplots(5,5)
# Plot AtoC
a = [0, 0.1, 0.2, 0.3, 0.4, 0.5]
a = [0.3, -0.3, 0.3, -0.3]
b = [-0, 0.1, 0.2, 0.3, 0.4, 0.5]
b = [-0.3, 0.3, 0.3, -0.3]
cP = [0, 0.1, 0.2, 0.3, 0.4, 0.5]
cP = [ 0]
for k in cP:
for i in a:
for j in b:
Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
df2 = df[Filter]
df2 = df2.sort_values("N")
bStr = "%0.1f, %0.2f"%(j,df2['SbMean'].mean())
plt.plot(df2["N"], df2["IEBCaPow"], label=bStr)
plt.legend(title="b")
plt.xlabel('Sample Size')
plt.ylabel('Power of Indirect Effect')
plt.title("a = %0.1f (%0.2f), c' = %0.1f"%(i,df2['SaMean'].mean(),k))
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
# Save each figure
#OutFileName = "PowerPlot_a_%0.1f_cP_%0.1f_Atype_Uniform.png"%(i,k)
#plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
# Plot a=0.5, b = 0.3 AND a = 0.3, b = 0.5
a1 = 0.5
b1 = 0.2
a2 = 0.2
b2 = 0.5
Filter1 = ((df["a"] == a1) & (df["b"] == b1) & (df["cP"] == 0.0) & (df["typeA"] == 99))
Str1 = 'a = %0.1f, b = %0.1f'%(a1,b1)
Filter2 = ((df["a"] == a2) & (df["b"] == b2) & (df["cP"] == 0.0) & (df["typeA"] == 99))
Str2 = 'a = %0.1f, b = %0.1f'%(a2,b2)
N1 = df[Filter1]["N"]
N2 = df[Filter2]["N"]
df21 = df[Filter1]
df21 = df21.sort_values("N")
plt.plot(df21["N"], df21["IEBCaPow"], label = Str1)
df22 = df[Filter2]
df22 = df22.sort_values("N")
plt.plot(df22["N"], df22["IEBCaPow"], label = Str2)
plt.legend()
plt.xlabel('Sample Size')
plt.ylabel('Power of Indirect Effect')
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
plt.show()
# Plot Compare CIs
a1 = 0.4
b1 = 0.3
Filter1 = ((df["a"] == a1) & (df["b"] == b1) & (df["cP"] == 0.0) & (df["typeA"] == 99))
Str1 = 'BCa, a = %0.1f, b = %0.1f'%(a1,b1)
Str2 = 'BC'
Str3 = 'Perc'
N1 = df[Filter1]["N"]
N2 = df[Filter2]["N"]
df21 = df[Filter1]
df21 = df21.sort_values("N")
plt.plot(df21["N"], df21["IEBCaPow"], label = Str1)
plt.plot(df21["N"], df21["IEBCPow"], label = Str2)
plt.plot(df21["N"], df21["IEPercPow"], label = Str3)
plt.legend()
plt.xlabel('Sample Size')
plt.ylabel('Power of Indirect Effect')
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
plt.show()
# Calculate how many more people are needed for every level of power
# between the BC and Perc methods
dBC = df21["IEBCPow"]
dPC = df21["IEPercPow"]
dN = df21["N"]
# Interpolate between the two curves
# Interpolate these curves to 1000 points
PowerInterp = np.arange(0,1.001,0.001)
NInterp = np.arange(0,200+200/1000,200/1000)
iBC = np.interp(NInterp, dN, dBC)
iPC = np.interp(NInterp, dN, dPC)
# cycle over the values of power and find the closest N values
# This will allow us to make a plot
DiffPowLevels = np.arange(0.1,1,0.2)
DiffN = np.zeros(DiffPowLevels.shape)
count = 0
for i in DiffPowLevels:
value = next(x for x in iBC if x > i)
BCindex = np.where(iBC == value)[0][0]
value = next(x for x in iPC if x > i)
PCindex = np.where(iPC == value)[0][0]
DiffN[count] = np.round(NInterp[PCindex] - NInterp[BCindex])
count += 1
plt.plot(DiffPowLevels, DiffN)
# Compare A types
a1 = 0.5
b1 = 0.4
Filter1 = ((df["a"] == a1) & (df["b"] == b1) & (df["cP"] == 0.0) & (df["typeA"] == 1))
Filter2 = ((df["a"] == a1) & (df["b"] == b1) & (df["cP"] == 0.0) & (df["typeA"] == 2))
Filter3 = ((df["a"] == a1) & (df["b"] == b1) & (df["cP"] == 0.0) & (df["typeA"] == 99))
Str1 = 'Uniform, a = %0.1f, b = %0.1f'%(a1,b1)
Str2 = 'Dicotomous'
Str3 = 'Continuous'
df21 = df[Filter1]
df21 = df21.sort_values("N")
df22 = df[Filter2]
df22 = df22.sort_values("N")
df23 = df[Filter3]
df23 = df23.sort_values("N")
plt.plot(df21["N"], df21["IEBCaPow"], label = Str1)
plt.plot(df22["N"], df22["IEBCaPow"], label = Str2)
plt.plot(df23["N"], df23["IEBCaPow"], label = Str3)
plt.legend()
plt.xlabel('Sample Size')
plt.ylabel('Power of Indirect Effect')
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
plt.show()
# TOTAL EFFECTS
# Plot AtoC
# a = [0, 0.1, 0.2, 0.3, 0.4, 0.5]
a = [0.5]
# b = [-0, 0.1, 0.2, 0.3, 0.4, 0.5]
b = [0.5]
cP = [-0.5,-0.4,-0.3,-0.2,-0.1,0, 0.1, 0.2, 0.3, 0.4, 0.5]
for k in cP:
for i in a:
for j in b:
Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
df2 = df[Filter]
df2 = df2.sort_values("N")
bStr = "%0.1f, %0.2f"%(j,df2['SbMean'].mean())
plt.plot(df2["N"], df2["TEBCaPow"], label=bStr)
plt.legend(title="b")
plt.xlabel('Sample Size')
plt.ylabel('Power of Total Effect')
plt.title("a = %0.1f (%0.2f), c' = %0.1f"%(i,df2['SaMean'].mean(),k))
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
# Save each figure
#OutFileName = "PowerPlot_a_%0.1f_cP_%0.1f_Atype_Uniform.png"%(i,k)
#plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
# Fix a, fix b, change cP and see how Sb changes
# Plot N versus b and Sb for different cP values
a = [0.5]
# b = [-0, 0.1, 0.2, 0.3, 0.4, 0.5]
b = [-0.5]
cP = [0]
for i in a:
for j in b:
for k in cP:
Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
df2 = df[Filter]
df2 = df2.sort_values("N")
bStr = "%0.1f, %0.2f, %0.2f, %0.2f"%(j,df2['SbMean'].mean(),k,df2['SaMean'].mean())
plt.plot(df2["N"], df2["SbMean"], label=bStr)
plt.legend(title="b")
plt.xlabel('Sample Size')
plt.ylabel('Power of Total Effect')
plt.title("a = %0.1f (%0.2f), c' = %0.1f"%(i,df2['SaMean'].mean(),k))
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
# Save each figure
#OutFileName = "PowerPlot_a_%0.1f_cP_%0.1f_Atype_Uniform.png"%(i,k)
#plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
# SUPPRESSION
# Plot AtoC
a = [0.3]
b = [0.3]
cP = [-0.1]
for i in a:
for j in b:
for k in cP:
Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
df2 = df[Filter]
df2 = df2.sort_values("N")
bStr = "%0.1f"%(j)
plt.plot(df2["N"], df2["IEBCaPow"], label='Indirect')
plt.plot(df2["N"], df2["TEBCaPow"], label='Total')
plt.legend(title="Effect")
plt.xlabel('Sample Size')
plt.ylabel('Power')
plt.title("a = %0.1f, b = %0.1f, c' = %0.1f"%(i,j,k))
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
# Save each figure
OutFileName = "SUPP_PowerPlot_a_%0.1f_b_%0.1f_cP_%0.1f_Atype_Uniform.png"%(i,j,k)
plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
# FULL AND PARTIAL MEDIATION
a = [0.3]
b = [0.3]
cP = [0.1,0.3,0.5]
for i in a:
for j in b:
for k in cP:
Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
df2 = df[Filter]
df2 = df2.sort_values("N")
bStr = "%0.1f"%(k)
plt.plot(df2["N"], df2["IEBCaPow"], label=bStr)
#plt.plot(df2["N"], df2["TEBCaPow"], label='Total')
plt.legend(title="c'")
plt.xlabel('Sample Size')
plt.ylabel('Power')
plt.title("a = %0.1f, b = %0.1f"%(i,j))
plt.xlim(0,200)
plt.ylim(0,1)
plt.hlines(0.8,0,200,linestyles='dashed')
# Save each figure
OutFileName = "FullPart_PowerPlot_a_%0.1f_b_%0.1f_Atype_Uniform.png"%(i,j)
plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
# Make plots of collinearity
def PlotCollinearity():
# Make plot of the power of DIRECT as a changes
# Pick a sample size
N = [20,40,60,80,100,120,140,160,180,200]
N = [100]# Pick value
b = [0.3]
cP = [0.3]
for k in cP:
for j in b:
for i in N:
#Filter = ((df["a"] == i) & (df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
Filter = ((df["N"] == i) &(df["b"] == j) & (df["cP"] == k) & (df["typeA"] == 99))
N = df[Filter]["N"]
a = df[Filter]["a"]
df2 = df[Filter]
df2 = df2.sort_values("a")
#bStr = "%0.1f, %0.2f, %0.2f, %0.2f"%(j,df2['SbMean'].mean(),k,df2['SaMean'].mean())
bStr = "%0d"%(i)
plt.plot(df2["a"], df2["DEBCPow"], label=bStr)
plt.legend(title="N")
plt.xlabel('a')
plt.ylabel('Power of Direct Effect')
#plt.title("a = %0.1f (%0.2f), c' = %0.1f"%(i,df2['SaMean'].mean(),k))
plt.title("b = %0.1f, Direct effect = %0.1f"%(j,k))
plt.xlim(-0.5,0.5)
plt.ylim(0,1)
plt.hlines(0.8,-0.5,0.5,linestyles='dashed')
# Save each figure
#OutFileName = "PowerPlot_a_%0.1f_cP_%0.1f_Atype_Uniform.png"%(i,k)
#plt.savefig(os.path.join(BaseDir, OutFileName))
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"os.path.join",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"numpy.round",
"numpy.zeros",
"numpy.where",
"numpy.arange",
"numpy.interp",
"matplotlib.pyplot.ylabel",
"matplotli... | [((1865, 1914), 'matplotlib.pyplot.plot', 'plt.plot', (["df21['N']", "df21['IEBCaPow']"], {'label': 'Str1'}), "(df21['N'], df21['IEBCaPow'], label=Str1)\n", (1873, 1914), True, 'import matplotlib.pyplot as plt\n'), ((1966, 2015), 'matplotlib.pyplot.plot', 'plt.plot', (["df22['N']", "df22['IEBCaPow']"], {'label': 'Str2'}), "(df22['N'], df22['IEBCaPow'], label=Str2)\n", (1974, 2015), True, 'import matplotlib.pyplot as plt\n'), ((2019, 2031), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2029, 2031), True, 'import matplotlib.pyplot as plt\n'), ((2032, 2057), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (2042, 2057), True, 'import matplotlib.pyplot as plt\n'), ((2058, 2096), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Indirect Effect"""'], {}), "('Power of Indirect Effect')\n", (2068, 2096), True, 'import matplotlib.pyplot as plt\n'), ((2097, 2113), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (2105, 2113), True, 'import matplotlib.pyplot as plt\n'), ((2113, 2127), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (2121, 2127), True, 'import matplotlib.pyplot as plt\n'), ((2127, 2171), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (2137, 2171), True, 'import matplotlib.pyplot as plt\n'), ((2169, 2179), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2177, 2179), True, 'import matplotlib.pyplot as plt\n'), ((2472, 2521), 'matplotlib.pyplot.plot', 'plt.plot', (["df21['N']", "df21['IEBCaPow']"], {'label': 'Str1'}), "(df21['N'], df21['IEBCaPow'], label=Str1)\n", (2480, 2521), True, 'import matplotlib.pyplot as plt\n'), ((2524, 2572), 'matplotlib.pyplot.plot', 'plt.plot', (["df21['N']", "df21['IEBCPow']"], {'label': 'Str2'}), "(df21['N'], df21['IEBCPow'], label=Str2)\n", (2532, 2572), True, 'import matplotlib.pyplot as plt\n'), ((2575, 2625), 'matplotlib.pyplot.plot', 'plt.plot', (["df21['N']", "df21['IEPercPow']"], {'label': 'Str3'}), "(df21['N'], df21['IEPercPow'], label=Str3)\n", (2583, 2625), True, 'import matplotlib.pyplot as plt\n'), ((2629, 2641), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2639, 2641), True, 'import matplotlib.pyplot as plt\n'), ((2642, 2667), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (2652, 2667), True, 'import matplotlib.pyplot as plt\n'), ((2668, 2706), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Indirect Effect"""'], {}), "('Power of Indirect Effect')\n", (2678, 2706), True, 'import matplotlib.pyplot as plt\n'), ((2707, 2723), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (2715, 2723), True, 'import matplotlib.pyplot as plt\n'), ((2723, 2737), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (2731, 2737), True, 'import matplotlib.pyplot as plt\n'), ((2737, 2781), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (2747, 2781), True, 'import matplotlib.pyplot as plt\n'), ((2779, 2789), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2787, 2789), True, 'import matplotlib.pyplot as plt\n'), ((3049, 3075), 'numpy.arange', 'np.arange', (['(0)', '(1.001)', '(0.001)'], {}), '(0, 1.001, 0.001)\n', (3058, 3075), True, 'import numpy as np\n'), ((3084, 3126), 'numpy.arange', 'np.arange', (['(0)', '(200 + 200 / 1000)', '(200 / 1000)'], {}), '(0, 200 + 200 / 1000, 200 / 1000)\n', (3093, 3126), True, 'import numpy as np\n'), ((3125, 3152), 'numpy.interp', 'np.interp', (['NInterp', 'dN', 'dBC'], {}), '(NInterp, dN, dBC)\n', (3134, 3152), True, 'import numpy as np\n'), ((3159, 3186), 'numpy.interp', 'np.interp', (['NInterp', 'dN', 'dPC'], {}), '(NInterp, dN, dPC)\n', (3168, 3186), True, 'import numpy as np\n'), ((3303, 3325), 'numpy.arange', 'np.arange', (['(0.1)', '(1)', '(0.2)'], {}), '(0.1, 1, 0.2)\n', (3312, 3325), True, 'import numpy as np\n'), ((3332, 3361), 'numpy.zeros', 'np.zeros', (['DiffPowLevels.shape'], {}), '(DiffPowLevels.shape)\n', (3340, 3361), True, 'import numpy as np\n'), ((3647, 3677), 'matplotlib.pyplot.plot', 'plt.plot', (['DiffPowLevels', 'DiffN'], {}), '(DiffPowLevels, DiffN)\n', (3655, 3677), True, 'import matplotlib.pyplot as plt\n'), ((4210, 4259), 'matplotlib.pyplot.plot', 'plt.plot', (["df21['N']", "df21['IEBCaPow']"], {'label': 'Str1'}), "(df21['N'], df21['IEBCaPow'], label=Str1)\n", (4218, 4259), True, 'import matplotlib.pyplot as plt\n'), ((4262, 4311), 'matplotlib.pyplot.plot', 'plt.plot', (["df22['N']", "df22['IEBCaPow']"], {'label': 'Str2'}), "(df22['N'], df22['IEBCaPow'], label=Str2)\n", (4270, 4311), True, 'import matplotlib.pyplot as plt\n'), ((4314, 4363), 'matplotlib.pyplot.plot', 'plt.plot', (["df23['N']", "df23['IEBCaPow']"], {'label': 'Str3'}), "(df23['N'], df23['IEBCaPow'], label=Str3)\n", (4322, 4363), True, 'import matplotlib.pyplot as plt\n'), ((4367, 4379), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4377, 4379), True, 'import matplotlib.pyplot as plt\n'), ((4380, 4405), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (4390, 4405), True, 'import matplotlib.pyplot as plt\n'), ((4406, 4444), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Indirect Effect"""'], {}), "('Power of Indirect Effect')\n", (4416, 4444), True, 'import matplotlib.pyplot as plt\n'), ((4445, 4461), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (4453, 4461), True, 'import matplotlib.pyplot as plt\n'), ((4461, 4475), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (4469, 4475), True, 'import matplotlib.pyplot as plt\n'), ((4475, 4519), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (4485, 4519), True, 'import matplotlib.pyplot as plt\n'), ((4517, 4527), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4525, 4527), True, 'import matplotlib.pyplot as plt\n'), ((321, 352), 'os.path.join', 'os.path.join', (['BaseDir', 'FileName'], {}), '(BaseDir, FileName)\n', (333, 352), False, 'import os\n'), ((3585, 3630), 'numpy.round', 'np.round', (['(NInterp[PCindex] - NInterp[BCindex])'], {}), '(NInterp[PCindex] - NInterp[BCindex])\n', (3593, 3630), True, 'import numpy as np\n'), ((984, 1005), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""b"""'}), "(title='b')\n", (994, 1005), True, 'import matplotlib.pyplot as plt\n'), ((1014, 1039), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (1024, 1039), True, 'import matplotlib.pyplot as plt\n'), ((1048, 1086), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Indirect Effect"""'], {}), "('Power of Indirect Effect')\n", (1058, 1086), True, 'import matplotlib.pyplot as plt\n'), ((1173, 1189), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (1181, 1189), True, 'import matplotlib.pyplot as plt\n'), ((1197, 1211), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (1205, 1211), True, 'import matplotlib.pyplot as plt\n'), ((1219, 1263), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (1229, 1263), True, 'import matplotlib.pyplot as plt\n'), ((1429, 1439), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1437, 1439), True, 'import matplotlib.pyplot as plt\n'), ((5087, 5108), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""b"""'}), "(title='b')\n", (5097, 5108), True, 'import matplotlib.pyplot as plt\n'), ((5117, 5142), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (5127, 5142), True, 'import matplotlib.pyplot as plt\n'), ((5151, 5186), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Total Effect"""'], {}), "('Power of Total Effect')\n", (5161, 5186), True, 'import matplotlib.pyplot as plt\n'), ((5273, 5289), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (5281, 5289), True, 'import matplotlib.pyplot as plt\n'), ((5297, 5311), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (5305, 5311), True, 'import matplotlib.pyplot as plt\n'), ((5319, 5363), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (5329, 5363), True, 'import matplotlib.pyplot as plt\n'), ((5529, 5539), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5537, 5539), True, 'import matplotlib.pyplot as plt\n'), ((6130, 6151), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""b"""'}), "(title='b')\n", (6140, 6151), True, 'import matplotlib.pyplot as plt\n'), ((6160, 6185), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (6170, 6185), True, 'import matplotlib.pyplot as plt\n'), ((6194, 6229), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Total Effect"""'], {}), "('Power of Total Effect')\n", (6204, 6229), True, 'import matplotlib.pyplot as plt\n'), ((6316, 6332), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (6324, 6332), True, 'import matplotlib.pyplot as plt\n'), ((6340, 6354), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (6348, 6354), True, 'import matplotlib.pyplot as plt\n'), ((6362, 6406), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (6372, 6406), True, 'import matplotlib.pyplot as plt\n'), ((6572, 6582), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6580, 6582), True, 'import matplotlib.pyplot as plt\n'), ((7055, 7081), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""Effect"""'}), "(title='Effect')\n", (7065, 7081), True, 'import matplotlib.pyplot as plt\n'), ((7090, 7115), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (7100, 7115), True, 'import matplotlib.pyplot as plt\n'), ((7124, 7143), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power"""'], {}), "('Power')\n", (7134, 7143), True, 'import matplotlib.pyplot as plt\n'), ((7152, 7209), 'matplotlib.pyplot.title', 'plt.title', (['("a = %0.1f, b = %0.1f, c\' = %0.1f" % (i, j, k))'], {}), '("a = %0.1f, b = %0.1f, c\' = %0.1f" % (i, j, k))\n', (7161, 7209), True, 'import matplotlib.pyplot as plt\n'), ((7214, 7230), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (7222, 7230), True, 'import matplotlib.pyplot as plt\n'), ((7238, 7252), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (7246, 7252), True, 'import matplotlib.pyplot as plt\n'), ((7260, 7304), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (7270, 7304), True, 'import matplotlib.pyplot as plt\n'), ((7483, 7493), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7491, 7493), True, 'import matplotlib.pyplot as plt\n'), ((7987, 8009), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""c\'"""'}), '(title="c\'")\n', (7997, 8009), True, 'import matplotlib.pyplot as plt\n'), ((8018, 8043), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sample Size"""'], {}), "('Sample Size')\n", (8028, 8043), True, 'import matplotlib.pyplot as plt\n'), ((8052, 8071), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power"""'], {}), "('Power')\n", (8062, 8071), True, 'import matplotlib.pyplot as plt\n'), ((8080, 8122), 'matplotlib.pyplot.title', 'plt.title', (["('a = %0.1f, b = %0.1f' % (i, j))"], {}), "('a = %0.1f, b = %0.1f' % (i, j))\n", (8089, 8122), True, 'import matplotlib.pyplot as plt\n'), ((8128, 8144), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(200)'], {}), '(0, 200)\n', (8136, 8144), True, 'import matplotlib.pyplot as plt\n'), ((8152, 8166), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (8160, 8166), True, 'import matplotlib.pyplot as plt\n'), ((8174, 8218), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(0)', '(200)'], {'linestyles': '"""dashed"""'}), "(0.8, 0, 200, linestyles='dashed')\n", (8184, 8218), True, 'import matplotlib.pyplot as plt\n'), ((8390, 8400), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8398, 8400), True, 'import matplotlib.pyplot as plt\n'), ((928, 975), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['IEBCaPow']"], {'label': 'bStr'}), "(df2['N'], df2['IEBCaPow'], label=bStr)\n", (936, 975), True, 'import matplotlib.pyplot as plt\n'), ((3452, 3474), 'numpy.where', 'np.where', (['(iBC == value)'], {}), '(iBC == value)\n', (3460, 3474), True, 'import numpy as np\n'), ((3537, 3559), 'numpy.where', 'np.where', (['(iPC == value)'], {}), '(iPC == value)\n', (3545, 3559), True, 'import numpy as np\n'), ((5031, 5078), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['TEBCaPow']"], {'label': 'bStr'}), "(df2['N'], df2['TEBCaPow'], label=bStr)\n", (5039, 5078), True, 'import matplotlib.pyplot as plt\n'), ((6076, 6121), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['SbMean']"], {'label': 'bStr'}), "(df2['N'], df2['SbMean'], label=bStr)\n", (6084, 6121), True, 'import matplotlib.pyplot as plt\n'), ((6930, 6983), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['IEBCaPow']"], {'label': '"""Indirect"""'}), "(df2['N'], df2['IEBCaPow'], label='Indirect')\n", (6938, 6983), True, 'import matplotlib.pyplot as plt\n'), ((6996, 7046), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['TEBCaPow']"], {'label': '"""Total"""'}), "(df2['N'], df2['TEBCaPow'], label='Total')\n", (7004, 7046), True, 'import matplotlib.pyplot as plt\n'), ((7431, 7465), 'os.path.join', 'os.path.join', (['BaseDir', 'OutFileName'], {}), '(BaseDir, OutFileName)\n', (7443, 7465), False, 'import os\n'), ((7867, 7914), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['N']", "df2['IEBCaPow']"], {'label': 'bStr'}), "(df2['N'], df2['IEBCaPow'], label=bStr)\n", (7875, 7914), True, 'import matplotlib.pyplot as plt\n'), ((8338, 8372), 'os.path.join', 'os.path.join', (['BaseDir', 'OutFileName'], {}), '(BaseDir, OutFileName)\n', (8350, 8372), False, 'import os\n'), ((9312, 9333), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""N"""'}), "(title='N')\n", (9322, 9333), True, 'import matplotlib.pyplot as plt\n'), ((9346, 9361), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""a"""'], {}), "('a')\n", (9356, 9361), True, 'import matplotlib.pyplot as plt\n'), ((9374, 9410), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Power of Direct Effect"""'], {}), "('Power of Direct Effect')\n", (9384, 9410), True, 'import matplotlib.pyplot as plt\n'), ((9506, 9560), 'matplotlib.pyplot.title', 'plt.title', (["('b = %0.1f, Direct effect = %0.1f' % (j, k))"], {}), "('b = %0.1f, Direct effect = %0.1f' % (j, k))\n", (9515, 9560), True, 'import matplotlib.pyplot as plt\n'), ((9570, 9589), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-0.5)', '(0.5)'], {}), '(-0.5, 0.5)\n', (9578, 9589), True, 'import matplotlib.pyplot as plt\n'), ((9601, 9615), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (9609, 9615), True, 'import matplotlib.pyplot as plt\n'), ((9627, 9674), 'matplotlib.pyplot.hlines', 'plt.hlines', (['(0.8)', '(-0.5)', '(0.5)'], {'linestyles': '"""dashed"""'}), "(0.8, -0.5, 0.5, linestyles='dashed')\n", (9637, 9674), True, 'import matplotlib.pyplot as plt\n'), ((9856, 9866), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9864, 9866), True, 'import matplotlib.pyplot as plt\n'), ((9253, 9299), 'matplotlib.pyplot.plot', 'plt.plot', (["df2['a']", "df2['DEBCPow']"], {'label': 'bStr'}), "(df2['a'], df2['DEBCPow'], label=bStr)\n", (9261, 9299), True, 'import matplotlib.pyplot as plt\n')] |
from random import randint
import numpy as np
import pandas as pd
from math import log
import scipy.stats.distributions
from sklearn.preprocessing import MinMaxScaler
def scale(x):
return np.log(x + 1)
class customScaler():
def __init__(self, feature_range=(0,100)):
self.feature_range = feature_range
def fit(self, x):
scaled_data = scale(np.array(x, dtype=np.float))
self.scaler = MinMaxScaler(feature_range=self.feature_range)
self.scaler.fit(scaled_data)
def transform(self, data):
scaled_data = scale(np.array(data, dtype=np.float))
transformed = self.scaler.transform(scaled_data).astype(int)
return np.array(transformed, dtype=np.int64)
def poisson(x, l):
return_value = 1
for x_i, l_i in zip(x, l):
return_value *= scipy.stats.distributions.poisson.pmf(x_i, l_i)
return return_value
def calculate_likelihood_em(em, data, kmeans, take_mean=False, weight=0.5, verbose=0):
# first reset previous point for all hosts for rerun
previous_points = {}
for host in em.hosts:
previous_points[host] = em.hosts[host]['hard_previous']
total_likelihood = []
i = 0
for point in data:
i += 1
if verbose > 0 and i % 10000 == 0:
print(i, sum(total_likelihood) / len(total_likelihood))
host = point[-1]
previous_point = previous_points[host]
point_center = em.closest_centers([point])
closest_center = np.argmax(point_center)
previous_points[host] = closest_center
if take_mean:
kmeans_probabilities = kmeans.centers[kmeans.assignments[host]][previous_point]
host_probabilities = em.hosts[host]['transition_matrix'][previous_point]
probabilities = kmeans_probabilities * weight + host_probabilities * (1 - weight)
else:
probabilities = kmeans.centers[kmeans.assignments[host]][previous_point]
participation = probabilities * np.array([poisson(point, lambda_i) for lambda_i in em.lambdas])
likelihood = log(np.sum(participation))
total_likelihood.append(likelihood)
return sum(total_likelihood) / len(total_likelihood)
def get_random_initialize_lamdas(data, number_of_mixtures=4):
mins = np.min(data, axis=0)
maxs = np.max(data, axis=0)
dims = len(mins)
lambdas = [[] for _ in range(number_of_mixtures)]
for i in range(dims):
for j in range(number_of_mixtures):
lambdas[j].append(randint(int(mins[i]), int(maxs[i])))
return np.vstack(lambdas)
# TODO remove this
def get_data_by_dataframe(df, size_of_bin_seconds=50, doScale=True, scaler=None):
"""
:param size_of_bin_seconds: the time period of each bin,
assumes the dataframe has a column names 'source computer' and a name 'byte count'
:return: a dictionary containing for each host the features, the hosts
"""
hosts = np.array(list(set(df['source computer'].values)))
bins = np.arange(df.index.min(), df.index.max() + size_of_bin_seconds + 1, size_of_bin_seconds)
groups = df[['byte count','source computer']].groupby([np.digitize(df.index, bins),'source computer'])
data = groups.count()
data.columns = ['number of flows']
data['mean(byte count)'] = groups.mean().values
if doScale:
scaler.fit(np.append(data.values, np.array([[0, 0]]), axis=0))
data_by_host = {}
for host in hosts:
for i in range(len(bins) - 1):
try:
if doScale == True:
values = scaler.transform(np.array([data.loc[(i + 1, host)].values]))
else:
values = np.array([data.loc[(i + 1, host)].values])
if i == 0:
data_by_host[host] = np.array(values)
else:
data_by_host[host] = np.append(data_by_host[host], np.array(values), axis=0)
except:
pass
return data_by_host, hosts
def group_data(df, size_of_bin_seconds=50, doScale=True, scaler=None):
"""
:param size_of_bin_seconds: the time period of each bin,
assumes the dataframe has a column names 'source computer' and a name 'byte count'
:return: a dictionary containing for each host the features, the hosts
"""
hosts = np.array(list(set(df['source computer'].values)))
bins = np.arange(df.index.min(), df.index.max() + size_of_bin_seconds + 1, size_of_bin_seconds)
groups = df[['byte count','source computer']].groupby([np.digitize(df.index, bins),'source computer'])
data = groups.count()
data.columns = ['number of flows']
data['mean(byte count)'] = groups.mean().values
data_reset = data.reset_index()
if doScale:
scaler.fit(np.append(data.values, np.array([[0, 0]]), axis=0))
groupped_data = pd.DataFrame(scaler.transform(data), columns=['number of flows', 'mean(byte count)'])
groupped_data['source computer'] = data_reset['source computer']
else:
groupped_data = pd.DataFrame(data.values, columns=['number of flows', 'mean(byte count)'])
groupped_data['source computer'] = data_reset['source computer']
return groupped_data, hosts
def clear_df(df, hosts):
return df[df['source computer'].isin(hosts)]
def group_scale_data(df, size_of_bin_seconds=60, doScale=False, scaler='log', addZeros=True, hosts=None, verbose=0):
"""
:param size_of_bin_seconds: the time period of each bin,
assumes the dataframe has a column names 'source computer' and a name 'byte count'
:param addZeros: add values (0, 0) where no data has been received for this bucket
:return: a dictionary containing for each host the features, the hosts
"""
# only log scale offered
assert scaler == 'log'
if doScale and scaler == 'log':
scaler = customScaler()
if hosts is None:
hosts = np.array(list(set(df['source computer'].values)))
else:
df = clear_df(df, hosts)
bins = np.arange(df.index.min(), df.index.max() + size_of_bin_seconds + 1, size_of_bin_seconds)
groups = df[['byte count','source computer']].groupby([np.digitize(df.index, bins),'source computer'])
data = groups.count()
data.columns = ['number of flows']
data['mean(byte count)'] = groups.mean().values
data_reset = data.reset_index()
if verbose > 0:
print('A total of', len(bins) - 1, 'time epochs have been encountered')
len_hosts = len(hosts)
intervals = int(len_hosts / 10)
i = 0
if addZeros:
add_new = []
for host in hosts:
if verbose > 0 and i % intervals == 0:
print('Done with', i, 'hosts out of', len_hosts)
i += 1
for bin_i in range(1,len(bins)):
if (bin_i, host) not in data.index:
new_row = [bin_i, host, 0.0, 0.0]
add_new.append(new_row)
data_reset = data_reset.append(pd.DataFrame(add_new, columns=data_reset.columns), ignore_index=True )
if verbose > 0:
print('Scaling...')
if doScale:
scaler.fit(np.append(data_reset.values[:,2:], np.array([[0, 0]]), axis=0))
groupped_data = pd.DataFrame(scaler.transform(data_reset.values[:,2:]), columns=['number of flows', 'mean(byte count)'])
groupped_data['epoch'] = data_reset['level_0']
groupped_data['source computer'] = data_reset['source computer']
else:
groupped_data = pd.DataFrame(data_reset.values[:,2:], columns=['number of flows', 'mean(byte count)'])
groupped_data['epoch'] = data_reset['level_0']
groupped_data['source computer'] = data_reset['source computer']
# set parameters for next acquisition of data
parameters = {}
parameters['scaler'] = scaler
parameters['doScale'] = doScale
parameters['size_of_bin_seconds'] = size_of_bin_seconds
parameters['hosts'] = hosts
parameters['addZeros'] = addZeros
groupped_data = groupped_data.sample(frac=1)
return groupped_data.sort_values(by=['epoch']), hosts, parameters
def group_scale_data_batch(df, parameters, setHosts=False, verbose=0):
"""
:param setHosts: get the new hosts if True else get the hosts we are interested in from the parameters
"""
scaler = parameters['scaler']
doScale = parameters['doScale']
size_of_bin_seconds = parameters['size_of_bin_seconds']
addZeros = parameters['addZeros']
if setHosts:
hosts = np.array(list(set(df['source computer'].values)))
else:
hosts = parameters['hosts']
df = clear_df(df, hosts)
bins = np.arange(df.index.min(), df.index.max() + size_of_bin_seconds + 1, size_of_bin_seconds)
groups = df[['byte count','source computer']].groupby([np.digitize(df.index, bins),'source computer'])
data = groups.count()
data.columns = ['number of flows']
data['mean(byte count)'] = groups.mean().values
data_reset = data.reset_index()
len_hosts = len(hosts)
intervals = int(len_hosts / 10)
i = 0
if addZeros:
add_new = []
for host in hosts:
if verbose > 0 and i % intervals == 0:
print('Done with', i, 'hosts out of', len_hosts)
i += 1
for bin_i in range(1,len(bins)):
if (bin_i, host) not in data.index:
new_row = [bin_i, host, 0.0, 0.0]
add_new.append(new_row)
data_reset = data_reset.append(pd.DataFrame(add_new, columns=data_reset.columns), ignore_index=True )
if doScale:
groupped_data = pd.DataFrame(scaler.transform(data_reset.values[:,2:]), columns=['number of flows', 'mean(byte count)'])
groupped_data['epoch'] = data_reset['level_0']
groupped_data['source computer'] = data_reset['source computer']
else:
groupped_data = pd.DataFrame(data_reset.values[:,2:], columns=['number of flows', 'mean(byte count)'])
groupped_data['epoch'] = data_reset['level_0']
groupped_data['source computer'] = data_reset['source computer']
groupped_data = groupped_data.sample(frac=1)
return groupped_data.sort_values(by=['epoch']), hosts | [
"pandas.DataFrame",
"numpy.sum",
"numpy.log",
"numpy.argmax",
"sklearn.preprocessing.MinMaxScaler",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.digitize",
"numpy.vstack"
] | [((195, 208), 'numpy.log', 'np.log', (['(x + 1)'], {}), '(x + 1)\n', (201, 208), True, 'import numpy as np\n'), ((2343, 2363), 'numpy.min', 'np.min', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (2349, 2363), True, 'import numpy as np\n'), ((2375, 2395), 'numpy.max', 'np.max', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (2381, 2395), True, 'import numpy as np\n'), ((2637, 2655), 'numpy.vstack', 'np.vstack', (['lambdas'], {}), '(lambdas)\n', (2646, 2655), True, 'import numpy as np\n'), ((432, 478), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': 'self.feature_range'}), '(feature_range=self.feature_range)\n', (444, 478), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((692, 729), 'numpy.array', 'np.array', (['transformed'], {'dtype': 'np.int64'}), '(transformed, dtype=np.int64)\n', (700, 729), True, 'import numpy as np\n'), ((1518, 1541), 'numpy.argmax', 'np.argmax', (['point_center'], {}), '(point_center)\n', (1527, 1541), True, 'import numpy as np\n'), ((5194, 5268), 'pandas.DataFrame', 'pd.DataFrame', (['data.values'], {'columns': "['number of flows', 'mean(byte count)']"}), "(data.values, columns=['number of flows', 'mean(byte count)'])\n", (5206, 5268), True, 'import pandas as pd\n'), ((7708, 7799), 'pandas.DataFrame', 'pd.DataFrame', (['data_reset.values[:, 2:]'], {'columns': "['number of flows', 'mean(byte count)']"}), "(data_reset.values[:, 2:], columns=['number of flows',\n 'mean(byte count)'])\n", (7720, 7799), True, 'import pandas as pd\n'), ((10160, 10251), 'pandas.DataFrame', 'pd.DataFrame', (['data_reset.values[:, 2:]'], {'columns': "['number of flows', 'mean(byte count)']"}), "(data_reset.values[:, 2:], columns=['number of flows',\n 'mean(byte count)'])\n", (10172, 10251), True, 'import pandas as pd\n'), ((381, 408), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.float'}), '(x, dtype=np.float)\n', (389, 408), True, 'import numpy as np\n'), ((576, 606), 'numpy.array', 'np.array', (['data'], {'dtype': 'np.float'}), '(data, dtype=np.float)\n', (584, 606), True, 'import numpy as np\n'), ((2134, 2155), 'numpy.sum', 'np.sum', (['participation'], {}), '(participation)\n', (2140, 2155), True, 'import numpy as np\n'), ((3241, 3268), 'numpy.digitize', 'np.digitize', (['df.index', 'bins'], {}), '(df.index, bins)\n', (3252, 3268), True, 'import numpy as np\n'), ((4683, 4710), 'numpy.digitize', 'np.digitize', (['df.index', 'bins'], {}), '(df.index, bins)\n', (4694, 4710), True, 'import numpy as np\n'), ((6346, 6373), 'numpy.digitize', 'np.digitize', (['df.index', 'bins'], {}), '(df.index, bins)\n', (6357, 6373), True, 'import numpy as np\n'), ((7198, 7247), 'pandas.DataFrame', 'pd.DataFrame', (['add_new'], {'columns': 'data_reset.columns'}), '(add_new, columns=data_reset.columns)\n', (7210, 7247), True, 'import pandas as pd\n'), ((9018, 9045), 'numpy.digitize', 'np.digitize', (['df.index', 'bins'], {}), '(df.index, bins)\n', (9029, 9045), True, 'import numpy as np\n'), ((9781, 9830), 'pandas.DataFrame', 'pd.DataFrame', (['add_new'], {'columns': 'data_reset.columns'}), '(add_new, columns=data_reset.columns)\n', (9793, 9830), True, 'import pandas as pd\n'), ((3470, 3488), 'numpy.array', 'np.array', (['[[0, 0]]'], {}), '([[0, 0]])\n', (3478, 3488), True, 'import numpy as np\n'), ((4948, 4966), 'numpy.array', 'np.array', (['[[0, 0]]'], {}), '([[0, 0]])\n', (4956, 4966), True, 'import numpy as np\n'), ((7388, 7406), 'numpy.array', 'np.array', (['[[0, 0]]'], {}), '([[0, 0]])\n', (7396, 7406), True, 'import numpy as np\n'), ((3788, 3828), 'numpy.array', 'np.array', (['[data.loc[i + 1, host].values]'], {}), '([data.loc[i + 1, host].values])\n', (3796, 3828), True, 'import numpy as np\n'), ((3920, 3936), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (3928, 3936), True, 'import numpy as np\n'), ((3693, 3733), 'numpy.array', 'np.array', (['[data.loc[i + 1, host].values]'], {}), '([data.loc[i + 1, host].values])\n', (3701, 3733), True, 'import numpy as np\n'), ((4030, 4046), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (4038, 4046), True, 'import numpy as np\n')] |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.distributions as tdist
from .invgamma import InverseGamma
from .kl import kl_normal_invgamma, kl_normal_laplace
class GaussianVar(object):
def __init__(self, mean, var):
self.mean = mean
self.var = var
self.shape = mean.shape
class Parameter(nn.Module):
def __init__(self, prior, approximation, q_loc, log_q_scale):
super(Parameter, self).__init__()
self.prior = prior
self.approximation = approximation
self.q_loc = q_loc
self.log_q_scale = log_q_scale
def q(self):
return self.approximation(loc=self.q_loc, scale=torch.exp(self.log_q_scale))
def __repr__(self):
args_string = 'Prior: {}\n Variational: {}'.format(
self.prior,
self.q()
)
return self.__class__.__name__ + '(\n ' + args_string + '\n)'
def surprise(self):
q = self.q()
p = self.prior
return tdist.kl_divergence(q, p)
def sample(self, n_sample=None, average=False):
if n_sample is None:
n_sample = 1
samples = self.q().rsample((n_sample,))
return samples
def get_variance_scale(initialization_type, shape):
if initialization_type == "standard":
prior_var = 1.0
elif initialization_type == "wide":
prior_var = 100.0
elif initialization_type == "narrow":
prior_var = 0.01
elif initialization_type == "glorot":
prior_var = (2.0 / (shape[-1] + shape[-2]))
elif initialization_type == "xavier":
prior_var = 1.0/shape[-1]
elif initialization_type == "he":
prior_var = 2.0/shape[-1]
elif initialization_type == "wider_he":
prior_var = 5.0/shape[-1]
else:
raise NotImplementedError('prior type "%s" not recognized' % initialization_type)
return prior_var
def gaussian_init(loc, scale, shape):
return loc + scale * torch.randn(*shape)
def laplace_init(loc, scale, shape):
return torch.from_numpy(np.random.laplace(loc, scale/np.sqrt(2.0), size=shape).astype(np.float32))
def make_weight_matrix(shape, prior_type, variance):
"""
Args:
shape (list, required): The shape of weight matrix. It should be `(out_features, in_features)`.
prior_type (list, required): Prior Type. It should be `[prior, weight_scale, bias_scale]`
`["gaussian", "wider_he", "wider_he"]`.
"""
variance = get_variance_scale(variance.strip().lower(), shape)
stddev = torch.sqrt(torch.ones(shape) * variance).float()
log_stddev = nn.Parameter(torch.log(stddev))
stddev = torch.exp(log_stddev)
prior = prior_type.strip().lower()
if prior == 'empirical':
a = 4.4798
alpha = a
beta = (1 + a) * variance
prior = InverseGamma(alpha, beta)
mean = nn.Parameter(torch.Tensor(*shape))
nn.init.normal_(mean, 0.0, math.sqrt(variance))
return Parameter(prior, tdist.Normal, mean, log_stddev)
elif prior == 'gaussian' or prior == 'normal':
init_function = gaussian_init
prior_generator = tdist.Normal
elif prior == 'laplace':
init_function = laplace_init
prior_generator = tdist.Laplace
else:
raise NotImplementedError('prior type "{}" not recognized'.format(prior))
mean = nn.Parameter(init_function(0.0, math.sqrt(variance), shape))
prior_loc = torch.zeros(*shape)
prior_scale = torch.ones(*shape) * math.sqrt(variance)
prior = prior_generator(prior_loc, prior_scale)
return Parameter(prior, tdist.Normal, mean, log_stddev)
def make_bias_vector(shape, prior_type, variance):
fudge_factor = 10.0
variance = get_variance_scale(variance.strip().lower(), shape)
stddev = torch.sqrt(torch.ones(shape[-2],) * variance / fudge_factor)
log_stddev = nn.Parameter(torch.log(stddev))
stddev = torch.exp(log_stddev)
prior = prior_type.strip().lower()
if prior == 'empirical':
a = 4.4798
alpha = a
beta = (1 + a) * variance
prior = InverseGamma(alpha, beta)
mean = nn.Parameter(torch.zeros(shape[-2],))
return Parameter(prior, tdist.Normal, mean, log_stddev)
else:
raise NotImplementedError('prior type "{}" not recognized'.format(prior))
| [
"torch.ones",
"math.sqrt",
"torch.randn",
"torch.distributions.kl_divergence",
"torch.exp",
"torch.Tensor",
"torch.zeros",
"torch.log",
"numpy.sqrt"
] | [((2658, 2679), 'torch.exp', 'torch.exp', (['log_stddev'], {}), '(log_stddev)\n', (2667, 2679), False, 'import torch\n'), ((3452, 3471), 'torch.zeros', 'torch.zeros', (['*shape'], {}), '(*shape)\n', (3463, 3471), False, 'import torch\n'), ((3924, 3945), 'torch.exp', 'torch.exp', (['log_stddev'], {}), '(log_stddev)\n', (3933, 3945), False, 'import torch\n'), ((1011, 1036), 'torch.distributions.kl_divergence', 'tdist.kl_divergence', (['q', 'p'], {}), '(q, p)\n', (1030, 1036), True, 'import torch.distributions as tdist\n'), ((2626, 2643), 'torch.log', 'torch.log', (['stddev'], {}), '(stddev)\n', (2635, 2643), False, 'import torch\n'), ((3490, 3508), 'torch.ones', 'torch.ones', (['*shape'], {}), '(*shape)\n', (3500, 3508), False, 'import torch\n'), ((3511, 3530), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (3520, 3530), False, 'import math\n'), ((3892, 3909), 'torch.log', 'torch.log', (['stddev'], {}), '(stddev)\n', (3901, 3909), False, 'import torch\n'), ((1974, 1993), 'torch.randn', 'torch.randn', (['*shape'], {}), '(*shape)\n', (1985, 1993), False, 'import torch\n'), ((2893, 2913), 'torch.Tensor', 'torch.Tensor', (['*shape'], {}), '(*shape)\n', (2905, 2913), False, 'import torch\n'), ((2950, 2969), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (2959, 2969), False, 'import math\n'), ((3406, 3425), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (3415, 3425), False, 'import math\n'), ((4159, 4181), 'torch.zeros', 'torch.zeros', (['shape[-2]'], {}), '(shape[-2])\n', (4170, 4181), False, 'import torch\n'), ((686, 713), 'torch.exp', 'torch.exp', (['self.log_q_scale'], {}), '(self.log_q_scale)\n', (695, 713), False, 'import torch\n'), ((3812, 3833), 'torch.ones', 'torch.ones', (['shape[-2]'], {}), '(shape[-2])\n', (3822, 3833), False, 'import torch\n'), ((2558, 2575), 'torch.ones', 'torch.ones', (['shape'], {}), '(shape)\n', (2568, 2575), False, 'import torch\n'), ((2090, 2102), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (2097, 2102), True, 'import numpy as np\n')] |
import numpy as np
import cvxpy as cp
import pandas as pd
from scoring import *
# %%
def main():
year = int(input('Enter Year: '))
week = int(input('Enter Week: '))
budget = int(input('Enter Budget: '))
source = 'NFL'
print(f'Source = {source}')
df = read_data(year=year, week=week, source=source)
df = get_costs(df)
lineup, proj_pts, cost = get_optimal_lineup(df, budget)
print('---------- \n Lineup: \n', lineup)
print('---------- \n Projected Points: \n', proj_pts)
print(f'--------- \n Cost={cost}, Budget={budget}, Cap Room={budget-cost}')
return
def read_data(year, week, source):
POS = 'QB RB WR TE K DST'.split()
d = {'QB': scoring_QB,
'RB': scoring_RB,
'WR': scoring_WR,
'TE': scoring_TE,
'K': scoring_K,
'DST': scoring_DST}
player_dfs = {}
for pos in POS:
filepath = f'../data/{year}/{week}/{pos}/'
df = pd.read_csv(filepath+source+'.csv')
df = d[pos](df)
player_dfs[pos] = df
df = pd.concat(player_dfs).reset_index(drop=True)
df = df.join(pd.get_dummies(df['pos']), how='left')
return df
# make random costs
def get_costs(df):
N = len(df)
costs = np.random.randint(low=10, high=600, size=N)*10
df['cost'] = costs
df.set_index('player', inplace=True)
return df
def get_optimal_lineup(df, budget):
N = len(df)
W = cp.Variable((N, 1), boolean=True)
constrs = [cp.sum(cp.multiply(W, df['cost'].values.reshape(N, 1)))<=budget,
cp.sum(W)<=9,
cp.sum(cp.multiply(W, df['QB'].values.reshape(N, 1)))==1,
cp.sum(cp.multiply(W, df['RB'].values.reshape(N, 1)))<=3,
cp.sum(cp.multiply(W, df['WR'].values.reshape(N, 1)))<=3,
cp.sum(cp.multiply(W, df['TE'].values.reshape(N, 1)))<=2,
cp.sum(cp.multiply(W, df['TE'].values.reshape(N, 1)))>=1,
cp.sum(cp.multiply(W, df['K'].values.reshape(N, 1)))==1,
cp.sum(cp.multiply(W, df['DST'].values.reshape(N, 1)))==1]
obj = cp.Maximize(cp.sum(cp.multiply(W, df['proj'].values.reshape(N, 1))))
prob = cp.Problem(obj, constrs)
prob.solve()
W.value = W.value.round()
idx = []
for i, w in enumerate(W.value):
if w == 1:
idx.append(i)
proj_pts = round(df.iloc[idx]['proj'].sum(),2)
lineup_cost = df.iloc[idx]['cost'].sum()
lineup = df.iloc[idx]['team pos proj cost'.split()]
pos_map = {'QB': 1, 'RB': 2, 'WR': 3, 'TE': 4, 'K': 5, 'DST': 6}
pos_num = [pos_map[pos] for pos in lineup['pos'].values]
lineup['pos_num'] = pos_num
lineup = lineup.sort_values('pos_num')
lineup.drop('pos_num', axis=1, inplace=True)
return lineup, proj_pts, lineup_cost
# %%
if __name__ == '__main__':
main()
| [
"pandas.read_csv",
"pandas.get_dummies",
"cvxpy.sum",
"numpy.random.randint",
"cvxpy.Problem",
"cvxpy.Variable",
"pandas.concat"
] | [((1407, 1440), 'cvxpy.Variable', 'cp.Variable', (['(N, 1)'], {'boolean': '(True)'}), '((N, 1), boolean=True)\n', (1418, 1440), True, 'import cvxpy as cp\n'), ((2184, 2208), 'cvxpy.Problem', 'cp.Problem', (['obj', 'constrs'], {}), '(obj, constrs)\n', (2194, 2208), True, 'import cvxpy as cp\n'), ((941, 980), 'pandas.read_csv', 'pd.read_csv', (["(filepath + source + '.csv')"], {}), "(filepath + source + '.csv')\n", (952, 980), True, 'import pandas as pd\n'), ((1101, 1126), 'pandas.get_dummies', 'pd.get_dummies', (["df['pos']"], {}), "(df['pos'])\n", (1115, 1126), True, 'import pandas as pd\n'), ((1221, 1264), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(10)', 'high': '(600)', 'size': 'N'}), '(low=10, high=600, size=N)\n', (1238, 1264), True, 'import numpy as np\n'), ((1039, 1060), 'pandas.concat', 'pd.concat', (['player_dfs'], {}), '(player_dfs)\n', (1048, 1060), True, 'import pandas as pd\n'), ((1540, 1549), 'cvxpy.sum', 'cp.sum', (['W'], {}), '(W)\n', (1546, 1549), True, 'import cvxpy as cp\n')] |
# encoding: utf-8
# Sample-based Monte Carlo Denoising using a Kernel-Splatting Network
# <NAME> <NAME>
# Siggraph 2019
#
# Copyright (c) 2019 <NAME>
#
# 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 collection of random scene generators."""
import os
from bridson import poisson_disc_samples as pdisc
import numpy as np
import ttools
from .scene import Camera
from .converters import ObjConverter
from . import geometry
from . import randomizers
from . import xforms
__all__ = ["OutdoorSceneGenerator"]
class SceneGenerator():
"""Base class for the random scene generators.
Args:
envmaps(list of str): absolute paths to .pfm HDR images to use as
envmaps.
textures(list of str): absolute paths to .tga images used to texture
scene objects.
models(list of str): absolute paths to .obj files containing the
geometry.
pbrt_converter(str): path to the PBRTv2 executable that converts .obj
to the .pbrt text format.
"""
def __init__(self, envmaps, textures, models, pbrt_converter):
self._envmaps = envmaps
self._textures = textures
self._current_textures = []
self._models = models
self._converter = ObjConverter(pbrt_converter)
self._randomize_textures()
self._log = ttools.get_logger(self.__class__.__name__)
def __str__(self):
return self.__class__.__name__
def _randomize_textures(self):
"""Shuffle the available textures. Stores them in
`self._current_textures`.
"""
if self._textures:
self._current_textures = list(
np.random.choice(self._textures,
size=(min(30, len(self._textures)), ),
replace=False))
else:
self._current_textures = []
class OutdoorSceneGenerator(SceneGenerator):
"""Generates random outdoor scene with a envmap and a ground plane."""
def _sample_camera(self):
r_cam = np.random.uniform(1.0, 2.5)
theta_cam = np.random.uniform(0, 2*np.pi)
z_cam = np.random.uniform(0.01, 0.1)
cam_fov = np.random.uniform(15, 65)
cam_up = np.random.uniform(size=(3,))
cam_pos = np.array([r_cam*np.cos(theta_cam), r_cam*np.sin(theta_cam),
z_cam])
cam_target = np.random.uniform(0, 1, size=3)
cam_target[2] = np.random.uniform(1., 2.)*z_cam
cam_params = {"position": list(cam_pos), "target": list(cam_target),
"up": list(cam_up), "fov": cam_fov}
return cam_params
def _obj_pos(self, cam):
factor = 5
# Camera's fulcrum
cam_direction = np.array(cam["target"][:2]) - \
np.array(cam["position"][:2])
cam_direction /= np.linalg.norm(cam_direction) # normalized
cam_halfangle = 1.1*cam["fov"]/180*np.pi # add 10% for geometry bounds
c, s = np.cos(cam_halfangle), np.sin(cam_halfangle)
rot = np.matrix([[c, -s], [s, c]])
u1 = factor*np.linalg.inv(rot).dot(cam_direction)
u2 = factor*rot.dot(cam_direction)
xform = np.vstack([u1, u2]).T
radius = np.random.uniform(0.13, 0.28)
scaled_radius = radius*factor
# Place object centers
xy = pdisc(width=1, height=1, r=radius/factor)
np.random.shuffle(xy) # randomize order
xx = [x_[0] for x_ in xy]
yy = [x_[1] for x_ in xy]
xy = np.vstack([xx, yy])
# transform coordinates to the fulcrum of the camera
xy = xform.dot(xy)
# project along camera direction, reject objects that are too close or
# too far
proj = np.ravel(cam_direction.dot(xy))
keep = np.logical_and(proj > 0.1*scaled_radius, proj < factor)
xy = xy[:, keep]
# keep max 50 objects
nmax = 50
if xy.shape[1] > nmax:
xy = xy[:, :nmax]
proj /= proj.max()
# move origin at camera
xy[0, :] += cam["position"][0]
xy[1, :] += cam["position"][1]
return xy, scaled_radius, proj
def sample(self, scn, dst_dir, params=None):
self._log.debug("Sampling new outdoor scene")
self._randomize_textures()
# Random camera
do_dof = np.random.choice([True, False])
do_mblur = np.random.choice([True, False])
cam = self._sample_camera()
if do_mblur:
cam["shutterclose"] = 1.0
if do_dof:
aperture = _random_aperture()
else:
aperture = 0.0
# Sample objects in the fulcrum of the camera
self._log.debug("Sampling object positions")
coords, radius, proj = self._obj_pos(cam)
count = coords.shape[1]
# Focus on one of the objects
if count > 0:
focus_at = np.random.randint(0, count)
# Randomizes the number of possible object altitudes
z_layers = np.random.poisson(0.5) + 1
count_blurred = 0 # Counts the number of objects that have motion blur
self._log.debug("Adding %d objects.", count)
for o_idx in range(count): # Populate the scene
# If motion blur is activated, maybe blur this object
this_mblur = do_mblur and np.random.choice([True, False])
if this_mblur:
count_blurred += 1
# Sample a motion vector
mvec_r = np.random.uniform(0.00, 2)*radius
mvec_dir = np.random.uniform(size=(3,))
mvec_dir /= np.linalg.norm(mvec_dir)
mvec = mvec_dir*mvec_r
# Fetch a random object from the library
dst = os.path.join(dst_dir, "geometry")
mdl = np.random.choice(self._models)
pbrt_objects = self._converter(mdl, dst)
# Randomize the scale and position
scl = radius*np.random.exponential(0.5)*np.ones((3,))
z_idx = np.random.randint(0, z_layers)
altitude = np.random.normal(0.1, 0.2)
position = [coords[0, o_idx], coords[1, o_idx], altitude]
# Create a ground plane
plane = geometry.Plane(20)
xforms.rotate(plane, [0, 1, 0], 90)
material = randomizers.random_material(
id="floormat", textures_list=self._current_textures)
plane.assign_material(material)
scn.shapes.append(plane)
scn.materials.append(material)
# Compute the focus distance and update the camera paramters
if do_dof and z_idx == 0 and o_idx == focus_at:
dist = np.linalg.norm(
np.array(cam["position"])-np.array(position))
if dist > 0:
cam["focaldistance"] = dist
cam["lensradius"] = aperture
# Obj files may contain multiple pieces, add them all
for obj in pbrt_objects:
geom = geometry.ExternalGeometry(os.path.join("geometry",
obj.path))
xforms.rotate(geom, np.random.uniform(size=(3,)),
np.random.uniform(0, 360))
xforms.rotate(geom, np.random.uniform(size=(3,)),
np.random.uniform(0, 360))
xforms.scale(geom, scl)
xforms.translate(geom, position)
# Get a material for this piece
material = randomizers.random_material(
id=obj.material.id, textures_list=self._current_textures)
scn.materials.append(material)
if this_mblur:
xforms.translate(geom, mvec, target="end")
scn.shapes.append(geom)
self._log.debug("%s objects have motion blur", count_blurred)
# Add an envmap
env = randomizers.random_envmap(self._envmaps, nsamples=8)
xforms.rotate(env, [0, 0, 1], np.random.uniform(0, 360))
scn.lights.append(env)
# Attach the camera to the scene
scn.camera = Camera(**cam)
self._log.debug("Camera parameters %s. Motion blur? %s DoF? %s",
scn.camera, do_mblur, do_dof)
if do_mblur:
if (scn.camera.shutteropen != 0.0 or
scn.camera.shutterclose != 1.0):
return False
if do_dof:
if (not scn.camera.lensradius > 0.0 or not
scn.camera.focaldistance > 0.0):
return False
self._log.debug("Generated Outdoor scene")
return True
def _random_aperture(min_=0.001, max_=0.05):
"""Sample a camera aperture value, uniformly in log domain).
Args:
min_(float): smallest aperture.
max_(float): largest aperture.
"""
log_aperture = np.random.uniform(np.log(min_), np.log(max_))
aperture = np.exp(log_aperture)
return aperture
| [
"numpy.random.exponential",
"numpy.ones",
"numpy.sin",
"numpy.linalg.norm",
"numpy.exp",
"numpy.random.randint",
"numpy.random.normal",
"os.path.join",
"ttools.get_logger",
"numpy.random.poisson",
"numpy.random.choice",
"numpy.random.shuffle",
"bridson.poisson_disc_samples",
"numpy.linalg.... | [((9444, 9464), 'numpy.exp', 'np.exp', (['log_aperture'], {}), '(log_aperture)\n', (9450, 9464), True, 'import numpy as np\n'), ((1825, 1867), 'ttools.get_logger', 'ttools.get_logger', (['self.__class__.__name__'], {}), '(self.__class__.__name__)\n', (1842, 1867), False, 'import ttools\n'), ((2533, 2560), 'numpy.random.uniform', 'np.random.uniform', (['(1.0)', '(2.5)'], {}), '(1.0, 2.5)\n', (2550, 2560), True, 'import numpy as np\n'), ((2581, 2612), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)'], {}), '(0, 2 * np.pi)\n', (2598, 2612), True, 'import numpy as np\n'), ((2627, 2655), 'numpy.random.uniform', 'np.random.uniform', (['(0.01)', '(0.1)'], {}), '(0.01, 0.1)\n', (2644, 2655), True, 'import numpy as np\n'), ((2674, 2699), 'numpy.random.uniform', 'np.random.uniform', (['(15)', '(65)'], {}), '(15, 65)\n', (2691, 2699), True, 'import numpy as np\n'), ((2718, 2746), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3,)'}), '(size=(3,))\n', (2735, 2746), True, 'import numpy as np\n'), ((2882, 2913), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '(3)'}), '(0, 1, size=3)\n', (2899, 2913), True, 'import numpy as np\n'), ((3332, 3361), 'numpy.linalg.norm', 'np.linalg.norm', (['cam_direction'], {}), '(cam_direction)\n', (3346, 3361), True, 'import numpy as np\n'), ((3530, 3558), 'numpy.matrix', 'np.matrix', (['[[c, -s], [s, c]]'], {}), '([[c, -s], [s, c]])\n', (3539, 3558), True, 'import numpy as np\n'), ((3716, 3745), 'numpy.random.uniform', 'np.random.uniform', (['(0.13)', '(0.28)'], {}), '(0.13, 0.28)\n', (3733, 3745), True, 'import numpy as np\n'), ((3829, 3872), 'bridson.poisson_disc_samples', 'pdisc', ([], {'width': '(1)', 'height': '(1)', 'r': '(radius / factor)'}), '(width=1, height=1, r=radius / factor)\n', (3834, 3872), True, 'from bridson import poisson_disc_samples as pdisc\n'), ((3879, 3900), 'numpy.random.shuffle', 'np.random.shuffle', (['xy'], {}), '(xy)\n', (3896, 3900), True, 'import numpy as np\n'), ((4001, 4020), 'numpy.vstack', 'np.vstack', (['[xx, yy]'], {}), '([xx, yy])\n', (4010, 4020), True, 'import numpy as np\n'), ((4269, 4326), 'numpy.logical_and', 'np.logical_and', (['(proj > 0.1 * scaled_radius)', '(proj < factor)'], {}), '(proj > 0.1 * scaled_radius, proj < factor)\n', (4283, 4326), True, 'import numpy as np\n'), ((4820, 4851), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {}), '([True, False])\n', (4836, 4851), True, 'import numpy as np\n'), ((4871, 4902), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {}), '([True, False])\n', (4887, 4902), True, 'import numpy as np\n'), ((9401, 9413), 'numpy.log', 'np.log', (['min_'], {}), '(min_)\n', (9407, 9413), True, 'import numpy as np\n'), ((9415, 9427), 'numpy.log', 'np.log', (['max_'], {}), '(max_)\n', (9421, 9427), True, 'import numpy as np\n'), ((2938, 2965), 'numpy.random.uniform', 'np.random.uniform', (['(1.0)', '(2.0)'], {}), '(1.0, 2.0)\n', (2955, 2965), True, 'import numpy as np\n'), ((3233, 3260), 'numpy.array', 'np.array', (["cam['target'][:2]"], {}), "(cam['target'][:2])\n", (3241, 3260), True, 'import numpy as np\n'), ((3277, 3306), 'numpy.array', 'np.array', (["cam['position'][:2]"], {}), "(cam['position'][:2])\n", (3285, 3306), True, 'import numpy as np\n'), ((3471, 3492), 'numpy.cos', 'np.cos', (['cam_halfangle'], {}), '(cam_halfangle)\n', (3477, 3492), True, 'import numpy as np\n'), ((3494, 3515), 'numpy.sin', 'np.sin', (['cam_halfangle'], {}), '(cam_halfangle)\n', (3500, 3515), True, 'import numpy as np\n'), ((3676, 3695), 'numpy.vstack', 'np.vstack', (['[u1, u2]'], {}), '([u1, u2])\n', (3685, 3695), True, 'import numpy as np\n'), ((5376, 5403), 'numpy.random.randint', 'np.random.randint', (['(0)', 'count'], {}), '(0, count)\n', (5393, 5403), True, 'import numpy as np\n'), ((5485, 5507), 'numpy.random.poisson', 'np.random.poisson', (['(0.5)'], {}), '(0.5)\n', (5502, 5507), True, 'import numpy as np\n'), ((6018, 6046), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3,)'}), '(size=(3,))\n', (6035, 6046), True, 'import numpy as np\n'), ((6071, 6095), 'numpy.linalg.norm', 'np.linalg.norm', (['mvec_dir'], {}), '(mvec_dir)\n', (6085, 6095), True, 'import numpy as np\n'), ((6203, 6236), 'os.path.join', 'os.path.join', (['dst_dir', '"""geometry"""'], {}), "(dst_dir, 'geometry')\n", (6215, 6236), False, 'import os\n'), ((6255, 6285), 'numpy.random.choice', 'np.random.choice', (['self._models'], {}), '(self._models)\n', (6271, 6285), True, 'import numpy as np\n'), ((6473, 6503), 'numpy.random.randint', 'np.random.randint', (['(0)', 'z_layers'], {}), '(0, z_layers)\n', (6490, 6503), True, 'import numpy as np\n'), ((6527, 6553), 'numpy.random.normal', 'np.random.normal', (['(0.1)', '(0.2)'], {}), '(0.1, 0.2)\n', (6543, 6553), True, 'import numpy as np\n'), ((8511, 8536), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(360)'], {}), '(0, 360)\n', (8528, 8536), True, 'import numpy as np\n'), ((5808, 5839), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {}), '([True, False])\n', (5824, 5839), True, 'import numpy as np\n'), ((5961, 5986), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(2)'], {}), '(0.0, 2)\n', (5978, 5986), True, 'import numpy as np\n'), ((6439, 6452), 'numpy.ones', 'np.ones', (['(3,)'], {}), '((3,))\n', (6446, 6452), True, 'import numpy as np\n'), ((2781, 2798), 'numpy.cos', 'np.cos', (['theta_cam'], {}), '(theta_cam)\n', (2787, 2798), True, 'import numpy as np\n'), ((2806, 2823), 'numpy.sin', 'np.sin', (['theta_cam'], {}), '(theta_cam)\n', (2812, 2823), True, 'import numpy as np\n'), ((3579, 3597), 'numpy.linalg.inv', 'np.linalg.inv', (['rot'], {}), '(rot)\n', (3592, 3597), True, 'import numpy as np\n'), ((6412, 6438), 'numpy.random.exponential', 'np.random.exponential', (['(0.5)'], {}), '(0.5)\n', (6433, 6438), True, 'import numpy as np\n'), ((7511, 7545), 'os.path.join', 'os.path.join', (['"""geometry"""', 'obj.path'], {}), "('geometry', obj.path)\n", (7523, 7545), False, 'import os\n'), ((7645, 7673), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3,)'}), '(size=(3,))\n', (7662, 7673), True, 'import numpy as np\n'), ((7705, 7730), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(360)'], {}), '(0, 360)\n', (7722, 7730), True, 'import numpy as np\n'), ((7768, 7796), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(3,)'}), '(size=(3,))\n', (7785, 7796), True, 'import numpy as np\n'), ((7828, 7853), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(360)'], {}), '(0, 360)\n', (7845, 7853), True, 'import numpy as np\n'), ((7186, 7211), 'numpy.array', 'np.array', (["cam['position']"], {}), "(cam['position'])\n", (7194, 7211), True, 'import numpy as np\n'), ((7212, 7230), 'numpy.array', 'np.array', (['position'], {}), '(position)\n', (7220, 7230), True, 'import numpy as np\n')] |
"""
Copyright 2018 The Johns Hopkins University Applied Physics Laboratory.
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 sys
import time
import numpy as np
import json
np.random.seed(9999)
import image_handler as ih
from intern.remote.boss import BossRemote
from intern.resource.boss.resource import *
from cnn_tools import *
from data_tools import *
K.set_image_dim_ordering('th')
defaults = {
"use_boss": False,
"train_pct": 0.50,
"n_epochs": 10,
"mb_size": 4,
"n_mb_per_epoch": 3,
"save_freq": 50,
"do_warp": False,
"weights_file": None
}
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def parse_args(json_file=None):
args = defaults
if json_file:
with open(json_file, 'r') as f:
json_args = json.load(f)
args.update(json_args)
return Namespace(**args)
def get_boss_data(args):
config = {"protocol": "https",
"host": "api.theBoss.io",
"token": args.token}
rmt = BossRemote(config)
chan = ChannelResource(args.img_channel,
args.collection,
args.experiment,
'image',
datatype='uint8')
# Get the image data from the BOSS
x_train = rmt.get_cutout(chan, args.resolution,
args.x_rng,
args.y_rng,
args.z_rng)
lchan = ChannelResource(args.lbl_channel,
args.collection,
args.experiment,
'annotation',
datatype='uint64')
y_train = rmt.get_cutout(lchan, args.resolution,
args.x_rng,
args.y_rng,
args.z_rng)
# Data must be [slices, chan, row, col] (i.e., [Z, chan, Y, X])
x_train = x_train[:, np.newaxis, :, :].astype(np.float32)
y_train = y_train[:, np.newaxis, :, :].astype(np.float32)
# Pixel values must be in [0,1]
x_train /= 255.
y_train = (y_train > 0).astype('float32')
return x_train, y_train
def get_file_data(args):
file_type = args.img_file.split('.')[-1]
if file_type == 'gz' or file_type == 'nii':
x_train = ih.load_nii(args.img_file, data_type='uint8')
y_train = ih.load_nii(args.lbl_file, data_type='uint8')
elif file_type == 'npz':
x_train = np.load(args.img_file)
y_train = np.load(args.lbl_file)
# Data must be [slices, chan, row, col] (i.e., [Z, chan, Y, X])
x_train = x_train[:, np.newaxis, :, :].astype(np.float32)
y_train = y_train[:, np.newaxis, :, :].astype(np.float32)
# Pixel values must be in [0,1]
x_train /= 255.
y_train = (y_train > 0).astype('float32')
return x_train, y_train
if __name__ == '__main__':
# -------------------------------------------------------------------------
if len(sys.argv) < 2:
exit('JSON config file was not provided.')
args = parse_args(sys.argv[1])
if args.use_boss:
x_train, y_train = get_boss_data(args)
else:
x_train, y_train = get_file_data(args)
tile_size = tuple(args.tile_size)
train_pct = args.train_pct
# -------------------------------------------------------------------------
# Data must be [slices, chan, row, col] (i.e., [Z, chan, Y, X])
# split into train and valid
train_slices = range(int(train_pct * x_train.shape[0]))
x_train = x_train[train_slices, ...]
y_train = y_train[train_slices, ...]
valid_slices = range(int(train_pct * x_train.shape[0]), x_train.shape[0])
x_valid = x_train[valid_slices, ...]
y_valid = y_train[valid_slices, ...]
print('[info]: training data has shape: %s' % str(x_train.shape))
print('[info]: training labels has shape: %s' % str(y_train.shape))
print('[info]: validation data has shape: %s' % str(x_valid.shape))
print('[info]: validation labels has shape: %s' % str(y_valid.shape))
print('[info]: tile size: %s' % str(tile_size))
# train model
tic = time.time()
model = create_unet((1, tile_size[0], tile_size[1]))
if args.do_synapse:
model.compile(optimizer=Adam(lr=1e-4),
loss=pixelwise_crossentropy_loss_w,
metrics=[f1_score])
else:
model.compile(optimizer=Adam(lr=1e-4),
loss=pixelwise_crossentropy_loss,
metrics=[f1_score])
if args.weights_file:
model.load_weights(args.weights_file)
train_model(x_train, y_train, x_valid, y_valid, model,
args.output_dir, do_augment=args.do_warp,
n_epochs=args.n_epochs, mb_size=args.mb_size,
n_mb_per_epoch=args.n_mb_per_epoch,
save_freq=args.save_freq)
print('[info]: total time to train model: %0.2f min' %
((time.time() - tic) / 60.))
| [
"numpy.load",
"json.load",
"numpy.random.seed",
"time.time",
"intern.remote.boss.BossRemote",
"image_handler.load_nii"
] | [((668, 688), 'numpy.random.seed', 'np.random.seed', (['(9999)'], {}), '(9999)\n', (682, 688), True, 'import numpy as np\n'), ((1529, 1547), 'intern.remote.boss.BossRemote', 'BossRemote', (['config'], {}), '(config)\n', (1539, 1547), False, 'from intern.remote.boss import BossRemote\n'), ((4692, 4703), 'time.time', 'time.time', ([], {}), '()\n', (4701, 4703), False, 'import time\n'), ((2845, 2890), 'image_handler.load_nii', 'ih.load_nii', (['args.img_file'], {'data_type': '"""uint8"""'}), "(args.img_file, data_type='uint8')\n", (2856, 2890), True, 'import image_handler as ih\n'), ((2909, 2954), 'image_handler.load_nii', 'ih.load_nii', (['args.lbl_file'], {'data_type': '"""uint8"""'}), "(args.lbl_file, data_type='uint8')\n", (2920, 2954), True, 'import image_handler as ih\n'), ((1307, 1319), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1316, 1319), False, 'import json\n'), ((3003, 3025), 'numpy.load', 'np.load', (['args.img_file'], {}), '(args.img_file)\n', (3010, 3025), True, 'import numpy as np\n'), ((3044, 3066), 'numpy.load', 'np.load', (['args.lbl_file'], {}), '(args.lbl_file)\n', (3051, 3066), True, 'import numpy as np\n'), ((5506, 5517), 'time.time', 'time.time', ([], {}), '()\n', (5515, 5517), False, 'import time\n')] |
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
import plotly.graph_objs as go
from dash.dependencies import Input, Output, State
from datetime import datetime, date, timedelta
import json, csv, dash_table, time, operator
from connect import norm_records, rec_lows, rec_highs, all_temps
import pandas as pd
import numpy as np
from numpy import arange,array,ones
from scipy import stats
import psycopg2
import os
# app.Title = 'Denver Temp Dashboard'
DATABASE_URL = os.environ['DATABASE_URL']
df_all_temps = pd.DataFrame(all_temps,columns=['dow','sta','Date','TMAX','TMIN'])
df_norms = pd.DataFrame(norm_records)
df_rec_lows = pd.DataFrame(rec_lows)
df_rec_highs = pd.DataFrame(rec_highs)
current_year = datetime.now().year
today = time.strftime("%Y-%m-%d")
startyr = 1999
year_count = current_year-startyr
def get_layout():
return html.Div(
[
html.Div([
html.H4(
'DENVER TEMPERATURE RECORD',
className='twelve columns',
style={'text-align': 'center'}
),
],
className='row'
),
html.Div([
html.H6(
id='title-date-range',
className='twelve columns',
style={'text-align': 'center'}
),
],
className='row'
),
html.Div([
html.Div([
html.Label('Select Product'),
dcc.RadioItems(
id='product',
options=[
{'label':'Temperature graphs', 'value':'temp-graph'},
{'label':'Climatology for a day', 'value':'climate-for-day'},
{'label':'5 Year Moving Avgs', 'value':'fyma-graph'},
],
# value='temp-graph',
labelStyle={'display': 'block'},
),
],
className='three columns',
),
html.Div([
# html.Label('Options'),
html.Div(
id='year-picker'
),
html.Div(
id='date-picker'
),
],
className='four columns',
),
],
className='row'
),
html.Div([
html.Div(
[
html.Div(id='period-picker'),
],
className='pretty_container'
),
]),
html.Div([
html.Div([
html.Div(
id='graph'
),
],
className='eight columns'
),
html.Div([
html.Div([
html.Div(id='graph-stats'
),
],
),
],
className='four columns'
),
],
className='row'
),
html.Div([
html.Div([
html.Div(
id='climate-day-table'
),
],
className='five columns'
),
html.Div([
html.Div([
html.Div(id='daily-max-t'),
],
className='twelve columns'
),
html.Div([
html.Div(id='daily-min-t'),
],
className='twelve columns'
),
],
className='seven columns'
),
],
className='row'
),
html.Div([
html.Div([
html.Div(
id='bar'
),
],
className='eight columns'
),
],
className='row'
),
html.Div(id='all-data', style={'display': 'none'}),
html.Div(id='rec-highs', style={'display': 'none'}),
html.Div(id='rec-lows', style={'display': 'none'}),
html.Div(id='norms', style={'display': 'none'}),
html.Div(id='temp-data', style={'display': 'none'}),
html.Div(id='df5', style={'display': 'none'}),
html.Div(id='max-trend', style={'display': 'none'}),
html.Div(id='min-trend', style={'display': 'none'}),
html.Div(id='d-max-max', style={'display': 'none'}),
html.Div(id='avg-of-dly-highs', style={'display': 'none'}),
html.Div(id='d-min-max', style={'display': 'none'}),
html.Div(id='d-min-min', style={'display': 'none'}),
html.Div(id='avg-of-dly-lows', style={'display': 'none'}),
html.Div(id='d-max-min', style={'display': 'none'}),
html.Div(id='temps', style={'display': 'none'}),
]
)
app = dash.Dash(__name__)
# app.layout = get_layout()
app.config['suppress_callback_exceptions']=True
server = app.server
app.layout = get_layout
@app.callback(
Output('graph-stats', 'children'),
[Input('temps', 'children'),
Input('product','value')])
def display_graph_stats(temps, selected_product):
temps = pd.read_json(temps)
temps.index = pd.to_datetime(temps.index, unit='ms')
temps = temps[np.isfinite(temps['TMAX'])]
# print(temps)
day_count = temps.shape[0]
rec_highs = len(temps[temps['TMAX'] == temps['rh']])
rec_lows = len(temps[temps['TMIN'] == temps['rl']])
days_abv_norm = len(temps[temps['TMAX'] > temps['nh']])
days_blw_norm = len(temps[temps['TMIN'] < temps['nl']])
nh = temps['nh'].sum()
nl = temps['nl'].sum()
tmax = temps['TMAX'].sum()
tmin = temps['TMIN'].sum()
# print(nh)
# print(nl)
# print(tmax)
# print(tmin)
degree_days = ((temps['TMAX'].sum() - temps['nh'].sum()) + (temps['TMIN'].sum() - temps['nl'].sum())) / 2
if degree_days > 0:
color = 'red'
elif degree_days < 0:
color = 'blue'
if selected_product == 'temp-graph':
return html.Div(
[
html.Div([
html.Div('Day Count', style={'text-align':'center'}),
html.Div('{}'.format(day_count), style={'text-align': 'center'})
],
className='round1'
),
html.Div([
html.Div('Records', style={'text-align':'center'}),
html.Div([
html.Div([
html.Div('High: {}'.format(rec_highs), style={'text-align': 'center', 'color':'red'}),
],
className='six columns'
),
html.Div([
html.Div('Low: {}'.format(rec_lows), style={'text-align': 'center', 'color':'blue'})
],
className='six columns'
),
],
className='row'
),
],
className='round1'
),
html.Div([
html.Div('Days Above/Below Normal', style={'text-align':'center'}),
html.Div([
html.Div([
html.Div('Above: {}'.format(days_abv_norm), style={'text-align': 'center', 'color':'red'}),
],
className='six columns'
),
html.Div([
html.Div('Below: {}'.format(days_blw_norm), style={'text-align': 'center', 'color':'blue'})
],
className='six columns'
),
],
className='row'
),
],
className='round1'
),
html.Div([
html.Div('Degree Days Over/Under Normal', style={'text-align':'center'}),
html.Div(html.Div('{:.0f} Degree Days'.format(degree_days), style={'text-align': 'center', 'color':color})),
],
className='round1'
),
],
className='round1'
),
@app.callback(
Output('daily-max-t', 'children'),
[Input('product', 'value'),
Input('d-max-max', 'children'),
Input('avg-of-dly-highs', 'children'),
Input('d-min-max', 'children')])
def max_stats(product, d_max_max, admaxh, d_min_max):
dly_max_max = d_max_max
admaxh = admaxh
dly_min_max = d_min_max
print(dly_max_max)
if product == 'climate-for-day':
return html.Div([
html.Div([
html.H6('Maximum Temperatures', style={'text-align':'center', 'color':'red'})
]),
html.Div([
html.Div([
html.Div([
html.H6('Maximum', style={'text-align':'center', 'color': 'red'}),
html.H6('{}'.format(dly_max_max), style={'text-align':'center'})
],
className='round1 four columns'
),
html.Div([
html.H6('Average', style={'text-align':'center', 'color': 'red'}),
html.H6('{:.0f}'.format(admaxh), style={'text-align':'center'})
],
className='round1 four columns'
),
html.Div([
html.H6('Minimum', style={'text-align':'center', 'color': 'red'}),
html.H6('{}'.format(dly_min_max), style={'text-align':'center'})
],
className='round1 four columns'
),
],
className='row'
),
],
className='pretty_container'
),
],
# className='twelve columns'
),
@app.callback(
Output('daily-min-t', 'children'),
[Input('product', 'value'),
Input('d-min-min', 'children'),
Input('avg-of-dly-lows', 'children'),
Input('d-max-min', 'children')])
def min_stats(product, d_min_min, adminl, d_max_min):
dly_min_min = d_min_min
adminl = adminl
dly_max_min = d_max_min
if product == 'climate-for-day':
return html.Div([
html.Div([
html.H6('Minimum Temperatures', style={'text-align':'center', 'color':'blue'})
]),
html.Div([
html.Div([
html.Div([
html.H6('Minimum', style={'text-align':'center', 'color': 'blue'}),
html.H6('{}'.format(dly_min_min), style={'text-align':'center'})
],
className='round1 four columns'
),
html.Div([
html.H6('Average', style={'text-align':'center', 'color': 'blue'}),
html.H6('{:.0f}'.format(adminl), style={'text-align':'center'})
],
className='round1 four columns'
),
html.Div([
html.H6('Maximum', style={'text-align':'center', 'color': 'blue'}),
html.H6('{}'.format(dly_max_min), style={'text-align':'center'})
],
className='round1 four columns'
),
],
className='row'
),
],
className='pretty_container'
),
],
# className='twelve columns'
),
@app.callback([
Output('datatable-interactivity', 'data'),
Output('datatable-interactivity', 'columns'),
Output('d-max-max', 'children'),
Output('avg-of-dly-highs', 'children'),
Output('d-min-max', 'children'),
Output('d-min-min', 'children'),
Output('avg-of-dly-lows', 'children'),
Output('d-max-min', 'children')],
[Input('all-data', 'children'),
Input('date', 'date')])
def display_climate_day_table(all_data, selected_date):
dr = pd.read_json(all_data)
# dr['Date']=dr['Date'].dt.strftime("%Y-%m-%d")
dr.set_index(['Date'], inplace=True)
# print(dr)
# print(selected_date)
dr = dr[(dr.index.month == int(selected_date[5:7])) & (dr.index.day == int(selected_date[8:10]))]
# dr = df_all_temps[(df_all_temps['Date'][5:7] == date[5:7]) & (df_all_temps['Date'][8:10] == date[8:10])]
dr = dr.reset_index()
# print(dr)
columns=[
{"name": i, "id": i,"selectable": True} for i in dr.columns
]
dr['Date'] = dr['Date'].dt.strftime('%Y-%m-%d')
d_max_max = dr['TMAX'].max()
avg_of_dly_highs = dr['TMAX'].mean()
d_min_max = dr['TMAX'].min()
# print(avg_of_dly_highs)
d_min_min = dr['TMIN'].min()
avg_of_dly_lows = dr['TMIN'].mean()
d_max_min = dr['TMIN'].max()
return dr.to_dict('records'), columns, d_max_max, avg_of_dly_highs, d_min_max, d_min_min, avg_of_dly_lows, d_max_min
@app.callback(
Output('climate-day-bar', 'figure'),
[Input('date', 'date'),
Input('all-data', 'children'),
Input('temp-param', 'value'),
Input('product', 'value')])
def climate_day_graph(selected_date, all_data, selected_param, selected_product):
dr = pd.read_json(all_data)
dr.set_index(['Date'], inplace=True)
dr = dr[(dr.index.month == int(selected_date[5:7])) & (dr.index.day == int(selected_date[8:10]))]
dr['AMAX'] = dr['TMAX'].mean()
dr['AMIN'] = dr['TMIN'].mean()
xi = arange(0,len(dr['TMAX']))
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,dr['TMAX'])
max_trend = (slope*xi+intercept)
dr['MXTRND'] = max_trend
xi = arange(0,len(dr['TMIN']))
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,dr['TMIN'])
min_trend = (slope*xi+intercept)
dr['MNTRND'] = min_trend
all_max_temp_fit = pd.DataFrame(max_trend)
all_max_temp_fit.index = dr.index
all_min_temp_fit = pd.DataFrame(min_trend)
all_min_temp_fit.index = dr.index
title_param = dr.index[0].strftime('%B %d')
if selected_param == 'TMAX':
y = dr[selected_param]
base = 0
color_a = 'tomato'
color_b = 'red'
avg_y = dr['AMAX']
trend_y = dr['MXTRND']
name = 'temp'
name_a = 'avg high'
name_b = 'trend'
hovertemplate='Temp Range: %{y}'
elif selected_param == 'TMIN':
y = dr[selected_param]
base = 0
color_a = 'blue'
color_b = 'dodgerblue'
avg_y = dr['AMIN']
trend_y = dr['MNTRND']
name = 'temp'
name_a = 'avg low'
name_b = 'trend'
hovertemplate='Temp Range: %{y}'
else:
y = dr['TMAX'] - dr['TMIN']
base = dr['TMIN']
color_a = 'dodgerblue'
color_b = 'tomato'
avg_y = dr['AMIN']
trend_y = dr['AMAX']
name = 'range'
name_a = 'avg low'
name_b = 'avg high'
hovertemplate='Temp Range: %{y} - %{base}<extra></extra><br>'
data = [
go.Bar(
y=y,
x=dr.index,
base=base,
marker={'color':'black'},
name=name,
hovertemplate=hovertemplate
),
go.Scatter(
y=avg_y,
x=dr.index,
name=name_a,
marker={'color': color_a}
),
go.Scatter(
y=trend_y,
x=dr.index,
name=name_b,
marker={'color': color_b}
),
]
layout = go.Layout(
xaxis={'title': 'Year'},
yaxis={'title': 'Deg F'},
title='{} for {}'.format(selected_param,title_param),
plot_bgcolor = 'lightgray',
)
return {'data': data, 'layout': layout}
@app.callback(
Output('bar', 'children'),
[Input('product', 'value' )])
def display_day_bar(selected_product):
print(selected_product)
if selected_product == 'climate-for-day':
return dcc.Graph(id='climate-day-bar')
@app.callback(
Output('climate-day-table', 'children'),
[Input('product', 'value')])
def display_climate_stuff(value):
if value == 'climate-for-day':
return dt.DataTable(id='datatable-interactivity',
data=[{}],
columns=[{}],
fixed_rows={'headers': True, 'data': 0},
style_cell_conditional=[
{'if': {'column_id': 'Date'},
'width':'100px'},
{'if': {'column_id': 'TMAX'},
'width':'100px'},
{'if': {'column_id': 'TMIN'},
'width':'100px'},
],
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
},
],
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
},
# editable=True,
# filter_action="native",
sort_action="native",
sort_mode="multi",
column_selectable="single",
selected_columns=[],
selected_rows=[],
# page_action="native",
page_current= 0,
page_size= 10,
)
@app.callback(
Output('period-picker', 'children'),
[Input('product', 'value')])
def display_period_selector(product_value):
if product_value == 'temp-graph':
return dcc.RadioItems(
id = 'period',
options = [
{'label':'Annual (Jan-Dec)', 'value':'annual'},
{'label':'Winter (Dec-Feb)', 'value':'winter'},
{'label':'Spring (Mar-May)', 'value':'spring'},
{'label':'Summer (Jun-Aug)', 'value':'summer'},
{'label':'Fall (Sep-Nov)', 'value':'fall'},
],
value = 'annual',
labelStyle = {'display':'inline'}
)
elif product_value == 'fyma-graph' or product_value == 'climate-for-day':
return dcc.RadioItems(
id = 'temp-param',
options = [
{'label':'Max Temp', 'value':'TMAX'},
{'label':'Min Temp', 'value':'TMIN'},
{'label':'Temp Range', 'value':'RANGE'},
],
value = 'TMAX',
labelStyle = {'display':'inline-block'}
)
@app.callback(
Output('date-picker', 'children'),
[Input('product', 'value')])
# Input('year', 'value')])
def display_date_selector(product_value):
if product_value == 'climate-for-day':
return html.P('Select Date (MM-DD)'), dcc.DatePickerSingle(
id='date',
display_format='MM-DD',
date=today
)
@app.callback(
Output('year-picker', 'children'),
[Input('product', 'value')])
def display_year_selector(product_value):
if product_value == 'temp-graph':
return html.P('Enter Year (YYYY)') ,dcc.Input(
id = 'year',
type = 'number',
# value = 2019,
min = 2000, max = current_year
)
@app.callback([Output('graph1', 'figure'),
Output('temps', 'children')],
[Input('temp-data', 'children'),
Input('rec-highs', 'children'),
Input('rec-lows', 'children'),
Input('norms', 'children'),
Input('year', 'value'),
Input('period', 'value')])
def update_figure(temp_data, rec_highs, rec_lows, norms, selected_year, period):
# print(period)
previous_year = int(selected_year) - 1
selected_year = selected_year
temps = pd.read_json(temp_data)
temps = temps.drop([0,1], axis=1)
temps.columns = ['date','TMAX','TMIN']
# temps['date'] = pd.to_datetime(temps['date'])
temps['date'] = pd.to_datetime(temps['date'], unit='ms')
temps = temps.set_index(['date'])
temps['dif'] = temps['TMAX'] - temps['TMIN']
# temps_cy = temps[temps.index.year.isin([selected_year])]
# temps_py = temps[temps.index.year.isin([previous_year])]
temps_cy = temps[(temps.index.year==selected_year)]
# temps_py = temps[temps.index.year.isin([previous_year])]
temps_py = temps[(temps.index.year==previous_year)]
df_record_highs_ly = pd.read_json(rec_highs)
df_record_highs_ly = df_record_highs_ly.set_index(1)
df_record_lows_ly = pd.read_json(rec_lows)
df_record_lows_ly = df_record_lows_ly.set_index(1)
df_rl_cy = df_record_lows_ly[:len(temps_cy.index)]
df_rh_cy = df_record_highs_ly[:len(temps_cy.index)]
df_norms = pd.read_json(norms)
df_norms_cy = df_norms[:len(temps_cy.index)]
temps_cy.loc[:,'rl'] = df_rl_cy[0].values
temps_cy.loc[:,'rh'] = df_rh_cy[0].values
temps_cy.loc[:,'nh'] = df_norms_cy[3].values
temps_cy.loc[:,'nl'] = df_norms_cy[4].values
if period == 'spring':
temps = temps_cy[temps_cy.index.month.isin([3,4,5])]
nh_value = temps['nh']
nl_value = temps['nl']
rh_value = temps['rh']
rl_value = temps['rl']
bar_x = temps.index
elif period == 'summer':
temps = temps_cy[temps_cy.index.month.isin([6,7,8])]
nh_value = temps['nh']
nl_value = temps['nl']
rh_value = temps['rh']
rl_value = temps['rl']
bar_x = temps.index
elif period == 'fall':
temps = temps_cy[temps_cy.index.month.isin([9,10,11])]
nh_value = temps['nh']
nl_value = temps['nl']
rh_value = temps['rh']
rl_value = temps['rl']
bar_x = temps.index
elif period == 'winter':
date_range = []
date_time = []
sdate = date(int(previous_year), 12, 1)
edate = date(int(selected_year), 12, 31)
delta = edate - sdate
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
date_range.append(day)
for j in date_range:
day = j.strftime("%Y-%m-%d")
date_time.append(day)
temps_py = temps_py[temps_py.index.month.isin([12])]
temps_cy = temps_cy[temps_cy.index.month.isin([1,2])]
temp_frames = [temps_py, temps_cy]
temps = pd.concat(temp_frames, sort=True)
date_time = date_time[:91]
df_record_highs_jan_feb = df_record_highs_ly[df_record_highs_ly.index.str.match(pat = '(01-)|(02-)')]
df_record_highs_dec = df_record_highs_ly[df_record_highs_ly.index.str.match(pat = '(12-)')]
high_frames = [df_record_highs_dec, df_record_highs_jan_feb]
df_record_highs = pd.concat(high_frames)
df_record_lows_jan_feb = df_record_lows_ly[df_record_lows_ly.index.str.match(pat = '(01-)|(02-)')]
df_record_lows_dec = df_record_lows_ly[df_record_lows_ly.index.str.match(pat = '(12-)')]
low_frames = [df_record_lows_dec, df_record_lows_jan_feb]
df_record_lows = pd.concat(low_frames)
df_high_norms_jan_feb = df_norms[3][0:60]
df_high_norms_dec = df_norms[3][335:]
high_norm_frames = [df_high_norms_dec, df_high_norms_jan_feb]
df_high_norms = pd.concat(high_norm_frames)
df_low_norms_jan_feb = df_norms[4][0:60]
df_low_norms_dec = df_norms[4][335:]
low_norm_frames = [df_low_norms_dec, df_low_norms_jan_feb]
df_low_norms = pd.concat(low_norm_frames)
bar_x = date_time
nh_value = df_high_norms
nl_value = df_low_norms
rh_value = df_record_highs[0]
rl_value = df_record_lows[0]
else:
temps = temps_cy
nh_value = temps['nh']
nl_value = temps['nl']
rh_value = temps['rh']
rl_value = temps['rl']
bar_x = temps.index
mkr_color = {'color':'black'}
trace = [
go.Bar(
y = temps['dif'],
x = bar_x,
base = temps['TMIN'],
name='Temp Range',
marker = mkr_color,
hovertemplate = 'Temp Range: %{y} - %{base}<extra></extra><br>'
# 'Record High: %{temps[6]}'
),
go.Scatter(
y = nh_value,
x = bar_x,
# hoverinfo='none',
name='Normal High',
marker = {'color':'indianred'}
),
go.Scatter(
y = nl_value,
x = bar_x,
# hoverinfo='none',
name='Normal Low',
marker = {'color':'slateblue'}
),
go.Scatter(
y = rh_value,
x = bar_x,
# hoverinfo='none',
name='Record High',
marker = {'color':'red'}
),
go.Scatter(
y = rl_value,
x = bar_x,
# hoverinfo='none',
name='Record Low',
marker = {'color':'blue'}
),
]
layout = go.Layout(
# xaxis = {'rangeslider': {'visible':True},},
yaxis = {"title": 'Temperature F'},
title ='Daily Temps',
plot_bgcolor = 'lightgray',
height = 500,
)
return {'data': trace, 'layout': layout}, temps.to_json()
@app.callback(Output('fyma-graph', 'figure'),
[Input('temp-param', 'value'),
Input('df5', 'children'),
Input('max-trend', 'children'),
Input('min-trend', 'children'),
Input('all-data', 'children')])
def update_fyma_graph(selected_param, df_5, max_trend, min_trend, all_data):
print(all_data)
fyma_temps = pd.read_json(all_data)
fyma_temps['Date']=fyma_temps['Date'].dt.strftime("%Y-%m-%d")
fyma_temps.set_index(['Date'], inplace=True)
df_5 = pd.read_json(df_5)
all_max_temp_fit = pd.DataFrame(max_trend)
all_max_temp_fit.index = df_5.index
all_max_temp_fit.index = all_max_temp_fit.index.strftime("%Y-%m-%d")
all_min_temp_fit = pd.DataFrame(min_trend)
all_min_temp_fit.index = df_5.index
all_min_temp_fit.index = all_min_temp_fit.index.strftime("%Y-%m-%d")
all_max_rolling = fyma_temps['TMAX'].dropna().rolling(window=365)
all_max_rolling_mean = all_max_rolling.mean()
all_min_rolling = fyma_temps['TMIN'].dropna().rolling(window=365)
all_min_rolling_mean = all_min_rolling.mean()
if selected_param == 'TMAX':
trace = [
go.Scatter(
y = all_max_rolling_mean,
x = fyma_temps.index,
name='Max Temp'
),
go.Scatter(
y = all_max_temp_fit[0],
x = all_max_temp_fit.index,
mode = 'lines',
name = 'trend',
line = {'color':'red'},
),
]
elif selected_param == 'TMIN':
trace = [
go.Scatter(
y = all_min_rolling_mean,
x = fyma_temps.index,
name='Min Temp'
),
go.Scatter(
y = all_min_temp_fit[0],
x = all_min_temp_fit.index,
mode = 'lines',
name = 'trend',
line = {'color':'red'},
),
]
layout = go.Layout(
xaxis = {'rangeslider': {'visible':True},},
yaxis = {"title": 'Temperature F'},
title ='365 Day Rolling Mean {}'.format(selected_param),
plot_bgcolor = 'lightgray',
height = 500,
)
return {'data': trace, 'layout': layout}
@app.callback(
Output('graph', 'children'),
[Input('product', 'value')])
def display_graph(value):
if value == 'temp-graph':
return dcc.Graph(id='graph1')
elif value == 'fyma-graph':
return dcc.Graph(id='fyma-graph')
@app.callback(Output('all-data', 'children'),
[Input('product', 'value')])
def all_temps_cleaner(product_value):
# print(product_value)
cleaned_all_temps = df_all_temps
cleaned_all_temps.columns=['dow','sta','Date','TMAX','TMIN']
cleaned_all_temps['Date'] = pd.to_datetime(cleaned_all_temps['Date'])
cleaned_all_temps = cleaned_all_temps.drop(['dow','sta'], axis=1)
# return cleaned_all_temps.to_json(date_format='iso')
return cleaned_all_temps.to_json()
@app.callback(Output('title-date-range', 'children'),
[Input('product', 'value'),
Input('all-data', 'children')])
def all_temps_cleaner(product, temps):
# print(temps)
title_temps = pd.read_json(temps)
title_temps['Date']=title_temps['Date'].dt.strftime("%Y-%m-%d")
last_day = title_temps.iloc[-1, 0]
return '2000-01-01 through {}'.format(last_day)
@app.callback(Output('rec-highs', 'children'),
[Input('year', 'value')])
def rec_high_temps(selected_year):
if int(selected_year) % 4 == 0:
rec_highs = df_rec_highs
else:
rec_highs = df_rec_highs.drop(df_rec_highs.index[59])
return rec_highs.to_json()
@app.callback(Output('rec-lows', 'children'),
[Input('year', 'value')])
def rec_low_temps(selected_year):
if int(selected_year) % 4 == 0:
rec_lows = df_rec_lows
else:
rec_lows = df_rec_lows.drop(df_rec_lows.index[59])
return rec_lows.to_json()
@app.callback(Output('norms', 'children'),
[Input('year', 'value')])
def norm_highs(selected_year):
if int(selected_year) % 4 == 0:
norms = df_norms
else:
norms = df_norms.drop(df_norms.index[59])
return norms.to_json()
@app.callback(
Output('df5', 'children'),
[Input('all-data', 'children'),
Input('product', 'value')])
def clean_df5(all_data, product_value):
title_temps = pd.read_json(all_data)
title_temps['Date']=title_temps['Date'].dt.strftime("%Y-%m-%d")
df_date_index = df_all_temps.set_index(['Date'])
df_ya_max = df_date_index.resample('Y').mean()
df5 = df_ya_max[:-1]
df5 = df5.drop(['dow'], axis=1)
# print(df5)
return df5.to_json(date_format='iso')
@app.callback(
Output('max-trend', 'children'),
[Input('df5', 'children'),
Input('product', 'value')])
def all_max_trend(df_5, product_value):
df5 = pd.read_json(df_5)
xi = arange(0,year_count)
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,df5['TMAX'])
return (slope*xi+intercept)
@app.callback(
Output('min-trend', 'children'),
[Input('df5', 'children'),
Input('product', 'value')])
def all_min_trend(df_5, product_value):
df5 = pd.read_json(df_5)
xi = arange(0,year_count)
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,df5['TMIN'])
return (slope*xi+intercept)
@app.callback(Output('temp-data', 'children'),
[Input('year', 'value'),
Input('period', 'value')])
def all_temps(selected_year, period):
previous_year = int(selected_year) - 1
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
postgreSQL_select_year_Query = 'SELECT * FROM temps WHERE EXTRACT(year FROM "DATE"::TIMESTAMP) IN ({},{}) ORDER BY "DATE" ASC'.format(selected_year, previous_year)
cursor.execute(postgreSQL_select_year_Query)
temp_records = cursor.fetchall()
df = pd.DataFrame(temp_records)
# try:
# conn = psycopg2.connect(DATABASE_URL, sslmode='require')
# # connection = psycopg2.connect(user = "postgres",
# # password = "<PASSWORD>",
# # host = "localhost",
# # database = "denver_temps")
# cursor = connection.cursor()
# postgreSQL_select_year_Query = 'SELECT * FROM temps WHERE EXTRACT(year FROM "DATE"::TIMESTAMP) IN ({},{}) ORDER BY "DATE" ASC'.format(selected_year, previous_year)
# cursor.execute(postgreSQL_select_year_Query)
# temp_records = cursor.fetchall()
# df = pd.DataFrame(temp_records)
# except (Exception, psycopg2.Error) as error :
# print ("Error while fetching data from PostgreSQL", error)
# finally:
# #closing database connection.
# if(connection):
# cursor.close()
# connection.close()
# print("PostgreSQL connection is closed")
return df.to_json()
# app.layout = html.Div(body)
if __name__ == "__main__":
app.run_server(debug=False) | [
"dash_core_components.DatePickerSingle",
"time.strftime",
"dash_core_components.Input",
"numpy.arange",
"pandas.DataFrame",
"dash.Dash",
"dash_html_components.Div",
"dash_html_components.Label",
"numpy.isfinite",
"connect.rec_lows.to_json",
"scipy.stats.linregress",
"datetime.timedelta",
"da... | [((570, 641), 'pandas.DataFrame', 'pd.DataFrame', (['all_temps'], {'columns': "['dow', 'sta', 'Date', 'TMAX', 'TMIN']"}), "(all_temps, columns=['dow', 'sta', 'Date', 'TMAX', 'TMIN'])\n", (582, 641), True, 'import pandas as pd\n'), ((649, 675), 'pandas.DataFrame', 'pd.DataFrame', (['norm_records'], {}), '(norm_records)\n', (661, 675), True, 'import pandas as pd\n'), ((691, 713), 'pandas.DataFrame', 'pd.DataFrame', (['rec_lows'], {}), '(rec_lows)\n', (703, 713), True, 'import pandas as pd\n'), ((730, 753), 'pandas.DataFrame', 'pd.DataFrame', (['rec_highs'], {}), '(rec_highs)\n', (742, 753), True, 'import pandas as pd\n'), ((798, 823), 'time.strftime', 'time.strftime', (['"""%Y-%m-%d"""'], {}), "('%Y-%m-%d')\n", (811, 823), False, 'import json, csv, dash_table, time, operator\n'), ((5446, 5465), 'dash.Dash', 'dash.Dash', (['__name__'], {}), '(__name__)\n', (5455, 5465), False, 'import dash\n'), ((770, 784), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (782, 784), False, 'from datetime import datetime, date, timedelta\n'), ((5769, 5788), 'pandas.read_json', 'pd.read_json', (['temps'], {}), '(temps)\n', (5781, 5788), True, 'import pandas as pd\n'), ((5807, 5845), 'pandas.to_datetime', 'pd.to_datetime', (['temps.index'], {'unit': '"""ms"""'}), "(temps.index, unit='ms')\n", (5821, 5845), True, 'import pandas as pd\n'), ((5608, 5641), 'dash.dependencies.Output', 'Output', (['"""graph-stats"""', '"""children"""'], {}), "('graph-stats', 'children')\n", (5614, 5641), False, 'from dash.dependencies import Input, Output, State\n'), ((9143, 9176), 'dash.dependencies.Output', 'Output', (['"""daily-max-t"""', '"""children"""'], {}), "('daily-max-t', 'children')\n", (9149, 9176), False, 'from dash.dependencies import Input, Output, State\n'), ((10952, 10985), 'dash.dependencies.Output', 'Output', (['"""daily-min-t"""', '"""children"""'], {}), "('daily-min-t', 'children')\n", (10958, 10985), False, 'from dash.dependencies import Input, Output, State\n'), ((13192, 13214), 'pandas.read_json', 'pd.read_json', (['all_data'], {}), '(all_data)\n', (13204, 13214), True, 'import pandas as pd\n'), ((14402, 14424), 'pandas.read_json', 'pd.read_json', (['all_data'], {}), '(all_data)\n', (14414, 14424), True, 'import pandas as pd\n'), ((14727, 14759), 'scipy.stats.linregress', 'stats.linregress', (['xi', "dr['TMAX']"], {}), "(xi, dr['TMAX'])\n", (14743, 14759), False, 'from scipy import stats\n'), ((14913, 14945), 'scipy.stats.linregress', 'stats.linregress', (['xi', "dr['TMIN']"], {}), "(xi, dr['TMIN'])\n", (14929, 14945), False, 'from scipy import stats\n'), ((15035, 15058), 'pandas.DataFrame', 'pd.DataFrame', (['max_trend'], {}), '(max_trend)\n', (15047, 15058), True, 'import pandas as pd\n'), ((15125, 15148), 'pandas.DataFrame', 'pd.DataFrame', (['min_trend'], {}), '(min_trend)\n', (15137, 15148), True, 'import pandas as pd\n'), ((14145, 14180), 'dash.dependencies.Output', 'Output', (['"""climate-day-bar"""', '"""figure"""'], {}), "('climate-day-bar', 'figure')\n", (14151, 14180), False, 'from dash.dependencies import Input, Output, State\n'), ((16948, 16973), 'dash.dependencies.Output', 'Output', (['"""bar"""', '"""children"""'], {}), "('bar', 'children')\n", (16954, 16973), False, 'from dash.dependencies import Input, Output, State\n'), ((17189, 17228), 'dash.dependencies.Output', 'Output', (['"""climate-day-table"""', '"""children"""'], {}), "('climate-day-table', 'children')\n", (17195, 17228), False, 'from dash.dependencies import Input, Output, State\n'), ((18336, 18371), 'dash.dependencies.Output', 'Output', (['"""period-picker"""', '"""children"""'], {}), "('period-picker', 'children')\n", (18342, 18371), False, 'from dash.dependencies import Input, Output, State\n'), ((19603, 19636), 'dash.dependencies.Output', 'Output', (['"""date-picker"""', '"""children"""'], {}), "('date-picker', 'children')\n", (19609, 19636), False, 'from dash.dependencies import Input, Output, State\n'), ((20001, 20034), 'dash.dependencies.Output', 'Output', (['"""year-picker"""', '"""children"""'], {}), "('year-picker', 'children')\n", (20007, 20034), False, 'from dash.dependencies import Input, Output, State\n'), ((20910, 20933), 'pandas.read_json', 'pd.read_json', (['temp_data'], {}), '(temp_data)\n', (20922, 20933), True, 'import pandas as pd\n'), ((21087, 21127), 'pandas.to_datetime', 'pd.to_datetime', (["temps['date']"], {'unit': '"""ms"""'}), "(temps['date'], unit='ms')\n", (21101, 21127), True, 'import pandas as pd\n'), ((21549, 21572), 'pandas.read_json', 'pd.read_json', (['rec_highs'], {}), '(rec_highs)\n', (21561, 21572), True, 'import pandas as pd\n'), ((21654, 21676), 'pandas.read_json', 'pd.read_json', (['rec_lows'], {}), '(rec_lows)\n', (21666, 21676), True, 'import pandas as pd\n'), ((21863, 21882), 'pandas.read_json', 'pd.read_json', (['norms'], {}), '(norms)\n', (21875, 21882), True, 'import pandas as pd\n'), ((26275, 26381), 'plotly.graph_objs.Layout', 'go.Layout', ([], {'yaxis': "{'title': 'Temperature F'}", 'title': '"""Daily Temps"""', 'plot_bgcolor': '"""lightgray"""', 'height': '(500)'}), "(yaxis={'title': 'Temperature F'}, title='Daily Temps',\n plot_bgcolor='lightgray', height=500)\n", (26284, 26381), True, 'import plotly.graph_objs as go\n'), ((26963, 26985), 'pandas.read_json', 'pd.read_json', (['all_data'], {}), '(all_data)\n', (26975, 26985), True, 'import pandas as pd\n'), ((27114, 27132), 'pandas.read_json', 'pd.read_json', (['df_5'], {}), '(df_5)\n', (27126, 27132), True, 'import pandas as pd\n'), ((27157, 27180), 'pandas.DataFrame', 'pd.DataFrame', (['max_trend'], {}), '(max_trend)\n', (27169, 27180), True, 'import pandas as pd\n'), ((27318, 27341), 'pandas.DataFrame', 'pd.DataFrame', (['min_trend'], {}), '(min_trend)\n', (27330, 27341), True, 'import pandas as pd\n'), ((26599, 26629), 'dash.dependencies.Output', 'Output', (['"""fyma-graph"""', '"""figure"""'], {}), "('fyma-graph', 'figure')\n", (26605, 26629), False, 'from dash.dependencies import Input, Output, State\n'), ((28933, 28960), 'dash.dependencies.Output', 'Output', (['"""graph"""', '"""children"""'], {}), "('graph', 'children')\n", (28939, 28960), False, 'from dash.dependencies import Input, Output, State\n'), ((29450, 29491), 'pandas.to_datetime', 'pd.to_datetime', (["cleaned_all_temps['Date']"], {}), "(cleaned_all_temps['Date'])\n", (29464, 29491), True, 'import pandas as pd\n'), ((29178, 29208), 'dash.dependencies.Output', 'Output', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (29184, 29208), False, 'from dash.dependencies import Input, Output, State\n'), ((29875, 29894), 'pandas.read_json', 'pd.read_json', (['temps'], {}), '(temps)\n', (29887, 29894), True, 'import pandas as pd\n'), ((29675, 29713), 'dash.dependencies.Output', 'Output', (['"""title-date-range"""', '"""children"""'], {}), "('title-date-range', 'children')\n", (29681, 29713), False, 'from dash.dependencies import Input, Output, State\n'), ((30334, 30353), 'connect.rec_highs.to_json', 'rec_highs.to_json', ([], {}), '()\n', (30351, 30353), False, 'from connect import norm_records, rec_lows, rec_highs, all_temps\n'), ((30075, 30106), 'dash.dependencies.Output', 'Output', (['"""rec-highs"""', '"""children"""'], {}), "('rec-highs', 'children')\n", (30081, 30106), False, 'from dash.dependencies import Input, Output, State\n'), ((30621, 30639), 'connect.rec_lows.to_json', 'rec_lows.to_json', ([], {}), '()\n', (30637, 30639), False, 'from connect import norm_records, rec_lows, rec_highs, all_temps\n'), ((30369, 30399), 'dash.dependencies.Output', 'Output', (['"""rec-lows"""', '"""children"""'], {}), "('rec-lows', 'children')\n", (30375, 30399), False, 'from dash.dependencies import Input, Output, State\n'), ((30655, 30682), 'dash.dependencies.Output', 'Output', (['"""norms"""', '"""children"""'], {}), "('norms', 'children')\n", (30661, 30682), False, 'from dash.dependencies import Input, Output, State\n'), ((31075, 31097), 'pandas.read_json', 'pd.read_json', (['all_data'], {}), '(all_data)\n', (31087, 31097), True, 'import pandas as pd\n'), ((30922, 30947), 'dash.dependencies.Output', 'Output', (['"""df5"""', '"""children"""'], {}), "('df5', 'children')\n", (30928, 30947), False, 'from dash.dependencies import Input, Output, State\n'), ((31561, 31579), 'pandas.read_json', 'pd.read_json', (['df_5'], {}), '(df_5)\n', (31573, 31579), True, 'import pandas as pd\n'), ((31589, 31610), 'numpy.arange', 'arange', (['(0)', 'year_count'], {}), '(0, year_count)\n', (31595, 31610), False, 'from numpy import arange, array, ones\n'), ((31660, 31693), 'scipy.stats.linregress', 'stats.linregress', (['xi', "df5['TMAX']"], {}), "(xi, df5['TMAX'])\n", (31676, 31693), False, 'from scipy import stats\n'), ((31410, 31441), 'dash.dependencies.Output', 'Output', (['"""max-trend"""', '"""children"""'], {}), "('max-trend', 'children')\n", (31416, 31441), False, 'from dash.dependencies import Input, Output, State\n'), ((31897, 31915), 'pandas.read_json', 'pd.read_json', (['df_5'], {}), '(df_5)\n', (31909, 31915), True, 'import pandas as pd\n'), ((31925, 31946), 'numpy.arange', 'arange', (['(0)', 'year_count'], {}), '(0, year_count)\n', (31931, 31946), False, 'from numpy import arange, array, ones\n'), ((31996, 32029), 'scipy.stats.linregress', 'stats.linregress', (['xi', "df5['TMIN']"], {}), "(xi, df5['TMIN'])\n", (32012, 32029), False, 'from scipy import stats\n'), ((31746, 31777), 'dash.dependencies.Output', 'Output', (['"""min-trend"""', '"""children"""'], {}), "('min-trend', 'children')\n", (31752, 31777), False, 'from dash.dependencies import Input, Output, State\n'), ((32330, 32379), 'psycopg2.connect', 'psycopg2.connect', (['DATABASE_URL'], {'sslmode': '"""require"""'}), "(DATABASE_URL, sslmode='require')\n", (32346, 32379), False, 'import psycopg2\n'), ((32670, 32696), 'pandas.DataFrame', 'pd.DataFrame', (['temp_records'], {}), '(temp_records)\n', (32682, 32696), True, 'import pandas as pd\n'), ((32081, 32112), 'dash.dependencies.Output', 'Output', (['"""temp-data"""', '"""children"""'], {}), "('temp-data', 'children')\n", (32087, 32112), False, 'from dash.dependencies import Input, Output, State\n'), ((5864, 5890), 'numpy.isfinite', 'np.isfinite', (["temps['TMAX']"], {}), "(temps['TMAX'])\n", (5875, 5890), True, 'import numpy as np\n'), ((5648, 5674), 'dash.dependencies.Input', 'Input', (['"""temps"""', '"""children"""'], {}), "('temps', 'children')\n", (5653, 5674), False, 'from dash.dependencies import Input, Output, State\n'), ((5680, 5705), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (5685, 5705), False, 'from dash.dependencies import Input, Output, State\n'), ((9191, 9216), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (9196, 9216), False, 'from dash.dependencies import Input, Output, State\n'), ((9230, 9260), 'dash.dependencies.Input', 'Input', (['"""d-max-max"""', '"""children"""'], {}), "('d-max-max', 'children')\n", (9235, 9260), False, 'from dash.dependencies import Input, Output, State\n'), ((9274, 9311), 'dash.dependencies.Input', 'Input', (['"""avg-of-dly-highs"""', '"""children"""'], {}), "('avg-of-dly-highs', 'children')\n", (9279, 9311), False, 'from dash.dependencies import Input, Output, State\n'), ((9325, 9355), 'dash.dependencies.Input', 'Input', (['"""d-min-max"""', '"""children"""'], {}), "('d-min-max', 'children')\n", (9330, 9355), False, 'from dash.dependencies import Input, Output, State\n'), ((11000, 11025), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (11005, 11025), False, 'from dash.dependencies import Input, Output, State\n'), ((11039, 11069), 'dash.dependencies.Input', 'Input', (['"""d-min-min"""', '"""children"""'], {}), "('d-min-min', 'children')\n", (11044, 11069), False, 'from dash.dependencies import Input, Output, State\n'), ((11083, 11119), 'dash.dependencies.Input', 'Input', (['"""avg-of-dly-lows"""', '"""children"""'], {}), "('avg-of-dly-lows', 'children')\n", (11088, 11119), False, 'from dash.dependencies import Input, Output, State\n'), ((11133, 11163), 'dash.dependencies.Input', 'Input', (['"""d-max-min"""', '"""children"""'], {}), "('d-max-min', 'children')\n", (11138, 11163), False, 'from dash.dependencies import Input, Output, State\n'), ((12734, 12775), 'dash.dependencies.Output', 'Output', (['"""datatable-interactivity"""', '"""data"""'], {}), "('datatable-interactivity', 'data')\n", (12740, 12775), False, 'from dash.dependencies import Input, Output, State\n'), ((12781, 12825), 'dash.dependencies.Output', 'Output', (['"""datatable-interactivity"""', '"""columns"""'], {}), "('datatable-interactivity', 'columns')\n", (12787, 12825), False, 'from dash.dependencies import Input, Output, State\n'), ((12831, 12862), 'dash.dependencies.Output', 'Output', (['"""d-max-max"""', '"""children"""'], {}), "('d-max-max', 'children')\n", (12837, 12862), False, 'from dash.dependencies import Input, Output, State\n'), ((12868, 12906), 'dash.dependencies.Output', 'Output', (['"""avg-of-dly-highs"""', '"""children"""'], {}), "('avg-of-dly-highs', 'children')\n", (12874, 12906), False, 'from dash.dependencies import Input, Output, State\n'), ((12912, 12943), 'dash.dependencies.Output', 'Output', (['"""d-min-max"""', '"""children"""'], {}), "('d-min-max', 'children')\n", (12918, 12943), False, 'from dash.dependencies import Input, Output, State\n'), ((12949, 12980), 'dash.dependencies.Output', 'Output', (['"""d-min-min"""', '"""children"""'], {}), "('d-min-min', 'children')\n", (12955, 12980), False, 'from dash.dependencies import Input, Output, State\n'), ((12986, 13023), 'dash.dependencies.Output', 'Output', (['"""avg-of-dly-lows"""', '"""children"""'], {}), "('avg-of-dly-lows', 'children')\n", (12992, 13023), False, 'from dash.dependencies import Input, Output, State\n'), ((13029, 13060), 'dash.dependencies.Output', 'Output', (['"""d-max-min"""', '"""children"""'], {}), "('d-max-min', 'children')\n", (13035, 13060), False, 'from dash.dependencies import Input, Output, State\n'), ((13068, 13097), 'dash.dependencies.Input', 'Input', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (13073, 13097), False, 'from dash.dependencies import Input, Output, State\n'), ((13103, 13124), 'dash.dependencies.Input', 'Input', (['"""date"""', '"""date"""'], {}), "('date', 'date')\n", (13108, 13124), False, 'from dash.dependencies import Input, Output, State\n'), ((16216, 16321), 'plotly.graph_objs.Bar', 'go.Bar', ([], {'y': 'y', 'x': 'dr.index', 'base': 'base', 'marker': "{'color': 'black'}", 'name': 'name', 'hovertemplate': 'hovertemplate'}), "(y=y, x=dr.index, base=base, marker={'color': 'black'}, name=name,\n hovertemplate=hovertemplate)\n", (16222, 16321), True, 'import plotly.graph_objs as go\n'), ((16408, 16479), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'avg_y', 'x': 'dr.index', 'name': 'name_a', 'marker': "{'color': color_a}"}), "(y=avg_y, x=dr.index, name=name_a, marker={'color': color_a})\n", (16418, 16479), True, 'import plotly.graph_objs as go\n'), ((16547, 16620), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'trend_y', 'x': 'dr.index', 'name': 'name_b', 'marker': "{'color': color_b}"}), "(y=trend_y, x=dr.index, name=name_b, marker={'color': color_b})\n", (16557, 16620), True, 'import plotly.graph_objs as go\n'), ((14187, 14208), 'dash.dependencies.Input', 'Input', (['"""date"""', '"""date"""'], {}), "('date', 'date')\n", (14192, 14208), False, 'from dash.dependencies import Input, Output, State\n'), ((14214, 14243), 'dash.dependencies.Input', 'Input', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (14219, 14243), False, 'from dash.dependencies import Input, Output, State\n'), ((14249, 14277), 'dash.dependencies.Input', 'Input', (['"""temp-param"""', '"""value"""'], {}), "('temp-param', 'value')\n", (14254, 14277), False, 'from dash.dependencies import Input, Output, State\n'), ((14283, 14308), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (14288, 14308), False, 'from dash.dependencies import Input, Output, State\n'), ((17137, 17168), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""climate-day-bar"""'}), "(id='climate-day-bar')\n", (17146, 17168), True, 'import dash_core_components as dcc\n'), ((16980, 17005), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (16985, 17005), False, 'from dash.dependencies import Input, Output, State\n'), ((17347, 17971), 'dash_table.DataTable', 'dt.DataTable', ([], {'id': '"""datatable-interactivity"""', 'data': '[{}]', 'columns': '[{}]', 'fixed_rows': "{'headers': True, 'data': 0}", 'style_cell_conditional': "[{'if': {'column_id': 'Date'}, 'width': '100px'}, {'if': {'column_id':\n 'TMAX'}, 'width': '100px'}, {'if': {'column_id': 'TMIN'}, 'width': '100px'}\n ]", 'style_data_conditional': "[{'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)'}]", 'style_header': "{'backgroundColor': 'rgb(230, 230, 230)', 'fontWeight': 'bold'}", 'sort_action': '"""native"""', 'sort_mode': '"""multi"""', 'column_selectable': '"""single"""', 'selected_columns': '[]', 'selected_rows': '[]', 'page_current': '(0)', 'page_size': '(10)'}), "(id='datatable-interactivity', data=[{}], columns=[{}],\n fixed_rows={'headers': True, 'data': 0}, style_cell_conditional=[{'if':\n {'column_id': 'Date'}, 'width': '100px'}, {'if': {'column_id': 'TMAX'},\n 'width': '100px'}, {'if': {'column_id': 'TMIN'}, 'width': '100px'}],\n style_data_conditional=[{'if': {'row_index': 'odd'}, 'backgroundColor':\n 'rgb(248, 248, 248)'}], style_header={'backgroundColor':\n 'rgb(230, 230, 230)', 'fontWeight': 'bold'}, sort_action='native',\n sort_mode='multi', column_selectable='single', selected_columns=[],\n selected_rows=[], page_current=0, page_size=10)\n", (17359, 17971), True, 'import dash_table as dt\n'), ((17235, 17260), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (17240, 17260), False, 'from dash.dependencies import Input, Output, State\n'), ((18504, 18853), 'dash_core_components.RadioItems', 'dcc.RadioItems', ([], {'id': '"""period"""', 'options': "[{'label': 'Annual (Jan-Dec)', 'value': 'annual'}, {'label':\n 'Winter (Dec-Feb)', 'value': 'winter'}, {'label': 'Spring (Mar-May)',\n 'value': 'spring'}, {'label': 'Summer (Jun-Aug)', 'value': 'summer'}, {\n 'label': 'Fall (Sep-Nov)', 'value': 'fall'}]", 'value': '"""annual"""', 'labelStyle': "{'display': 'inline'}"}), "(id='period', options=[{'label': 'Annual (Jan-Dec)', 'value':\n 'annual'}, {'label': 'Winter (Dec-Feb)', 'value': 'winter'}, {'label':\n 'Spring (Mar-May)', 'value': 'spring'}, {'label': 'Summer (Jun-Aug)',\n 'value': 'summer'}, {'label': 'Fall (Sep-Nov)', 'value': 'fall'}],\n value='annual', labelStyle={'display': 'inline'})\n", (18518, 18853), True, 'import dash_core_components as dcc\n'), ((18378, 18403), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (18383, 18403), False, 'from dash.dependencies import Input, Output, State\n'), ((19643, 19668), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (19648, 19668), False, 'from dash.dependencies import Input, Output, State\n'), ((20041, 20066), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (20046, 20066), False, 'from dash.dependencies import Input, Output, State\n'), ((25053, 25213), 'plotly.graph_objs.Bar', 'go.Bar', ([], {'y': "temps['dif']", 'x': 'bar_x', 'base': "temps['TMIN']", 'name': '"""Temp Range"""', 'marker': 'mkr_color', 'hovertemplate': '"""Temp Range: %{y} - %{base}<extra></extra><br>"""'}), "(y=temps['dif'], x=bar_x, base=temps['TMIN'], name='Temp Range',\n marker=mkr_color, hovertemplate=\n 'Temp Range: %{y} - %{base}<extra></extra><br>')\n", (25059, 25213), True, 'import plotly.graph_objs as go\n'), ((25417, 25503), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'nh_value', 'x': 'bar_x', 'name': '"""Normal High"""', 'marker': "{'color': 'indianred'}"}), "(y=nh_value, x=bar_x, name='Normal High', marker={'color':\n 'indianred'})\n", (25427, 25503), True, 'import plotly.graph_objs as go\n'), ((25632, 25717), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'nl_value', 'x': 'bar_x', 'name': '"""Normal Low"""', 'marker': "{'color': 'slateblue'}"}), "(y=nl_value, x=bar_x, name='Normal Low', marker={'color':\n 'slateblue'})\n", (25642, 25717), True, 'import plotly.graph_objs as go\n'), ((25846, 25922), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'rh_value', 'x': 'bar_x', 'name': '"""Record High"""', 'marker': "{'color': 'red'}"}), "(y=rh_value, x=bar_x, name='Record High', marker={'color': 'red'})\n", (25856, 25922), True, 'import plotly.graph_objs as go\n'), ((26055, 26131), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'rl_value', 'x': 'bar_x', 'name': '"""Record Low"""', 'marker': "{'color': 'blue'}"}), "(y=rl_value, x=bar_x, name='Record Low', marker={'color': 'blue'})\n", (26065, 26131), True, 'import plotly.graph_objs as go\n'), ((20396, 20422), 'dash.dependencies.Output', 'Output', (['"""graph1"""', '"""figure"""'], {}), "('graph1', 'figure')\n", (20402, 20422), False, 'from dash.dependencies import Input, Output, State\n'), ((20437, 20464), 'dash.dependencies.Output', 'Output', (['"""temps"""', '"""children"""'], {}), "('temps', 'children')\n", (20443, 20464), False, 'from dash.dependencies import Input, Output, State\n'), ((20481, 20511), 'dash.dependencies.Input', 'Input', (['"""temp-data"""', '"""children"""'], {}), "('temp-data', 'children')\n", (20486, 20511), False, 'from dash.dependencies import Input, Output, State\n'), ((20526, 20556), 'dash.dependencies.Input', 'Input', (['"""rec-highs"""', '"""children"""'], {}), "('rec-highs', 'children')\n", (20531, 20556), False, 'from dash.dependencies import Input, Output, State\n'), ((20571, 20600), 'dash.dependencies.Input', 'Input', (['"""rec-lows"""', '"""children"""'], {}), "('rec-lows', 'children')\n", (20576, 20600), False, 'from dash.dependencies import Input, Output, State\n'), ((20615, 20641), 'dash.dependencies.Input', 'Input', (['"""norms"""', '"""children"""'], {}), "('norms', 'children')\n", (20620, 20641), False, 'from dash.dependencies import Input, Output, State\n'), ((20656, 20678), 'dash.dependencies.Input', 'Input', (['"""year"""', '"""value"""'], {}), "('year', 'value')\n", (20661, 20678), False, 'from dash.dependencies import Input, Output, State\n'), ((20693, 20717), 'dash.dependencies.Input', 'Input', (['"""period"""', '"""value"""'], {}), "('period', 'value')\n", (20698, 20717), False, 'from dash.dependencies import Input, Output, State\n'), ((26645, 26673), 'dash.dependencies.Input', 'Input', (['"""temp-param"""', '"""value"""'], {}), "('temp-param', 'value')\n", (26650, 26673), False, 'from dash.dependencies import Input, Output, State\n'), ((26688, 26712), 'dash.dependencies.Input', 'Input', (['"""df5"""', '"""children"""'], {}), "('df5', 'children')\n", (26693, 26712), False, 'from dash.dependencies import Input, Output, State\n'), ((26727, 26757), 'dash.dependencies.Input', 'Input', (['"""max-trend"""', '"""children"""'], {}), "('max-trend', 'children')\n", (26732, 26757), False, 'from dash.dependencies import Input, Output, State\n'), ((26772, 26802), 'dash.dependencies.Input', 'Input', (['"""min-trend"""', '"""children"""'], {}), "('min-trend', 'children')\n", (26777, 26802), False, 'from dash.dependencies import Input, Output, State\n'), ((26817, 26846), 'dash.dependencies.Input', 'Input', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (26822, 26846), False, 'from dash.dependencies import Input, Output, State\n'), ((29066, 29088), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""graph1"""'}), "(id='graph1')\n", (29075, 29088), True, 'import dash_core_components as dcc\n'), ((28967, 28992), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (28972, 28992), False, 'from dash.dependencies import Input, Output, State\n'), ((29223, 29248), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (29228, 29248), False, 'from dash.dependencies import Input, Output, State\n'), ((29728, 29753), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (29733, 29753), False, 'from dash.dependencies import Input, Output, State\n'), ((29767, 29796), 'dash.dependencies.Input', 'Input', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (29772, 29796), False, 'from dash.dependencies import Input, Output, State\n'), ((30122, 30144), 'dash.dependencies.Input', 'Input', (['"""year"""', '"""value"""'], {}), "('year', 'value')\n", (30127, 30144), False, 'from dash.dependencies import Input, Output, State\n'), ((30415, 30437), 'dash.dependencies.Input', 'Input', (['"""year"""', '"""value"""'], {}), "('year', 'value')\n", (30420, 30437), False, 'from dash.dependencies import Input, Output, State\n'), ((30698, 30720), 'dash.dependencies.Input', 'Input', (['"""year"""', '"""value"""'], {}), "('year', 'value')\n", (30703, 30720), False, 'from dash.dependencies import Input, Output, State\n'), ((30954, 30983), 'dash.dependencies.Input', 'Input', (['"""all-data"""', '"""children"""'], {}), "('all-data', 'children')\n", (30959, 30983), False, 'from dash.dependencies import Input, Output, State\n'), ((30989, 31014), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (30994, 31014), False, 'from dash.dependencies import Input, Output, State\n'), ((31448, 31472), 'dash.dependencies.Input', 'Input', (['"""df5"""', '"""children"""'], {}), "('df5', 'children')\n", (31453, 31472), False, 'from dash.dependencies import Input, Output, State\n'), ((31478, 31503), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (31483, 31503), False, 'from dash.dependencies import Input, Output, State\n'), ((31784, 31808), 'dash.dependencies.Input', 'Input', (['"""df5"""', '"""children"""'], {}), "('df5', 'children')\n", (31789, 31808), False, 'from dash.dependencies import Input, Output, State\n'), ((31814, 31839), 'dash.dependencies.Input', 'Input', (['"""product"""', '"""value"""'], {}), "('product', 'value')\n", (31819, 31839), False, 'from dash.dependencies import Input, Output, State\n'), ((32128, 32150), 'dash.dependencies.Input', 'Input', (['"""year"""', '"""value"""'], {}), "('year', 'value')\n", (32133, 32150), False, 'from dash.dependencies import Input, Output, State\n'), ((32165, 32189), 'dash.dependencies.Input', 'Input', (['"""period"""', '"""value"""'], {}), "('period', 'value')\n", (32170, 32189), False, 'from dash.dependencies import Input, Output, State\n'), ((4463, 4513), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""all-data"""', 'style': "{'display': 'none'}"}), "(id='all-data', style={'display': 'none'})\n", (4471, 4513), True, 'import dash_html_components as html\n'), ((4527, 4578), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""rec-highs"""', 'style': "{'display': 'none'}"}), "(id='rec-highs', style={'display': 'none'})\n", (4535, 4578), True, 'import dash_html_components as html\n'), ((4592, 4642), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""rec-lows"""', 'style': "{'display': 'none'}"}), "(id='rec-lows', style={'display': 'none'})\n", (4600, 4642), True, 'import dash_html_components as html\n'), ((4656, 4703), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""norms"""', 'style': "{'display': 'none'}"}), "(id='norms', style={'display': 'none'})\n", (4664, 4703), True, 'import dash_html_components as html\n'), ((4717, 4768), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""temp-data"""', 'style': "{'display': 'none'}"}), "(id='temp-data', style={'display': 'none'})\n", (4725, 4768), True, 'import dash_html_components as html\n'), ((4782, 4827), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""df5"""', 'style': "{'display': 'none'}"}), "(id='df5', style={'display': 'none'})\n", (4790, 4827), True, 'import dash_html_components as html\n'), ((4841, 4892), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""max-trend"""', 'style': "{'display': 'none'}"}), "(id='max-trend', style={'display': 'none'})\n", (4849, 4892), True, 'import dash_html_components as html\n'), ((4906, 4957), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""min-trend"""', 'style': "{'display': 'none'}"}), "(id='min-trend', style={'display': 'none'})\n", (4914, 4957), True, 'import dash_html_components as html\n'), ((4971, 5022), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""d-max-max"""', 'style': "{'display': 'none'}"}), "(id='d-max-max', style={'display': 'none'})\n", (4979, 5022), True, 'import dash_html_components as html\n'), ((5036, 5094), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""avg-of-dly-highs"""', 'style': "{'display': 'none'}"}), "(id='avg-of-dly-highs', style={'display': 'none'})\n", (5044, 5094), True, 'import dash_html_components as html\n'), ((5108, 5159), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""d-min-max"""', 'style': "{'display': 'none'}"}), "(id='d-min-max', style={'display': 'none'})\n", (5116, 5159), True, 'import dash_html_components as html\n'), ((5173, 5224), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""d-min-min"""', 'style': "{'display': 'none'}"}), "(id='d-min-min', style={'display': 'none'})\n", (5181, 5224), True, 'import dash_html_components as html\n'), ((5238, 5295), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""avg-of-dly-lows"""', 'style': "{'display': 'none'}"}), "(id='avg-of-dly-lows', style={'display': 'none'})\n", (5246, 5295), True, 'import dash_html_components as html\n'), ((5309, 5360), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""d-max-min"""', 'style': "{'display': 'none'}"}), "(id='d-max-min', style={'display': 'none'})\n", (5317, 5360), True, 'import dash_html_components as html\n'), ((5374, 5421), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""temps"""', 'style': "{'display': 'none'}"}), "(id='temps', style={'display': 'none'})\n", (5382, 5421), True, 'import dash_html_components as html\n'), ((19170, 19396), 'dash_core_components.RadioItems', 'dcc.RadioItems', ([], {'id': '"""temp-param"""', 'options': "[{'label': 'Max Temp', 'value': 'TMAX'}, {'label': 'Min Temp', 'value':\n 'TMIN'}, {'label': 'Temp Range', 'value': 'RANGE'}]", 'value': '"""TMAX"""', 'labelStyle': "{'display': 'inline-block'}"}), "(id='temp-param', options=[{'label': 'Max Temp', 'value':\n 'TMAX'}, {'label': 'Min Temp', 'value': 'TMIN'}, {'label': 'Temp Range',\n 'value': 'RANGE'}], value='TMAX', labelStyle={'display': 'inline-block'})\n", (19184, 19396), True, 'import dash_core_components as dcc\n'), ((19803, 19832), 'dash_html_components.P', 'html.P', (['"""Select Date (MM-DD)"""'], {}), "('Select Date (MM-DD)')\n", (19809, 19832), True, 'import dash_html_components as html\n'), ((19834, 19901), 'dash_core_components.DatePickerSingle', 'dcc.DatePickerSingle', ([], {'id': '"""date"""', 'display_format': '"""MM-DD"""', 'date': 'today'}), "(id='date', display_format='MM-DD', date=today)\n", (19854, 19901), True, 'import dash_core_components as dcc\n'), ((20164, 20191), 'dash_html_components.P', 'html.P', (['"""Enter Year (YYYY)"""'], {}), "('Enter Year (YYYY)')\n", (20170, 20191), True, 'import dash_html_components as html\n'), ((20193, 20256), 'dash_core_components.Input', 'dcc.Input', ([], {'id': '"""year"""', 'type': '"""number"""', 'min': '(2000)', 'max': 'current_year'}), "(id='year', type='number', min=2000, max=current_year)\n", (20202, 20256), True, 'import dash_core_components as dcc\n'), ((27765, 27836), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'all_max_rolling_mean', 'x': 'fyma_temps.index', 'name': '"""Max Temp"""'}), "(y=all_max_rolling_mean, x=fyma_temps.index, name='Max Temp')\n", (27775, 27836), True, 'import plotly.graph_objs as go\n'), ((27916, 28030), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'all_max_temp_fit[0]', 'x': 'all_max_temp_fit.index', 'mode': '"""lines"""', 'name': '"""trend"""', 'line': "{'color': 'red'}"}), "(y=all_max_temp_fit[0], x=all_max_temp_fit.index, mode='lines',\n name='trend', line={'color': 'red'})\n", (27926, 28030), True, 'import plotly.graph_objs as go\n'), ((29136, 29162), 'dash_core_components.Graph', 'dcc.Graph', ([], {'id': '"""fyma-graph"""'}), "(id='fyma-graph')\n", (29145, 29162), True, 'import dash_core_components as dcc\n'), ((28224, 28295), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'all_min_rolling_mean', 'x': 'fyma_temps.index', 'name': '"""Min Temp"""'}), "(y=all_min_rolling_mean, x=fyma_temps.index, name='Min Temp')\n", (28234, 28295), True, 'import plotly.graph_objs as go\n'), ((28375, 28489), 'plotly.graph_objs.Scatter', 'go.Scatter', ([], {'y': 'all_min_temp_fit[0]', 'x': 'all_min_temp_fit.index', 'mode': '"""lines"""', 'name': '"""trend"""', 'line': "{'color': 'red'}"}), "(y=all_min_temp_fit[0], x=all_min_temp_fit.index, mode='lines',\n name='trend', line={'color': 'red'})\n", (28385, 28489), True, 'import plotly.graph_objs as go\n'), ((964, 1065), 'dash_html_components.H4', 'html.H4', (['"""DENVER TEMPERATURE RECORD"""'], {'className': '"""twelve columns"""', 'style': "{'text-align': 'center'}"}), "('DENVER TEMPERATURE RECORD', className='twelve columns', style={\n 'text-align': 'center'})\n", (971, 1065), True, 'import dash_html_components as html\n'), ((1241, 1336), 'dash_html_components.H6', 'html.H6', ([], {'id': '"""title-date-range"""', 'className': '"""twelve columns"""', 'style': "{'text-align': 'center'}"}), "(id='title-date-range', className='twelve columns', style={\n 'text-align': 'center'})\n", (1248, 1336), True, 'import dash_html_components as html\n'), ((23473, 23506), 'pandas.concat', 'pd.concat', (['temp_frames'], {'sort': '(True)'}), '(temp_frames, sort=True)\n', (23482, 23506), True, 'import pandas as pd\n'), ((23858, 23880), 'pandas.concat', 'pd.concat', (['high_frames'], {}), '(high_frames)\n', (23867, 23880), True, 'import pandas as pd\n'), ((24177, 24198), 'pandas.concat', 'pd.concat', (['low_frames'], {}), '(low_frames)\n', (24186, 24198), True, 'import pandas as pd\n'), ((24390, 24417), 'pandas.concat', 'pd.concat', (['high_norm_frames'], {}), '(high_norm_frames)\n', (24399, 24417), True, 'import pandas as pd\n'), ((24603, 24629), 'pandas.concat', 'pd.concat', (['low_norm_frames'], {}), '(low_norm_frames)\n', (24612, 24629), True, 'import pandas as pd\n'), ((1543, 1571), 'dash_html_components.Label', 'html.Label', (['"""Select Product"""'], {}), "('Select Product')\n", (1553, 1571), True, 'import dash_html_components as html\n'), ((1593, 1852), 'dash_core_components.RadioItems', 'dcc.RadioItems', ([], {'id': '"""product"""', 'options': "[{'label': 'Temperature graphs', 'value': 'temp-graph'}, {'label':\n 'Climatology for a day', 'value': 'climate-for-day'}, {'label':\n '5 Year Moving Avgs', 'value': 'fyma-graph'}]", 'labelStyle': "{'display': 'block'}"}), "(id='product', options=[{'label': 'Temperature graphs',\n 'value': 'temp-graph'}, {'label': 'Climatology for a day', 'value':\n 'climate-for-day'}, {'label': '5 Year Moving Avgs', 'value':\n 'fyma-graph'}], labelStyle={'display': 'block'})\n", (1607, 1852), True, 'import dash_core_components as dcc\n'), ((2265, 2291), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""year-picker"""'}), "(id='year-picker')\n", (2273, 2291), True, 'import dash_html_components as html\n'), ((2359, 2385), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""date-picker"""'}), "(id='date-picker')\n", (2367, 2385), True, 'import dash_html_components as html\n'), ((2676, 2704), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""period-picker"""'}), "(id='period-picker')\n", (2684, 2704), True, 'import dash_html_components as html\n'), ((2900, 2920), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""graph"""'}), "(id='graph')\n", (2908, 2920), True, 'import dash_html_components as html\n'), ((3454, 3486), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""climate-day-table"""'}), "(id='climate-day-table')\n", (3462, 3486), True, 'import dash_html_components as html\n'), ((4226, 4244), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""bar"""'}), "(id='bar')\n", (4234, 4244), True, 'import dash_html_components as html\n'), ((6692, 6745), 'dash_html_components.Div', 'html.Div', (['"""Day Count"""'], {'style': "{'text-align': 'center'}"}), "('Day Count', style={'text-align': 'center'})\n", (6700, 6745), True, 'import dash_html_components as html\n'), ((6963, 7014), 'dash_html_components.Div', 'html.Div', (['"""Records"""'], {'style': "{'text-align': 'center'}"}), "('Records', style={'text-align': 'center'})\n", (6971, 7014), True, 'import dash_html_components as html\n'), ((7842, 7909), 'dash_html_components.Div', 'html.Div', (['"""Days Above/Below Normal"""'], {'style': "{'text-align': 'center'}"}), "('Days Above/Below Normal', style={'text-align': 'center'})\n", (7850, 7909), True, 'import dash_html_components as html\n'), ((8749, 8822), 'dash_html_components.Div', 'html.Div', (['"""Degree Days Over/Under Normal"""'], {'style': "{'text-align': 'center'}"}), "('Degree Days Over/Under Normal', style={'text-align': 'center'})\n", (8757, 8822), True, 'import dash_html_components as html\n'), ((9613, 9692), 'dash_html_components.H6', 'html.H6', (['"""Maximum Temperatures"""'], {'style': "{'text-align': 'center', 'color': 'red'}"}), "('Maximum Temperatures', style={'text-align': 'center', 'color': 'red'})\n", (9620, 9692), True, 'import dash_html_components as html\n'), ((11398, 11483), 'dash_html_components.H6', 'html.H6', (['"""Minimum Temperatures"""'], {'style': "{'text-align': 'center', 'color': 'blue'}"}), "('Minimum Temperatures', style={'text-align': 'center', 'color': 'blue'}\n )\n", (11405, 11483), True, 'import dash_html_components as html\n'), ((23133, 23150), 'datetime.timedelta', 'timedelta', ([], {'days': 'i'}), '(days=i)\n', (23142, 23150), False, 'from datetime import datetime, date, timedelta\n'), ((3134, 3160), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""graph-stats"""'}), "(id='graph-stats')\n", (3142, 3160), True, 'import dash_html_components as html\n'), ((3699, 3725), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""daily-max-t"""'}), "(id='daily-max-t')\n", (3707, 3725), True, 'import dash_html_components as html\n'), ((3879, 3905), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""daily-min-t"""'}), "(id='daily-min-t')\n", (3887, 3905), True, 'import dash_html_components as html\n'), ((9812, 9878), 'dash_html_components.H6', 'html.H6', (['"""Maximum"""'], {'style': "{'text-align': 'center', 'color': 'red'}"}), "('Maximum', style={'text-align': 'center', 'color': 'red'})\n", (9819, 9878), True, 'import dash_html_components as html\n'), ((10125, 10191), 'dash_html_components.H6', 'html.H6', (['"""Average"""'], {'style': "{'text-align': 'center', 'color': 'red'}"}), "('Average', style={'text-align': 'center', 'color': 'red'})\n", (10132, 10191), True, 'import dash_html_components as html\n'), ((10437, 10503), 'dash_html_components.H6', 'html.H6', (['"""Minimum"""'], {'style': "{'text-align': 'center', 'color': 'red'}"}), "('Minimum', style={'text-align': 'center', 'color': 'red'})\n", (10444, 10503), True, 'import dash_html_components as html\n'), ((11598, 11665), 'dash_html_components.H6', 'html.H6', (['"""Minimum"""'], {'style': "{'text-align': 'center', 'color': 'blue'}"}), "('Minimum', style={'text-align': 'center', 'color': 'blue'})\n", (11605, 11665), True, 'import dash_html_components as html\n'), ((11912, 11979), 'dash_html_components.H6', 'html.H6', (['"""Average"""'], {'style': "{'text-align': 'center', 'color': 'blue'}"}), "('Average', style={'text-align': 'center', 'color': 'blue'})\n", (11919, 11979), True, 'import dash_html_components as html\n'), ((12225, 12292), 'dash_html_components.H6', 'html.H6', (['"""Maximum"""'], {'style': "{'text-align': 'center', 'color': 'blue'}"}), "('Maximum', style={'text-align': 'center', 'color': 'blue'})\n", (12232, 12292), True, 'import dash_html_components as html\n')] |
import numpy as np
# Individual heatmap for each ID computed for a batch of frames, offline processing
# Watershed to see the networks of connected entities per frame
# answer
# Rework the data dump
from yolox.swarm_metrics.swarm_metrics_utils import dump_frame_swarm_metrics_in_database
from yolox.swarm_metrics.swarm_metrics_GUI import SWARMMetricsGUI
from yolox.tracking_utils.timer import Timer
import cv2
from collections import deque
import numpy as np
import matplotlib.pyplot as plt
class SWARMMetrics(object):
def __init__(self, args, vis_folder, width, height):
self.args = args
self.number_of_metric_queues = 9
self.number_of_persistent_queues = 1
self.number_of_graph_queues = 4
self.max_trail_size = 8000
self.current_entity_number = 0
self.moving_average_global_center = 5 # Should be below or equal to "max_queue_size" // Can't be zero
self.moving_average_fastest_entity = 5 # Should be below or equal to "max_queue_size"
self.moving_average_global_velocity = 5 # Should be below or equal to "max_queue_size"
self.object_disk_size_in_heatmap = 90
self.individual_object_disk_size_in_heatmap = 30
self.max_queue_size = 15
self.persistent_queue_size = 99999
self.paused = True
self.max_graph_size = 40
self.frame_count = 0
self.frame_id = 0
self.velocity_vector_scale = 2
self.visualization_folder = vis_folder
self.database_dump = True
self.tracking_datas = deque(maxlen=self.max_queue_size)
self.objects_trails = deque(maxlen=self.max_trail_size)
self.elapsed_time_in_paused_mode = Timer()
self.pySimpleGui = SWARMMetricsGUI(width, height)
"""
metric_main_stack[0] = metric_1 : float_global_centers
metric_main_stack[1] = metric_2 : float_mean_global_centers
metric_main_stack[2] = metric_3 : individual centers, velocity vectors and norms ?
metric_main_stack[3] = metric_4 : fastest_entity
metric_main_stack[4] = metric_5 : float_global_velocity_deltas
metric_main_stack[5] = metric_6 : float_mean_global_velocity_deltas
metric_main_stack[6] = metric_7 : mean_fastest_entity
metric_main_stack[7] = metric_8 : heat map of positions
"""
self.metric_main_stack = []
for i in range(self.number_of_metric_queues):
self.metric_main_stack.append(deque(maxlen=self.max_queue_size))
self.metric_persistent_stack = []
for i in range(self.number_of_persistent_queues):
self.metric_persistent_stack.append(deque(maxlen=self.persistent_queue_size))
self.metric_graph_stack = []
for i in range(self.number_of_graph_queues):
self.metric_graph_stack.append(deque(maxlen=self.max_graph_size))
self.figures = [[], []]
self.launch_graphs()
self.init_control_gui()
def online_metrics_inputs(self, im, im_h, im_w, tlwhs, obj_ids, frame_id=0, timer=None):
self.tracking_datas.append([im, [im_w, im_h], tlwhs, obj_ids])
self.frame_id = frame_id
self.select_online_metrics(timer, frame_id, len(tlwhs))
self.dump_metrics_in_database()
self.stack_trim()
# Return an annotated image
return self.tracking_datas[-1][0]
def dump_metrics_in_database(self):
if self.database_dump:
dump_frame_swarm_metrics_in_database(self)
def stack_trim(self):
if len(self.tracking_datas) > self.max_queue_size:
self.tracking_datas.popleft()
for i in range(self.number_of_metric_queues):
if len(self.metric_main_stack[i]) > self.max_queue_size:
self.metric_main_stack[i].popleft()
for i in range(self.number_of_graph_queues):
if len(self.metric_graph_stack[i]) > self.max_graph_size:
self.metric_graph_stack[i].popleft()
for i in range(self.number_of_persistent_queues):
if len(self.metric_persistent_stack[i]) > self.persistent_queue_size:
self.metric_persistent_stack[i].popleft()
if len(self.objects_trails) > self.max_trail_size * self.current_entity_number:
self.objects_trails.popleft()
def select_online_metrics(self, timer, frame_id, objects_count):
self.verify_attributes_consistency()
self.compute_metric_1_immediate_global_center()
self.compute_metric_2_immediate_global_center_moving_average()
self.compute_metric_3_and_4_and_5_velocity_vectors()
self.compute_metric_6_global_velocity_vector_moving_average()
self.compute_metric_7_mean_fastest_entity()
self.compute_metric_8_networks()
self.compute_metric_9_individual_heatmaps()
self.update_graphs()
while 1:
self.pySimpleGui.refresh_gui(timer, frame_id, objects_count)
if not self.paused:
break
timer.clear()
timer.tic()
def verify_attributes_consistency(self):
if self.moving_average_global_center > self.max_queue_size:
self.moving_average_global_center = self.max_queue_size
if self.moving_average_fastest_entity > self.max_queue_size:
self.moving_average_fastest_entity = self.max_queue_size
"""
'Immediate' center of mass location of each of the tracked entity, for the current frame.
Significant oscillations could occurs in the case of weak tracking.
"""
def compute_metric_1_immediate_global_center(self, ):
sum_mass = 0.000001
sum_x = 0
sum_y = 0
# from https://stackoverflow.com/questions/12801400/find-the-center-of-mass-of-points
for i, tlwh in enumerate(self.tracking_datas[-1][2]):
x1, y1, w, h = tlwh
sum_mass += 1
sum_x += x1 + w / 2
sum_y += y1 + h / 2
float_immediate_global_center = [sum_x / sum_mass, sum_y / sum_mass]
self.metric_main_stack[0].append(float_immediate_global_center)
self.metric_graph_stack[0].append(float_immediate_global_center)
"""
Moving average of the center masses locations over the last x=moving_average_global_center frames
"""
def compute_metric_2_immediate_global_center_moving_average(self, ):
sum_x = 0
sum_y = 0
i = 0
for center in reversed(self.metric_main_stack[0]):
if i < self.moving_average_global_center:
x, y = center
sum_x += x
sum_y += y
i += 1
else:
break
if self.moving_average_global_center is not 0:
float_mean_global_center = (
sum_x / self.moving_average_global_center, sum_y / self.moving_average_global_center)
else:
float_mean_global_center = (0.0, 0.0)
self.metric_main_stack[1].append(float_mean_global_center)
self.metric_graph_stack[1].append(float_mean_global_center)
def compute_metric_3_and_4_and_5_velocity_vectors(self, ):
sum_velocity_vector_x = 0
sum_velocity_vector_y = 0
fastest_entity = [None, 0, [0, 0]]
tracks_records_number = len(self.tracking_datas)
self.current_entity_number = len(self.tracking_datas[-1][2])
self.metric_main_stack[2].append([self.frame_id, []])
if tracks_records_number >= 2:
for i, tlwh_current in enumerate(self.tracking_datas[-1][2]):
obj_id_current = int(self.tracking_datas[-1][3][i])
for j, tlwh_previous in enumerate(self.tracking_datas[-2][2]):
obj_id_previous = int(self.tracking_datas[-2][3][j])
if obj_id_previous == obj_id_current:
center_current, norm, x_delta, y_delta = self.find_object_center_and_velocity(tlwh_current,
tlwh_previous,
obj_id_previous)
sum_velocity_vector_x += x_delta
sum_velocity_vector_y += y_delta
if norm >= fastest_entity[1]:
fastest_entity = obj_id_current, norm, center_current
self.find_global_velocity_vector(sum_velocity_vector_x, sum_velocity_vector_y, self.current_entity_number)
self.metric_main_stack[3].append(fastest_entity)
def find_object_center_and_velocity(self, tlwh_current, tlwh_previous, obj_id_previous):
x1, y1, w1, h1 = tlwh_current
x2, y2, w2, h2 = tlwh_previous
center_current_float = [x1 + w1 / 2, y1 + h1 / 2]
center_previous_float = [x2 + w2 / 2, y2 + h2 / 2]
x_delta_float = center_current_float[0] - center_previous_float[0]
y_delta_float = center_current_float[1] - center_previous_float[1]
norm = x_delta_float * x_delta_float + y_delta_float * y_delta_float
self.objects_trails.append([center_current_float, obj_id_previous])
self.metric_main_stack[2][-1][1].append(
[center_current_float, [x_delta_float, y_delta_float], norm, obj_id_previous])
return center_current_float, norm, x_delta_float, y_delta_float
def find_global_velocity_vector(self, sum_velocity_vector_x, sum_velocity_vector_y, current_entity_number):
if current_entity_number > 0:
# Store the global velocity vector of the current frame into the corresponding graph stack & main stack.
float_global_velocity_deltas = [sum_velocity_vector_x / current_entity_number,
sum_velocity_vector_y / current_entity_number]
self.metric_main_stack[4].append(float_global_velocity_deltas)
self.metric_graph_stack[2].append(float_global_velocity_deltas)
else:
self.metric_main_stack[4].append([None,None])
self.metric_graph_stack[2].append(
(0, 0)) # TODO null velocities should be distinct from non available datas
"""
Moving average of the global velocity vector ; displayed with "moving average of center of masses" as the vector's tail
"""
def compute_metric_6_global_velocity_vector_moving_average(self, ):
if len(self.metric_main_stack[4]) > 1:
sum_dx = 0
sum_dy = 0
i = 0
for _, deltas in enumerate(self.metric_main_stack[4]):
if i > self.moving_average_global_velocity:
break
if deltas[0] is not None:
dx, dy = deltas
sum_dx += dx
sum_dy += dy
i += 1
float_mean_global_velocity_deltas = [sum_dx / self.moving_average_global_velocity, sum_dy / self.moving_average_global_velocity]
self.metric_main_stack[5].append(float_mean_global_velocity_deltas)
self.metric_graph_stack[3].append(float_mean_global_velocity_deltas)
else:
self.metric_main_stack[5].append(None)
self.metric_graph_stack[3].append(
[0, 0]) # TODO null velocities should be distinct from non available datas
def compute_metric_7_mean_fastest_entity(self, ):
norms_stack = []
if len(self.metric_main_stack[2]) > 1:
for entity_center_and_velocity in self.metric_main_stack[2][-1][1]:
norms_stack.append([self.average_last_known_norms_for_entity(entity_center_and_velocity),
entity_center_and_velocity[3]])
mean_fastest_entity = self.find_fastest_entity_and_his_position(norms_stack)
self.metric_main_stack[6].append(mean_fastest_entity)
def average_last_known_norms_for_entity(self,entity_data):
known_norms = [None for i in range(self.moving_average_fastest_entity)]
i = 0
for entities_description_per_frame in reversed(self.metric_main_stack[2]):
if i >= self.moving_average_fastest_entity:
break
# The entries in entities_description_per_frame[1] are
# [center_current_float, [x_delta_float, y_delta_float], norm, obj_id_previous]
for entity_center_and_velocity in entities_description_per_frame[1]:
if entity_center_and_velocity[3] == entity_data[3]:
known_norms[i] = entity_center_and_velocity[2]
i += 1
final_average = self.compute_average_on_sparse_list(known_norms)
return final_average
def compute_average_on_sparse_list(self, input_list):
sum = 0
none_count = 0
list_size = len(input_list)
for item in input_list:
if item is not None:
sum += item
else:
none_count += 1
if (list_size - none_count) is not 0:
return sum / (list_size - none_count)
else:
return 0
def find_fastest_entity_and_his_position(self, average_list):
actual_best = 0
candidate_id = None
winner = [None, 0, [0, 0]]
if len(average_list) > 0:
for candidate in average_list:
if candidate[0] > actual_best:
actual_best = candidate[0]
candidate_id = candidate[1]
if len(self.metric_main_stack[2]) > 0:
for entity_center_and_velocity in self.metric_main_stack[2][-1][1]:
if entity_center_and_velocity[3] == candidate_id:
winner = [candidate_id, actual_best, entity_center_and_velocity[0]]
return winner
def compute_metric_8_networks(self, ):
heatmap_mask = np.zeros_like(self.tracking_datas[-1][0][:, :, 0]).astype("uint8")
if len(self.metric_main_stack[2]) > 0:
for entity_center_and_velocity in self.metric_main_stack[2][-1][1]:
object_mask = np.zeros_like(self.tracking_datas[-1][0][:, :, 0]).astype("uint8")
cv2.circle(object_mask, tuple(map(int, entity_center_and_velocity[0])),
self.object_disk_size_in_heatmap, 1, -1)
heatmap_mask[object_mask == 1] = 1
# Uncomment to visualize the network masks
#cv2.namedWindow('img', cv2.WINDOW_AUTOSIZE)
#cv2.imshow("img", heatmap_mask*255)
#cv2.waitKey(1)
self.metric_main_stack[7].append(heatmap_mask)
def compute_metric_9_individual_heatmaps(self):
current_entity_masks = [self.frame_id, []]
if len(self.metric_main_stack[2]) > 0:
for entity_center_and_velocity in self.metric_main_stack[2][-1][1]:
current_entity_masks[1].append([entity_center_and_velocity[3], np.zeros_like(self.tracking_datas[-1][0][:, :, 0]).astype("float")])
object_mask = np.zeros_like(self.tracking_datas[-1][0][:, :, 0]).astype("float")
cv2.circle(object_mask, tuple(map(int, entity_center_and_velocity[0])),
self.individual_object_disk_size_in_heatmap, 1, -1)
current_entity_masks[1][-1][1][object_mask == 1] = 255
self.accumulate_individual_heatmaps(current_entity_masks)
def accumulate_individual_heatmaps(self, masks_list):
for current_obj_id_and_mask in masks_list[1]:
is_in_stack_0, index = self.is_ID_already_in_stack_0(current_obj_id_and_mask[0])
if is_in_stack_0:
self.metric_persistent_stack[0][index][1][current_obj_id_and_mask[1] == 255] += 0.00001
else:
self.metric_persistent_stack[0].append([current_obj_id_and_mask[0], np.zeros_like(self.tracking_datas[-1][0][:, :, 0]).astype("float")])
def is_ID_already_in_stack_0(self, obj_id):
i = 0
if len(self.metric_persistent_stack[0])>0:
for id_and_heatmap in self.metric_persistent_stack[0]:
if id_and_heatmap[0] == obj_id:
return True, i
i+=1
return False, i
def update_graph_data(self, metric_graph, plot_id):
x_values = len(metric_graph)
x_time = np.linspace(0, x_values, x_values)
self.figures[1][plot_id][0].set_xdata(x_time)
self.figures[1][plot_id][0].set_ydata([x_location[0] for x_location in metric_graph])
self.figures[1][plot_id][1].set_xdata(x_time)
self.figures[1][plot_id][1].set_ydata([y_location[1] for y_location in metric_graph])
def update_graphs(self):
self.frame_count += 1
if self.frame_count >= 1:
for i in range(self.number_of_graph_queues):
self.update_graph_data(self.metric_graph_stack[i], i)
self.figures[0][0].canvas.flush_events()
# https://stackoverflow.com/questions/53324068/a-faster-refresh-rate-with-plt-imshow
"""
cv2.namedWindow('img', cv2.WINDOW_AUTOSIZE)
cv2.imshow("img", self.tracking_datas[-1][0])
cv2.waitKey(1)
"""
def create_plot(self, gridx, gridy, title, xlabel, ylabel, curve_1_color, curve_2_color, axs, y_range):
axs[gridx, gridy].set_title(title)
axs[gridx, gridy].set(xlabel=xlabel, ylabel=ylabel)
x = np.linspace(0, self.max_graph_size, self.max_graph_size)
y = np.linspace(y_range[0], y_range[1], self.max_graph_size)
line1, = axs[gridx, gridy].plot(x, y, curve_1_color)
line2, = axs[gridx, gridy].plot(x, y, curve_2_color)
self.figures[1].append([line1, line2])
def launch_graphs(self):
# From https://www.delftstack.com/howto/matplotlib/how-to-plot-in-real-time-using-matplotlib/
# From https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
plt.ion()
figure1, axs = plt.subplots(2, 2, figsize=(12, 8),
gridspec_kw={'width_ratios': [1, 1], 'height_ratios': [1, 1]})
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.35, hspace=0.40)
figure1.suptitle('Online metrics', size=22)
figure1.canvas.set_window_title('Online swarm metrics')
self.create_plot(0, 0, 'Centers of mass (x,y)', 'Frames', 'x(Orange),y(green)', 'tab:orange', 'tab:green', axs,
[0, 1280])
self.create_plot(0, 1, 'Moving Average', 'Frames', 'x(Orange),y(green)', 'tab:orange',
'tab:green', axs, [0, 1280])
self.create_plot(1, 0, 'Global velocity vector (Dx,Dy)', 'Frames', 'Dx(Blue),Dy(Red)', 'tab:blue', 'tab:red',
axs, [-20, 20])
self.create_plot(1, 1, 'Moving Average', 'Frames', 'Dx(Blue),Dy(Red)', 'tab:blue', 'tab:red', axs,
[-20, 20])
self.figures[0].append(figure1)
def init_control_gui(self):
self.pySimpleGui.set_swarm_metric(self)
self.pySimpleGui.init_gui()
| [
"numpy.zeros_like",
"yolox.swarm_metrics.swarm_metrics_GUI.SWARMMetricsGUI",
"yolox.swarm_metrics.swarm_metrics_utils.dump_frame_swarm_metrics_in_database",
"matplotlib.pyplot.ion",
"numpy.linspace",
"yolox.tracking_utils.timer.Timer",
"matplotlib.pyplot.subplots",
"collections.deque",
"matplotlib.p... | [((1551, 1584), 'collections.deque', 'deque', ([], {'maxlen': 'self.max_queue_size'}), '(maxlen=self.max_queue_size)\n', (1556, 1584), False, 'from collections import deque\n'), ((1615, 1648), 'collections.deque', 'deque', ([], {'maxlen': 'self.max_trail_size'}), '(maxlen=self.max_trail_size)\n', (1620, 1648), False, 'from collections import deque\n'), ((1692, 1699), 'yolox.tracking_utils.timer.Timer', 'Timer', ([], {}), '()\n', (1697, 1699), False, 'from yolox.tracking_utils.timer import Timer\n'), ((1727, 1757), 'yolox.swarm_metrics.swarm_metrics_GUI.SWARMMetricsGUI', 'SWARMMetricsGUI', (['width', 'height'], {}), '(width, height)\n', (1742, 1757), False, 'from yolox.swarm_metrics.swarm_metrics_GUI import SWARMMetricsGUI\n'), ((16329, 16363), 'numpy.linspace', 'np.linspace', (['(0)', 'x_values', 'x_values'], {}), '(0, x_values, x_values)\n', (16340, 16363), True, 'import numpy as np\n'), ((17429, 17485), 'numpy.linspace', 'np.linspace', (['(0)', 'self.max_graph_size', 'self.max_graph_size'], {}), '(0, self.max_graph_size, self.max_graph_size)\n', (17440, 17485), True, 'import numpy as np\n'), ((17498, 17554), 'numpy.linspace', 'np.linspace', (['y_range[0]', 'y_range[1]', 'self.max_graph_size'], {}), '(y_range[0], y_range[1], self.max_graph_size)\n', (17509, 17554), True, 'import numpy as np\n'), ((17962, 17971), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (17969, 17971), True, 'import matplotlib.pyplot as plt\n'), ((17996, 18098), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': '(12, 8)', 'gridspec_kw': "{'width_ratios': [1, 1], 'height_ratios': [1, 1]}"}), "(2, 2, figsize=(12, 8), gridspec_kw={'width_ratios': [1, 1],\n 'height_ratios': [1, 1]})\n", (18008, 18098), True, 'import matplotlib.pyplot as plt\n'), ((18139, 18229), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.1)', 'bottom': '(0.1)', 'right': '(0.9)', 'top': '(0.9)', 'wspace': '(0.35)', 'hspace': '(0.4)'}), '(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.35,\n hspace=0.4)\n', (18158, 18229), True, 'import matplotlib.pyplot as plt\n'), ((3475, 3517), 'yolox.swarm_metrics.swarm_metrics_utils.dump_frame_swarm_metrics_in_database', 'dump_frame_swarm_metrics_in_database', (['self'], {}), '(self)\n', (3511, 3517), False, 'from yolox.swarm_metrics.swarm_metrics_utils import dump_frame_swarm_metrics_in_database\n'), ((2498, 2531), 'collections.deque', 'deque', ([], {'maxlen': 'self.max_queue_size'}), '(maxlen=self.max_queue_size)\n', (2503, 2531), False, 'from collections import deque\n'), ((2681, 2721), 'collections.deque', 'deque', ([], {'maxlen': 'self.persistent_queue_size'}), '(maxlen=self.persistent_queue_size)\n', (2686, 2721), False, 'from collections import deque\n'), ((2856, 2889), 'collections.deque', 'deque', ([], {'maxlen': 'self.max_graph_size'}), '(maxlen=self.max_graph_size)\n', (2861, 2889), False, 'from collections import deque\n'), ((13891, 13941), 'numpy.zeros_like', 'np.zeros_like', (['self.tracking_datas[-1][0][:, :, 0]'], {}), '(self.tracking_datas[-1][0][:, :, 0])\n', (13904, 13941), True, 'import numpy as np\n'), ((14115, 14165), 'numpy.zeros_like', 'np.zeros_like', (['self.tracking_datas[-1][0][:, :, 0]'], {}), '(self.tracking_datas[-1][0][:, :, 0])\n', (14128, 14165), True, 'import numpy as np\n'), ((15027, 15077), 'numpy.zeros_like', 'np.zeros_like', (['self.tracking_datas[-1][0][:, :, 0]'], {}), '(self.tracking_datas[-1][0][:, :, 0])\n', (15040, 15077), True, 'import numpy as np\n'), ((14928, 14978), 'numpy.zeros_like', 'np.zeros_like', (['self.tracking_datas[-1][0][:, :, 0]'], {}), '(self.tracking_datas[-1][0][:, :, 0])\n', (14941, 14978), True, 'import numpy as np\n'), ((15840, 15890), 'numpy.zeros_like', 'np.zeros_like', (['self.tracking_datas[-1][0][:, :, 0]'], {}), '(self.tracking_datas[-1][0][:, :, 0])\n', (15853, 15890), True, 'import numpy as np\n')] |
# -*- coding: cp1252 -*-
# Minimize a continuous differentialble multivariate function. Starting point
# is given by "X" (D by 1), and the function named in the string "f", must
# return a function value and a vector of partial derivatives. The Polack-
# Ribiere flavour of conjugate gradients is used to compute search directions,
# and a line search using quadratic and cubic polynomial approximations and the
# Wolfe-Powell stopping criteria is used together with the slope ratio method
# for guessing initial step sizes. Additionally a bunch of checks are made to
# make sure that exploration is taking place and that extrapolation will not
# be unboundedly large. The "length" gives the length of the run: if it is
# positive, it gives the maximum number of line searches, if negative its
# absolute gives the maximum allowed number of function evaluations. You can
# (optionally) give "length" a second component, which will indicate the
# reduction in function value to be expected in the first line-search (defaults
# to 1.0). The function returns when either its length is up, or if no further
# progress can be made (ie, we are at a minimum, or so close that due to
# numerical problems, we cannot get any closer). If the function terminates
# within a few iterations, it could be an indication that the function value
# and derivatives are not consistent (ie, there may be a bug in the
# implementation of your "f" function). The function returns the found
# solution "X", a vector of function values "fX" indicating the progress made
# and "i" the number of iterations (line searches or function evaluations,
# depending on the sign of "length") used.
# %
# Usage: X, fX, i = fmincg(f, X, options)
# %
# See also: checkgrad
# %
# Copyright (C) 2001 and 2002 by <NAME>. Date 2002-02-13
# %
# %
# (C) Copyright 1999, 2000 & 2001, <NAME>ussen
# Permission is granted for anyone to copy, use, or modify these
# programs and accompanying documents for purposes of research or
# education, provided this copyright notice is retained, and note is
# made of any changes that have been made.
# These programs and documents are distributed without any warranty,
# express or implied. As the programs were written for research
# purposes only, they have not been tested to the degree that would be
# advisable in any important application. All use of these programs is
# entirely at the user's own risk.
# [ml-class] Changes Made:
# 1) Function name and argument specifications
# 2) Output display
# [<NAME>] Changes Made:
# 1) Python translation
# [<NAME>] Changes Made:
# 1) added option['maxiter'] passing
# 2) changed a few np.dots to np.multiplys
# 3) changed the conatenation line so that now it can handle one item arrays
# 4) changed the printing part to print the Iteration lines to the same row
import numpy as np
import sys
import numpy.linalg as la
from math import isnan, isinf
def fmincg(f, X, options):
if options['maxiter']:
length = options['maxiter']
else:
length = 100
RHO = 0.01 # a bunch of constants for line searches
SIG = 0.5 # RHO and SIG are the constants in the Wolfe-Powell conditions
INT = 0.1 # don't reevaluate within 0.1 of the limit of the current bracket
EXT = 3.0 # extrapolate maximum 3 times the current bracket
MAX = 20 # max 20 function evaluations per line search
RATIO = 100 # maximum allowed slope ratio
# FIXME
red = 1
i = 0 # zero the run length counter
ls_failed = 0 # no previous line search has failed
fX = np.array([])
f1, df1 = f(X) # get function value and gradient
i = i + (length<0) # count epochs?!
s = -df1 # search direction is steepest
d1 = np.dot(-s.T, s) # this is the slope
z1 = red/(1-d1) # initial step is red/(|s|+1)
while i < abs(length): # while not finished
i = i + (length>0) # count iterations?!
X0 = X; f0 = f1; df0 = df1 # make a copy of current values # begin line search
X = X + np.multiply(z1,s) # begin line search
f2, df2 = f(X)
i = i + (length<0) # count epochs?!
d2 = np.dot(df2.T, s)
f3 = f1
d3 = d1
z3 = -z1 # initialize point 3 equal to point 1
if length>0:
M = MAX
else:
M = min(MAX, -length-i)
success = 0
limit = -1 # initialize quanteties
while True:
while ((f2 > f1+np.dot(np.dot(z1,RHO),d1)) or (d2 > np.dot(-SIG, d1))) and (M > 0):
limit = z1 # tighten the bracket
if f2 > f1:
z2 = z3 - (0.5*np.dot(np.dot(d3,z3),z3))/(np.dot(d3, z3)+f2-f3) # quadratic fit
else:
A = 6*(f2-f3)/z3+3*(d2+d3) # cubic fit
B = 3*(f3-f2)-np.dot(z3,(d3+2*d2))
z2 = (np.sqrt(np.dot(B, B)-np.dot(np.dot(np.dot(A,d2),z3),z3))-B)/A # numerical error possible - ok!
if isnan(z2) | isinf(z2):
z2 = z3/2 # if we had a numerical problem then bisect
z2 = max(min(z2, INT*z3),(1-INT)*z3) # don't accept too close to limits
z1 = z1 + z2 # update the step
X = X + np.multiply(z2,s)
f2, df2 = f(X)
M = M - 1
i = i + (length<0) # count epochs?!
d2 = np.dot(np.transpose(df2),s)
z3 = z3-z2 # z3 is now relative to the location of z2
if (f2 > f1+np.dot(z1*RHO,d1)) or (d2 > -SIG*d1):
break # this is a failure
elif d2 > SIG*d1:
success = 1
break # success
elif M == 0:
break # failure
A = 6*(f2-f3)/z3+3*(d2+d3) # make cubic extrapolation
B = 3*(f3-f2)-np.dot(z3, (d3+2*d2))
z2 = -np.dot(np.dot(d2,z3),z3)/(B+np.sqrt(np.dot(B,B)-np.dot(np.dot(np.dot(A,d2),z3),z3))) # num. error possible - ok!
if z2 is not float or isnan(z2) or isinf(z2) or z2 < 0: # num prob or wrong sign?
if limit < -0.5: # if we have no upper limit
z2 = z1 * (EXT-1) # the extrapolate the maximum amount
else:
z2 = (limit-z1)/2 # otherwise bisect
elif (limit > -0.5) and (z2+z1 > limit): # extraplation beyond max?
z2 = (limit-z1)/2 # bisect
elif (limit < -0.5) and (z2+z1 > z1*EXT): # extrapolation beyond limit
z2 = z1*(EXT-1.0) # set to extrapolation limit
elif z2 < -z3*INT:
z2 = -z3*INT
elif (limit > -0.5) and (z2 < (limit-z1)*(1.0-INT)): # too close to limit?
z2 = (limit-z1)*(1.0-INT)
f3 = f2; d3 = d2; z3 = -z2 # set point 3 equal to point 2
z1 = z1 + z2
X = X + np.multiply(z2,s) # update current estimates
f2, df2 = f(X)
M = M - 1
i = i + (length<0) # count epochs?!
d2 = np.dot(df2.T,s)
if success: # if line search succeeded
f1 = f2
## print (fX.T).shape
## print isinstance(f1, np.generic)
fX = np.append(fX.T, [float(f1)]).T
## fX = np.concatenate(([fX.T], [f1]) ,1).T
## print("Iteration %i | Cost: %f \r" %(i,f1)),
s = np.multiply((np.dot(df2.T,df2)-np.dot(df1.T,df2))/(np.dot(df1.T,df1)), s) - df2 # Polack-Ribiere direction
tmp = df1
df1 = df2
df2 = tmp # swap derivatives
d2 = np.dot(df1.T,s)
if d2 > 0: # new slope must be negative
s = -df1 # otherwise use steepest direction
d2 = np.dot(-s.T,s)
z1 = z1 * min(RATIO, d1/(d2-sys.float_info.min)) # slope ratio but max RATIO
d1 = d2
ls_failed = 0 # this line search did not fail
else:
X = X0
f1 = f0
df1 = df0 # restore point from before failed line search
if ls_failed or (i > abs(length)): # line search failed twice in a row
break # or we ran out of time, so we give up
tmp = df1
df1 = df2
df2 = tmp # swap derivatives
s = -df1 # try steepest
d1 = np.dot(-s.T,s)
z1 = 1/(1-d1)
ls_failed = 1 # this line search failed
## print
return X, fX, i | [
"math.isnan",
"math.isinf",
"numpy.multiply",
"numpy.transpose",
"numpy.array",
"numpy.dot"
] | [((3734, 3746), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3742, 3746), True, 'import numpy as np\n'), ((3996, 4011), 'numpy.dot', 'np.dot', (['(-s.T)', 's'], {}), '(-s.T, s)\n', (4002, 4011), True, 'import numpy as np\n'), ((4670, 4686), 'numpy.dot', 'np.dot', (['df2.T', 's'], {}), '(df2.T, s)\n', (4676, 4686), True, 'import numpy as np\n'), ((4489, 4507), 'numpy.multiply', 'np.multiply', (['z1', 's'], {}), '(z1, s)\n', (4500, 4507), True, 'import numpy as np\n'), ((8184, 8200), 'numpy.dot', 'np.dot', (['df2.T', 's'], {}), '(df2.T, s)\n', (8190, 8200), True, 'import numpy as np\n'), ((8827, 8843), 'numpy.dot', 'np.dot', (['df1.T', 's'], {}), '(df1.T, s)\n', (8833, 8843), True, 'import numpy as np\n'), ((9770, 9785), 'numpy.dot', 'np.dot', (['(-s.T)', 's'], {}), '(-s.T, s)\n', (9776, 9785), True, 'import numpy as np\n'), ((6746, 6769), 'numpy.dot', 'np.dot', (['z3', '(d3 + 2 * d2)'], {}), '(z3, d3 + 2 * d2)\n', (6752, 6769), True, 'import numpy as np\n'), ((6940, 6949), 'math.isnan', 'isnan', (['z2'], {}), '(z2)\n', (6945, 6949), False, 'from math import isnan, isinf\n'), ((6953, 6962), 'math.isinf', 'isinf', (['z2'], {}), '(z2)\n', (6958, 6962), False, 'from math import isnan, isinf\n'), ((7976, 7994), 'numpy.multiply', 'np.multiply', (['z2', 's'], {}), '(z2, s)\n', (7987, 7994), True, 'import numpy as np\n'), ((9042, 9057), 'numpy.dot', 'np.dot', (['(-s.T)', 's'], {}), '(-s.T, s)\n', (9048, 9057), True, 'import numpy as np\n'), ((5623, 5632), 'math.isnan', 'isnan', (['z2'], {}), '(z2)\n', (5628, 5632), False, 'from math import isnan, isinf\n'), ((5635, 5644), 'math.isinf', 'isinf', (['z2'], {}), '(z2)\n', (5640, 5644), False, 'from math import isnan, isinf\n'), ((5939, 5957), 'numpy.multiply', 'np.multiply', (['z2', 's'], {}), '(z2, s)\n', (5950, 5957), True, 'import numpy as np\n'), ((6120, 6137), 'numpy.transpose', 'np.transpose', (['df2'], {}), '(df2)\n', (6132, 6137), True, 'import numpy as np\n'), ((5044, 5060), 'numpy.dot', 'np.dot', (['(-SIG)', 'd1'], {}), '(-SIG, d1)\n', (5050, 5060), True, 'import numpy as np\n'), ((5456, 5479), 'numpy.dot', 'np.dot', (['z3', '(d3 + 2 * d2)'], {}), '(z3, d3 + 2 * d2)\n', (5462, 5479), True, 'import numpy as np\n'), ((6258, 6278), 'numpy.dot', 'np.dot', (['(z1 * RHO)', 'd1'], {}), '(z1 * RHO, d1)\n', (6264, 6278), True, 'import numpy as np\n'), ((6793, 6807), 'numpy.dot', 'np.dot', (['d2', 'z3'], {}), '(d2, z3)\n', (6799, 6807), True, 'import numpy as np\n'), ((8640, 8658), 'numpy.dot', 'np.dot', (['df1.T', 'df1'], {}), '(df1.T, df1)\n', (8646, 8658), True, 'import numpy as np\n'), ((6822, 6834), 'numpy.dot', 'np.dot', (['B', 'B'], {}), '(B, B)\n', (6828, 6834), True, 'import numpy as np\n'), ((8602, 8620), 'numpy.dot', 'np.dot', (['df2.T', 'df2'], {}), '(df2.T, df2)\n', (8608, 8620), True, 'import numpy as np\n'), ((8620, 8638), 'numpy.dot', 'np.dot', (['df1.T', 'df2'], {}), '(df1.T, df2)\n', (8626, 8638), True, 'import numpy as np\n'), ((5015, 5030), 'numpy.dot', 'np.dot', (['z1', 'RHO'], {}), '(z1, RHO)\n', (5021, 5030), True, 'import numpy as np\n'), ((5235, 5249), 'numpy.dot', 'np.dot', (['d3', 'z3'], {}), '(d3, z3)\n', (5241, 5249), True, 'import numpy as np\n'), ((5255, 5269), 'numpy.dot', 'np.dot', (['d3', 'z3'], {}), '(d3, z3)\n', (5261, 5269), True, 'import numpy as np\n'), ((5511, 5523), 'numpy.dot', 'np.dot', (['B', 'B'], {}), '(B, B)\n', (5517, 5523), True, 'import numpy as np\n'), ((6848, 6861), 'numpy.dot', 'np.dot', (['A', 'd2'], {}), '(A, d2)\n', (6854, 6861), True, 'import numpy as np\n'), ((5538, 5551), 'numpy.dot', 'np.dot', (['A', 'd2'], {}), '(A, d2)\n', (5544, 5551), True, 'import numpy as np\n')] |
# ****数据预处理代码-第一步:数据清洗**** #
import pandas as pd
import numpy as np
import random
from collections import Counter
from sklearn import preprocessing
from matplotlib import pyplot as plt
import seaborn as sns
import missingno
from scipy import stats
import math
# 绘图预处理
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 预备数据
list_prov_code = { # <province, adcode>
'河南': '410000', '广东': '440000', '山东': '370000', '河北': '130000', '江苏': '320000', '四川': '510000',
'上海': '310000', '云南': '530000', '陕西': '610000', '山西': '140000', '广西': '450000', '重庆': '150000',
'内蒙古': '320000', '湖南': '430000', '北京': '110000', '安徽': '340000','辽宁': '210000',
'黑龙江': '230000', '江西': '360000', '福建': '350000', '浙江': '330000', '湖北': '420000'
}
list_season = {'season1-2016': 0, 'season2-2016': 0, 'season3-2016': 0, 'season4-2016': 0,
'season1-2017': 0, 'season2-2017': 0, 'season3-2017': 0, 'season4-2017': 0}
list_province = list_prov_code.keys() # [province]
list_adcode = list_prov_code.values() # [adcode]
list_model = [] # [model] 通过遍历数据添加
dict_model_int = dict() # <model, int> 车型的数据映射
list_bodyType = ['SUV', 'Sedan', 'MPV', 'Hatchback'] # [bodyType]
sum_sales = 0 # 销量总和
# 自定义函数
def is_digit(num): # 判断是否为数值
if isinstance(num, np.int64) or isinstance(num, float) or isinstance(num, int) and not math.isnan(num):
return True
return False
def is_str(string, this_list): # 判断是否为合理字符串
if isinstance(string, str):
if str in this_list:
return True
return False
def add_model(df): # 获取model数据并映射到dict_model_int
i = 1
for model in df['model']:
if model not in list_model:
list_model.append(model)
dict_model_int.update({model: i})
i += 1
def sales_sum_prov(df): # 分省份对销量求和,返回<省,销量>
prov_data = dict()
list_str = list_province
for str in list_str:
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[6]): # 把异常省份名称和异常销量值、空数据排除
if str in prov_data.keys():
prov_data[str] += row_date[6]
else:
prov_data.update({str: row_date[6]})
print(prov_data)
return prov_data
def sales_sum_season(df, str): # 对某一省份按季度销量求和,返回<季度,销量>
season_data = dict(list_season)
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[6]): # 把异常省份名称和异常销量值排除
if not (math.isnan(row_date[5]) and math.isnan(row_date[4])): # 排除年月为空
if row_date[5] in [1, 2, 3]: # 找到对应月份的季度
if row_date[4] == 2016:
season_data['season1-2016'] += row_date[6]
else:
season_data['season1-2017'] += row_date[6]
elif row_date[5] in [4, 5, 6]:
if row_date[4] == 2016:
season_data['season2-2016'] += row_date[6]
else:
season_data['season2-2017'] += row_date[6]
elif row_date[5] in [7, 8, 9]:
if row_date[4] == 2016:
season_data['season3-2016'] += row_date[6]
else:
season_data['season3-2017'] += row_date[6]
elif row_date[5] in [10, 11, 12]:
if row_date[4] == 2016:
season_data['season4-2016'] += row_date[6]
else:
season_data['season4-2017'] += row_date[6]
return season_data
def body_type_sales_sum(df): # 对车身类型销量求和,返回<车身类型,销量>
global sum_sales # 声明全局变量
dict_bodyType_sales = dict({'SUV': 0, 'Sedan': 0, 'MPV': 0, 'Hatchback': 0})
for str in list_bodyType:
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[3] == str and is_digit(row_date[6]):
dict_bodyType_sales[str] += row_date[6]
sum_sales += row_date[6]
return dict_bodyType_sales.values()
def model_sales_sum(df): # 销售量求和,返回字典<车型,销售量>
dict_sales_model = dict()
for str in list_model:
dict_sales_model.update({dict_model_int[str]: 0})
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[2] == str and is_digit(row_date[6]):
dict_sales_model[dict_model_int[str]] += row_date[6]
return dict_sales_model
def search_sum_model(df): # 搜索量求和,返回字典<车型,搜索量>
dict_search_model = dict()
for str in list_model:
dict_search_model.update({dict_model_int[str]: 0})
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[2] == str and is_digit(row_date[5]):
dict_search_model[dict_model_int[str]] += row_date[5]
return dict_search_model
def comment_sum_model(df): # 评论量求和,返回字典<车型,评论量>
dict_comment_model = dict()
for str in list_model:
dict_comment_model.update({dict_model_int[str]: 0})
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[3]):
dict_comment_model[dict_model_int[str]] += row_date[3]
return dict_comment_model
def com_rep_sum_season(df, index): # 对评论量和回复量求和,并绘制对比折线图
season_data_com = dict(list_season)
season_data_rep = dict(list_season)
str = list(dict_model_int.keys())[list(dict_model_int.values()).index(index)]
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[3]) and is_digit(row_date[4]):
if not (math.isnan(row_date[1]) and math.isnan(row_date[2])):
if row_date[2] in [1, 2, 3]: # 找到对应月份的季度
if row_date[1] == 2016:
season_data_com['season1-2016'] += row_date[3]
season_data_rep['season1-2016'] += row_date[4]
else:
season_data_com['season1-2017'] += row_date[3]
season_data_rep['season1-2017'] += row_date[4]
elif row_date[2] in [4, 5, 6]:
if row_date[1] == 2016:
season_data_com['season2-2016'] += row_date[3]
season_data_rep['season2-2016'] += row_date[4]
else:
season_data_com['season2-2017'] += row_date[3]
season_data_rep['season2-2017'] += row_date[4]
elif row_date[2] in [7, 8, 9]:
if row_date[1] == 2016:
season_data_com['season3-2016'] += row_date[3]
season_data_rep['season3-2016'] += row_date[4]
else:
season_data_com['season3-2017'] += row_date[3]
season_data_rep['season3-2017'] += row_date[4]
elif row_date[2] in [10, 11, 12]:
if row_date[1] == 2016:
season_data_com['season4-2016'] += row_date[3]
season_data_rep['season4-2016'] += row_date[4]
else:
season_data_com['season4-2017'] += row_date[3]
season_data_rep['season4-2017'] += row_date[4]
x1 = list(season_data_com.keys())
y1 = list(season_data_com.values())
x2 = list(season_data_rep.keys())
y2 = list(season_data_rep.values())
name1 = '车型对应的季度评论'
name2 = '车型对应的季度回复'
addr = '../result/com_rep_man_Plot2.png'
x_name = '季度'
y_name = '数量'
title = '最高评论量车型季度走势'
graph_plot2(x1, y1, name1, x2, y2, name2, addr, x_name, y_name, title)
def model1_sales_list(df): # 车型1销量列表
list_sales_model1 = []
str = list(dict_model_int.keys())[list(dict_model_int.values()).index(31)]
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[2] == str and is_digit(row_date[6]):
list_sales_model1.append(row_date[6])
return list_sales_model1
def model1_search_list(df): # 车型1搜索量列表
list_sea_model1 = []
str = list(dict_model_int.keys())[list(dict_model_int.values()).index(31)]
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[2] == str and is_digit(row_date[5]):
list_sea_model1.append(row_date[5])
return list_sea_model1
def model1_com_list(df): # 车型1评论量列表
list_com_model1 = []
str = list(dict_model_int.keys())[list(dict_model_int.values()).index(31)]
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[3]):
list_com_model1.append(row_date[3])
return list_com_model1
def model1_rep_list(df): #车型1回复量列表
list_rep_model1 = []
str = list(dict_model_int.keys())[list(dict_model_int.values()).index(31)]
for i in range(1, df.shape[0]):
row_date = df.iloc[i]
if row_date[0] == str and is_digit(row_date[4]):
list_rep_model1.append(row_date[4])
return list_rep_model1
def graph_bar(x, y, addr, x_name, y_name, title): # 绘制条形图
#plt.figure()
plt.bar(x, y)
plt.axis('tight')
plt.xlabel(x_name)
plt.ylabel(y_name)
# plt.xlim((-3, 5)) 坐标区间
plt.title(title)
#plt.tight_layout(w_pad=3.0)
plt.savefig(addr)
plt.show()
def graph_plot(x, y, addr, x_name, y_name, title): # 绘制折现图
plt.plot(x, y, marker='.', mec='r', mfc='w')
plt.axis('tight')
plt.xlabel(x_name)
plt.ylabel(y_name)
plt.title(title)
plt.savefig(addr)
plt.show()
def graph_plot2(x1, y1, name1, x2, y2, name2, addr, x_name, y_name, title): # 绘制两条对比折现图
plt.plot(x1, y1, marker='.', mec='r', mfc='w', label=name1)
plt.plot(x2, y2, marker='+', ms=10, label=name2)
plt.legend()
plt.axis('tight')
plt.xlabel(x_name)
plt.ylabel(y_name)
plt.title(title)
plt.savefig(addr)
plt.show()
def graph_pie(x, addr, title): # 绘制饼图
explode = [0, 0.05, 0, 0.02]
# explode一个列表,用于指定每块饼片边缘偏离半径的百分比
plt.pie(list(x), explode=explode,
labels=list_bodyType, autopct='%3.1f%%',
startangle=180, shadow=True, colors=['cyan', 'lightpink', 'green', 'yellow'])
plt.title(title)
plt.savefig(addr)
plt.show()
def norm_fun(x, mu, sigma): # 概率密度函数
f = np.exp(-((x - mu)**2) / (2 * sigma**2)) / (sigma * np.sqrt(2 * np.pi))
return f
def graph_f_plot(df, x_l, x_r, x_len, x_name, title, addr): # 正态分布图
mean = df.mean() # 得到均值
std = df.std() # 得到标准差
x = np.arange(x_l, x_r, x_len)
# 设定 y 轴,载入刚才的正态分布函数
y = norm_fun(x, mean, std)
plt.plot(x, y)
# 画出直方图,最后的“normed”参数,是赋范的意思,数学概念
plt.hist(df, bins=100, rwidth=0.5, normed=True)
plt.axis('tight')
plt.title(title)
plt.xlabel(x_name)
plt.ylabel('Probability')
plt.savefig(addr)
plt.show()
def pier(a, b): # 计算皮尔逊相关系数
r = stats.pearsonr(a, b)
return r
# 从表格导入数据
data_sales = pd.read_excel('../data/train_sales_data.xls') # 读入csv文件
data_search = pd.read_excel('../data/train_search_data.xls')
data_user = pd.read_excel('../data/train_user_reply_data.xls')
data_test = pd.read_excel('../data/test.xls')
add_model(data_sales) # 获取model数据,并映射
# .shape获取表格行列数
print('数据行列数:')
print("\t销售数据:{}".format(data_sales.shape))
print("\t搜索数据:{}".format(data_search.shape))
print("\t评论数据:{}".format(data_user.shape))
print("\t测试数据:{}".format(data_test.shape))
'''
# 预处理前数据统计图
# #对省份总销量绘图
list_sales_prov = sales_sum_prov(data_sales)
print('各省份的总销量数据:')
print(list_sales_prov)
list_x_sales = list_sales_prov.keys() # 省份
list_y_sales = list_sales_prov.values() # 销量
graph_bar(list_x_sales, list_y_sales, '../result/sales_data_Bar.png', '省份', '销量', '各省份总销量条形图')
# #对销量最高和销量最低省份按季度绘图折线图
max_sales = max(list_y_sales) # 得到最大销量数
province_max_sales = list(list_x_sales)[list(list_y_sales).index(max_sales)] # 通过value在字典中的下标获取对应的键值
min_sales = min(list_y_sales) # 最小销量数
province_min_sales = list(list_x_sales)[list(list_y_sales).index(min_sales)]
list_sales_max = sales_sum_season(data_sales, province_max_sales)
list_sales_min = sales_sum_season(data_sales, province_min_sales)
print('最高销售量省份分季度销量数据:')
print(list_sales_max)
print('最低销售量省份分季度销量数据:')
print(list_sales_min)
graph_plot(list_sales_max.keys(), list_sales_max.values(), '../result/sales_max_Plot.png', '季度', '销量',
province_max_sales + '省各季度销量')
graph_plot(list_sales_min.keys(), list_sales_min.values(), '../result/sales_min_Plot.png', '季度', '销量',
province_min_sales + '省各季度销量')
graph_plot2(list_sales_max.keys(), list_sales_max.values(), province_max_sales,
list_sales_min.keys(), list_sales_min.values(), province_min_sales,
'../result/sales_min_Plot.png', '季度', '销量', '最高最低省份季度销量对比')
# #对销售量按车身类型绘图饼图
list_bodyType_sales = body_type_sales_sum(data_sales)
graph_pie(list_bodyType_sales, '../result/bodyType_sales_Pie.png', '车身类型销量图')
# #对销售量求和按车型列表并排序
dict_model_sales = model_sales_sum(data_sales)
print("销售量按车型列表并排序:{}".format(sorted(dict_model_sales.items(), key=lambda x: x[1], reverse=True)))
# #搜索量求和按车型列表并排序
dict_search_sum_model = search_sum_model(data_search)
print("搜索量按车型列表并排序:{}".format(sorted(dict_search_sum_model.items(), key=lambda x: x[1], reverse=True)))
'''
# #评论量求和按车型列表并排序
dict_comment_sum_model = comment_sum_model(data_user)
print("评论量按车型列表并排序:{}".format(sorted(dict_comment_sum_model.items(), key=lambda x: x[1], reverse=True)))
# #某个车型的评论量与回复量对比折线图
max_comment_model = max(dict_comment_sum_model, key=dict_comment_sum_model.get) # 获取评论量最高的车型
com_rep_sum_season(data_user, max_comment_model) # 对最高评论量车型绘制评论和回复量季度走势
# 数据清洗部分
# 统计重复记录数
'''
print('数据重复记录行数:')
print("\t销售数据:{:d}".format(data_sales.duplicated().sum()))
print("\t搜索数据:{:d}".format(data_search.duplicated().sum()))
print("\t评论数据:{:d}".format(data_user.duplicated().sum()))
print("\t测试数据:{:d}".format(data_test.duplicated().sum()))
# 删除重复记录行
print('正在删除重复记录数据……')
data_sales = data_sales.drop_duplicates()
data_search = data_search.drop_duplicates()
data_user = data_user.drop_duplicates()
print("删除结束!")
# 删除4个以上缺失值的整行以及空行
print('删除空行以及缺失值有4个及以上的行……')
data_sales.dropna(axis=0, how='all')
data_search.dropna(axis=0, how='all')
data_user.dropna(axis=0, how='all')
data_sales = data_sales.dropna(thresh=4) # 删除4个以上缺失值的行
data_search = data_search.dropna(thresh=4)
data_user = data_user.dropna(thresh=4)
print('删除结束')
print('新数据行列数:')
print("\t销售数据:{}".format(data_sales.shape))
print("\t搜索数据:{}".format(data_search.shape))
print("\t评论数据:{}".format(data_user.shape))
'''
# 根据已有数据补充部分缺失值以及异常值
# 提取出需要统计的行
'''cat_col = ['regYear', 'province']
d = data_test[cat_col]
c = d['上海']
print(c)
ave_regYear = data_test[data_test['province'].isin('上海')].mean() # 获取该列的均值
print(ave_regYear)
data_test = data_test.fillna(ave_regYear) # 用该均值去填充缺失值
print(data_test)'''
# 随机抽样10%数据
# n抽取的行数,frac抽取的比列,replace=True时为有放回抽样,axis=0的时是抽取行,axis=1时是抽取列
sample_sales = data_sales.sample(frac=0.1, replace=True, axis=0)
sample_search = data_search.sample(frac=0.1, replace=True, axis=0) # frac=0.1
sample_user = data_user.sample(frac=0.1, replace=True, axis=0)
'''
# 求解正态分布、方差、均值、极大极小值
print('样本方差:')
print("\t销售量:{:.2f}".format(sample_sales['salesVolume'].var()))
print("\t搜索量:{:.2f}".format(sample_search['popularity'].var()))
print("\t评论量:{:.2f}".format(sample_user['carCommentVolum'].var()))
print("\t回复量:{:.2f}".format(sample_user['newsReplyVolum'].var()))
print('样本均值:')
print("\t销售量:{:.2f}".format(sample_sales['salesVolume'].mean()))
print("\t搜索量:{:.2f}".format(sample_search['popularity'].mean()))
print("\t评论量:{:.2f}".format(sample_user['carCommentVolum'].mean()))
print("\t回复量:{:.2f}".format(sample_user['newsReplyVolum'].mean()))
print('样本极值:')
print("\t销售量极大值:{0}, 极小值:{1}".format(data_sales['salesVolume'].max(), data_sales['salesVolume'].min()))
print("\t搜索量极大值:{0}, 极小值:{1}".format(data_search['popularity'].max(), data_search['popularity'].min()))
print("\t评论量极大值:{0}, 极小值:{1}".format(data_user['carCommentVolum'].max(), data_user['carCommentVolum'].min()))
print("\t回复量极大值:{0}, 极小值:{1}".format(data_user['newsReplyVolum'].max(), data_user['newsReplyVolum'].min()))'''
# #画正态分布图
'''graph_f_plot(data_sales['salesVolume'], -1000, 3000, 0.1, '销售量', '销售量正态分布图', '../result/data_sales_f.png')
graph_f_plot(data_search['popularity'], -5000, 20000, 1, '搜索量', '搜索量正态分布图', '../result/data_search_f.png')'''
'''
# 数据相关性,另确定一定的事故发生率导致的评论数上升,即(1 - 评论与销量相关性)/2
# #验证搜索量与销量的相关性,必须为同一车型,这里取车型31,抽取500个数据
data_sea_sales = pd.DataFrame({'搜索量': model1_search_list(data_search), '销售量': model1_sales_list(data_sales)})
sample_sea_sales = data_sea_sales.sample(n=500, replace=False, axis=0)
search_a1 = sample_sea_sales['搜索量']
sales_a1 = sample_sea_sales['销售量']
sea_rel_sales_rate = pier(sales_a1, search_a1)
print("搜索量与销售量的相关性:{}".format(sea_rel_sales_rate))
# #验证评论与回复量的相关性
data_com_rep = pd.DataFrame({'评论量': model1_com_list(data_user), '回复量': model1_rep_list(data_user)})
sample_com_rep = data_com_rep.sample(n=20, replace=False, axis=0)
com_c1 = sample_com_rep['评论量']
rep_c1 = sample_com_rep['回复量']
com_rel_rep_rate = pier(com_c1, rep_c1)
print("评论量与回复量的相关性:{}".format(com_rel_rep_rate))
accidence_rel_rate = (1 - sea_rel_sales_rate[0]) / 2
print("事故导致搜索量增加率:{:.4f}".format(accidence_rel_rate))
'''
| [
"matplotlib.pyplot.title",
"math.isnan",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.axis",
"scipy.stats.pearsonr",
"pandas.read_excel",
"numpy.arange",
"numpy.exp",
"matplotlib.pyplot.y... | [((11418, 11463), 'pandas.read_excel', 'pd.read_excel', (['"""../data/train_sales_data.xls"""'], {}), "('../data/train_sales_data.xls')\n", (11431, 11463), True, 'import pandas as pd\n'), ((11490, 11536), 'pandas.read_excel', 'pd.read_excel', (['"""../data/train_search_data.xls"""'], {}), "('../data/train_search_data.xls')\n", (11503, 11536), True, 'import pandas as pd\n'), ((11550, 11600), 'pandas.read_excel', 'pd.read_excel', (['"""../data/train_user_reply_data.xls"""'], {}), "('../data/train_user_reply_data.xls')\n", (11563, 11600), True, 'import pandas as pd\n'), ((11614, 11647), 'pandas.read_excel', 'pd.read_excel', (['"""../data/test.xls"""'], {}), "('../data/test.xls')\n", (11627, 11647), True, 'import pandas as pd\n'), ((9514, 9527), 'matplotlib.pyplot.bar', 'plt.bar', (['x', 'y'], {}), '(x, y)\n', (9521, 9527), True, 'from matplotlib import pyplot as plt\n'), ((9533, 9550), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (9541, 9550), True, 'from matplotlib import pyplot as plt\n'), ((9556, 9574), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_name'], {}), '(x_name)\n', (9566, 9574), True, 'from matplotlib import pyplot as plt\n'), ((9580, 9598), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_name'], {}), '(y_name)\n', (9590, 9598), True, 'from matplotlib import pyplot as plt\n'), ((9635, 9651), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (9644, 9651), True, 'from matplotlib import pyplot as plt\n'), ((9691, 9708), 'matplotlib.pyplot.savefig', 'plt.savefig', (['addr'], {}), '(addr)\n', (9702, 9708), True, 'from matplotlib import pyplot as plt\n'), ((9714, 9724), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9722, 9724), True, 'from matplotlib import pyplot as plt\n'), ((9795, 9839), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'marker': '"""."""', 'mec': '"""r"""', 'mfc': '"""w"""'}), "(x, y, marker='.', mec='r', mfc='w')\n", (9803, 9839), True, 'from matplotlib import pyplot as plt\n'), ((9845, 9862), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (9853, 9862), True, 'from matplotlib import pyplot as plt\n'), ((9868, 9886), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_name'], {}), '(x_name)\n', (9878, 9886), True, 'from matplotlib import pyplot as plt\n'), ((9892, 9910), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_name'], {}), '(y_name)\n', (9902, 9910), True, 'from matplotlib import pyplot as plt\n'), ((9916, 9932), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (9925, 9932), True, 'from matplotlib import pyplot as plt\n'), ((9938, 9955), 'matplotlib.pyplot.savefig', 'plt.savefig', (['addr'], {}), '(addr)\n', (9949, 9955), True, 'from matplotlib import pyplot as plt\n'), ((9961, 9971), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9969, 9971), True, 'from matplotlib import pyplot as plt\n'), ((10071, 10130), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'y1'], {'marker': '"""."""', 'mec': '"""r"""', 'mfc': '"""w"""', 'label': 'name1'}), "(x1, y1, marker='.', mec='r', mfc='w', label=name1)\n", (10079, 10130), True, 'from matplotlib import pyplot as plt\n'), ((10136, 10184), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y2'], {'marker': '"""+"""', 'ms': '(10)', 'label': 'name2'}), "(x2, y2, marker='+', ms=10, label=name2)\n", (10144, 10184), True, 'from matplotlib import pyplot as plt\n'), ((10190, 10202), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (10200, 10202), True, 'from matplotlib import pyplot as plt\n'), ((10208, 10225), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (10216, 10225), True, 'from matplotlib import pyplot as plt\n'), ((10231, 10249), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_name'], {}), '(x_name)\n', (10241, 10249), True, 'from matplotlib import pyplot as plt\n'), ((10255, 10273), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_name'], {}), '(y_name)\n', (10265, 10273), True, 'from matplotlib import pyplot as plt\n'), ((10279, 10295), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (10288, 10295), True, 'from matplotlib import pyplot as plt\n'), ((10301, 10318), 'matplotlib.pyplot.savefig', 'plt.savefig', (['addr'], {}), '(addr)\n', (10312, 10318), True, 'from matplotlib import pyplot as plt\n'), ((10324, 10334), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10332, 10334), True, 'from matplotlib import pyplot as plt\n'), ((10640, 10656), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (10649, 10656), True, 'from matplotlib import pyplot as plt\n'), ((10662, 10679), 'matplotlib.pyplot.savefig', 'plt.savefig', (['addr'], {}), '(addr)\n', (10673, 10679), True, 'from matplotlib import pyplot as plt\n'), ((10685, 10695), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10693, 10695), True, 'from matplotlib import pyplot as plt\n'), ((10975, 11001), 'numpy.arange', 'np.arange', (['x_l', 'x_r', 'x_len'], {}), '(x_l, x_r, x_len)\n', (10984, 11001), True, 'import numpy as np\n'), ((11065, 11079), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (11073, 11079), True, 'from matplotlib import pyplot as plt\n'), ((11124, 11171), 'matplotlib.pyplot.hist', 'plt.hist', (['df'], {'bins': '(100)', 'rwidth': '(0.5)', 'normed': '(True)'}), '(df, bins=100, rwidth=0.5, normed=True)\n', (11132, 11171), True, 'from matplotlib import pyplot as plt\n'), ((11177, 11194), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (11185, 11194), True, 'from matplotlib import pyplot as plt\n'), ((11200, 11216), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (11209, 11216), True, 'from matplotlib import pyplot as plt\n'), ((11222, 11240), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_name'], {}), '(x_name)\n', (11232, 11240), True, 'from matplotlib import pyplot as plt\n'), ((11246, 11271), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Probability"""'], {}), "('Probability')\n", (11256, 11271), True, 'from matplotlib import pyplot as plt\n'), ((11277, 11294), 'matplotlib.pyplot.savefig', 'plt.savefig', (['addr'], {}), '(addr)\n', (11288, 11294), True, 'from matplotlib import pyplot as plt\n'), ((11300, 11310), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11308, 11310), True, 'from matplotlib import pyplot as plt\n'), ((11354, 11374), 'scipy.stats.pearsonr', 'stats.pearsonr', (['a', 'b'], {}), '(a, b)\n', (11368, 11374), False, 'from scipy import stats\n'), ((10748, 10789), 'numpy.exp', 'np.exp', (['(-(x - mu) ** 2 / (2 * sigma ** 2))'], {}), '(-(x - mu) ** 2 / (2 * sigma ** 2))\n', (10754, 10789), True, 'import numpy as np\n'), ((10799, 10817), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (10806, 10817), True, 'import numpy as np\n'), ((1443, 1458), 'math.isnan', 'math.isnan', (['num'], {}), '(num)\n', (1453, 1458), False, 'import math\n'), ((2671, 2694), 'math.isnan', 'math.isnan', (['row_date[5]'], {}), '(row_date[5])\n', (2681, 2694), False, 'import math\n'), ((2699, 2722), 'math.isnan', 'math.isnan', (['row_date[4]'], {}), '(row_date[4])\n', (2709, 2722), False, 'import math\n'), ((5916, 5939), 'math.isnan', 'math.isnan', (['row_date[1]'], {}), '(row_date[1])\n', (5926, 5939), False, 'import math\n'), ((5944, 5967), 'math.isnan', 'math.isnan', (['row_date[2]'], {}), '(row_date[2])\n', (5954, 5967), False, 'import math\n')] |
#!/usr/bin/env python
import os
import argparse
import collections
import json
import numpy as np
import pandas as pd
import h5py
# import sklearn.metrics
import Cell_BLAST as cb
import utils
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--ref", dest="ref", type=str, nargs="+")
parser.add_argument("-t", "--true", dest="true", type=str, nargs="+")
parser.add_argument("-p", "--pred", dest="pred", type=str, nargs="+")
parser.add_argument("-o", "--output", dest="output", type=str, required=True)
parser.add_argument("-c", "--cell-type-specific", dest="cell_type_specific", type=str, required=True)
parser.add_argument("-l", "--label", dest="label", type=str, required=True)
parser.add_argument("-e", "--expect", dest="expect", type=str, required=True)
cmd_args = parser.parse_args()
cmd_args.output = [cmd_args.output, cmd_args.cell_type_specific]
cmd_args.input = argparse.Namespace(
ref=cmd_args.ref,
true=cmd_args.true,
pred=cmd_args.pred
)
cmd_args.config = {"label": cmd_args.label}
cmd_args.params = argparse.Namespace(expect=cmd_args.expect)
del cmd_args.ref, cmd_args.true, cmd_args.pred, cmd_args.label, \
cmd_args.expect, cmd_args.cell_type_specific
return cmd_args
def main():
ref = np.concatenate([cb.data.read_hybrid_path("{file}//obs/{label}".format(
file=item, label=snakemake.config["label"]
)) for item in snakemake.input.ref])
ref = ref[~utils.na_mask(ref)]
pos_types = np.unique(ref)
expect = pd.read_csv(snakemake.params.expect, index_col=0)
# # Pos/neg weighed
# true = np.concatenate([cb.data.read_hybrid_path("{file}//obs/{label}".format(
# file=item, label=snakemake.config["label"]
# )) for item in snakemake.input.true])
# true = true[~utils.na_mask(true)]
# tp = np.in1d(true, pos_types)
# tn = ~tp
# weight = np.ones(true.size)
# weight[tp] = 1 / tp.sum()
# weight[tn] = 1 / tn.sum()
# weight /= weight.sum() / weight.size
# Dataset weighed
true = [cb.data.read_hybrid_path("{file}//obs/{label}".format(
file=item, label=snakemake.config["label"]
)) for item in snakemake.input.true]
true = [item[~utils.na_mask(item)] for item in true]
weight = np.concatenate([np.repeat(1 / item.size, item.size) for item in true])
weight /= weight.sum() / weight.size
true = np.concatenate(true)
tp = np.in1d(true, pos_types)
tn = ~tp
pred_dict = collections.defaultdict(list)
for item in snakemake.input.pred:
with h5py.File(item, "r") as f:
g = f["prediction"]
for threshold in g:
pred_dict[float(threshold)].append(
cb.data.read_clean(g[threshold][...]))
cell_type_specific_excel = pd.ExcelWriter(snakemake.output[1])
performance = []
for threshold in sorted(pred_dict.keys(), key=float):
pred = pred_dict[threshold] = np.concatenate(pred_dict[threshold])
assert len(pred) == len(true)
pn = np.vectorize(
lambda x: x in ("unassigned", "ambiguous", "rejected")
)(pred)
pp = ~pn
sensitivity = (weight * np.logical_and(tp, pp)).sum() / (weight * tp).sum()
specificity = (weight * np.logical_and(tn, pn)).sum() / (weight * tn).sum()
class_specific_accuracy = cb.metrics.class_specific_accuracy(true, pred, expect)
class_specific_accuracy.insert(0, "positive", np.in1d(class_specific_accuracy.index, pos_types))
pos_mba = class_specific_accuracy.loc[class_specific_accuracy["positive"], "accuracy"].mean()
neg_mba = class_specific_accuracy.loc[~class_specific_accuracy["positive"], "accuracy"].mean()
mba = (pos_mba + neg_mba) / 2
performance.append(dict(
ref_size=ref.size,
threshold=threshold,
sensitivity=sensitivity,
specificity=specificity,
pos_mba=pos_mba,
neg_mba=neg_mba,
mba=mba
))
class_specific_accuracy.to_excel(
cell_type_specific_excel, str(threshold),
index_label=snakemake.config["label"]
)
cell_type_specific_excel.save()
with open(snakemake.output[0], "w") as f:
json.dump(performance, f, indent=4)
if __name__ == "__main__":
if "snakemake" not in globals():
snakemake = parse_args()
main()
| [
"argparse.Namespace",
"json.dump",
"h5py.File",
"numpy.vectorize",
"argparse.ArgumentParser",
"numpy.logical_and",
"pandas.read_csv",
"utils.na_mask",
"numpy.unique",
"collections.defaultdict",
"Cell_BLAST.metrics.class_specific_accuracy",
"numpy.repeat",
"Cell_BLAST.data.read_clean",
"pan... | [((226, 251), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (249, 251), False, 'import argparse\n'), ((947, 1023), 'argparse.Namespace', 'argparse.Namespace', ([], {'ref': 'cmd_args.ref', 'true': 'cmd_args.true', 'pred': 'cmd_args.pred'}), '(ref=cmd_args.ref, true=cmd_args.true, pred=cmd_args.pred)\n', (965, 1023), False, 'import argparse\n'), ((1124, 1166), 'argparse.Namespace', 'argparse.Namespace', ([], {'expect': 'cmd_args.expect'}), '(expect=cmd_args.expect)\n', (1142, 1166), False, 'import argparse\n'), ((1548, 1562), 'numpy.unique', 'np.unique', (['ref'], {}), '(ref)\n', (1557, 1562), True, 'import numpy as np\n'), ((1577, 1626), 'pandas.read_csv', 'pd.read_csv', (['snakemake.params.expect'], {'index_col': '(0)'}), '(snakemake.params.expect, index_col=0)\n', (1588, 1626), True, 'import pandas as pd\n'), ((2440, 2460), 'numpy.concatenate', 'np.concatenate', (['true'], {}), '(true)\n', (2454, 2460), True, 'import numpy as np\n'), ((2470, 2494), 'numpy.in1d', 'np.in1d', (['true', 'pos_types'], {}), '(true, pos_types)\n', (2477, 2494), True, 'import numpy as np\n'), ((2525, 2554), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (2548, 2554), False, 'import collections\n'), ((2840, 2875), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['snakemake.output[1]'], {}), '(snakemake.output[1])\n', (2854, 2875), True, 'import pandas as pd\n'), ((2993, 3029), 'numpy.concatenate', 'np.concatenate', (['pred_dict[threshold]'], {}), '(pred_dict[threshold])\n', (3007, 3029), True, 'import numpy as np\n'), ((3397, 3451), 'Cell_BLAST.metrics.class_specific_accuracy', 'cb.metrics.class_specific_accuracy', (['true', 'pred', 'expect'], {}), '(true, pred, expect)\n', (3431, 3451), True, 'import Cell_BLAST as cb\n'), ((4311, 4346), 'json.dump', 'json.dump', (['performance', 'f'], {'indent': '(4)'}), '(performance, f, indent=4)\n', (4320, 4346), False, 'import json\n'), ((1512, 1530), 'utils.na_mask', 'utils.na_mask', (['ref'], {}), '(ref)\n', (1525, 1530), False, 'import utils\n'), ((2333, 2368), 'numpy.repeat', 'np.repeat', (['(1 / item.size)', 'item.size'], {}), '(1 / item.size, item.size)\n', (2342, 2368), True, 'import numpy as np\n'), ((2606, 2626), 'h5py.File', 'h5py.File', (['item', '"""r"""'], {}), "(item, 'r')\n", (2615, 2626), False, 'import h5py\n'), ((3081, 3149), 'numpy.vectorize', 'np.vectorize', (["(lambda x: x in ('unassigned', 'ambiguous', 'rejected'))"], {}), "(lambda x: x in ('unassigned', 'ambiguous', 'rejected'))\n", (3093, 3149), True, 'import numpy as np\n'), ((3506, 3555), 'numpy.in1d', 'np.in1d', (['class_specific_accuracy.index', 'pos_types'], {}), '(class_specific_accuracy.index, pos_types)\n', (3513, 3555), True, 'import numpy as np\n'), ((2265, 2284), 'utils.na_mask', 'utils.na_mask', (['item'], {}), '(item)\n', (2278, 2284), False, 'import utils\n'), ((2769, 2806), 'Cell_BLAST.data.read_clean', 'cb.data.read_clean', (['g[threshold][...]'], {}), '(g[threshold][...])\n', (2787, 2806), True, 'import Cell_BLAST as cb\n'), ((3227, 3249), 'numpy.logical_and', 'np.logical_and', (['tp', 'pp'], {}), '(tp, pp)\n', (3241, 3249), True, 'import numpy as np\n'), ((3311, 3333), 'numpy.logical_and', 'np.logical_and', (['tn', 'pn'], {}), '(tn, pn)\n', (3325, 3333), True, 'import numpy as np\n')] |
import os
import argparse
import numpy as np
import cv2
from PIL import Image
import caffe
def get_files_in_dir(path):
folder = os.fsencode(path)
filenames = []
for file in os.listdir(folder):
filename = os.fsdecode(file)
if filename.endswith(('jpg', '.jpeg', '.png', '.gif')):
filenames.append('{bg}/{f}'.format(bg=path, f=filename))
return filenames
def get_segment_model():
caffe.set_device(0)
caffe.set_mode_gpu()
path1 = 'face_seg_fcn8s/face_seg_fcn8s_deploy.prototxt'
path2 = 'face_seg_fcn8s/face_seg_fcn8s.caffemodel'
return caffe.Net(path1, path2, caffe.TEST)
def get_face(segment_model, file, convex_fill=False):
image, bool_mask = _get_mask(segment_model, file, convex_fill=convex_fill)
return _apply_mask(image, bool_mask)
def _apply_mask(image, bool_mask):
return np.array(np.multiply(image, bool_mask), dtype=np.uint8)
def _get_mask(segment_model, file_path, convex_fill=False):
im = Image.open(file_path)
width, height = im.size
im = im.resize((500, 500))
in_ = np.array(im, dtype=np.float32)
in_ = in_[:, :, ::-1]
# subtract mean
in_ -= np.array((104.00698793, 116.66876762, 122.67891434))
in_ = in_.transpose((2, 0, 1))
# shape for input (data blob is N x C x H x W), set data
segment_model.blobs['data'].reshape(1, *in_.shape)
segment_model.blobs['data'].data[...] = in_
# run net and take argmax for prediction
segment_model.forward()
mask = segment_model.blobs['score'].data[0].argmax(axis=0)
mask = (mask - np.min(mask))/np.ptp(mask)
mask = (mask*255).astype(np.uint8)
if convex_fill:
mask = __apply_convex_fill(mask)
mask = cv2.cvtColor(cv2.resize(mask, (width, height)), cv2.COLOR_GRAY2BGR)
bool_mask = (mask != 0)
return cv2.imread(file_path), bool_mask
def __apply_convex_fill(image, kernel_size=8):
border_size = kernel_size * 2
image_ = cv2.copyMakeBorder(image, top=border_size, bottom=border_size, left=border_size, right=border_size,
borderType=cv2.BORDER_CONSTANT, value=(0, 0, 0))
kernel = np.ones((kernel_size, kernel_size))
image_ = cv2.dilate(image_, kernel, iterations=1)
image_ = __column_fill(image_)
image_ = __row_fill(image_)
image_ = cv2.erode(image_, kernel, iterations=1)
width_n, height_n = image_.shape[:2]
return image_[border_size:height_n - border_size, border_size:width_n - border_size]
def __column_fill(mask):
width, height = mask.shape[:2]
for i in range(width):
non_zero = np.nonzero(mask[:, i])[0]
if len(non_zero) == 0:
continue
ind_min = min(non_zero)
ind_max = max(non_zero)
mask[ind_min:ind_max, i] = 255
return mask
def __row_fill(mask):
width, height = mask.shape[:2]
for i in range(height):
non_zero = np.nonzero(mask[i, :])[0]
if len(non_zero) == 0:
continue
ind_min = min(non_zero)
ind_max = max(non_zero)
mask[i, ind_min:ind_max] = 255
return mask
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", default=None, type=str, help="Single file to segment")
parser.add_argument("-d", "--dir", default=None, type=str, help="Directory of files to segment")
parser.add_argument("-o", "--output", default=None, type=str, required=True,
help="Where to output/save the segments to")
parser.add_argument("-c", "--convex_fill", default=False, action='store_true', help="Whether to fill masks")
args = parser.parse_args()
if args.file is None and args.dir is None:
raise ValueError("At least one of `file` or `dir` must be given.")
if not os.path.exists(args.output):
os.makedirs(args.output)
segment_model = get_segment_model()
i = 0
if args.file:
img = get_face(segment_model, args.file, convex_fill=args.convex_fill)
cv2.imwrite('{output}/{ind}.png'.format(output=args.output, ind=i), img)
i += 1
if args.dir:
img_paths = get_files_in_dir(args.dir)
for img_path in img_paths:
img = get_face(segment_model, img_path, convex_fill=args.convex_fill)
cv2.imwrite('{output}/{ind}.jpg'.format(output=args.output, ind=i), img)
i += 1
if __name__ == "__main__":
main()
| [
"argparse.ArgumentParser",
"numpy.ones",
"cv2.erode",
"numpy.multiply",
"cv2.dilate",
"os.fsdecode",
"cv2.copyMakeBorder",
"os.path.exists",
"caffe.set_device",
"cv2.resize",
"caffe.set_mode_gpu",
"numpy.min",
"os.fsencode",
"caffe.Net",
"os.listdir",
"os.makedirs",
"numpy.ptp",
"P... | [((136, 153), 'os.fsencode', 'os.fsencode', (['path'], {}), '(path)\n', (147, 153), False, 'import os\n'), ((189, 207), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (199, 207), False, 'import os\n'), ((431, 450), 'caffe.set_device', 'caffe.set_device', (['(0)'], {}), '(0)\n', (447, 450), False, 'import caffe\n'), ((455, 475), 'caffe.set_mode_gpu', 'caffe.set_mode_gpu', ([], {}), '()\n', (473, 475), False, 'import caffe\n'), ((602, 637), 'caffe.Net', 'caffe.Net', (['path1', 'path2', 'caffe.TEST'], {}), '(path1, path2, caffe.TEST)\n', (611, 637), False, 'import caffe\n'), ((989, 1010), 'PIL.Image.open', 'Image.open', (['file_path'], {}), '(file_path)\n', (999, 1010), False, 'from PIL import Image\n'), ((1080, 1110), 'numpy.array', 'np.array', (['im'], {'dtype': 'np.float32'}), '(im, dtype=np.float32)\n', (1088, 1110), True, 'import numpy as np\n'), ((1169, 1221), 'numpy.array', 'np.array', (['(104.00698793, 116.66876762, 122.67891434)'], {}), '((104.00698793, 116.66876762, 122.67891434))\n', (1177, 1221), True, 'import numpy as np\n'), ((1955, 2113), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['image'], {'top': 'border_size', 'bottom': 'border_size', 'left': 'border_size', 'right': 'border_size', 'borderType': 'cv2.BORDER_CONSTANT', 'value': '(0, 0, 0)'}), '(image, top=border_size, bottom=border_size, left=\n border_size, right=border_size, borderType=cv2.BORDER_CONSTANT, value=(\n 0, 0, 0))\n', (1973, 2113), False, 'import cv2\n'), ((2149, 2184), 'numpy.ones', 'np.ones', (['(kernel_size, kernel_size)'], {}), '((kernel_size, kernel_size))\n', (2156, 2184), True, 'import numpy as np\n'), ((2198, 2238), 'cv2.dilate', 'cv2.dilate', (['image_', 'kernel'], {'iterations': '(1)'}), '(image_, kernel, iterations=1)\n', (2208, 2238), False, 'import cv2\n'), ((2319, 2358), 'cv2.erode', 'cv2.erode', (['image_', 'kernel'], {'iterations': '(1)'}), '(image_, kernel, iterations=1)\n', (2328, 2358), False, 'import cv2\n'), ((3124, 3149), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3147, 3149), False, 'import argparse\n'), ((228, 245), 'os.fsdecode', 'os.fsdecode', (['file'], {}), '(file)\n', (239, 245), False, 'import os\n'), ((871, 900), 'numpy.multiply', 'np.multiply', (['image', 'bool_mask'], {}), '(image, bool_mask)\n', (882, 900), True, 'import numpy as np\n'), ((1592, 1604), 'numpy.ptp', 'np.ptp', (['mask'], {}), '(mask)\n', (1598, 1604), True, 'import numpy as np\n'), ((1731, 1764), 'cv2.resize', 'cv2.resize', (['mask', '(width, height)'], {}), '(mask, (width, height))\n', (1741, 1764), False, 'import cv2\n'), ((1826, 1847), 'cv2.imread', 'cv2.imread', (['file_path'], {}), '(file_path)\n', (1836, 1847), False, 'import cv2\n'), ((3774, 3801), 'os.path.exists', 'os.path.exists', (['args.output'], {}), '(args.output)\n', (3788, 3801), False, 'import os\n'), ((3811, 3835), 'os.makedirs', 'os.makedirs', (['args.output'], {}), '(args.output)\n', (3822, 3835), False, 'import os\n'), ((1578, 1590), 'numpy.min', 'np.min', (['mask'], {}), '(mask)\n', (1584, 1590), True, 'import numpy as np\n'), ((2597, 2619), 'numpy.nonzero', 'np.nonzero', (['mask[:, i]'], {}), '(mask[:, i])\n', (2607, 2619), True, 'import numpy as np\n'), ((2900, 2922), 'numpy.nonzero', 'np.nonzero', (['mask[i, :]'], {}), '(mask[i, :])\n', (2910, 2922), True, 'import numpy as np\n')] |
# ----------------------------------------------------
# Name : smoothline.py
# Author : E.Taskesen
# Contact : <EMAIL>
# Licence : MIT
# ----------------------------------------------------
import numpy as np
from scipy.interpolate import make_interp_spline
def smoothline(xs, ys=None, interpol=3, window=1, verbose=3):
"""Smoothing 1D vector.
Description
-----------
Smoothing a 1d vector can be challanging if the number of data is low sampled.
This smoothing function therefore contains two steps. First interpolation of the
input line followed by a convolution.
Parameters
----------
xs : array-like
Data points for the x-axis.
ys : array-like
Data points for the y-axis.
interpol : int, (default : 3)
The interpolation factor. The data is interpolation by a factor n before the smoothing step.
window : int, (default : 1)
Smoothing window that is used to create the convolution and gradually smoothen the line.
verbose : int [1-5], default: 3
Print information to screen. A higher number will print more.
Returns
-------
xnew : array-like
Data points for the x-axis.
ynew : array-like
Data points for the y-axis.
"""
if window is not None:
if verbose>=3: print('[smoothline] >Smoothing by interpolation..')
# Specify number of points to interpolate the data
# Interpolate
extpoints = np.linspace(0, len(xs), len(xs) * interpol)
spl = make_interp_spline(range(0, len(xs)), xs, k=3)
# Compute x-labels
xnew = spl(extpoints)
xnew[window:-window]
# First smoothing on the raw input data
ynew=None
if ys is not None:
ys = _smooth(ys,window)
# Interpolate ys line
spl = make_interp_spline(range(0, len(ys)), ys, k=3)
ynew = spl(extpoints)
ynew[window:-window]
else:
xnew, ynew = xs, ys
return xnew, ynew
def _smooth(X, window):
box = np.ones(window) / window
X_smooth = np.convolve(X, box, mode='same')
return X_smooth
| [
"numpy.convolve",
"numpy.ones"
] | [((2108, 2140), 'numpy.convolve', 'np.convolve', (['X', 'box'], {'mode': '"""same"""'}), "(X, box, mode='same')\n", (2119, 2140), True, 'import numpy as np\n'), ((2068, 2083), 'numpy.ones', 'np.ones', (['window'], {}), '(window)\n', (2075, 2083), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pickle
import os, sys
import math
BOARD_ROWS = 3
BOARD_COLS = 3
class State:
def __init__(self, p1, p2):
self.board = np.zeros(( BOARD_ROWS, BOARD_COLS ))
self.p1 = p1
self.p2 = p2
self.isEnd = False
self.boardHash = None
# init p1 plays first, 1 for p1, -1 for p2, fill playerSymbol in board
self.playerSymbol = 1
# board reset
def reset(self):
self.board = np.zeros((BOARD_ROWS, BOARD_COLS))
self.boardHash = None
self.isEnd = False
self.playerSymbol = 1
def getHash(self):
self.boardHash = str(self.board.reshape( BOARD_ROWS*BOARD_COLS ))
return self.boardHash
def winner(self):
# row
for i in range(BOARD_ROWS):
s = sum(self.board[i, :])
if s == 3:
self.isEnd = True
return 1
if s == -3:
self.isEnd = True
return -1
# col
for i in range(BOARD_COLS):
s = sum(self.board[:, i])
if s == 3:
self.isEnd = True
return 1
if s == -3:
self.isEnd = True
return -1
# diagonal
diag_sum1 = sum([self.board[i, i] for i in range(BOARD_COLS)])
diag_sum2 = sum([self.board[i, BOARD_COLS-1-i] for i in range(BOARD_COLS)])
diag_sum = max(abs(diag_sum1), abs(diag_sum2))
if diag_sum == 3:
self.isEnd = True
if diag_sum1 == 3 or diag_sum2 == 3:
return 1
else:
return -1
# tie
# no available position
if len(self.availablePositions()) == 0:
self.isEnd = True
return 0
# not end
self.isEnd = False
return None
def availablePositions(self):
return availablePositionsFuck(self.board)
# positions = []
# for i in range(self.board.shape[0]):
# for j in range(self.board.shape[1]):
# if self.board[i, j] == 0:
# positions.append((i, j))
# return positions
def updateState(self, position):
self.board[position] = self.playerSymbol
# switch to another player
self.playerSymbol = -1 if self.playerSymbol == 1 else 1
# only when game ends
def giveReward(self):
result = self.winner()
# backpropagate reward
if result == 1:
self.p1.feedReward(1)
self.p2.feedReward(0)
elif result == -1:
self.p1.feedReward(0)
self.p2.feedReward(1)
else:
self.p1.feedReward(0.1)
self.p2.feedReward(0.5)
def play(self, rounds=100):
for i in range(rounds):
if i % 1000 == 0:
print("Rounds {}".format(i))
while not self.isEnd:
# Player 1
positions = self.availablePositions()
p1_action = self.p1.chooseAction(positions, self.board, self.playerSymbol)
# take action and update board state
self.updateState(p1_action)
# board_hash = self.getHash()
self.p1.addState(self.board.copy())
# check board status if it is end
win = self.winner()
if win is not None:
# self.showBoard()
# ended with p1 either win or draw
self.giveReward()
self.p1.reset()
self.p2.reset()
self.reset()
break
else:
# Player 2
positions = self.availablePositions()
p2_action = self.p2.chooseAction(positions, self.board, self.playerSymbol)
self.updateState(p2_action)
# board_hash = self.getHash()
self.p2.addState(self.board.copy())
win = self.winner()
if win is not None:
# self.showBoard()
# ended with p2 either win or draw
self.giveReward()
self.p1.reset()
self.p2.reset()
self.reset()
break
self.p1.savePolicy()
self.p2.savePolicy()
# play with human
def play2(self):
while not self.isEnd:
# Player 1
positions = self.availablePositions()
p1_action = self.p1.chooseAction(positions, self.board, self.playerSymbol)
# take action and update board state
self.updateState(p1_action)
self.showBoard()
# check board status if it is end
win = self.winner()
if win is not None:
if win == 1:
print(self.p1.name, "wins!")
else:
print("tie!")
self.reset()
break
else:
# Player 2
positions = self.availablePositions()
p2_action = self.p2.chooseAction(positions, self.board, self.playerSymbol)
self.updateState(p2_action)
self.showBoard()
win = self.winner()
if win is not None:
if win == -1:
print(self.p2.name, "wins!")
else:
print("tie!")
self.reset()
break
def showBoard(self):
# p1: x p2: o
for i in range(0, BOARD_ROWS):
print('-------------')
out = '| '
for j in range(0, BOARD_COLS):
if self.board[i, j] == 1:
token = 'x'
if self.board[i, j] == -1:
token = 'o'
if self.board[i, j] == 0:
token = ' '
out += token + ' | '
print(out)
print('-------------')
class Player:
def __init__(self, name, exp_rate=0.3):
self.name = name
self.exp_rate = exp_rate # possibility that take random action
self.states = [] # record all positions taken
self.learningRate = 0.2
self.decay_gamma = 0.9
self.states_value = {} # state -> value
def getHash(self, board):
boardHash = str(board.reshape(BOARD_COLS*BOARD_ROWS))
return boardHash
def chooseAction(self, positions, current_board, symbol):
action = None
if np.random.uniform(0, 1) <= self.exp_rate:
# take random action
idx = np.random.choice(len(positions))
action = positions[idx]
else:
value_max = -999
for p in positions:
next_board = current_board.copy()
next_board[p] = symbol
next_boardHash = self.getHash(next_board)
value = self.states_value.get(next_boardHash)
value = 0 if value is None else value
# print("value:", value)
if value >= value_max:
value_max = value
action = p
# print("{} takes action {}".format(self.name, action))
return action
# append a hash state
def addState(self, state):
self.states.append(state)
def genAllSimilarStatesHash(self, state):
st = state
arr = [self.getHash(np.rot90(st, i)) for i in range(4)] # 正面 4 个角度
arr.extend([self.getHash(np.fliplr(np.rot90(st, i))) for i in range(4)]) # 背面 4 个角度
return set(arr)
# at the end of game, backpropagate and update states value
def feedReward(self, reward):
for st in reversed(self.states):
hsh = self.getHash(st)
if self.states_value.get(hsh) is None:
self.states_value[hsh] = 0
self.states_value[hsh] += self.learningRate * (self.decay_gamma * reward - self.states_value[hsh])
reward = self.states_value[hsh]
# 同一形状的棋盘,奖励也一样
for hsh in self.genAllSimilarStatesHash(st):
self.states_value[hsh] = reward
def reset(self):
self.states = []
def savePolicy(self):
fw = open('policy_' + str(self.name), 'wb')
pickle.dump(self.states_value, fw)
fw.close()
def loadPolicy(self, file=None):
file = file or 'policy_' + str(self.name)
if not os.path.exists(file):
return
fr = open(file, 'rb')
self.states_value = pickle.load(fr)
fr.close()
class HumanPlayer:
def __init__(self, name):
self.name = name
def chooseAction(self, positions, current_board, symbol):
while True:
row = int(input("Input your action row:"))
col = int(input("Input your action col:"))
action = (row, col)
if action in positions:
return action
# append a hash state
def addState(self, state):
pass
# at the end of game, backpropagate and update state value
def feedReward(self, reward):
pass
def reset(self):
pass
class Color:
color_ = 2
def __init__(self):
Color.color_ = Color.color_ + 1
self.color = Color.color_
def colorTheBoard(b):
# b == b.T => b[x][y] == b[y][x] # transpose 也就是 「 \ 」轴对称
# b == np.fliplr(np.rot90(b)) => b[x][y] == b[b.shape[1] - 1 - y][b.shape[0] - 1 - x] # 「 / 」轴对称
# b == np.flipud(b) => b[x][y] == b[b.shape[0] - 1 - x][y] # up down 翻转,也就是「 — 」轴对称
# b == np.fliplr(b) => b[x][y] == b[x][b.shape[1] - 1 - y] # up down 翻转,也就是「 | 」轴对称
# b == np.rot90(np.rot90(b)) => b[x][y] == b[b.shape[0] - 1 - x][b.shape[1] - 1 - y] # 中心对称
colorB = b.tolist() # get a copy of the array data as a (nested) Python list
if (b == b.T).all():
for x in range(b.shape[0]):
for y in range(x, b.shape[1]):
if colorB[x][y] == 0:
colorB[x][y] = colorB[y][x] = Color()
elif type(colorB[x][y]) == Color:
colorB[x][y].color = colorB[y][x].color
if (b == np.fliplr(np.rot90(b))).all():
for x in range(b.shape[0]):
for y in range(b.shape[1] - x):
if colorB[x][y] == 0:
colorB[x][y] = colorB[b.shape[1] - 1 - y][b.shape[0] - 1 - x] = Color()
elif type(colorB[x][y]) == Color:
colorB[x][y].color = colorB[b.shape[1] - 1 - y][b.shape[0] - 1 - x].color
if (b == np.flipud(b)).all():
for x in range(math.ceil(b.shape[0]/2)):
for y in range(b.shape[1]):
if colorB[x][y] == 0:
colorB[x][y] = colorB[b.shape[0] - 1 - x][y] = Color()
elif type(colorB[x][y]) == Color:
colorB[x][y].color = colorB[b.shape[0] - 1 - x][y].color
if (b == np.fliplr(b)).all():
for x in range(b.shape[0]):
for y in range(math.ceil(b.shape[1]/2)):
if colorB[x][y] == 0:
colorB[x][y] = colorB[x][b.shape[1] - 1 - y] = Color()
elif type(colorB[x][y]) == Color:
colorB[x][y].color = colorB[x][b.shape[1] - 1 - y].color
if (b == np.rot90(np.rot90(b))).all():
for x in range(math.ceil(b.shape[0]/2)):
for y in range(b.shape[1]):
if colorB[x][y] == 0:
colorB[x][y] = colorB[b.shape[0] - 1 - x][b.shape[1] - 1 - y] = Color()
elif type(colorB[x][y]) == Color:
colorB[x][y].color = colorB[b.shape[0] - 1 - x][b.shape[1] - 1 - y].color
# 完全不对称的情况
for x in range(b.shape[0]):
for y in range(b.shape[1]):
if colorB[x][y] == 0:
colorB[x][y] = Color()
# for x in range(b.shape[0]):
# for y in range(b.shape[1]):
# if type(colorB[x][y]) == Color:
# colorB[x][y] = colorB[x][y].color
# print(np.array(colorB))
# [[ b[x][y] for y in range(b.shape[1])] for x in range(b.shape[0])]
return colorB
def availablePositionsFuck(board):
b = colorTheBoard(board)
# print('colored:\n', b)
kv = {}
for x in range(len(b)):
for y in range(len(b[0])):
if type(b[x][y]) == Color:
if kv.get( b[x][y].color ) == None:
kv[ b[x][y].color ] = (x,y)
return list(kv.values())
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: {0} test|train|play".format(sys.argv[0]))
exit(1)
if sys.argv[1] == 'test':
b = np.zeros((3,3))
b[0][0] = 1
b[0][1] = -1
print(b)
# print(b[0][2] == 0)
c = availablePositionsFuck(b)
print(c)
if sys.argv[1] == 'train':
# training
p1 = Player("p1")
p2 = Player("p2")
# p1.loadPolicy()
# p2.loadPolicy()
st = State(p1, p2)
print("training...")
st.play(int(sys.argv[2]))
# print(p1.states_value)
# print(p2.states_value)
if sys.argv[1] == 'play':
# play with human
p1 = Player("computer", exp_rate=0)
p1.loadPolicy("policy_p1")
p2 = HumanPlayer("human")
st = State(p1, p2)
st.play2()
| [
"numpy.random.uniform",
"pickle.dump",
"math.ceil",
"numpy.zeros",
"os.path.exists",
"numpy.flipud",
"numpy.fliplr",
"pickle.load",
"numpy.rot90"
] | [((207, 241), 'numpy.zeros', 'np.zeros', (['(BOARD_ROWS, BOARD_COLS)'], {}), '((BOARD_ROWS, BOARD_COLS))\n', (215, 241), True, 'import numpy as np\n'), ((513, 547), 'numpy.zeros', 'np.zeros', (['(BOARD_ROWS, BOARD_COLS)'], {}), '((BOARD_ROWS, BOARD_COLS))\n', (521, 547), True, 'import numpy as np\n'), ((8537, 8571), 'pickle.dump', 'pickle.dump', (['self.states_value', 'fw'], {}), '(self.states_value, fw)\n', (8548, 8571), False, 'import pickle\n'), ((8793, 8808), 'pickle.load', 'pickle.load', (['fr'], {}), '(fr)\n', (8804, 8808), False, 'import pickle\n'), ((13016, 13032), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (13024, 13032), True, 'import numpy as np\n'), ((6760, 6783), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (6777, 6783), True, 'import numpy as np\n'), ((8693, 8713), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (8707, 8713), False, 'import os, sys\n'), ((10975, 11000), 'math.ceil', 'math.ceil', (['(b.shape[0] / 2)'], {}), '(b.shape[0] / 2)\n', (10984, 11000), False, 'import math\n'), ((11712, 11737), 'math.ceil', 'math.ceil', (['(b.shape[0] / 2)'], {}), '(b.shape[0] / 2)\n', (11721, 11737), False, 'import math\n'), ((7681, 7696), 'numpy.rot90', 'np.rot90', (['st', 'i'], {}), '(st, i)\n', (7689, 7696), True, 'import numpy as np\n'), ((10931, 10943), 'numpy.flipud', 'np.flipud', (['b'], {}), '(b)\n', (10940, 10943), True, 'import numpy as np\n'), ((11295, 11307), 'numpy.fliplr', 'np.fliplr', (['b'], {}), '(b)\n', (11304, 11307), True, 'import numpy as np\n'), ((11379, 11404), 'math.ceil', 'math.ceil', (['(b.shape[1] / 2)'], {}), '(b.shape[1] / 2)\n', (11388, 11404), False, 'import math\n'), ((10542, 10553), 'numpy.rot90', 'np.rot90', (['b'], {}), '(b)\n', (10550, 10553), True, 'import numpy as np\n'), ((11668, 11679), 'numpy.rot90', 'np.rot90', (['b'], {}), '(b)\n', (11676, 11679), True, 'import numpy as np\n'), ((7771, 7786), 'numpy.rot90', 'np.rot90', (['st', 'i'], {}), '(st, i)\n', (7779, 7786), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 20:12:18 2021
@author: arnep
"""
from kalman import state_spacer as StateSpacer
import numpy as np
class eStateSpacer(StateSpacer):
"""Class which implements the extended Kalman Filter. This technique
uses a Taylor transformation of the first order for linearising non-linear
functions and then uses the Kalman filter on the linearised function.
"""
def __init__(self, ZFun, ZDotFun, TFun, TDotFun, ZArgs = {}, ZDotArgs = {},
TArgs = {}, TDotArgs = {}, *matrices
):
"""
Implementation of the following model:
yt = c + Z(alphat) + epst , epst ~ NID(0,H)
alphat+1 = d + T(alphat) + Rt*etat , etat ~NID(0,Q)
With Z(), and T() differentiable (non-)linear functions
define time-varying structural matrices in dimension (row, column, time)
Parameters
----------
ZFun : function
Definition of the Z function.
ZDotFun : function
Definition of the derivative of the Z function.
TFun : function
Definition of the T function.
TDotFun : function
Definition of the derivative of the T function.
ZArgs : dict, optional
Additional arguments for the Z function.
The default is {}.
ZDotArgs : dict, optional
Additional arguments for the derivative of the Z function.
The default is {}.
TArgs : dict, optional
Additional arguments for the T function.
The default is {}.
TDotArgs : dict, optional
Additional arguments for the derivative of the T function.
The default is {}.
*matrices : dict
System matrices of the state space model.
Returns
-------
None.
"""
self.ZFun = ZFun
self.ZDotFun = ZDotFun
self.TFun = TFun
self.TDotFun = TDotFun
self.ZArgs = ZArgs
self.ZDotArgs = ZDotArgs
self.TArgs = TArgs
self.TDotArgs = TDotArgs
super().__init__(*matrices)
def get_Z(self, x, *args):
"""
Evaluate the Z function at x.
Parameters
----------
x : input of the Z function.
*args : additional arguments for the Z function.
Returns
-------
int
evaluation of the Z function.
"""
return np.matrix(self.ZFun(x, *args, **self.ZArgs))
def get_Z_dot(self, x, *args):
"""
Evaluate the derivative of the Z function at x.
Parameters
----------
x : input of the derivative of the Z function.
*args : additional arguments for the derivative of the Z function.
Returns
-------
int
evaluation of the derivative of the Z function.
"""
return np.matrix(self.ZDotFun(x, *args, **self.ZDotArgs))
def get_T(self, x, *args):
"""
Evaluate the T function at x.
Parameters
----------
x : input of the T function.
*args : additional arguments for the T function.
Returns
-------
int
evaluation of the T function.
"""
return np.matrix(self.TFun(x, *args, **self.TArgs))
def get_T_dot(self, x, *args):
"""
Evaluate the derivative of the T function at x.
Parameters
----------
x : input of the derivative of the T function.
*args : additional arguments for the derivative of the T function.
Returns
-------
int
evaluation of the derivative of the T function.
"""
return np.matrix(self.TDotFun(x, *args, **self.TDotArgs))
def kalman_filter_iteration(self, yt, a, P, Z, T, c, d, H, Q, R,
v, F, att, Ptt, tol=1e7):
"""
Single iteration of the Kalman filter.
v_t = y_t - Z(a) - c_t
F_t = Zdot_t*P_t* Zdot_t' + H_t
K_t = T_t*P_t*Zdot_t'*F_t-1
a_{t+1} = T(at) + K_t*v_t + d
P_{t+1} = Tdot_t*P_t*Tdot_t' + R_t*Q_t*R_t' - K_t*F_t*K_t'
Parameters
----------
yt : int or array-like
Observation data at time t.
a : int or array-like
State prediction for time t.
P : int or array-like
Variance of state prediction for time t.
Z : array-like
System matrix Zt.
T : array-like
System matrix Tt.
c : array-like
System matrix ct.
d : array-like
System matrix dt.
H : array-like
System matrix Ht.
Q : array-like
System matrix Qt.
R : array-like
System matrix Rt.
v : int or array-like
Previous prediction error.
F : int or array-like
Previous prediction error variance.
att : int or array-like
Previous filtered state (t-1).
Ptt : int or array-like
Previous filtered state variance (t-1).
Returns
-------
v : int or array-like
New prediction error.
F : int or array-like
New prediction error variance.
K : int or array-like
New K.
att : int or array-like
New filtered state (time t).
Ptt : int or array-like
New filtered state variance (time t).
at1 : int or array-like
New state prediction for t + 1.
Pt1 : int or array-like
Variance of state prediction for t + 1.
c : array-like
Just c, no transformation happens in normal Kalman filter.
d : array-like
Just d, no transformation happens in normal Kalman filter.
"""
T_new = np.matrix(self.get_T_dot(att, T))
Z_new = np.matrix(self.get_Z_dot(a, Z))
if not np.isnan(yt):
v = yt - self.get_Z(a, Z).transpose() - c.transpose()
#F, P and K are not transposed
F = Z_new*P*Z_new.transpose() + H
M = P*Z_new.transpose()*np.linalg.inv(F)
K = T_new*M
att = a + v*M.transpose()
Ptt = P - M.transpose()*F*M
else:
v = yt*np.nan
#F, P and K are not transposed
F = np.matrix(np.ones(H.shape)*tol)
M = np.matrix(np.zeros((P*Z_new.transpose()*np.linalg.inv(F)).shape)) #set zeros
K = T_new*M
att = a
Ptt = P
at1 = self.get_T(att, T) + d
Pt1 = T_new*Ptt*T_new.transpose() + R*Q*R.transpose()
return v, F, K, att, Ptt, at1, Pt1, c, d
def smoothing_iteration(self, v, F, r, T, K, Z, N, P, a):
"""
Single smoothing iteration recursion when the observation is available.
Lt+1 = Tt+1 - Kt+1 Zt+1
r_t = v_t+1*(F_{t+1}^-1)'*Z_t + r{t+1}*L{t+1}
N_t = Z'*F_{t+1}^-1*Z_t + L{t+1}*N{t+1}*L{t+1}
alpha{t+1} = a{t+1} + r[t]*P{t+1}'
V{t+1} = P{t+1} - P{t+1}*N_t*P{t+1}
Parameters
----------
v : array-like
Prediction error (value of t+1).
F : array-like
Prediction error variance (value of t+1).
r : array-like
Intermediate result in the smoothing recursions (value of t+1).
T : array-like
System matrix T (value of t+1).
K : array-like
Intermediate result K in the filter recursions (value of t+1).
Z : array-like
System matrix Z (value of t+1).
N : array-like
Intermediate result N in the filter recursions (value of t+1).
P : array-like
State prediction variance (value of t+1).
a : array-like
State prediction (value of t+1).
Returns
-------
L : array-like
Intermediate result in the smoothing recursions (value of t).
r : array-like
Intermediate result in the smoothing recursions (value of t).
N : array-like
Intermediate result N in the filter recursions (value of t).
alpha : array-like
Smoothed state (value of t).
V : array-like
Smoothed state variance (value of t).
"""
Z_new = np.matrix(self.get_Z_dot(a, Z))
M = P*Z_new.transpose()*np.linalg.inv(F)
att = a + v*M.transpose()
T_new = np.matrix(self.get_T_dot(att, T))
if not np.isnan(v):
L_new = T_new - K*Z_new
r= v*np.linalg.inv(F).transpose()*Z_new + (r*L_new)
N = Z_new.transpose()*np.linalg.inv(F)*Z_new + L_new.transpose()*N*L_new
else:
L_new = T_new
r= r*L_new
N = L_new.transpose()*N*L_new
alpha = a + np.dot(r,P.transpose())
V = P - P*N*P
return L_new, r, N, alpha, V
def alphaplus_yplus_generator(self,dist_fun_alpha1,filter_init,n, alphaplus, yplus, epsilon, eta):
matrices, list_3d = self.get_matrices(self.matr)
a1, P1 = filter_init
a1 = np.zeros((np.array(a1).shape))
if len(a1.shape)>1:
a1 = np.array(a1).reshape(a1.shape[1])
else:
P1 = np.sqrt(P1)
t=0
T, R, Z, Q, H, c, d = self.get_syst_matrices(list_3d, t, matrices.copy())
alphaplus[t] = dist_fun_alpha1(a1,P1,size=(n)).T
yplus[t] = self.ZFun(alphaplus[t+1].transpose(), Z).transpose() + epsilon[t+1]
for t in range(len(alphaplus)-1):
T, R, Z, Q, H, c, d = self.get_syst_matrices(list_3d, t, matrices.copy())
eta[t] = np.linalg.cholesky(Q)*np.matrix(eta[t])
epsilon[t] = np.linalg.cholesky(H)*np.matrix(epsilon[t])
alphaplus[t+1] = self.get_T(alphaplus[t].transpose(),T).transpose() + R*eta[t]
yplus[t+1] = self.get_Z(alphaplus[t+1].transpose(), Z).transpose() + epsilon[t+1]
return alphaplus, yplus
| [
"numpy.matrix",
"numpy.ones",
"numpy.isnan",
"numpy.array",
"numpy.linalg.inv",
"numpy.sqrt",
"numpy.linalg.cholesky"
] | [((6287, 6299), 'numpy.isnan', 'np.isnan', (['yt'], {}), '(yt)\n', (6295, 6299), True, 'import numpy as np\n'), ((8873, 8889), 'numpy.linalg.inv', 'np.linalg.inv', (['F'], {}), '(F)\n', (8886, 8889), True, 'import numpy as np\n'), ((9010, 9021), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (9018, 9021), True, 'import numpy as np\n'), ((9823, 9834), 'numpy.sqrt', 'np.sqrt', (['P1'], {}), '(P1)\n', (9830, 9834), True, 'import numpy as np\n'), ((6497, 6513), 'numpy.linalg.inv', 'np.linalg.inv', (['F'], {}), '(F)\n', (6510, 6513), True, 'import numpy as np\n'), ((9688, 9700), 'numpy.array', 'np.array', (['a1'], {}), '(a1)\n', (9696, 9700), True, 'import numpy as np\n'), ((10241, 10262), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['Q'], {}), '(Q)\n', (10259, 10262), True, 'import numpy as np\n'), ((10263, 10280), 'numpy.matrix', 'np.matrix', (['eta[t]'], {}), '(eta[t])\n', (10272, 10280), True, 'import numpy as np\n'), ((10314, 10335), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['H'], {}), '(H)\n', (10332, 10335), True, 'import numpy as np\n'), ((10336, 10357), 'numpy.matrix', 'np.matrix', (['epsilon[t]'], {}), '(epsilon[t])\n', (10345, 10357), True, 'import numpy as np\n'), ((6745, 6761), 'numpy.ones', 'np.ones', (['H.shape'], {}), '(H.shape)\n', (6752, 6761), True, 'import numpy as np\n'), ((9756, 9768), 'numpy.array', 'np.array', (['a1'], {}), '(a1)\n', (9764, 9768), True, 'import numpy as np\n'), ((9160, 9176), 'numpy.linalg.inv', 'np.linalg.inv', (['F'], {}), '(F)\n', (9173, 9176), True, 'import numpy as np\n'), ((6824, 6840), 'numpy.linalg.inv', 'np.linalg.inv', (['F'], {}), '(F)\n', (6837, 6840), True, 'import numpy as np\n'), ((9078, 9094), 'numpy.linalg.inv', 'np.linalg.inv', (['F'], {}), '(F)\n', (9091, 9094), True, 'import numpy as np\n')] |
#! encoding=<utf8>
from __future__ import division
import numpy as np
from fastkde import fastKDE
from warnings import warn
import pymc3 as pm
__all__ = ['find_mode']
def make_indices(dimensions):
# Generates complete set of indices for given dimensions
level = len(dimensions)
if level == 1:
return list(range(dimensions[0]))
indices = [[]]
while level:
_indices = []
for j in range(dimensions[level - 1]):
_indices += [[j] + i for i in indices]
indices = _indices
level -= 1
try:
return [tuple(i) for i in indices]
except TypeError:
return indices
def calc_min_interval(x, cred_mass):
"""Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array.
credit: pymc3
"""
n = len(x)
interval_idx_inc = int(np.floor(cred_mass * n))
n_intervals = n - interval_idx_inc
interval_width = x[interval_idx_inc:] - x[:n_intervals]
if len(interval_width) == 0:
raise ValueError('Too few elements for interval calculation')
min_idx = np.argmin(interval_width)
hdi_min = x[min_idx]
hdi_max = x[min_idx + interval_idx_inc]
return hdi_min, hdi_max
def calc_hpd(x, cred_mass=0.68, transform=lambda x: x):
"""Calculate highest posterior density (HPD) of array for given credible interval mass. The HPD is the
minimum width Bayesian credible interval (BCI).
:Arguments:
x : Numpy array
An array containing MCMC samples
cred_mass : float
Desired credible interval probability mass
transform : callable
Function to transform data (defaults to identity)
"""
# Make a copy of trace
x = transform(x.copy())
# For multivariate node
if x.ndim > 1:
# Transpose first, then sort
tx = np.transpose(x, list(range(x.ndim))[1:] + [0])
dims = np.shape(tx)
# Container list for intervals
intervals = np.resize(0.0, dims[:-1] + (2,))
for index in make_indices(dims[:-1]):
try:
index = tuple(index)
except TypeError:
pass
# Sort trace
sx = np.sort(tx[index])
# Append to list
intervals[index] = calc_min_interval(sx, cred_mass)
# Transpose back before returning
return np.array(intervals)
else:
# Sort univariate node
sx = np.sort(x)
return np.array(calc_min_interval(sx, cred_mass))
def find_mode(trace, credible_interval_mass=0.68, restrict=False, **fastkde_kwargs):
"""
Returns the estimated mode of your mcmc sample assuming it is generated from a continuous distribution
, along with the Highest Posterior Density credible interval containing `cred_mass` fraction of the total
probability. Bandwidth is calculated independently.
HPD is calculated using simple sorted arrays and the mode is calculated by the highest value in a KDE curve.
trace: nd trace or chain from analysis of shape (nsamples, ndims)
credible_interval_mass: The probability mass that the credible interval contains (0.68 == 1sigma)
restrict: If true, estimate the mode only using samples within the credible interval. Slight speed bonus with reduced accuracy.
The accuracy of the mode should not matter if its credible interval is larger than its accuracy.
numPointsPerSigma: how many points per sigma interval to draw the kde with
returns: mode, hpd_interval, (kde_x_axis, kde_pdf)
credit: https://stats.stackexchange.com/questions/259319/reliability-of-mode-from-an-mcmc-sample
cite:
"""
if isinstance(trace, pm.backends.base.MultiTrace):
return {v: find_mode(trace[v], credible_interval_mass, restrict, **fastkde_kwargs) for v in trace.varnames}
original_shape = trace.shape[1:]
if trace.ndim == 1:
trace = trace.reshape(-1, 1)
else:
trace = trace.reshape(trace.shape[0], -1) # ravel last axis (first axis is steps)
if 'numPointsPerSigma' not in fastkde_kwargs:
fastkde_kwargs['numPointsPerSigma'] = 30
hpd_estimates = np.atleast_2d(calc_hpd(trace, credible_interval_mass)) # (dims, interval)
modes = np.zeros(trace.shape[-1])
for i, (param, hpd) in enumerate(zip(trace.T, hpd_estimates)):
if restrict:
x = param[(param < hpd[1]) & (param > hpd[0])]
else:
x = param
if hpd[0] == hpd[1]:
modes[i] = hpd[0]
else:
kde = fastKDE.fastKDE(x, **fastkde_kwargs)
modes[i] = kde.axes[0][np.argmax(kde.pdf)]
modes = modes.reshape(original_shape)
hpd_estimates = hpd_estimates.T.reshape((2,) + original_shape)
if not np.all((modes <= hpd_estimates[1]) & (modes >= hpd_estimates[0])):
warn("Mode estimation has resulted in a mode outside of the HPD region.\n"
"HPD and mode are not reliable!")
return modes, hpd_estimates
def add_hpd_lines_corner_plot(corner_axes, param_label_list, mode, hpd, param_name):
i = param_label_list.index(param_name)
ax = corner_axes[i, i]
ax.axvline(mode, color='k', linestyle='-')
ax.axvline(hpd[0], color='k', linestyle='--')
ax.axvline(hpd[1], color='k', linestyle='--')
ax.set_title('{}$ = {:.2f}^{{+{:.2f}}}_{{-{:.2f}}}$'.format(param_name, mode, mode - min(hpd), max(hpd) - mode))
def corner_plot_hpd(data, labels, cred_mass=0.68, corner_kwargs=None, fastkde_kwargs=None):
if corner_kwargs is None:
corner_kwargs = {}
if fastkde_kwargs is None:
fastkde_kwargs = {}
figure = corner(data, labels=labels, **corner_kwargs)
axes = np.asarray(figure.axes).reshape(len(labels), len(labels))
modes, hpds = find_mode(data, cred_mass, **fastkde_kwargs)
for param, mode, hpd in zip(labels, modes, hpds):
add_hpd_lines_corner_plot(axes, labels, mode, hpd, param)
return figure, modes, hpds
if __name__ == '__main__':
from corner import corner
import matplotlib.pyplot as plt
# simulate a model with 3 parameters
x = np.random.normal(0, 1, size=(100, 1))
x = np.concatenate([x, np.random.normal(3, 0.2, size=(100, 1))], axis=1)
x = np.concatenate([x, np.random.normal(2, 0.01, size=(100, 1))], axis=1)
fig, mode, hpd = corner_plot_hpd(x, list('abc'))
print(mode)
print(hpd)
plt.show() | [
"corner.corner",
"matplotlib.pyplot.show",
"numpy.resize",
"numpy.argmax",
"numpy.floor",
"numpy.asarray",
"numpy.zeros",
"fastkde.fastKDE.fastKDE",
"numpy.argmin",
"numpy.shape",
"numpy.sort",
"numpy.array",
"numpy.random.normal",
"warnings.warn",
"numpy.all"
] | [((1120, 1145), 'numpy.argmin', 'np.argmin', (['interval_width'], {}), '(interval_width)\n', (1129, 1145), True, 'import numpy as np\n'), ((4269, 4294), 'numpy.zeros', 'np.zeros', (['trace.shape[-1]'], {}), '(trace.shape[-1])\n', (4277, 4294), True, 'import numpy as np\n'), ((5655, 5699), 'corner.corner', 'corner', (['data'], {'labels': 'labels'}), '(data, labels=labels, **corner_kwargs)\n', (5661, 5699), False, 'from corner import corner\n'), ((6128, 6165), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {'size': '(100, 1)'}), '(0, 1, size=(100, 1))\n', (6144, 6165), True, 'import numpy as np\n'), ((6410, 6420), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6418, 6420), True, 'import matplotlib.pyplot as plt\n'), ((877, 900), 'numpy.floor', 'np.floor', (['(cred_mass * n)'], {}), '(cred_mass * n)\n', (885, 900), True, 'import numpy as np\n'), ((1929, 1941), 'numpy.shape', 'np.shape', (['tx'], {}), '(tx)\n', (1937, 1941), True, 'import numpy as np\n'), ((2002, 2034), 'numpy.resize', 'np.resize', (['(0.0)', '(dims[:-1] + (2,))'], {}), '(0.0, dims[:-1] + (2,))\n', (2011, 2034), True, 'import numpy as np\n'), ((2402, 2421), 'numpy.array', 'np.array', (['intervals'], {}), '(intervals)\n', (2410, 2421), True, 'import numpy as np\n'), ((2477, 2487), 'numpy.sort', 'np.sort', (['x'], {}), '(x)\n', (2484, 2487), True, 'import numpy as np\n'), ((4782, 4847), 'numpy.all', 'np.all', (['((modes <= hpd_estimates[1]) & (modes >= hpd_estimates[0]))'], {}), '((modes <= hpd_estimates[1]) & (modes >= hpd_estimates[0]))\n', (4788, 4847), True, 'import numpy as np\n'), ((4857, 4975), 'warnings.warn', 'warn', (['"""Mode estimation has resulted in a mode outside of the HPD region.\nHPD and mode are not reliable!"""'], {}), '(\n """Mode estimation has resulted in a mode outside of the HPD region.\nHPD and mode are not reliable!"""\n )\n', (4861, 4975), False, 'from warnings import warn\n'), ((2231, 2249), 'numpy.sort', 'np.sort', (['tx[index]'], {}), '(tx[index])\n', (2238, 2249), True, 'import numpy as np\n'), ((4569, 4605), 'fastkde.fastKDE.fastKDE', 'fastKDE.fastKDE', (['x'], {}), '(x, **fastkde_kwargs)\n', (4584, 4605), False, 'from fastkde import fastKDE\n'), ((5711, 5734), 'numpy.asarray', 'np.asarray', (['figure.axes'], {}), '(figure.axes)\n', (5721, 5734), True, 'import numpy as np\n'), ((6193, 6232), 'numpy.random.normal', 'np.random.normal', (['(3)', '(0.2)'], {'size': '(100, 1)'}), '(3, 0.2, size=(100, 1))\n', (6209, 6232), True, 'import numpy as np\n'), ((6270, 6310), 'numpy.random.normal', 'np.random.normal', (['(2)', '(0.01)'], {'size': '(100, 1)'}), '(2, 0.01, size=(100, 1))\n', (6286, 6310), True, 'import numpy as np\n'), ((4641, 4659), 'numpy.argmax', 'np.argmax', (['kde.pdf'], {}), '(kde.pdf)\n', (4650, 4659), True, 'import numpy as np\n')] |
# Copyright 2020 Google LLC.
#
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v2 as tf
from tf_agents.specs import tensor_spec
from tf_agents.policies import tf_policy
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union
import dice_rl.data.dataset as dataset_lib
import dice_rl.estimators.estimator as estimator_lib
import dice_rl.utils.common as common_lib
class TabularSaddlePoint(object):
"""Tabular approximatation of Mirror Prox for saddle-point optimization."""
def __init__(self,
dataset_spec,
policy_optimizer,
gamma: Union[float, tf.Tensor],
z_learning_rate=0.5,
v_learning_rate=0.5,
entropy_reg=0.1,
reward_fn: Callable = None):
"""Initializes the solver.
Args:
dataset_spec: The spec of the dataset that will be given.
policy_optimizer: TF optimizer for distilling policy from z.
gamma: The discount factor to use.
z_learning_rate: Learning rate for z.
v_learning_rate: Learning rate for v. entropy_reg; Coefficient on entropy
regularization.
reward_fn: A function that takes in an EnvStep and returns the reward for
that step. If not specified, defaults to just EnvStep.reward.
"""
self._dataset_spec = dataset_spec
self._policy_optimizer = policy_optimizer
self._z_learning_rate = z_learning_rate
self._v_learning_rate = v_learning_rate
self._entropy_reg = entropy_reg
self._gamma = gamma
if reward_fn is None:
reward_fn = lambda env_step: env_step.reward
self._reward_fn = reward_fn
# Get number of states/actions.
observation_spec = self._dataset_spec.observation
action_spec = self._dataset_spec.action
if not common_lib.is_categorical_spec(observation_spec):
raise ValueError('Observation spec must be discrete and bounded.')
self._num_states = observation_spec.maximum + 1
if not common_lib.is_categorical_spec(action_spec):
raise ValueError('Action spec must be discrete and bounded.')
self._num_actions = action_spec.maximum + 1
self._zetas = np.zeros([self._num_states * self._num_actions])
self._values = np.zeros([self._num_states])
self._policy = tf.Variable(np.zeros([self._num_states, self._num_actions]))
def _get_z_index(self, env_step):
return env_step.observation * self._num_actions + env_step.action
def _get_v_index(self, env_step):
return env_step.observation
def _get_objective_and_grads(self, init_values, this_values, next_values,
zetas, rewards, discounts):
batch_size = tf.cast(tf.shape(zetas)[0], tf.float32)
normalized_zetas = batch_size * tf.nn.softmax(zetas)
log_normalized_zetas = tf.math.log(batch_size) + tf.nn.log_softmax(zetas)
residuals = rewards + self._gamma * discounts * next_values - this_values
objective = ((1 - self._gamma) * tf.reduce_mean(init_values) +
tf.reduce_mean(normalized_zetas * residuals))
entropy = -tf.reduce_mean(normalized_zetas * log_normalized_zetas)
init_v_grads = (1 - self._gamma) / batch_size
this_v_grads = -1 * normalized_zetas / batch_size
next_v_grads = self._gamma * discounts * normalized_zetas / batch_size
z_grads = (residuals -
self._entropy_reg * log_normalized_zetas) / batch_size
return ((objective, entropy), init_v_grads, this_v_grads, next_v_grads,
z_grads)
def _mirror_prox_step(self, init_steps, this_steps, next_steps):
init_v_indices = self._get_v_index(init_steps)
this_v_indices = self._get_v_index(this_steps)
next_v_indices = self._get_v_index(next_steps)
this_z_indices = self._get_z_index(this_steps)
# Mirror prox step.
init_v = tf.cast(tf.gather(self._values, init_v_indices), tf.float32)
this_v = tf.cast(tf.gather(self._values, this_v_indices), tf.float32)
next_v = tf.cast(tf.gather(self._values, next_v_indices), tf.float32)
this_z = tf.cast(tf.gather(self._zetas, this_z_indices), tf.float32)
rewards = self._reward_fn(this_steps)
discounts = next_steps.discount
(m_objective, m_init_v_grads, m_this_v_grads, m_next_v_grads,
m_z_grads) = self._get_objective_and_grads(init_v, this_v, next_v, this_z,
rewards, discounts)
np.add.at(self._values, init_v_indices,
-self._v_learning_rate * m_init_v_grads)
np.add.at(self._values, this_v_indices,
-self._v_learning_rate * m_this_v_grads)
np.add.at(self._values, next_v_indices,
-self._v_learning_rate * m_next_v_grads)
np.add.at(self._zetas, this_z_indices, self._z_learning_rate * m_z_grads)
# Mirror descent step.
init_v = tf.cast(tf.gather(self._values, init_v_indices), tf.float32)
this_v = tf.cast(tf.gather(self._values, this_v_indices), tf.float32)
next_v = tf.cast(tf.gather(self._values, next_v_indices), tf.float32)
this_z = tf.cast(tf.gather(self._zetas, this_z_indices), tf.float32)
(objective, init_v_grads, this_v_grads, next_v_grads,
z_grads) = self._get_objective_and_grads(init_v, this_v, next_v, this_z,
rewards, discounts)
np.add.at(self._values, init_v_indices,
-self._v_learning_rate * (init_v_grads - m_init_v_grads))
np.add.at(self._values, this_v_indices,
-self._v_learning_rate * (this_v_grads - m_this_v_grads))
np.add.at(self._values, next_v_indices,
-self._v_learning_rate * (next_v_grads - m_next_v_grads))
np.add.at(self._zetas, this_z_indices,
self._z_learning_rate * (z_grads - m_z_grads))
return objective
def _policy_step(self, steps):
z_indices = self._get_z_index(steps)
z = tf.gather(self._zetas, z_indices)
actions = steps.action
batch_size = tf.cast(tf.shape(z)[0], actions.dtype)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch([self._policy])
policy_logits = tf.gather(self._policy, steps.observation)
#print(steps.observation[:3], tf.nn.softmax(policy_logits[:3], axis=-1),
# tf.nn.softmax(z)[:3], actions[:3])
log_probs = tf.nn.log_softmax(policy_logits, axis=-1)
selected_log_probs = tf.gather_nd(
log_probs, tf.stack([tf.range(batch_size), actions], -1))
loss = -tf.reduce_mean(tf.nn.softmax(z) * selected_log_probs)
grads = tape.gradient(loss, [self._policy])
grad_op = self._policy_optimizer.apply_gradients([(grads[0], self._policy)])
return loss, grad_op
def train_step(self, initial_steps: dataset_lib.EnvStep,
transitions: dataset_lib.EnvStep):
"""Performs training step on z, v, and policy based on batch of transitions.
Args:
initial_steps: A batch of initial steps.
transitions: A batch of transitions. Members should have shape
[batch_size, 2, ...].
Returns:
A train op.
"""
this_steps = tf.nest.map_structure(lambda t: t[:, 0, ...], transitions)
next_steps = tf.nest.map_structure(lambda t: t[:, 1, ...], transitions)
loss = self._mirror_prox_step(initial_steps, this_steps, next_steps)
policy_loss, _ = self._policy_step(this_steps)
return loss, policy_loss
def get_policy(self):
"""Returns learned policy."""
return common_lib.create_tf_policy_from_table(
tf.nn.softmax(self._policy, axis=-1).numpy(),
obs_to_index_fn=lambda obs: obs,
return_distribution=True)
| [
"dice_rl.utils.common.is_categorical_spec",
"tensorflow.compat.v2.nest.map_structure",
"tensorflow.compat.v2.gather",
"tensorflow.compat.v2.GradientTape",
"numpy.zeros",
"tensorflow.compat.v2.nn.softmax",
"tensorflow.compat.v2.nn.log_softmax",
"tensorflow.compat.v2.shape",
"tensorflow.compat.v2.rang... | [((2804, 2852), 'numpy.zeros', 'np.zeros', (['[self._num_states * self._num_actions]'], {}), '([self._num_states * self._num_actions])\n', (2812, 2852), True, 'import numpy as np\n'), ((2872, 2900), 'numpy.zeros', 'np.zeros', (['[self._num_states]'], {}), '([self._num_states])\n', (2880, 2900), True, 'import numpy as np\n'), ((5031, 5116), 'numpy.add.at', 'np.add.at', (['self._values', 'init_v_indices', '(-self._v_learning_rate * m_init_v_grads)'], {}), '(self._values, init_v_indices, -self._v_learning_rate * m_init_v_grads\n )\n', (5040, 5116), True, 'import numpy as np\n'), ((5130, 5215), 'numpy.add.at', 'np.add.at', (['self._values', 'this_v_indices', '(-self._v_learning_rate * m_this_v_grads)'], {}), '(self._values, this_v_indices, -self._v_learning_rate * m_this_v_grads\n )\n', (5139, 5215), True, 'import numpy as np\n'), ((5229, 5314), 'numpy.add.at', 'np.add.at', (['self._values', 'next_v_indices', '(-self._v_learning_rate * m_next_v_grads)'], {}), '(self._values, next_v_indices, -self._v_learning_rate * m_next_v_grads\n )\n', (5238, 5314), True, 'import numpy as np\n'), ((5328, 5401), 'numpy.add.at', 'np.add.at', (['self._zetas', 'this_z_indices', '(self._z_learning_rate * m_z_grads)'], {}), '(self._zetas, this_z_indices, self._z_learning_rate * m_z_grads)\n', (5337, 5401), True, 'import numpy as np\n'), ((5932, 6034), 'numpy.add.at', 'np.add.at', (['self._values', 'init_v_indices', '(-self._v_learning_rate * (init_v_grads - m_init_v_grads))'], {}), '(self._values, init_v_indices, -self._v_learning_rate * (\n init_v_grads - m_init_v_grads))\n', (5941, 6034), True, 'import numpy as np\n'), ((6048, 6150), 'numpy.add.at', 'np.add.at', (['self._values', 'this_v_indices', '(-self._v_learning_rate * (this_v_grads - m_this_v_grads))'], {}), '(self._values, this_v_indices, -self._v_learning_rate * (\n this_v_grads - m_this_v_grads))\n', (6057, 6150), True, 'import numpy as np\n'), ((6164, 6266), 'numpy.add.at', 'np.add.at', (['self._values', 'next_v_indices', '(-self._v_learning_rate * (next_v_grads - m_next_v_grads))'], {}), '(self._values, next_v_indices, -self._v_learning_rate * (\n next_v_grads - m_next_v_grads))\n', (6173, 6266), True, 'import numpy as np\n'), ((6280, 6369), 'numpy.add.at', 'np.add.at', (['self._zetas', 'this_z_indices', '(self._z_learning_rate * (z_grads - m_z_grads))'], {}), '(self._zetas, this_z_indices, self._z_learning_rate * (z_grads -\n m_z_grads))\n', (6289, 6369), True, 'import numpy as np\n'), ((6485, 6518), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._zetas', 'z_indices'], {}), '(self._zetas, z_indices)\n', (6494, 6518), True, 'import tensorflow.compat.v2 as tf\n'), ((7694, 7752), 'tensorflow.compat.v2.nest.map_structure', 'tf.nest.map_structure', (['(lambda t: t[:, 0, ...])', 'transitions'], {}), '(lambda t: t[:, 0, ...], transitions)\n', (7715, 7752), True, 'import tensorflow.compat.v2 as tf\n'), ((7770, 7828), 'tensorflow.compat.v2.nest.map_structure', 'tf.nest.map_structure', (['(lambda t: t[:, 1, ...])', 'transitions'], {}), '(lambda t: t[:, 1, ...], transitions)\n', (7791, 7828), True, 'import tensorflow.compat.v2 as tf\n'), ((2437, 2485), 'dice_rl.utils.common.is_categorical_spec', 'common_lib.is_categorical_spec', (['observation_spec'], {}), '(observation_spec)\n', (2467, 2485), True, 'import dice_rl.utils.common as common_lib\n'), ((2624, 2667), 'dice_rl.utils.common.is_categorical_spec', 'common_lib.is_categorical_spec', (['action_spec'], {}), '(action_spec)\n', (2654, 2667), True, 'import dice_rl.utils.common as common_lib\n'), ((2932, 2979), 'numpy.zeros', 'np.zeros', (['[self._num_states, self._num_actions]'], {}), '([self._num_states, self._num_actions])\n', (2940, 2979), True, 'import numpy as np\n'), ((3386, 3406), 'tensorflow.compat.v2.nn.softmax', 'tf.nn.softmax', (['zetas'], {}), '(zetas)\n', (3399, 3406), True, 'import tensorflow.compat.v2 as tf\n'), ((3434, 3457), 'tensorflow.compat.v2.math.log', 'tf.math.log', (['batch_size'], {}), '(batch_size)\n', (3445, 3457), True, 'import tensorflow.compat.v2 as tf\n'), ((3460, 3484), 'tensorflow.compat.v2.nn.log_softmax', 'tf.nn.log_softmax', (['zetas'], {}), '(zetas)\n', (3477, 3484), True, 'import tensorflow.compat.v2 as tf\n'), ((3648, 3692), 'tensorflow.compat.v2.reduce_mean', 'tf.reduce_mean', (['(normalized_zetas * residuals)'], {}), '(normalized_zetas * residuals)\n', (3662, 3692), True, 'import tensorflow.compat.v2 as tf\n'), ((3709, 3764), 'tensorflow.compat.v2.reduce_mean', 'tf.reduce_mean', (['(normalized_zetas * log_normalized_zetas)'], {}), '(normalized_zetas * log_normalized_zetas)\n', (3723, 3764), True, 'import tensorflow.compat.v2 as tf\n'), ((4459, 4498), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'init_v_indices'], {}), '(self._values, init_v_indices)\n', (4468, 4498), True, 'import tensorflow.compat.v2 as tf\n'), ((4533, 4572), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'this_v_indices'], {}), '(self._values, this_v_indices)\n', (4542, 4572), True, 'import tensorflow.compat.v2 as tf\n'), ((4607, 4646), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'next_v_indices'], {}), '(self._values, next_v_indices)\n', (4616, 4646), True, 'import tensorflow.compat.v2 as tf\n'), ((4681, 4719), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._zetas', 'this_z_indices'], {}), '(self._zetas, this_z_indices)\n', (4690, 4719), True, 'import tensorflow.compat.v2 as tf\n'), ((5451, 5490), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'init_v_indices'], {}), '(self._values, init_v_indices)\n', (5460, 5490), True, 'import tensorflow.compat.v2 as tf\n'), ((5525, 5564), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'this_v_indices'], {}), '(self._values, this_v_indices)\n', (5534, 5564), True, 'import tensorflow.compat.v2 as tf\n'), ((5599, 5638), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._values', 'next_v_indices'], {}), '(self._values, next_v_indices)\n', (5608, 5638), True, 'import tensorflow.compat.v2 as tf\n'), ((5673, 5711), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._zetas', 'this_z_indices'], {}), '(self._zetas, this_z_indices)\n', (5682, 5711), True, 'import tensorflow.compat.v2 as tf\n'), ((6612, 6659), 'tensorflow.compat.v2.GradientTape', 'tf.GradientTape', ([], {'watch_accessed_variables': '(False)'}), '(watch_accessed_variables=False)\n', (6627, 6659), True, 'import tensorflow.compat.v2 as tf\n'), ((6724, 6766), 'tensorflow.compat.v2.gather', 'tf.gather', (['self._policy', 'steps.observation'], {}), '(self._policy, steps.observation)\n', (6733, 6766), True, 'import tensorflow.compat.v2 as tf\n'), ((6912, 6953), 'tensorflow.compat.v2.nn.log_softmax', 'tf.nn.log_softmax', (['policy_logits'], {'axis': '(-1)'}), '(policy_logits, axis=-1)\n', (6929, 6953), True, 'import tensorflow.compat.v2 as tf\n'), ((3318, 3333), 'tensorflow.compat.v2.shape', 'tf.shape', (['zetas'], {}), '(zetas)\n', (3326, 3333), True, 'import tensorflow.compat.v2 as tf\n'), ((3601, 3628), 'tensorflow.compat.v2.reduce_mean', 'tf.reduce_mean', (['init_values'], {}), '(init_values)\n', (3615, 3628), True, 'import tensorflow.compat.v2 as tf\n'), ((6571, 6582), 'tensorflow.compat.v2.shape', 'tf.shape', (['z'], {}), '(z)\n', (6579, 6582), True, 'import tensorflow.compat.v2 as tf\n'), ((8102, 8138), 'tensorflow.compat.v2.nn.softmax', 'tf.nn.softmax', (['self._policy'], {'axis': '(-1)'}), '(self._policy, axis=-1)\n', (8115, 8138), True, 'import tensorflow.compat.v2 as tf\n'), ((7026, 7046), 'tensorflow.compat.v2.range', 'tf.range', (['batch_size'], {}), '(batch_size)\n', (7034, 7046), True, 'import tensorflow.compat.v2 as tf\n'), ((7092, 7108), 'tensorflow.compat.v2.nn.softmax', 'tf.nn.softmax', (['z'], {}), '(z)\n', (7105, 7108), True, 'import tensorflow.compat.v2 as tf\n')] |
"""
CSfrag: build a dynamic library of analogous fragments, given a list
of assigned chemical shifts.
"""
import os
import numpy
import multiprocessing
import csb.io
import csb.apps
from csb.bio.io.wwpdb import FileSystemStructureProvider, StructureNotFoundError, PDBParseError
from csb.bio.nmr import RandomCoil, ChemShiftScoringModel
from csb.bio.structure import Chain, Broken3DStructureError
from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory
from csb.bio.io.cs import ChemShiftReader, ChemShiftFormatError
from csb.bio.io.fasta import SequenceParser, SequenceFormatError
class ExitCodes(csb.apps.ExitCodes):
IO_ERROR = 2
INVALID_DATA = 3
NO_OUTPUT = 5
class AppRunner(csb.apps.AppRunner):
@property
def target(self):
return CSfragApp
def command_line(self):
cmd = csb.apps.ArgHandler(self.program, __doc__)
cpu = multiprocessing.cpu_count()
cmd.add_scalar_option('database', 'd', str, 'PDBS25 database directory (containing PDBS25cs.scs)', required=True)
cmd.add_scalar_option('shifts', 's', str, 'assigned chemical shifts table (NMR STAR file fragment)', required=True)
cmd.add_scalar_option('window', 'w', int, 'sliding window size', default=8)
cmd.add_scalar_option('top', 't', int, 'maximum number per starting position', default=25)
cmd.add_scalar_option('cpu', 'c', int, 'maximum degree of parallelism', default=cpu)
cmd.add_scalar_option('verbosity', 'v', int, 'verbosity level', default=1)
cmd.add_scalar_option('output', 'o', str, 'output directory', default='.')
cmd.add_boolean_option('filtered-map', 'f', 'make an additional filtered fragment map of centroids', default=False)
cmd.add_positional_argument('QUERY', str, 'query sequence (FASTA file)')
return cmd
class CSfragApp(csb.apps.Application):
def main(self):
if not os.path.isdir(self.args.output):
CSfragApp.exit('Output directory does not exist', code=ExitCodes.INVALID_DATA, usage=True)
try:
csf = CSfrag(self.args.QUERY, self.args.shifts, self.args.database, self.args.window, logger=self)
output = os.path.join(self.args.output, csf.query.accession)
frags = csf.extract_fragments(self.args.top, self.args.cpu)
if len(frags) == 0:
CSfragApp.exit('No fragments found!', code=ExitCodes.NO_OUTPUT)
fragmap = csf.build_fragment_map()
fragmap.dump(output + '.csfrags.08')
if self.args.filtered_map:
fragmap = csf.build_filtered_map()
fragmap.dump(output + '.filtered.08')
self.log('\nDONE.')
except ArgumentIOError as ae:
CSfragApp.exit(str(ae), code=ExitCodes.IO_ERROR)
except ArgumentError as ae:
CSfragApp.exit(str(ae), code=ExitCodes.INVALID_DATA, usage=True)
except ChemShiftFormatError as ce:
msg = "Can't parse input chemical shifts: " + str(ce)
CSfragApp.exit(msg, code=ExitCodes.INVALID_DATA)
def log(self, message, ending='\n', level=1):
if level <= self.args.verbosity:
super(CSfragApp, self).log(message, ending)
class SecondaryShiftConverter(object):
"""
Helper, which reads assigned shifts from NMR STAR files and calculates
corrected secondary shifts.
"""
def convert(self, file, chain):
"""
Compute secondary shofts.
@param file: NMR STAR path and file name
@type file: str
@param chain: the protein chain, containing the chemical shifts
(L{Chain.from_sequence} may be useful)
@type chain: L{Chain}
@return: dictionary of the form: [rank: [nucleus: sec shift]]
@rtype: dict
"""
rc = RandomCoil.get()
cs = {}
for ni in ChemShiftReader().guess(file).read_file(file):
if ni.name in ChemShiftScoringModel.NUCLEI:
ni.shift = rc.secondary_shift(chain, ni.position, ni.name, ni.shift)
cs.setdefault(ni.position, {})
cs[ni.position][ni.name] = ni.shift
return cs
class SecondaryShiftReader(object):
"""
Reads secondary shifts from files in CSfrag format.
"""
DB = 'pdbs25cs.scs'
def read_shifts(self, string):
"""
Read secondary shifts.
@param string: complete secondary shift block
@type string: str
@return: dictionary of the form: [rank: [nucleus: sec shift]]
@rtype: dict
"""
shifts = {}
for l in string.splitlines():
if l.startswith('#') or not l.strip():
continue
l = l.split('\t')
rank = int(l[0])
for n, cs in zip(ChemShiftScoringModel.NUCLEI, l[1:]):
if cs != '':
shifts.setdefault(rank, {})[n] = float(cs)
return shifts
def load_database(self, path, file=DB):
"""
Read the entire PDBS25CS database.
@return: dictionary of the form: [entry ID: [rank: [nucleus: sec shift]]]
@rtype: dict
"""
db = {}
file = os.path.join(path, file)
with open(file) as stream:
er = csb.io.EntryReader(stream, '#', None)
for e in er.entries():
entry = e[10:15]
db[entry] = self.read_shifts(e)
return db
class ScoringHelper(object):
def __init__(self, window):
self._window = window
self._model = ChemShiftScoringModel()
@property
def window(self):
return self._window
def score(self, qcs, scs, qstart, qend, sstart, send):
window = self._window
if window is None:
window = min(qend - qstart + 1, send - sstart + 1)
off_start, off_end = self.offsets(qstart, qend, window=window)
qs = qstart + off_start
qe = qend - off_end
ss = sstart + off_start
se = send - off_end
assert qe - qs + 1 == se - ss + 1 == window
score = 0
for nucleus in ChemShiftScoringModel.NUCLEI:
query = []
subject = []
for qr, sr in zip(range(qs, qe + 1), range(ss, se + 1)):
try:
qshift = qcs[qr][nucleus]
sshift = scs[sr][nucleus]
if qshift is not None and sshift is not None:
query.append(qshift)
subject.append(sshift)
except KeyError:
continue
if query and subject:
deltas = numpy.array(query) - numpy.array(subject)
score += self._model.score(nucleus, deltas).sum()
return score
def offsets(self, start, end, window=6):
if end - start + 1 <= window:
return 0, 0
d1 = ((end - start + 1) - window) / 2
ns = start + d1
ne = ns + window - 1
d2 = end - ne
return d1, d2
class ArgumentError(ValueError):
pass
class ArgumentIOError(ArgumentError):
pass
class InvalidOperationError(ValueError):
pass
class CSfrag(object):
"""
@param query: query FASTA sequence path and file name
@type query: str
@param cstable: file, containing the table of assigned experimental chemical shifts
@type cstable: str
@param database: path to the PDBS25 directory
@type database: str
@param logger: logging client (needs to have a C{log} method)
@type logger: L{Application}
"""
def __init__(self, query, cstable, database, window=8, logger=None):
self._query = None
self._qcs = None
self._matches = None
self._helper = ScoringHelper(window)
self._database = None
self._window = None
self._app = logger
self._pdb = None
try:
fasta = SequenceParser().parse_file(query)
if len(fasta) != 1:
raise ArgumentError("The input FASTA file should contain one sequence")
elif fasta[0].length < 1:
raise ArgumentError("Zero-length query sequence")
self._query = Chain.from_sequence(fasta[0], 'A')
self._query.accession = fasta[0].id
self._qcs = SecondaryShiftConverter().convert(cstable, self._query)
if len(self._qcs) == 0:
raise ArgumentError("No chemical shifts read; check your input")
except IOError as io:
raise ArgumentIOError(str(io))
except SequenceFormatError as se:
raise ArgumentError("Can't parse FASTA file: {0}".format(str(se)))
self.database = database
self.window = window
@property
def query(self):
return self._query
@property
def database(self):
return self._database
@database.setter
def database(self, value):
database = value
pdbs25cs = os.path.join(value, SecondaryShiftReader.DB)
if not os.path.isfile(pdbs25cs):
raise ArgumentError('PDBS25CS not found here: ' + pdbs25cs)
self._database = database
self._pdb = FileSystemStructureProvider(database)
@property
def window(self):
return self._window
@window.setter
def window(self, value):
value = int(value)
if value < 1:
raise ValueError("Invalid sliding window: {0}".format(value))
self._window = value
def log(self, *a, **ka):
if self._app:
self._app.log(*a, **ka)
def extract_fragments(self, top=25, cpu=2):
"""
Extract fragments with matching chemical shifts using a sliding window.
@param top: L{MatchTable} capacity per starting position
@type top: int
@param cpu: degree of parallelism
@type cpu: int
@rtype: tuple of L{ChemShiftAssignment}s
"""
self.log("# Reading chemical shifts...", level=1)
db = SecondaryShiftReader().load_database(self.database)
matches = MatchTable(self.query.length, capacity=top)
slices = []
fragments = []
for qs in range(1, self.query.length + 1):
qe = qs + self.window - 1
if qe > self.query.length:
break
slices.append((qs, qe))
self.log("\n# Processing target {0}...".format(self.query.accession), level=1)
pool = multiprocessing.Pool(cpu)
try:
for subject in db:
tasks = []
for qs, qe in slices:
task = pool.apply_async(_task, [self._helper, subject, qs, qe, self._qcs, db[subject]])
tasks.append(task)
for task in tasks:
for result in task.get():
if result.score > ChemShiftAssignment.BIT_SCORE_THRESHOLD * self.window:
matches.add(result)
except KeyboardInterrupt:
pass
finally:
pool.terminate()
for rank in matches:
msg = '{0:3} {1:3} ({2:2} aa) {3:3} fragments'
self.log(msg.format(rank, rank + self.window - 1, self.window, len(matches[rank])),
level=1)
self.log("\n# Extracting fragments...")
for group in matches.by_source:
try:
source_id = group[0].entry_id
source = self._pdb.get(source_id).first_chain
source.compute_torsion()
for match in group:
try:
row = ' {0.entry_id:5} L{0.qs:3} {0.qe:3} {1}aa S:{0.score:5.1f}'
self.log(row.format(match, self.window), ending='', level=2)
fragment = ChemShiftAssignment(source=source, start=match.ss, end=match.se,
qstart=match.qs, qend=match.qe,
window=self.window, rmsd=None, score=match.score)
fragments.append(fragment)
self.log('', level=2)
except Broken3DStructureError:
self.log(' corrupt', level=2)
continue
except PDBParseError:
continue
except StructureNotFoundError:
self.log(" Warning: Template {0} is missing!".format(source_id))
self._matches = fragments
return tuple(fragments)
def build_fragment_map(self):
"""
Build a full Rosetta fragset.
@rtype: L{RosettaFragmentMap}
"""
if self._matches is None:
self.extract_fragments()
self.log('\n# Building fragment map...')
target = ChemShiftTarget(self.query.accession, self.query.length, self.query.residues)
target.assignall(self._matches)
factory = RosettaFragsetFactory()
return factory.make_fragset(target)
def build_filtered_map(self):
"""
Build a filtered fragset of centroids.
@rtype: L{RosettaFragmentMap}
"""
if self._matches is None:
self.extract_fragments()
self.log('\n# Building filtered map...')
target = ChemShiftTarget(self.query.accession, self.query.length, self.query.residues)
target.assignall(self._matches)
factory = RosettaFragsetFactory()
return factory.make_filtered(target, extend=False)
class MatchInfo(object):
def __init__(self, entry_id, qs, qe, ss, se, score):
self.entry_id = entry_id
self.qs = qs
self.qe = qe
self.ss = ss
self.se = se
self.score = score
def __str__(self):
return '{0.qs:4} {0.qe:4} {0.ss:4} {0.se:4} {0.score:10.3f}'.format(self)
def __cmp__(self, other):
return cmp(self.score, other.score)
class MatchTable(object):
def __init__(self, length, capacity=25):
if capacity < 1:
capacity = 1
self._capacity = capacity
self._length = length
self._t = {}
for i in range(1, length + 1):
self._t[i] = []
def add(self, m):
matches = self._t[m.qs]
if len(matches) < self._capacity:
matches.append(m)
matches.sort()
elif m.score > matches[-1].score:
matches.pop()
matches.append(m)
matches.sort()
def __getitem__(self, rank):
return tuple(self._t[rank])
def __iter__(self):
return iter(self._t)
@property
def by_source(self):
matches = {}
for rank in self:
for m in self[rank]:
if m.entry_id not in matches:
matches[m.entry_id] = []
matches[m.entry_id].append(m)
for entry_id in matches:
yield tuple(matches[entry_id])
def _task(helper, subject, qs, qe, qcs, scs):
try:
results = []
slength = max(scs or [0])
for ss in range(1, slength + 1, 3):
se = ss + helper.window - 1
if se > slength:
break
score = helper.score(qcs, scs, qs, qe, ss, se)
if score is not None:
info = MatchInfo(subject, qs, qe, ss, se, score)
results.append(info)
return results
except KeyboardInterrupt:
return []
def main():
AppRunner().run()
if __name__ == '__main__':
main() | [
"csb.bio.nmr.RandomCoil.get",
"csb.bio.nmr.ChemShiftScoringModel",
"os.path.isdir",
"csb.bio.io.wwpdb.FileSystemStructureProvider",
"csb.bio.fragments.RosettaFragsetFactory",
"os.path.isfile",
"numpy.array",
"csb.bio.io.cs.ChemShiftReader",
"csb.bio.fragments.ChemShiftAssignment",
"multiprocessing... | [((941, 968), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (966, 968), False, 'import multiprocessing\n'), ((4166, 4182), 'csb.bio.nmr.RandomCoil.get', 'RandomCoil.get', ([], {}), '()\n', (4180, 4182), False, 'from csb.bio.nmr import RandomCoil, ChemShiftScoringModel\n'), ((5735, 5759), 'os.path.join', 'os.path.join', (['path', 'file'], {}), '(path, file)\n', (5747, 5759), False, 'import os\n'), ((6160, 6183), 'csb.bio.nmr.ChemShiftScoringModel', 'ChemShiftScoringModel', ([], {}), '()\n', (6181, 6183), False, 'from csb.bio.nmr import RandomCoil, ChemShiftScoringModel\n'), ((9851, 9895), 'os.path.join', 'os.path.join', (['value', 'SecondaryShiftReader.DB'], {}), '(value, SecondaryShiftReader.DB)\n', (9863, 9895), False, 'import os\n'), ((10063, 10100), 'csb.bio.io.wwpdb.FileSystemStructureProvider', 'FileSystemStructureProvider', (['database'], {}), '(database)\n', (10090, 10100), False, 'from csb.bio.io.wwpdb import FileSystemStructureProvider, StructureNotFoundError, PDBParseError\n'), ((11456, 11481), 'multiprocessing.Pool', 'multiprocessing.Pool', (['cpu'], {}), '(cpu)\n', (11476, 11481), False, 'import multiprocessing\n'), ((14109, 14186), 'csb.bio.fragments.ChemShiftTarget', 'ChemShiftTarget', (['self.query.accession', 'self.query.length', 'self.query.residues'], {}), '(self.query.accession, self.query.length, self.query.residues)\n', (14124, 14186), False, 'from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory\n'), ((14259, 14282), 'csb.bio.fragments.RosettaFragsetFactory', 'RosettaFragsetFactory', ([], {}), '()\n', (14280, 14282), False, 'from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory\n'), ((14653, 14730), 'csb.bio.fragments.ChemShiftTarget', 'ChemShiftTarget', (['self.query.accession', 'self.query.length', 'self.query.residues'], {}), '(self.query.accession, self.query.length, self.query.residues)\n', (14668, 14730), False, 'from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory\n'), ((14790, 14813), 'csb.bio.fragments.RosettaFragsetFactory', 'RosettaFragsetFactory', ([], {}), '()\n', (14811, 14813), False, 'from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory\n'), ((2055, 2086), 'os.path.isdir', 'os.path.isdir', (['self.args.output'], {}), '(self.args.output)\n', (2068, 2086), False, 'import os\n'), ((2337, 2388), 'os.path.join', 'os.path.join', (['self.args.output', 'csf.query.accession'], {}), '(self.args.output, csf.query.accession)\n', (2349, 2388), False, 'import os\n'), ((9011, 9045), 'csb.bio.structure.Chain.from_sequence', 'Chain.from_sequence', (['fasta[0]', '"""A"""'], {}), "(fasta[0], 'A')\n", (9030, 9045), False, 'from csb.bio.structure import Chain, Broken3DStructureError\n'), ((9911, 9935), 'os.path.isfile', 'os.path.isfile', (['pdbs25cs'], {}), '(pdbs25cs)\n', (9925, 9935), False, 'import os\n'), ((7350, 7368), 'numpy.array', 'numpy.array', (['query'], {}), '(query)\n', (7361, 7368), False, 'import numpy\n'), ((7371, 7391), 'numpy.array', 'numpy.array', (['subject'], {}), '(subject)\n', (7382, 7391), False, 'import numpy\n'), ((8697, 8713), 'csb.bio.io.fasta.SequenceParser', 'SequenceParser', ([], {}), '()\n', (8711, 8713), False, 'from csb.bio.io.fasta import SequenceParser, SequenceFormatError\n'), ((4226, 4243), 'csb.bio.io.cs.ChemShiftReader', 'ChemShiftReader', ([], {}), '()\n', (4241, 4243), False, 'from csb.bio.io.cs import ChemShiftReader, ChemShiftFormatError\n'), ((12994, 13145), 'csb.bio.fragments.ChemShiftAssignment', 'ChemShiftAssignment', ([], {'source': 'source', 'start': 'match.ss', 'end': 'match.se', 'qstart': 'match.qs', 'qend': 'match.qe', 'window': 'self.window', 'rmsd': 'None', 'score': 'match.score'}), '(source=source, start=match.ss, end=match.se, qstart=\n match.qs, qend=match.qe, window=self.window, rmsd=None, score=match.score)\n', (13013, 13145), False, 'from csb.bio.fragments import ChemShiftTarget, ChemShiftAssignment, RosettaFragsetFactory\n')] |
"""
.. module:: single_conn
:synopsis: Module for visualization of C. Elegans' neural connections with a GUI
.. moduleauthor:: <NAME>
"""
from os.path import dirname
HERE = dirname(__file__)
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.patches import ArrowStyle
dfs = pd.read_csv(HERE+'/data/Neuro279_Syn.csv', index_col=0)
dfg = pd.read_csv(HERE+'/data/Neuro279_EJ.csv', index_col=0)
dfcat = pd.read_csv(HERE+'/data/neuron_categories.csv', index_col=1, header=0)
nbs = [i for i in range(len(dfs.index))]
cats = dfcat.loc[dfg.index]
motors = cats.index[cats['Category']=='MOTOR']
inters = cats.index[cats['Category']=='INTERNEURON']
sensors = cats.index[cats['Category']=='SENSORY']
""" Preferences : you can change the shape and colors of neuron categories here """
SENSOR_COLOR = '#006000'
SENSOR_SHAPE = 'o'
INTER_COLOR = '#000060'
INTER_SHAPE = 'o'
MOTOR_COLOR = '#600000'
MOTOR_SHAPE = 'o'
NODE_SIZE = 2500
style = ArrowStyle("wedge", tail_width=2., shrink_factor=0.2)
styleg = ArrowStyle("wedge", tail_width=0.6, shrink_factor=0.4)
CONN_STYLE = 'arc3, rad=0.3'
def connections(neuron='BAGL', connstyle=CONN_STYLE):
'''Prepare graph for plotting'''
G = nx.DiGraph()
syn_in = dfs.index[dfs[neuron] > 0].tolist()
intens_in = dfs.loc[dfs[neuron] > 0, neuron]
syni = [(pre, neuron, {}) for pre in syn_in]
G.add_edges_from(syni)
gaps_ = dfg.index[dfg[neuron] > 0].tolist()
intens_g = 0.1*dfg.loc[dfg[neuron] > 0, neuron]
gaps = [(neuron, k, {}) for k in gaps_] + [(k, neuron, {}) for k in gaps_]
G.add_edges_from(gaps)
syn_out = dfs.T.index[dfs.T[neuron] > 0].tolist()
intens_out = dfs.T.loc[dfs.T[neuron] > 0, neuron]
syno = [(neuron, post, {}) for post in syn_out]
G.add_edges_from(syno)
G.remove_node(neuron)
pos = nx.layout.circular_layout(G, scale=2)
G.add_node(neuron)
pos[neuron] = np.array([0,0])
def draw_nodes(shape='o', category=inters, col='k'):
nx.draw_networkx_nodes(G, pos, node_shape=shape, node_color=col,
nodelist=[n for n in G.nodes if n in category],
node_size=NODE_SIZE, alpha=0.9)
draw_nodes(SENSOR_SHAPE, sensors, SENSOR_COLOR)
draw_nodes(INTER_SHAPE, inters, INTER_COLOR)
draw_nodes(MOTOR_SHAPE, motors, MOTOR_COLOR)
nx.draw_networkx_labels(G, pos, font_color='w', font_weight='bold')
nx.draw_networkx_edges(G, pos, arrowstyle=style, edgelist=syni, edge_color='g', connectionstyle=connstyle,
arrowsize=10, alpha=0.7, width=intens_in, node_size=NODE_SIZE)
nx.draw_networkx_edges(G, pos, arrowstyle=style, edgelist=syno, edge_color='r', connectionstyle=connstyle,
arrowsize=10, alpha=0.5, width=intens_out, node_size=NODE_SIZE)
nx.draw_networkx_edges(G, pos, arrowstyle=styleg, edgelist=gaps, edge_color='Gold',
arrowsize=10, alpha=0.8, width=np.hstack((intens_g,intens_g)),
node_size=NODE_SIZE)
plt.axis('off')
return pos
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
class Visu(QVBoxLayout):
'''Layout for one neuron visualization'''
nb = 0
def __init__(self, img_size=12):
super(Visu, self).__init__()
Visu.nb += 1
self.nb = Visu.nb
# Figure and mouse clicking
self.figure = plt.figure(self.nb, figsize=(img_size,img_size))
self.canvas = FigureCanvas(self.figure)
self.canvas.setMouseTracking(True)
self.canvas.mousePressEvent = lambda e: Visu.mousePressEvent(e, self)
subl = QHBoxLayout()
'''List of neurons'''
self.cb = QComboBox()
self.cb.addItems(sorted(dfs.index))
self.cb.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.cb.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.cb.view().window().setMaximumHeight(400)
'''Style option'''
self.style = QCheckBox('Curved')
self.style.setChecked(True)
self.cb.currentIndexChanged.connect(lambda x: self.draw())
self.style.stateChanged.connect(lambda x: self.draw())
'''Add everything in layout'''
self.addWidget(self.canvas)
subl.addStretch()
subl.addWidget(self.cb)
subl.addWidget(self.style)
subl.addStretch()
self.addLayout(subl)
self.pos = None
self.draw()
def draw(self, neur=None, style=None):
'''Draw with @neur in the center'''
self.figure.clf()
plt.figure(self.nb)
if neur is None:
neur = self.cb.currentText()
if self.style.isChecked():
style = CONN_STYLE
self.pos = connections(neur, style)
self.canvas.draw()
@staticmethod
def mousePressEvent(event, self):
'''Put clicked neuron on the center'''
X = self.canvas.width()
Y = self.canvas.height()
x = (event.pos().x() * 6 / X) - 3
y = - (event.pos().y() * 6 / Y) + 3
p = np.array([[x, y]])
nodes = np.array(list(self.pos.values()))
dist = np.sum((nodes - p)**2, axis=1)
close = np.argmin(dist)
if dist[close] < 0.2:
neur = list(self.pos.keys())[close]
self.draw(neur=neur)
def delete(self):
'''Delete slot'''
self.setParent(None)
self.cb.setParent(None)
self.style.setParent(None)
self.canvas.setParent(None)
class Window(QWidget):
'''Main window containing potentially several visualisations'''
def __init__(self):
super(Window, self).__init__()
self.neurons = []
layout = QVBoxLayout()
self.visu_layout = QHBoxLayout()
'''Buttons to add or remove slots'''
self.b1 = QPushButton("Add slot")
self.b1.clicked.connect(self.add_visu)
self.b2 = QPushButton("Remove slot")
self.b2.clicked.connect(self.remove_visu)
subl = QHBoxLayout()
subl.addWidget(self.b1)
subl.addWidget(self.b2)
layout.addLayout(subl)
self.visu_layout.addLayout(Visu())
layout.addLayout(self.visu_layout)
self.setLayout(layout)
self.resize(500, 500)
self.move(300, 300)
self.setWindowTitle("Connectome Visualizer")
def add_visu(self):
'''Add neuron visalization'''
self.neurons.append(Visu())
self.visu_layout.addLayout(self.neurons[-1])
def remove_visu(self):
'''Remove last neuron visualization'''
self.neurons[-1].delete()
self.visu_layout.removeItem(self.neurons[-1])
self.neurons.pop()
if __name__=='__main__':
app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
| [
"numpy.sum",
"networkx.draw_networkx_edges",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg",
"pandas.read_csv",
"os.path.dirname",
"matplotlib.pyplot.axis",
"numpy.argmin",
"numpy.hstack",
"matplotlib.pyplot.figure",
"networkx.layout.circular_layout",
"numpy.array",
"networkx.draw_netw... | [((179, 196), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (186, 196), False, 'from os.path import dirname\n'), ((340, 397), 'pandas.read_csv', 'pd.read_csv', (["(HERE + '/data/Neuro279_Syn.csv')"], {'index_col': '(0)'}), "(HERE + '/data/Neuro279_Syn.csv', index_col=0)\n", (351, 397), True, 'import pandas as pd\n'), ((402, 458), 'pandas.read_csv', 'pd.read_csv', (["(HERE + '/data/Neuro279_EJ.csv')"], {'index_col': '(0)'}), "(HERE + '/data/Neuro279_EJ.csv', index_col=0)\n", (413, 458), True, 'import pandas as pd\n'), ((470, 542), 'pandas.read_csv', 'pd.read_csv', (["(HERE + '/data/neuron_categories.csv')"], {'index_col': '(1)', 'header': '(0)'}), "(HERE + '/data/neuron_categories.csv', index_col=1, header=0)\n", (481, 542), True, 'import pandas as pd\n'), ((1000, 1054), 'matplotlib.patches.ArrowStyle', 'ArrowStyle', (['"""wedge"""'], {'tail_width': '(2.0)', 'shrink_factor': '(0.2)'}), "('wedge', tail_width=2.0, shrink_factor=0.2)\n", (1010, 1054), False, 'from matplotlib.patches import ArrowStyle\n'), ((1063, 1117), 'matplotlib.patches.ArrowStyle', 'ArrowStyle', (['"""wedge"""'], {'tail_width': '(0.6)', 'shrink_factor': '(0.4)'}), "('wedge', tail_width=0.6, shrink_factor=0.4)\n", (1073, 1117), False, 'from matplotlib.patches import ArrowStyle\n'), ((1248, 1260), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (1258, 1260), True, 'import networkx as nx\n'), ((1880, 1917), 'networkx.layout.circular_layout', 'nx.layout.circular_layout', (['G'], {'scale': '(2)'}), '(G, scale=2)\n', (1905, 1917), True, 'import networkx as nx\n'), ((1959, 1975), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (1967, 1975), True, 'import numpy as np\n'), ((2408, 2475), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['G', 'pos'], {'font_color': '"""w"""', 'font_weight': '"""bold"""'}), "(G, pos, font_color='w', font_weight='bold')\n", (2431, 2475), True, 'import networkx as nx\n'), ((2485, 2664), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['G', 'pos'], {'arrowstyle': 'style', 'edgelist': 'syni', 'edge_color': '"""g"""', 'connectionstyle': 'connstyle', 'arrowsize': '(10)', 'alpha': '(0.7)', 'width': 'intens_in', 'node_size': 'NODE_SIZE'}), "(G, pos, arrowstyle=style, edgelist=syni, edge_color=\n 'g', connectionstyle=connstyle, arrowsize=10, alpha=0.7, width=\n intens_in, node_size=NODE_SIZE)\n", (2507, 2664), True, 'import networkx as nx\n'), ((2686, 2866), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['G', 'pos'], {'arrowstyle': 'style', 'edgelist': 'syno', 'edge_color': '"""r"""', 'connectionstyle': 'connstyle', 'arrowsize': '(10)', 'alpha': '(0.5)', 'width': 'intens_out', 'node_size': 'NODE_SIZE'}), "(G, pos, arrowstyle=style, edgelist=syno, edge_color=\n 'r', connectionstyle=connstyle, arrowsize=10, alpha=0.5, width=\n intens_out, node_size=NODE_SIZE)\n", (2708, 2866), True, 'import networkx as nx\n'), ((3115, 3130), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3123, 3130), True, 'import matplotlib.pyplot as plt\n'), ((2045, 2194), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['G', 'pos'], {'node_shape': 'shape', 'node_color': 'col', 'nodelist': '[n for n in G.nodes if n in category]', 'node_size': 'NODE_SIZE', 'alpha': '(0.9)'}), '(G, pos, node_shape=shape, node_color=col, nodelist=[\n n for n in G.nodes if n in category], node_size=NODE_SIZE, alpha=0.9)\n', (2067, 2194), True, 'import networkx as nx\n'), ((3590, 3639), 'matplotlib.pyplot.figure', 'plt.figure', (['self.nb'], {'figsize': '(img_size, img_size)'}), '(self.nb, figsize=(img_size, img_size))\n', (3600, 3639), True, 'import matplotlib.pyplot as plt\n'), ((3661, 3686), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg', 'FigureCanvas', (['self.figure'], {}), '(self.figure)\n', (3673, 3686), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((4796, 4815), 'matplotlib.pyplot.figure', 'plt.figure', (['self.nb'], {}), '(self.nb)\n', (4806, 4815), True, 'import matplotlib.pyplot as plt\n'), ((5294, 5312), 'numpy.array', 'np.array', (['[[x, y]]'], {}), '([[x, y]])\n', (5302, 5312), True, 'import numpy as np\n'), ((5378, 5410), 'numpy.sum', 'np.sum', (['((nodes - p) ** 2)'], {'axis': '(1)'}), '((nodes - p) ** 2, axis=1)\n', (5384, 5410), True, 'import numpy as np\n'), ((5425, 5440), 'numpy.argmin', 'np.argmin', (['dist'], {}), '(dist)\n', (5434, 5440), True, 'import numpy as np\n'), ((3030, 3061), 'numpy.hstack', 'np.hstack', (['(intens_g, intens_g)'], {}), '((intens_g, intens_g))\n', (3039, 3061), True, 'import numpy as np\n')] |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""
##############export checkpoint file into air and onnx models#################
python export.py --net squeezenet --dataset cifar10 --checkpoint_path squeezenet_cifar10-120_1562.ckpt
"""
import numpy as np
from mindspore import Tensor
from mindspore.train.serialization import load_checkpoint, load_param_into_net, export
from model_utils.config import config
if __name__ == '__main__':
if config.net_name == "squeezenet":
from src.squeezenet import SqueezeNet as squeezenet
else:
from src.squeezenet import SqueezeNet_Residual as squeezenet
if config.dataset == "cifar10":
num_classes = 10
else:
num_classes = 1000
onnx_filename = config.net_name + '_' + config.dataset
air_filename = config.net_name + '_' + config.dataset
net = squeezenet(num_classes=num_classes)
assert config.checkpoint_file_path is not None, "checkpoint_file_path is None."
param_dict = load_checkpoint(config.checkpoint_file_path)
load_param_into_net(net, param_dict)
input_arr = Tensor(np.zeros([1, 3, 227, 227], np.float32))
export(net, input_arr, file_name=onnx_filename, file_format="ONNX")
export(net, input_arr, file_name=air_filename, file_format="AIR")
| [
"numpy.zeros",
"mindspore.train.serialization.load_checkpoint",
"src.squeezenet.SqueezeNet_Residual",
"mindspore.train.serialization.export",
"mindspore.train.serialization.load_param_into_net"
] | [((1465, 1500), 'src.squeezenet.SqueezeNet_Residual', 'squeezenet', ([], {'num_classes': 'num_classes'}), '(num_classes=num_classes)\n', (1475, 1500), True, 'from src.squeezenet import SqueezeNet_Residual as squeezenet\n'), ((1604, 1648), 'mindspore.train.serialization.load_checkpoint', 'load_checkpoint', (['config.checkpoint_file_path'], {}), '(config.checkpoint_file_path)\n', (1619, 1648), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net, export\n'), ((1653, 1689), 'mindspore.train.serialization.load_param_into_net', 'load_param_into_net', (['net', 'param_dict'], {}), '(net, param_dict)\n', (1672, 1689), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net, export\n'), ((1758, 1825), 'mindspore.train.serialization.export', 'export', (['net', 'input_arr'], {'file_name': 'onnx_filename', 'file_format': '"""ONNX"""'}), "(net, input_arr, file_name=onnx_filename, file_format='ONNX')\n", (1764, 1825), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net, export\n'), ((1830, 1895), 'mindspore.train.serialization.export', 'export', (['net', 'input_arr'], {'file_name': 'air_filename', 'file_format': '"""AIR"""'}), "(net, input_arr, file_name=air_filename, file_format='AIR')\n", (1836, 1895), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net, export\n'), ((1714, 1752), 'numpy.zeros', 'np.zeros', (['[1, 3, 227, 227]', 'np.float32'], {}), '([1, 3, 227, 227], np.float32)\n', (1722, 1752), True, 'import numpy as np\n')] |
import os
import random
import argparse
import functools
from math import e, log
import numpy as np
import torch
from torch.backends import cudnn
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from nni.algorithms.compression.pytorch.pruning \
import L1FilterPruner, L1FilterPrunerMasker
from utils.counter import count_flops_params
from utils.train_util import load_model_pytorch, train, test
from nets.resnet_cifar import ResNet_CIFAR
from nets.vgg import VGG_CIFAR
from cdp import acculumate_feature, calculate_cdp, \
get_threshold_by_flops, get_threshold_by_sparsity, \
TFIDFPruner
def str2bool(s):
if isinstance(s, bool):
return s
if s.lower() in ('yes', 'true', 't', 'y', '1'):
return True
if s.lower() in ('no', 'false', 'f', 'n', '0'):
return False
raise argparse.ArgumentTypeError('Boolean value expected.')
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
cudnn.deterministic = True
#cudnn.benchmark = False
#cudnn.enabled = False
parser = argparse.ArgumentParser(description='CDP Pruner')
parser.add_argument('--dataset', type=str, default='cifar10',
help='cifar10 or imagenet')
parser.add_argument('--model', type=str, default='resnet56',
help='model to use, only resnet56, resnet20')
parser.add_argument('--pretrained_dir', type=str, default=None,
help='pretrained file path')
# Data setting
# '/gdata/ImageNet2012/train/'
parser.add_argument('--dataroot', required=True, metavar='PATH',
help='Path to Dataset folder')
parser.add_argument('--batch_size', type=int, default=512,
help='input batch size for statistics (default: 128)')
parser.add_argument('--stop_batch', type=int, default=200, help="Sample batch number")
parser.add_argument('--search_batch_size', type=int, default=10000,
help='input batch size for search (default: 256)')
parser.add_argument('--test_batch_size', type=int, default=10000,
help='input batch size for testing (default: 256)')
# Environment Setting
parser.add_argument('--gpus', default=None, help='List of GPUs used for training - e.g 0,1,3')
parser.add_argument('-j', '--workers', default=8, type=int, metavar='N',
help='Number of data loading workers (default: 8)')
parser.add_argument('--seed', type=int, default=0, help='random seed')
# Training Setting
parser.add_argument('--epochs', type=int, default=300,
help='epochs to fine tune')
# CDP Setting
parser.add_argument('--coe', type=int,
help='whether to use balance coefficient')
parser.add_argument('--sparsity', type=float, default=0.39,
help='target overall target sparsity')
# Saver Setting
parser.add_argument('--save_acc', type=float, default=94.0,
help='save accuracy')
parser.add_argument('--savepath', type=str, default='./ckpt/',
help='model save directory')
args = parser.parse_args()
print(args)
#random.seed(args.seed)
#torch.manual_seed(args.seed)
setup_seed(args.seed)
sparsity = args.sparsity
save_file = '_'.join([str(args.model),
'coe{}'.format(args.coe),
'seed{}'.format(args.seed)
])
args.savepath=os.path.join(args.savepath,args.model)
save_info = os.path.join(args.savepath, save_file)
save_acc = args.save_acc
def load_model(args):
if args.model == 'resnet56':
net = ResNet_CIFAR(depth=56)
model_path = '../resnet56_base/checkpoint/model_best.pth.tar'
elif args.model == 'resnet20':
net = ResNet_CIFAR(depth=20)
model_path = './models/resnet20_base/checkpoint/model_best.pth.tar'
elif args.model == 'vgg':
net = VGG_CIFAR()
model_path = './models/vgg_base/checkpoint/model_best.pth.tar'
else:
print('no model')
return
if args.pretrained_dir:
model_path = args.pretrained_dir
net = net.cuda()
load_model_pytorch(net, model_path, args.model)
return net
mean=[125.31 / 255, 122.95 / 255, 113.87 / 255]
std=[63.0 / 255, 62.09 / 255, 66.70 / 255]
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean,std)
])
trainset = torchvision.datasets.CIFAR10(root=args.dataroot, train=True, download=False, transform=transform_train)
testset = torchvision.datasets.CIFAR10(root=args.dataroot, train=False, download=False, transform=transform_test)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=False, num_workers=4)
train_all_loader = torch.utils.data.DataLoader(trainset, batch_size=args.search_batch_size, shuffle=False, num_workers=4)
testloader = torch.utils.data.DataLoader(testset, batch_size=args.test_batch_size, shuffle=False, num_workers=4)
# load pretrained model
net = load_model(args)
feature_iit = acculumate_feature(net, train_all_loader, args.stop_batch)
tf_idf_map = calculate_cdp(feature_iit,args.coe)
threshold = get_threshold_by_sparsity(tf_idf_map,sparsity)
# threshold = get_threshold_by_flops(tf_idf_map,target_reduced_ratio,net)
print('threshold', threshold)
# pruning
net = load_model(args)
flops, param, detail_flops = count_flops_params(net, (1, 3, 32, 32))
test(net, testloader)
cdp_config={ "threshold": threshold, "map": tf_idf_map }
config_list = [{
'sparsity': sparsity,
'op_types': ['Conv2d']
}]
pruner = TFIDFPruner(net, config_list, cdp_config=cdp_config)
_ = pruner.compress()
flops, param, detail_flops = count_flops_params(net, (1, 3, 32, 32))
save_info += str(flops)[0:4]
print(save_info)
train(net, epochs=300, lr=0.1, train_loader=trainloader, test_loader=testloader, save_info=save_info, save_acc=save_acc)
| [
"numpy.random.seed",
"argparse.ArgumentParser",
"cdp.calculate_cdp",
"nets.vgg.VGG_CIFAR",
"torchvision.datasets.CIFAR10",
"utils.train_util.test",
"torchvision.transforms.Normalize",
"os.path.join",
"argparse.ArgumentTypeError",
"utils.counter.count_flops_params",
"torch.utils.data.DataLoader",... | [((1212, 1261), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""CDP Pruner"""'}), "(description='CDP Pruner')\n", (1235, 1261), False, 'import argparse\n'), ((3533, 3572), 'os.path.join', 'os.path.join', (['args.savepath', 'args.model'], {}), '(args.savepath, args.model)\n', (3545, 3572), False, 'import os\n'), ((3584, 3622), 'os.path.join', 'os.path.join', (['args.savepath', 'save_file'], {}), '(args.savepath, save_file)\n', (3596, 3622), False, 'import os\n'), ((4716, 4823), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': 'args.dataroot', 'train': '(True)', 'download': '(False)', 'transform': 'transform_train'}), '(root=args.dataroot, train=True, download=False,\n transform=transform_train)\n', (4744, 4823), False, 'import torchvision\n'), ((4830, 4938), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': 'args.dataroot', 'train': '(False)', 'download': '(False)', 'transform': 'transform_test'}), '(root=args.dataroot, train=False, download=\n False, transform=transform_test)\n', (4858, 4938), False, 'import torchvision\n'), ((4949, 5049), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(trainset, batch_size=args.batch_size, shuffle=\n False, num_workers=4)\n', (4976, 5049), False, 'import torch\n'), ((5064, 5170), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'args.search_batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(trainset, batch_size=args.search_batch_size,\n shuffle=False, num_workers=4)\n', (5091, 5170), False, 'import torch\n'), ((5180, 5283), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testset'], {'batch_size': 'args.test_batch_size', 'shuffle': '(False)', 'num_workers': '(4)'}), '(testset, batch_size=args.test_batch_size,\n shuffle=False, num_workers=4)\n', (5207, 5283), False, 'import torch\n'), ((5343, 5401), 'cdp.acculumate_feature', 'acculumate_feature', (['net', 'train_all_loader', 'args.stop_batch'], {}), '(net, train_all_loader, args.stop_batch)\n', (5361, 5401), False, 'from cdp import acculumate_feature, calculate_cdp, get_threshold_by_flops, get_threshold_by_sparsity, TFIDFPruner\n'), ((5415, 5451), 'cdp.calculate_cdp', 'calculate_cdp', (['feature_iit', 'args.coe'], {}), '(feature_iit, args.coe)\n', (5428, 5451), False, 'from cdp import acculumate_feature, calculate_cdp, get_threshold_by_flops, get_threshold_by_sparsity, TFIDFPruner\n'), ((5463, 5510), 'cdp.get_threshold_by_sparsity', 'get_threshold_by_sparsity', (['tf_idf_map', 'sparsity'], {}), '(tf_idf_map, sparsity)\n', (5488, 5510), False, 'from cdp import acculumate_feature, calculate_cdp, get_threshold_by_flops, get_threshold_by_sparsity, TFIDFPruner\n'), ((5687, 5726), 'utils.counter.count_flops_params', 'count_flops_params', (['net', '(1, 3, 32, 32)'], {}), '(net, (1, 3, 32, 32))\n', (5705, 5726), False, 'from utils.counter import count_flops_params\n'), ((5727, 5748), 'utils.train_util.test', 'test', (['net', 'testloader'], {}), '(net, testloader)\n', (5731, 5748), False, 'from utils.train_util import load_model_pytorch, train, test\n'), ((5890, 5942), 'cdp.TFIDFPruner', 'TFIDFPruner', (['net', 'config_list'], {'cdp_config': 'cdp_config'}), '(net, config_list, cdp_config=cdp_config)\n', (5901, 5942), False, 'from cdp import acculumate_feature, calculate_cdp, get_threshold_by_flops, get_threshold_by_sparsity, TFIDFPruner\n'), ((5995, 6034), 'utils.counter.count_flops_params', 'count_flops_params', (['net', '(1, 3, 32, 32)'], {}), '(net, (1, 3, 32, 32))\n', (6013, 6034), False, 'from utils.counter import count_flops_params\n'), ((6082, 6207), 'utils.train_util.train', 'train', (['net'], {'epochs': '(300)', 'lr': '(0.1)', 'train_loader': 'trainloader', 'test_loader': 'testloader', 'save_info': 'save_info', 'save_acc': 'save_acc'}), '(net, epochs=300, lr=0.1, train_loader=trainloader, test_loader=\n testloader, save_info=save_info, save_acc=save_acc)\n', (6087, 6207), False, 'from utils.train_util import load_model_pytorch, train, test\n'), ((881, 934), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Boolean value expected."""'], {}), "('Boolean value expected.')\n", (907, 934), False, 'import argparse\n'), ((962, 985), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (979, 985), False, 'import torch\n'), ((991, 1023), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (1017, 1023), False, 'import torch\n'), ((1029, 1057), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (1051, 1057), False, 'import torch\n'), ((1063, 1083), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1077, 1083), True, 'import numpy as np\n'), ((1089, 1106), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1100, 1106), False, 'import random\n'), ((4239, 4286), 'utils.train_util.load_model_pytorch', 'load_model_pytorch', (['net', 'model_path', 'args.model'], {}), '(net, model_path, args.model)\n', (4257, 4286), False, 'from utils.train_util import load_model_pytorch, train, test\n'), ((3723, 3745), 'nets.resnet_cifar.ResNet_CIFAR', 'ResNet_CIFAR', ([], {'depth': '(56)'}), '(depth=56)\n', (3735, 3745), False, 'from nets.resnet_cifar import ResNet_CIFAR\n'), ((4441, 4477), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(32)'], {'padding': '(4)'}), '(32, padding=4)\n', (4462, 4477), False, 'from torchvision import transforms\n'), ((4487, 4520), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (4518, 4520), False, 'from torchvision import transforms\n'), ((4530, 4551), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4549, 4551), False, 'from torchvision import transforms\n'), ((4561, 4592), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['mean', 'std'], {}), '(mean, std)\n', (4581, 4592), False, 'from torchvision import transforms\n'), ((4644, 4665), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4663, 4665), False, 'from torchvision import transforms\n'), ((4671, 4702), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['mean', 'std'], {}), '(mean, std)\n', (4691, 4702), False, 'from torchvision import transforms\n'), ((3866, 3888), 'nets.resnet_cifar.ResNet_CIFAR', 'ResNet_CIFAR', ([], {'depth': '(20)'}), '(depth=20)\n', (3878, 3888), False, 'from nets.resnet_cifar import ResNet_CIFAR\n'), ((4010, 4021), 'nets.vgg.VGG_CIFAR', 'VGG_CIFAR', ([], {}), '()\n', (4019, 4021), False, 'from nets.vgg import VGG_CIFAR\n')] |
'''Module for GS and Jacobi smoothers for the Poisson (classical) obstacle problem.'''
__all__ = ['PsmootherPoisson']
import numpy as np
from smoothers.base import SmootherObstacleProblem
def _pde2alpha(x):
return 2.0 + np.sin(2.0 * np.pi * x)
class PsmootherPoisson(SmootherObstacleProblem):
'''Class for the projected Gauss-Seidel (PGS) algorithm as a smoother
for the linear Poisson equation - (alpha u')' = f with u(0)=u(L)=0.'''
def __init__(self, args, admissibleeps=1.0e-10):
super().__init__(args, admissibleeps=admissibleeps)
# fix the random seed for repeatability
np.random.seed(self.args.randomseed)
if self.args.poissoncase == 'pde2':
self.alpha = _pde2alpha
else:
self.alpha = None
# smoother name
self.name = 'PJac' if self.args.jacobi else 'PGS'
def _diagonalentry(self, h, p):
'''Compute the diagonal value of a(.,.) at hat function psi_p^j:
a(psi_p,psi_p) = int_0^L alpha(x) (psi_p^j)'(x)^2 dx
Uses trapezoid rule if alpha(x) not constant.'''
if self.alpha is not None:
xx = h * np.array([p-1,p,p+1])
aa = self.alpha(xx)
return (1.0 / (2.0 * h)) * (aa[0] + 2.0 * aa[1] + aa[2])
else:
return 2.0 / h
def _pointresidual(self, h, w, ell, p):
'''Compute the value of the residual linear functional, in V^j', for given
iterate w, at one interior hat function psi_p^j:
F(w)[psi_p^j] = int_0^L alpha(x) w'(x) (psi_p^j)'(x) dx - ell(psi_p^j)
Uses trapezoid rule if alpha(x) not constant. Input ell is in V^j'.'''
if self.alpha is not None:
xx = h * np.array([p-1,p,p+1])
aa = self.alpha(xx)
zz = (aa[0] + aa[1]) * (w[p] - w[p-1]) \
- (aa[1] + aa[2]) * (w[p+1] - w[p])
return (1.0 / (2.0 * h)) * zz - ell[p]
else:
return (1.0 / h) * (2.0*w[p] - w[p-1] - w[p+1]) - ell[p]
def applyoperator(self, mesh, w):
raise NotImplementedError
def residual(self, mesh, w, ell):
'''Compute the residual functional for given iterate w. Note
ell is a source term in V^j'. Calls _pointresidual() for values.'''
mesh.checklen(w)
mesh.checklen(ell)
F = mesh.zeros()
for p in range(1, mesh.m+1):
F[p] = self._pointresidual(mesh.h, w, ell, p)
return F
def smoothersweep(self, mesh, w, ell, phi, forward=True):
'''Do either in-place GS or Jacobi smoothing.'''
mesh.checklen(w)
mesh.checklen(ell)
mesh.checklen(phi)
self._checkrepairadmissible(mesh, w, phi)
if self.args.jacobi:
self.jacobisweep(mesh, w, ell, phi, forward=forward)
else:
self.gssweep(mesh, w, ell, phi, forward=forward)
mesh.WU += 1
def gssweep(self, mesh, w, ell, phi, forward=True):
'''Do in-place projected Gauss-Seidel sweep, with relaxation factor
omega, over the interior points p=1,...,m, for the classical obstacle
problem
F(u)[v-u] = a(w,v-u) - ell[v-u] >= 0
for all v in V^j. Input iterate w is in V^j and ell is in V^j'.
At each p, solves
F(w + c psi_p)[psi_p] = 0
for c. Thus c = - F(w)[psi_p] / a(psi_p,psi_p). Update of w guarantees
admissibility:
w[p] <- max(w[p] + omega c, phi[p]).
Input mesh is of class MeshLevel1D.'''
for p in self._sweepindices(mesh, forward=forward):
c = - self._pointresidual(mesh.h, w, ell, p) / self._diagonalentry(mesh.h, p)
w[p] = max(w[p] + self.args.omega * c, phi[p])
def jacobisweep(self, mesh, w, ell, phi, forward=True):
'''Do in-place projected Jacobi sweep, with relaxation factor
omega, over the interior points p=1,...,m, for the classical obstacle
problem. Same as Gauss-Seidel but the new iterate values are NOT
used when updating the next point; the residual is evaluated
at the start and those values are used for the sweep. Tai (2003)
says underrelaxation is expected; omega = 0.8 seems to work.'''
r = self.residual(mesh, w, ell)
for p in self._sweepindices(mesh, forward=forward):
c = - r[p] / self._diagonalentry(mesh.h, p)
w[p] = max(w[p] + self.args.omega * c, phi[p])
def phi(self, x):
'''The obstacle: u >= phi.'''
if self.args.poissoncase == 'icelike':
ph = x * (1.0 - x)
elif self.args.poissoncase == 'traditional':
# maximum is at 2.0 + args.poissonparabolay
ph = 8.0 * x * (1.0 - x) + self.args.poissonparabolay
elif self.args.poissoncase in ['pde1', 'pde2']: # these u(x) are above axis
ph = - np.ones(np.shape(x))
else:
raise ValueError
if self.args.random:
perturb = np.zeros(len(x))
for jj in range(self.args.randommodes):
perturb += np.random.randn(1) * np.sin((jj+1) * np.pi * x)
perturb *= self.args.randomscale * 0.03 * np.exp(-10 * (x-0.5)**2)
ph += perturb
ph[[0, -1]] = [0.0, 0.0] # always force zero boundary conditions
return ph
def exact_available(self):
return (not self.args.random) and (self.args.poissonfscale == 1.0) \
and (self.args.poissonparabolay == -1.0 or self.args.poissonparabolay <= -2.25)
def source(self, x):
'''The source term f in the interior condition - (alpha u')' = f.'''
if self.args.poissoncase == 'icelike':
f = 8.0 * np.ones(np.shape(x))
f[x < 0.2] = -16.0
f[x > 0.8] = -16.0
elif self.args.poissoncase == 'traditional':
f = -2.0 * np.ones(np.shape(x))
elif self.args.poissoncase == 'pde1':
f = 12.0 * x * x - 2.0
elif self.args.poissoncase == 'pde2':
twopi = 2.0 * np.pi
f = - twopi * (10.0 - 2.0 * x) * np.cos(twopi * x) \
+ 2.0 * (2.0 + np.sin(twopi * x))
else:
raise ValueError
return self.args.poissonfscale * f
def exact(self, x):
'''Exact solution u(x), if available. Assumes x is a numpy array.'''
assert self.exact_available()
if self.args.poissoncase == 'icelike':
u = self.phi(x)
a, c0, c1, d0, d1 = 0.1, -0.8, 0.09, 4.0, -0.39 # exact values
mid = (x > 0.2) * (x < 0.8) # logical and
left = (x > a) * (x < 0.2)
right = (x > 0.8) * (x < 1.0-a)
u[mid] = -4.0*x[mid]**2 + d0*x[mid] + d1
u[left] = 8.0*x[left]**2 + c0*x[left] + c1
u[right] = 8.0*(1.0-x[right])**2 + c0*(1.0-x[right]) + c1
elif self.args.poissoncase == 'traditional':
if self.args.poissonparabolay == -1.0:
a = 1.0/3.0
def upoisson(x):
return x * (x - 18.0 * a + 8.0)
u = self.phi(x)
u[x < a] = upoisson(x[x < a])
u[x > 1.0-a] = upoisson(1.0 - x[x > 1.0-a])
elif self.args.poissonparabolay <= -2.25:
u = x * (x - 1.0) # solution without obstruction
else:
raise NotImplementedError
elif self.args.poissoncase == 'pde1':
u = x * x * (1.0 - x * x)
elif self.args.poissoncase == 'pde2':
u = x * (10.0 - x)
return u
| [
"numpy.random.seed",
"numpy.random.randn",
"numpy.shape",
"numpy.sin",
"numpy.array",
"numpy.exp",
"numpy.cos"
] | [((227, 250), 'numpy.sin', 'np.sin', (['(2.0 * np.pi * x)'], {}), '(2.0 * np.pi * x)\n', (233, 250), True, 'import numpy as np\n'), ((620, 656), 'numpy.random.seed', 'np.random.seed', (['self.args.randomseed'], {}), '(self.args.randomseed)\n', (634, 656), True, 'import numpy as np\n'), ((1150, 1177), 'numpy.array', 'np.array', (['[p - 1, p, p + 1]'], {}), '([p - 1, p, p + 1])\n', (1158, 1177), True, 'import numpy as np\n'), ((1717, 1744), 'numpy.array', 'np.array', (['[p - 1, p, p + 1]'], {}), '([p - 1, p, p + 1])\n', (1725, 1744), True, 'import numpy as np\n'), ((5166, 5194), 'numpy.exp', 'np.exp', (['(-10 * (x - 0.5) ** 2)'], {}), '(-10 * (x - 0.5) ** 2)\n', (5172, 5194), True, 'import numpy as np\n'), ((5064, 5082), 'numpy.random.randn', 'np.random.randn', (['(1)'], {}), '(1)\n', (5079, 5082), True, 'import numpy as np\n'), ((5085, 5113), 'numpy.sin', 'np.sin', (['((jj + 1) * np.pi * x)'], {}), '((jj + 1) * np.pi * x)\n', (5091, 5113), True, 'import numpy as np\n'), ((5695, 5706), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (5703, 5706), True, 'import numpy as np\n'), ((5854, 5865), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (5862, 5865), True, 'import numpy as np\n'), ((4861, 4872), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (4869, 4872), True, 'import numpy as np\n'), ((6071, 6088), 'numpy.cos', 'np.cos', (['(twopi * x)'], {}), '(twopi * x)\n', (6077, 6088), True, 'import numpy as np\n'), ((6122, 6139), 'numpy.sin', 'np.sin', (['(twopi * x)'], {}), '(twopi * x)\n', (6128, 6139), True, 'import numpy as np\n')] |
# coding: utf-8
# python 3.5
from itertools import product
from sklearn.metrics import accuracy_score
from multiprocessing import Pool
from multiprocessing import freeze_support
import numpy as np
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__))+'/../MLEM2')
import logging
logging.basicConfig(filename=os.path.dirname(os.path.abspath(__file__))+'/ExperimentsMLEM2.log',format='%(asctime)s,%(message)s',level=logging.DEBUG)
#import importlib
import mlem2
#importlib.reload(mlem2)
import LERS
# ========================================
# listの平均と分散を求める
# ========================================
def getEvalMeanVar(result):
ans = '{mean}±{std}'.format(mean=('%.3f' % round(np.mean(results),3)), std=('%.3f' % round(np.std(results),3)))
return(ans)
# ========================================
# results を saveする
# ========================================
def saveResults(results, FILENAME):
filename = FILENAME
outfile = open(filename, 'w')
for x in results:
outfile.write(str(x) + "\n")
outfile.close()
# ========================================
# multi に実行する
# ========================================
def multi_main(proc,FILENAMES):
pool = Pool(proc)
multiargs = []
for FILENAME, iter1, iter2 in product(FILENAMES, range(1,11), range(1,11)):
multiargs.append((FILENAME,iter1,iter2))
#results = pool.starmap(MLEM2_LERS, multiargs)
return(results)
# ========================================
# main
# ========================================
if __name__ == "__main__":
#FILENAMES = ['hayes-roth']
#rules =
rules = mlem2.getRulesByMLEM2('hayes-roth', 2, 2)
# シングルプロセスで実行
#for FILENAME, iter1, iter2 in product(FILENAMES, range(1,11), range(1,11)):
# print('{filename} {i1} {i2}'.format(filename=FILENAME, i1=iter1, i2=iter2))
# print(MLEM2_LERS(FILENAME, iter1, iter2))
# 並列実行
proc=4
freeze_support()
results = multi_main(proc, FILENAMES)
# 平均と分散
print(getEvalMeanVar(results))
# 保存する
#saveResults(results, "/data/uci/hayes-roth/accuracy.txt")
| [
"os.path.abspath",
"numpy.std",
"numpy.mean",
"multiprocessing.Pool",
"mlem2.getRulesByMLEM2",
"multiprocessing.freeze_support"
] | [((1218, 1228), 'multiprocessing.Pool', 'Pool', (['proc'], {}), '(proc)\n', (1222, 1228), False, 'from multiprocessing import Pool\n'), ((1645, 1686), 'mlem2.getRulesByMLEM2', 'mlem2.getRulesByMLEM2', (['"""hayes-roth"""', '(2)', '(2)'], {}), "('hayes-roth', 2, 2)\n", (1666, 1686), False, 'import mlem2\n'), ((1959, 1975), 'multiprocessing.freeze_support', 'freeze_support', ([], {}), '()\n', (1973, 1975), False, 'from multiprocessing import freeze_support\n'), ((250, 275), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (265, 275), False, 'import os\n'), ((350, 375), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (365, 375), False, 'import os\n'), ((711, 727), 'numpy.mean', 'np.mean', (['results'], {}), '(results)\n', (718, 727), True, 'import numpy as np\n'), ((753, 768), 'numpy.std', 'np.std', (['results'], {}), '(results)\n', (759, 768), True, 'import numpy as np\n')] |
#util.py
# A module that contains various small functions that the main engine makes use of.
import funs.learning as learning
import funs.inference as inference
import funs.engine as engine
import numpy as np
import scipy as sp
import scipy.io as sio
import scipy.optimize as op
from scipy.optimize import approx_fprime
import statsmodels.tools.numdiff as nd
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
import pdb
import copy
import pickle
import sys
import pandas
def JSLogdetDiv(X,Y):
return np.log(np.linalg.det((X+Y)/2)) - 1/2*np.log(np.linalg.det(X.dot(Y)))
def getMeanCovYfromParams(params, experiment):
T = experiment.T
rho = params['d']
n = len(rho)
lamb = np.dot(params['C'],params['C'].T)
E_y = np.exp(1/2*np.diag(lamb)+rho)
# E_yy = np.diag(E_y) + np.diag(np.exp(np.diag(lamb))*E_y**2)
E_yy = np.zeros([n,n])
for i in range(n):
for j in range(n):
if i == j:
E_yy[i,j] = E_y[i] + np.exp(lamb[i,i]/2)*E_y[i]**2
else:
E_yy[i,j] = E_y[i]*E_y[j]*np.exp(lamb[i,j]/2)
# E_yy = np.dot(E_y,E_y.T)*np.exp(lamb) + np.diag(E_y)
return E_y, E_yy
def stars(p):
if p < 0.0001:
return "****"
elif (p < 0.001):
return "***"
elif (p < 0.01):
return "**"
elif (p < 0.05):
return "*"
else:
return "-"
def raster(event_times_list, color='k'):
"""
Creates a raster plot
Parameters
----------
event_times_list : iterable
a list of event time iterables
color : string
color of vlines
Returns
-------
ax : an axis containing the raster plot
"""
ax = plt.gca()
for ith, trial in enumerate(event_times_list):
plt.vlines(trial, ith + .5, ith + 1.5, color=color)
plt.ylim(.5, len(event_times_list) + .5)
return ax
class load_crcns_data():
def __init__(
self,
filepath,
trialDur = 1000,
binSize = 20,
numTrials = None):
T = int(np.floor(trialDur/binSize))
spikeTimes = pandas.read_pickle(filepath)
uniqueUnits = np.unique(spikeTimes.unit.values)
ydim = len(uniqueUnits)
totalNumBins = int(np.floor(max(spikeTimes.time.values)/(binSize/1000)))
numBinPerTrial = int(np.floor(trialDur/binSize))
if numTrials == None: numTrials = int(np.floor(totalNumBins/T))
spikeCountsAll = np.zeros([ydim, totalNumBins])
spikeCountsTrial = np.zeros([numTrials,ydim,numBinPerTrial])
value_time = spikeTimes.time.values
value_unit = spikeTimes.unit.values
times = []
data = []
for yd in range(ydim):
times.append(spikeTimes.time[spikeTimes.unit == uniqueUnits[yd]])
spikeCountsAll[yd] = np.histogram(times[-1].values,totalNumBins)[0]
# pdb.set_trace()
for tr in range(numTrials):
spikeCountsTrial[tr,:,:] = spikeCountsAll[:,tr*numBinPerTrial:(tr+1)*numBinPerTrial]
data.append({'Y':spikeCountsTrial[tr,:,:]})
self.spikeTimes = spikeTimes
self.numTrials = numTrials
self.data = data
self.ydim = ydim
self.trialDur = trialDur
self.binSize = binSize
self.T = T
def simpleaxis(ax):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.get_yaxis().set_tick_params(which='major', direction='out')
ax.get_xaxis().set_tick_params(which='major', direction='out')
class Printer():
'''print things to stdout on one line dynamically.'''
def __init__(self,data):
sys.stdout.write('\r\x1b[K'+data.__str__())
sys.stdout.flush()
def stdout(message):
sys.stdout.write(message)
sys.stdout.write('\b' * len(message)) # \b: non-deleting backspace
class loadDataForGPFA_CV_comparison():
def __init__(self):
matdata = sio.loadmat('data/dat.mat')
ydim, trialDur = np.shape(matdata['dat']['spikes'][0][0][:,:-1])
numTrials = len(matdata['dat']['spikes'][0])
binSize = 20
T = int(trialDur/binSize)
data = []
allRaster = np.zeros([ydim, T*numTrials])
for tr in range(numTrials):
raster = matdata['dat']['spikes'][0][tr]
spkCts = np.zeros([ydim,T])
for t in range(T):
spkCts[:,t] = np.sum(raster[:,t*binSize:(t+1)*(binSize)],1)
data.append({'Y':spkCts})
allRaster[:,tr*T:(tr+1)*T] = spkCts
self.ydim = ydim
self.trialDur = trialDur
self.binSize = binSize
self.T = T
self.data = data
self.numTrials = numTrials
self.raster = allRaster
self.avgFR = np.sum(self.raster,1)/self.numTrials/self.trialDur*1000
class loadDataHighData():
def __init__(self,filename = 'data/ex1_spikecounts.mat'):
matdata = sio.loadmat(filename)
ydim, trialDur = np.shape(matdata['D']['data'][0][0])
binSize = 10
T = int(trialDur/binSize)
data = []
numTrials = len(matdata['D']['data'][0])
allRaster = np.zeros([ydim, T*numTrials])
for tr in range(numTrials):
raster = matdata['D']['data'][0][tr]
spkCts = np.zeros([ydim,T])
for t in range(T):
spkCts[:,t] = np.sum(raster[:,t*binSize:(t+1)*(binSize)],1)
data.append({'Y':spkCts})
allRaster[:,tr*T:(tr+1)*T] = spkCts
self.ydim = ydim
self.trialDur = trialDur
self.binSize = binSize
self.T = T
self.data = data
self.numTrials = numTrials
self.raster = allRaster
self.avgFR = np.sum(self.raster,1)/self.numTrials/self.trialDur*1000
class crossValidation():
def __init__(
self,
experiment,
numTrainingTrials = 10,
numTestTrials = 2,
maxXdim = 6,
maxEMiter = 3,
batchSize = 5,
inferenceMethod = 'laplace',
learningMethod = 'batch'):
print('Assessing optimal latent dimensionality will take a long time.')
trainingSet, testSet = splitTrainingTestDataset(experiment, numTrainingTrials, numTestTrials)
errs = []
fits = []
for xdimFit in np.arange(1,maxXdim+1):
initParams = initializeParams(xdimFit, trainingSet.ydim, trainingSet)
if learningMethod == 'batch':
fit = engine.PPGPFAfit(
experiment = trainingSet,
initParams = initParams,
inferenceMethod = inferenceMethod,
EMmode = 'Batch',
maxEMiter = maxEMiter)
predBatch,predErr = leaveOneOutPrediction(fit.optimParams, testSet)
errs.append(predErr)
if learningMethod == 'diag':
fit = engine.PPGPFAfit(
experiment = trainingSet,
initParams = initParams,
inferenceMethod = inferenceMethod,
EMmode = 'Online',
onlineParamUpdateMethod = 'diag',
maxEMiter = maxEMiter,
batchSize = batchSize)
predDiag,predErr = leaveOneOutPrediction(fit.optimParams, testSet)
errs.append(predErr)
if learningMethod == 'hess':
fit = engine.PPGPFAfit(
experiment = trainingSet,
initParams = initParams,
inferenceMethod = inferenceMethod,
EMmode = 'Online',
onlineParamUpdateMethod = 'hess',
maxEMiter = maxEMiter,
batchSize = batchSize)
predHess,predErr = leaveOneOutPrediction(fit.optimParams, testSet)
errs.append(predErr)
if learningMethod == 'grad':
fit = engine.PPGPFAfit(
experiment = trainingSet,
initParams = initParams,
inferenceMethod = inferenceMethod,
EMmode = 'Online',
onlineParamUpdateMethod = 'grad',
maxEMiter = maxEMiter,
batchSize = batchSize)
predGrad,predErr = leaveOneOutPrediction(fit.optimParams, testSet)
errs.append(predErr)
fits.append(fit)
self.inferenceMethod = inferenceMethod
self.learningMethod = learningMethod
self.optimXdim=np.argmin(errs)+1 # because python indexes from 0
self.errs = errs
self.maxXdim = maxXdim
self.fits = fits
def plotPredictionError(self):
plt.figure(figsize=(5,4))
plt.plot(np.arange(1,self.maxXdim+1),self.errs,'b.-',markersize=5,linewidth=2)
plt.legend([self.method],fontsize=9,framealpha=0.2)
plt.xlabel('Latent Dimensionality')
plt.ylabel('Error')
plt.title('Latent Dimension vs. Prediction Error')
plt.grid(which='both')
plt.tight_layout()
def splitTrainingTestDataset(experiment, numTrainingTrials, numTestTrials):
if numTestTrials + numTrainingTrials > experiment.numTrials:
print('Error: Number of training trials and test trials must sum to less than the number of available trials.')
trainingSet = copy.copy(experiment)
testSet = copy.copy(experiment)
trainingSet.data = experiment.data[:numTrainingTrials]
trainingSet.numTrials = numTrainingTrials
testSet.data = experiment.data[numTrainingTrials:numTrainingTrials+numTestTrials]
testSet.numTrials = numTestTrials
return trainingSet, testSet
def plotLeaveOneOutPrediction(pred_mode, testSet, trial, neuron):
plt.figure(figsize = (5,4))
plt.plot(pred_mode[trial][neuron],linewidth=2)
plt.plot(testSet.data[trial]['Y'][neuron],'.', markersize = 10)
plt.ylim([0,max(2,pred_mode[trial][neuron].all())])
plt.xlabel('Time ('+str(testSet.binSize)+' ms bins)')
plt.ylabel('Spike Counts')
plt.legend(['Prediction','True'])
plt.title('LNO prediction, trial ' +str(trial)+', neuron '+str(neuron))
plt.grid(which='both')
plt.tight_layout()
def leaveOneOutPrediction(params, experiment):
'''
Performs leave-one-out prediction.
'''
ydim, xdim = np.shape(params['C'])
print('Performing leave-one-out cross validation...')
y_pred_mode_all = []
pred_err_mode = 0
for tr in range(experiment.numTrials):
y_pred_mode_tr = []
for nrn in range(experiment.ydim):
# Make params without neuron# nrn
CwoNrn = np.delete(params['C'],nrn,0)
dwoNrn = np.delete(params['d'],nrn,0)
paramsSplit = {'C':CwoNrn, 'd':dwoNrn, 'tau':params['tau']}
# Make params with only neuron# nrn
C_nrn = params['C'][nrn]
d_nrn = params['d'][nrn]
# Make params big
C_big, d_big = makeCd_big(paramsSplit,experiment.T)
K_big, K = makeK_big(paramsSplit, experiment.trialDur, experiment.binSize)
K_bigInv = np.linalg.inv(K_big)
# Make data without neuron# nrn
y = np.delete(experiment.data[tr]['Y'],nrn,0)
ybar = np.ndarray.flatten(np.reshape(y, (experiment.ydim-1)*experiment.T))
xInit = np.ndarray.flatten(np.zeros([xdim*experiment.T,1]))
res = op.fmin_ncg(
f = inference.negLogPosteriorUnNorm,
x0 = xInit,
fprime = inference.negLogPosteriorUnNorm_grad,
fhess = inference.negLogPosteriorUnNorm_hess,
args = (ybar, C_big, d_big, K_bigInv, xdim, experiment.ydim-1),
disp = False,
full_output = True)
x_post_mode = np.reshape(res[0],[xdim,experiment.T])
y_pred_mode_nrn = np.exp(C_nrn.dot(x_post_mode).T + d_nrn)
pred_err_mode = pred_err_mode + np.dot(experiment.data[tr]['Y'][nrn]-y_pred_mode_nrn,experiment.data[tr]['Y'][nrn]-y_pred_mode_nrn)
y_pred_mode_tr.append(y_pred_mode_nrn)
y_pred_mode_all.append(y_pred_mode_tr)
y_pred_mode = np.asarray(y_pred_mode_all)
pred_err_mode = pred_err_mode
return y_pred_mode, pred_err_mode
def subspaceAngle(F,G):
'''Partial Translation of the MATLAB code for the article
- Principal angles between subspaces in an A-based scalar product: algorithms and perturbation estimates
Knyazev, <NAME> and Argentati, <NAME> '''
EPS = 2e-16
F = np.matrix(np.float64(F))
G = np.matrix(np.float64(G))
for i in range(F.shape[1]):
normi = np.max(F[:,i])
F[:,i] = F[:,i]/normi
for i in range(G.shape[1]):
normi = np.max(G[:,i])
G[:,i] = G[:,i]/normi
QF = np.matrix(sp.linalg.orth(F))
QG = np.matrix(sp.linalg.orth(G))
q = min(QF.shape[1],QG.shape[1])
Ys, s, Zs = sp.linalg.svd(QF.T.dot(QG))
s = np.matrix(np.diag(s))
if s.shape[0] == 1:
s = s[0]
s = np.minimum(np.diag(s),1)
theta = np.maximum(np.arccos(s),0)
return max(theta)
def saveVariables(variable, filename):
f = open(filename, 'wb')
pickle.dump(variable, f)
def openVariables(filename):
f = open(filename, 'rb')
return pickle.load(f)
def approx_jacobian(x,func,epsilon,*args):
'''Approximate the Jacobian matrix of callable function func
Parameters:
* x - The state vector at which the Jacobian matrix is desired
* func - A vector-valued function of the form f(x,*args)
* epsilon - The step size used to determine the partial derivatives. Set to None to select
the optimal step size.
* *args - Additional arguments passed to func
Returns:
An array of dimensions (lenf, lenx) where lenf is the length
of the outputs of func, and lenx is the number of inputs of func.
Notes:
The approximation is done using fourth order central difference method.
'''
if np.shape(x) == ():
n = 1
x = np.asarray([x])
else:
n = len(x)
method = 'FirstOrderCentralDifference'
method = 'FourthOrderCentralDifference'
x0 = np.asarray(x)
f0 = func(x0, *args)
if method == 'FirstOrderCentralDifference':
jac = np.zeros([len(x0),len(f0)])
df1 = np.zeros([len(x0),len(f0)])
df2 = np.zeros([len(x0),len(f0)])
dx = np.zeros(len(x0))
for i in range(len(x0)):
dx[i] = epsilon
df1[i] = func(*((x0+dx/2,)+args))
df2[i] = func(*((x0-dx/2,)+args))
jac[i] = (df1[i] - df2[i])/epsilon
dx[i] = 0.0
if method == 'FourthOrderCentralDifference':
epsilon = nd._get_epsilon(x,3,epsilon,n)/2.
jac = np.zeros([len(x0),len(f0)])
df1 = np.zeros([len(x0),len(f0)])
df2 = np.zeros([len(x0),len(f0)])
df3 = np.zeros([len(x0),len(f0)])
df4 = np.zeros([len(x0),len(f0)])
dx = np.zeros(len(x0))
for i in range(len(x0)):
dx[i] = epsilon[i]
df1[i] = -func(*((x0+2*dx,)+args))
df2[i] = 8*func(*((x0+dx,)+args))
df3[i] = -8*func(*((x0-dx,)+args))
df4[i] = func(*((x0-2*dx,)+args))
jac[i] = (df1[i]+df2[i] + df3[i] + df4[i])/(12*dx[i])
dx[i] = 0.0
return jac.transpose()
def getCdErrorBars(params, experiment, infRes):
ydim, xdim = np.shape(params['C'])
def cost(vecCd): return learning.MStepObservationCost(vecCd, xdim, ydim, experiment, infRes)
def grad(vecCd): return learning.MStepObservationCost_grad(vecCd, xdim, ydim, experiment, infRes)
vecCd = CdtoVecCd(params['C'],params['d'])
hess = nd.Jacobian(grad)
hessCd = (hess(vecCd))
invHessCd = np.linalg.inv(hessCd)#*sigma_C**2*(xdim*ydim+ydim)
errorBars = np.sqrt(np.diag(invHessCd))
return errorBars
def seenTrials(experiment, seenIdx):
seenTrials = []
seenIdx = np.asarray(seenIdx).flatten()
for idx in seenIdx:
seenTrials.append(experiment.data[idx])
seenExperiment = copy.copy(experiment)
seenExperiment.data = seenTrials
seenExperiment.numTrials = len(seenTrials)
return seenExperiment
def subsampleTrials(experiment, batchSize):
'''
Used for online EM.
'''
numTrials = len(experiment.data)
# batchTrIdx = np.random.randint(numTrials, size = batchSize)
batchTrIdx = np.random.choice(numTrials, batchSize, replace=False)
newTrials = []
for idx in batchTrIdx:
newTrials.append(experiment.data[idx])
newExperiment = copy.copy(experiment)
newExperiment.data = newTrials
newExperiment.numTrials = batchSize
newExperiment.batchTrIdx = batchTrIdx
return newExperiment
def mvnpdf(x,mean,cov):
k = len(x)
xmm = x - mean
# px = (((2*np.pi)**(-k/2)) * np.linalg.det(cov)**(-1/2)) * np.exp(-1/2*np.dot(xmm.T,np.dot(np.linalg.inv(cov),xmm)))
px = (2*np.pi)**(-k/2) * np.linalg.det(cov)**(-1/2) * np.exp(-1/2*xmm.T.dot(np.linalg.inv(cov).dot(xmm)))
return px
def mvnpdf_use_inv_cov(x,mean,invcov):
k = len(x)
xmm = x - mean
# px = (((2*np.pi)**(-k/2)) * np.linalg.det(cov)**(-1/2)) * np.exp(-1/2*np.dot(xmm.T,np.dot(np.linalg.inv(cov),xmm)))
px = (2*np.pi)**(-k/2) * np.linalg.det(invcov)**(1/2) * np.exp(-1/2*xmm.T.dot(invcov.dot(xmm)))
return px
#Homemade version of matlab tic and toc functions
def tic():
import time
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
import time
if 'startTime_for_tictoc' in globals():
print('Elapsed time is ' + str(time.time() - startTime_for_tictoc) + ' seconds.')
else:
print('Toc: start time not set')
# def getAvgFR(experiment):
def initializeParams(xdim, ydim, experiment = None):
'''Initializes Poisson-GPFA model parameters.
Parameters:
===========
* xdim : int, latent dimensionality to fit
* ydim : int, number of neurons in the dataset
* experiment : (optional) If a third optional argument of util.dataset object is given,
the fucntion returns a dictionary of parameters obtained by performing Poisson-
PCA Leave this argument empty to initialize randomly.
Returns:
========
A dictionary of model parameters.
'''
if experiment == None:
print('Initializing parameters randomly..')
params = {
'C': np.random.rand(ydim,xdim)*2 - 1,
'd': np.random.randn(ydim)*2 - 2,
'tau': np.random.rand(xdim)*0.5} # seconds
if experiment != None:
print('Initializing parameters with Poisson-PCA..')
# make a long raster from all trials called
spikes = np.zeros([experiment.ydim, experiment.T*experiment.numTrials])
for tr in range(experiment.numTrials):
spikes[:,tr*experiment.T:(tr+1)*experiment.T] = experiment.data[tr]['Y']
# get mean and cov
meanY = np.mean(spikes,1) + 1e-10
covY = np.cov(spikes)
# raise warning if there is a neuron with too few spikes
# if np.any(meanY/experiment.binSize*1000 < 3):
# print('Warning: there is a neuron with a very low firing rate.')
# moment conversion between Poisson & Gaussian with exponential nonlinearity
lamb = np.log(np.abs(covY + np.outer(meanY,meanY) - np.diag(meanY))) - np.log(np.outer(meanY,meanY))
gamma = np.log(meanY)
# PCA
evals, evecs= np.linalg.eig(lamb)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
# sort eigenvectors according to same index
evals = evals[idx]
# select the first xdim eigenvectors
evecs = evecs[:, :xdim]
initC = evecs
initd = gamma
params = {
'C': initC,
'd': initd,
# 'tau': np.linspace(0.1,1,xdim)} # seconds
'tau': np.random.rand(xdim)*0.5+0.1} # seconds
return params
def CdtoVecCd(C, d):
'''Given C,d returns vec(C,d).
Parameters:
===========
* C : numpy array of shape (xdim, ydim), loading matrix
* d : numpy array of shape (ydim, 1), offset parameter
Returns:
========
* vecCd : numpy array of shape (xdim*ydim+ydim, 1), vectorized C,d
'''
ydim,xdim = np.shape(C)
matCd = np.concatenate([C.T, np.asarray([d])]).T
vecCd = np.reshape(matCd.T, xdim*ydim + ydim)
return vecCd
def vecCdtoCd(vecCd, xdim, ydim):
'''Given vecCd, xdim, ydim, returns C,d.
Parameters:
===========
* vecCd : numpy array of shape (xdim*ydim+ydim, 1), vectorized C,d
* xdim : int, latent dimensionality
* ydim : int, number of neurons
Returns:
========
* C : numpy array of shape (xdim, ydim), loading matrix
'''
matCd = np.reshape(vecCd, [xdim+1, ydim]).T
C = matCd[:,:xdim]
d = matCd[:,xdim]
return C, d
def makeCd_big(params, T):
C_big = np.kron(params['C'],np.eye(T)).T
d_big = np.kron(np.ndarray.flatten(params['d']),np.ones(T)).T
return C_big, d_big
def makeK_big(params, trialDur, binSize, epsNoise = 0.001):
[ydim,xdim] = np.shape(params['C'])
epsSignal = 1 - epsNoise
params['tau'] = np.ndarray.flatten(params['tau'])
T = range(0,int(trialDur/binSize))
K = np.zeros([xdim, len(T), len(T)])
K_big = np.zeros([xdim*len(T), xdim*len(T)])
# Make small K (size TxT) for each xdim
for xd in range(xdim):
for i in T:
for j in T:
K[xd,i,j] = epsSignal*np.exp(-0.5*((T[i]*binSize-T[j]*binSize)**2/(params['tau'][xd]*1000)**2))
K[xd] = K[xd] + epsNoise * np.eye(len(T))
# Make big K
for xd in range(xdim):
K_big[xd*len(T):(xd+1)*len(T),xd*len(T):(xd+1)*len(T)] = K[xd]
return K_big, K
class dataset:
'''Dataset containing multiple trials of population spike counts. A dataset is sampled from the
Poisson-GPFA model as described by the equations
x ~ GP(0,K(tau)) - (1)
y ~ Poisson(exp(Cx+d)) - (2)
Attributes:
===========
* self.xdim : int, latent dimensionality.
* self.ydim : int, number of neurons.
* self.data : list of dictionaries
The nth element of the list is a dictionary containing the data such that
- self.data[n]['X'] : numpy array of shape (xdim x T)
The true latent trajectory of trial n
- self.data[n]['Y'] : numpy array of shape (ydim x T)
The spike counts of the population of trial n
* self.trialDur : int
The duration of each trial in ms. All trials must have the same length.
* self.binSize : int, the size of the bin in ms.
* self.T : int, the number of bins in each trial.
* self.numTrials : int, the number of trials in the dataset.
* self.seed : int, seed used to generate the dataset.
* self.dOffset : float
The elements of the vector d in equation (2) are drawn from U(-2,0) + dOffset.
* self.drawSameX : bool, if True, all trials have the same latent trajectory.
* self.avgFR : float
Population average firing rate in Hz. Returned by the bound method self.getAvgFiringRate.
Methods:
========
* self.getAvgFiringRate(self) : bound method
Computes the average firing rate of the population in Hz and returns it as the attribute
self.avgFR
* self.plotTrajectory(self, trialToShow) : bound method
Plots the latent trajectory and the spike counts of trialToShow (int).
* self.plotParams(self) : bound method, Plots the parameters.
'''
def __init__(self,
trialDur = 1000,
binSize = 10,
drawSameX = False,
numTrials = 20,
xdim = 3,
ydim = 30,
seed = 12,
dOffset = -1,
fixTau = False,
fixedTau = None,
params = None,
model = 'pgpfa'):
print('+------------- Simulated Dataset Options -------------+')
Printer.stdout((str(xdim)+' |').rjust(int(55)))
Printer.stdout('| Dimensionality of Latent State: ')
sys.stdout.flush()
print()
Printer.stdout((str(ydim)+' |').rjust(int(55)))
Printer.stdout('| Dimensionality of Observed State (# neurons): ')
sys.stdout.flush()
print()
Printer.stdout((str(trialDur)+' |').rjust(int(55)))
Printer.stdout('| Duration of trials (ms): ')
sys.stdout.flush()
print()
Printer.stdout((str(binSize)+' |').rjust(int(55)))
Printer.stdout('| Size of bins (ms): ')
sys.stdout.flush()
print()
Printer.stdout((str(numTrials)+' |').rjust(int(55)))
Printer.stdout('| Number of Trials: ')
sys.stdout.flush()
print()
print('+-----------------------------------------------------+')
self.trialDur = trialDur
self.binSize = binSize
self.drawSameX = drawSameX
self.numTrials = numTrials
self.xdim = xdim
self.ydim = ydim
self.seed = seed
T = range(int(self.trialDur/self.binSize))
np.random.seed(self.seed)
if params == None:
if model == 'pgpfa':
params = {
'C': np.random.rand(self.ydim, self.xdim)-0.5,
# 'd': np.random.rand(self.ydim) + dOffset,
'd': np.random.rand(self.ydim)*(-2) + dOffset,
'tau': np.abs(np.random.rand(self.xdim)) + 0.01}
if fixTau == True:
params['tau'] = fixedTau
if model == 'gpfa':
params = {
'C': np.random.rand(self.ydim, self.xdim)-0.5,
# 'd': np.random.rand(self.ydim) + dOffset,
'd': np.random.rand(self.ydim)*(-2) + dOffset,
'tau': np.abs(np.random.rand(self.xdim)) + 0.01,
'R': 10*np.diag(np.abs(np.random.rand(ydim)))}
if fixTau == True:
params['tau'] = fixedTau
self.params = params
epsSignal = 0.999
epsNoise = 0.001
K_big, K = makeK_big(params, trialDur, binSize, epsNoise)
data = []
if model == 'pgpfa':
# Draw same X for all trials
if drawSameX == True:
X0 = np.reshape(np.random.multivariate_normal(np.zeros(len(T)*xdim),K_big,1),[xdim,len(T)])
for i in range(numTrials):
data.append({
'X': X0,
'Y': np.random.poisson(lam=np.exp(np.dot(params['C'],X0)+np.transpose(np.kron(np.ones([len(T),1]),params['d']))))})
output = 'Sampling trial %d ...'%(i+1)
Printer(output)
# Draw different X for all trials
else:
for i in range(numTrials):
X = np.reshape(np.random.multivariate_normal(np.zeros(len(T)*xdim),K_big,1),[xdim,len(T)])
data.append({
'X': X,
'Y': np.random.poisson(lam=np.exp(np.dot(params['C'],X)+np.transpose(np.kron(np.ones([len(T),1]),params['d']))))})
output = 'Sampling trial %d ...'%(i+1)
Printer(output)
if model == 'gpfa':
# Draw same X for all trials
if drawSameX == True:
X0 = np.reshape(np.random.multivariate_normal(np.zeros(len(T)*xdim),K_big,1),[xdim,len(T)])
for i in range(numTrials):
data.append({
'X': X0,
'Y': np.random.multivariate_normal(
np.dot(params['C'],X0)+np.transpose(np.kron(np.ones([len(T),1]),params['d'])),
np.kron(np.ones([len(T),1]),params['R']))})
output = 'Sampling trial %d ...'%(i+1)
Printer(output)
# Draw different X for all trials
else:
for i in range(numTrials):
X = np.reshape(np.random.multivariate_normal(np.zeros(len(T)*xdim),K_big,1),[xdim,len(T)])
data.append({
'X': X,
'Y': np.random.multivariate_normal(
np.dot(params['C'],X).flatten()+np.transpose(np.kron(np.ones([len(T),1]),params['d'])).flatten(),
np.kron(np.eye(len(T)),params['R'])).reshape([ydim,len(T)])})
output = 'Sampling trial %d ...'%(i+1)
Printer(output)
self.T = len(T)
self.K_big = K_big
self.data = data
self.getAvgFiringRate()
message = '\nAverage firing rate per neuron in this dataset: %.3f Hz.' %np.mean(self.avgFR)
print(message)
self.getAllRaster()
self.getMeanAndVariance()
self.fitPolynomialToMeanVar()
def getAllRaster(self):
all_raster = np.zeros([self.ydim, len(self.data)*self.T])
for tr in range(len(self.data)):
all_raster[:,tr*self.T:(tr+1)*self.T] = self.data[tr]['Y']
self.all_raster = all_raster
def getMeanAndVariance(self):
means = np.zeros([self.ydim, self.T*len(self.data)])
variances = np.zeros([self.ydim, self.T*len(self.data)])
for tr in range(len(self.data)):
for yd in range(self.ydim):
means[yd,tr] = np.mean(self.data[tr]['Y'][yd,:])
variances[yd,tr] = np.var(self.data[tr]['Y'][yd,:])
self.means = means
self.variances = variances
def fitPolynomialToMeanVar(self):
means = self.means.flatten()
variances = self.variances.flatten()
def func(x,a,b): return a*x**b
p, cov = op.curve_fit(func, means, variances, maxfev = 100000)
self.curve_p = p
self.curve_p_cov = cov
def plotMeanVsVariance(self):
fig, ax = plt.subplots(ncols = 1, figsize = (4,4))
ax.plot(self.means.flatten(), self.variances.flatten(),'.')
ax.plot(
np.linspace(1e-2,max(np.max(self.means),np.max(self.variances)),20),
np.linspace(1e-2,max(np.max(self.means),np.max(self.variances)),20),
'g',linewidth=1)
ax.set_xlim([1e-2,max(np.max(self.means),np.max(self.variances))])
ax.set_ylim([1e-2,max(np.max(self.means),np.max(self.variances))])
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('Mean Spike Count')
ax.set_ylabel('Variance of Spike Count')
if hasattr(self,'curve_p'):
x = np.linspace(1e-2,max(np.max(self.means),np.max(self.variances)),20)
y = self.curve_p[0]*x**self.curve_p[1]
ax.plot(x,y,'r',linewidth=1)
plt.legend(['Neuron/Trial','x=y','$f(x) = ax^b$\na=%.2f,b=%.2f'%(self.curve_p[0],self.curve_p[1])],
frameon = False, framealpha = 0, fontsize = 10,loc = 'best')
plt.tight_layout()
ax.grid(which='major')
simpleaxis(ax)
def getAvgFiringRate(self):
avgFR = np.zeros(self.ydim)
totalSpkCt = 0
for i in range(self.numTrials):
avgFR = avgFR + np.sum(self.data[i]['Y'],1)
totalSpkCt += np.sum(self.data[i]['Y'])
avgFR = avgFR/self.numTrials/(self.trialDur/1000)
self.avgFR = avgFR
self.totalSpkCt = totalSpkCt
def plotTrajectory(self, trialToShow = 0):
'''
Plots ground truth latent trajectory, spike counts, parameters
'''
fig1, (ax0,ax1) = plt.subplots(nrows = 2, sharex = True, figsize = (5,4))
raster = ax0.imshow(self.data[trialToShow]['Y'],
interpolation = "nearest", aspect = 'auto', cmap = 'gray_r')
# raster.set_cmap('spectral')
ax0.set_ylabel('Neuron Index')
ax0.set_title('Binned Spike Counts')
ax1.plot(range(self.T),self.data[trialToShow]['X'].T,linewidth=2)
ax1.set_xlabel('Time ('+str(self.T)+' ms bins)')
ax1.set_title('Ground Truth Latent Trajectory')
ax1.set_xlim([0,self.T])
ax1.grid(which='both')
plt.tight_layout()
def plotParams(self):
gs = gridspec.GridSpec(2,2)
ax_C = plt.subplot(gs[0,0])
ax_d = plt.subplot(gs[1,0])
ax_K = plt.subplot(gs[:,1])
ax_C.imshow(self.datasetDetails['params']['C'].T, interpolation = "nearest")
ax_C.set_title('$C_{true}$')
ax_C.set_ylabel('Latent Dimension Index')
ax_C.set_xlabel('Neuron Index')
ax_C.set_yticks(range(self.xdim))
ax_d.plot(self.datasetDetails['params']['d'].T)
ax_d.set_title('$d_{true}$')
ax_d.set_xlabel('Neuron Index')
ax_K.imshow(self.K_big, interpolation = "nearest")
ax_K.set_title('$K_{tau_{true}}$')
plt.tight_layout()
class MATLABdataset():
def __init__(self,datfilename, paramfilename = None):
dataPPGPFA = sio.loadmat(datfilename)
data = []
ydim, T = np.shape(dataPPGPFA['dataPPGPFA'][0,0]['spkcount'])
# xdim, trash = np.shape(dataPPGPFA['dataPPGPFA'][0,0]['x'])
trialDur = int(dataPPGPFA['dataPPGPFA'][0,0]['trialDur']*1000)
binSize = int(trialDur/T)
numTrials = len(dataPPGPFA['dataPPGPFA'].T)
for i in range(numTrials):
data.append({
'Y':dataPPGPFA['dataPPGPFA'][0,i]['spkcount']})
# 'X':dataPPGPFA['dataPPGPFA'][0,i]['x']})
self.data = data
self.ydim = ydim
# self.xdim = xdim
self.T = T
self.trialDur = trialDur
self.binSize = binSize
self.numTrials = numTrials
if paramfilename != None:
importedParams = sio.loadmat(paramfilename)
initParams = importedParams['initParams']
tau = np.ndarray.flatten(initParams['tau'][0][0])
C = initParams['C'][0][0]
d = np.ndarray.flatten(initParams['d'][0][0])
self.initParams = {'tau': tau, 'C':C, 'd':d} | [
"sys.stdout.write",
"pickle.dump",
"numpy.random.seed",
"numpy.sum",
"scipy.io.loadmat",
"numpy.floor",
"numpy.ones",
"numpy.argmin",
"matplotlib.pylab.gca",
"numpy.shape",
"numpy.argsort",
"pickle.load",
"sys.stdout.flush",
"numpy.arange",
"numpy.mean",
"numpy.histogram",
"numpy.exp... | [((753, 787), 'numpy.dot', 'np.dot', (["params['C']", "params['C'].T"], {}), "(params['C'], params['C'].T)\n", (759, 787), True, 'import numpy as np\n'), ((904, 920), 'numpy.zeros', 'np.zeros', (['[n, n]'], {}), '([n, n])\n', (912, 920), True, 'import numpy as np\n'), ((1745, 1754), 'matplotlib.pylab.gca', 'plt.gca', ([], {}), '()\n', (1752, 1754), True, 'import matplotlib.pylab as plt\n'), ((9522, 9543), 'copy.copy', 'copy.copy', (['experiment'], {}), '(experiment)\n', (9531, 9543), False, 'import copy\n'), ((9558, 9579), 'copy.copy', 'copy.copy', (['experiment'], {}), '(experiment)\n', (9567, 9579), False, 'import copy\n'), ((9923, 9949), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\n', (9933, 9949), True, 'import matplotlib.pylab as plt\n'), ((9955, 10002), 'matplotlib.pylab.plot', 'plt.plot', (['pred_mode[trial][neuron]'], {'linewidth': '(2)'}), '(pred_mode[trial][neuron], linewidth=2)\n', (9963, 10002), True, 'import matplotlib.pylab as plt\n'), ((10006, 10068), 'matplotlib.pylab.plot', 'plt.plot', (["testSet.data[trial]['Y'][neuron]", '"""."""'], {'markersize': '(10)'}), "(testSet.data[trial]['Y'][neuron], '.', markersize=10)\n", (10014, 10068), True, 'import matplotlib.pylab as plt\n'), ((10188, 10214), 'matplotlib.pylab.ylabel', 'plt.ylabel', (['"""Spike Counts"""'], {}), "('Spike Counts')\n", (10198, 10214), True, 'import matplotlib.pylab as plt\n'), ((10219, 10253), 'matplotlib.pylab.legend', 'plt.legend', (["['Prediction', 'True']"], {}), "(['Prediction', 'True'])\n", (10229, 10253), True, 'import matplotlib.pylab as plt\n'), ((10333, 10355), 'matplotlib.pylab.grid', 'plt.grid', ([], {'which': '"""both"""'}), "(which='both')\n", (10341, 10355), True, 'import matplotlib.pylab as plt\n'), ((10360, 10378), 'matplotlib.pylab.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10376, 10378), True, 'import matplotlib.pylab as plt\n'), ((10500, 10521), 'numpy.shape', 'np.shape', (["params['C']"], {}), "(params['C'])\n", (10508, 10521), True, 'import numpy as np\n'), ((12351, 12378), 'numpy.asarray', 'np.asarray', (['y_pred_mode_all'], {}), '(y_pred_mode_all)\n', (12361, 12378), True, 'import numpy as np\n'), ((13375, 13399), 'pickle.dump', 'pickle.dump', (['variable', 'f'], {}), '(variable, f)\n', (13386, 13399), False, 'import pickle\n'), ((13470, 13484), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13481, 13484), False, 'import pickle\n'), ((14404, 14417), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (14414, 14417), True, 'import numpy as np\n'), ((15657, 15678), 'numpy.shape', 'np.shape', (["params['C']"], {}), "(params['C'])\n", (15665, 15678), True, 'import numpy as np\n'), ((15942, 15959), 'statsmodels.tools.numdiff.Jacobian', 'nd.Jacobian', (['grad'], {}), '(grad)\n', (15953, 15959), True, 'import statsmodels.tools.numdiff as nd\n'), ((16003, 16024), 'numpy.linalg.inv', 'np.linalg.inv', (['hessCd'], {}), '(hessCd)\n', (16016, 16024), True, 'import numpy as np\n'), ((16314, 16335), 'copy.copy', 'copy.copy', (['experiment'], {}), '(experiment)\n', (16323, 16335), False, 'import copy\n'), ((16653, 16706), 'numpy.random.choice', 'np.random.choice', (['numTrials', 'batchSize'], {'replace': '(False)'}), '(numTrials, batchSize, replace=False)\n', (16669, 16706), True, 'import numpy as np\n'), ((16820, 16841), 'copy.copy', 'copy.copy', (['experiment'], {}), '(experiment)\n', (16829, 16841), False, 'import copy\n'), ((17737, 17748), 'time.time', 'time.time', ([], {}), '()\n', (17746, 17748), False, 'import time\n'), ((20587, 20598), 'numpy.shape', 'np.shape', (['C'], {}), '(C)\n', (20595, 20598), True, 'import numpy as np\n'), ((20664, 20703), 'numpy.reshape', 'np.reshape', (['matCd.T', '(xdim * ydim + ydim)'], {}), '(matCd.T, xdim * ydim + ydim)\n', (20674, 20703), True, 'import numpy as np\n'), ((21437, 21458), 'numpy.shape', 'np.shape', (["params['C']"], {}), "(params['C'])\n", (21445, 21458), True, 'import numpy as np\n'), ((21508, 21541), 'numpy.ndarray.flatten', 'np.ndarray.flatten', (["params['tau']"], {}), "(params['tau'])\n", (21526, 21541), True, 'import numpy as np\n'), ((1814, 1866), 'matplotlib.pylab.vlines', 'plt.vlines', (['trial', '(ith + 0.5)', '(ith + 1.5)'], {'color': 'color'}), '(trial, ith + 0.5, ith + 1.5, color=color)\n', (1824, 1866), True, 'import matplotlib.pylab as plt\n'), ((2140, 2168), 'pandas.read_pickle', 'pandas.read_pickle', (['filepath'], {}), '(filepath)\n', (2158, 2168), False, 'import pandas\n'), ((2191, 2224), 'numpy.unique', 'np.unique', (['spikeTimes.unit.values'], {}), '(spikeTimes.unit.values)\n', (2200, 2224), True, 'import numpy as np\n'), ((2492, 2522), 'numpy.zeros', 'np.zeros', (['[ydim, totalNumBins]'], {}), '([ydim, totalNumBins])\n', (2500, 2522), True, 'import numpy as np\n'), ((2550, 2593), 'numpy.zeros', 'np.zeros', (['[numTrials, ydim, numBinPerTrial]'], {}), '([numTrials, ydim, numBinPerTrial])\n', (2558, 2593), True, 'import numpy as np\n'), ((3796, 3814), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3812, 3814), False, 'import sys\n'), ((3848, 3873), 'sys.stdout.write', 'sys.stdout.write', (['message'], {}), '(message)\n', (3864, 3873), False, 'import sys\n'), ((4041, 4068), 'scipy.io.loadmat', 'sio.loadmat', (['"""data/dat.mat"""'], {}), "('data/dat.mat')\n", (4052, 4068), True, 'import scipy.io as sio\n'), ((4094, 4142), 'numpy.shape', 'np.shape', (["matdata['dat']['spikes'][0][0][:, :-1]"], {}), "(matdata['dat']['spikes'][0][0][:, :-1])\n", (4102, 4142), True, 'import numpy as np\n'), ((4288, 4319), 'numpy.zeros', 'np.zeros', (['[ydim, T * numTrials]'], {}), '([ydim, T * numTrials])\n', (4296, 4319), True, 'import numpy as np\n'), ((5024, 5045), 'scipy.io.loadmat', 'sio.loadmat', (['filename'], {}), '(filename)\n', (5035, 5045), True, 'import scipy.io as sio\n'), ((5071, 5107), 'numpy.shape', 'np.shape', (["matdata['D']['data'][0][0]"], {}), "(matdata['D']['data'][0][0])\n", (5079, 5107), True, 'import numpy as np\n'), ((5250, 5281), 'numpy.zeros', 'np.zeros', (['[ydim, T * numTrials]'], {}), '([ydim, T * numTrials])\n', (5258, 5281), True, 'import numpy as np\n'), ((6393, 6418), 'numpy.arange', 'np.arange', (['(1)', '(maxXdim + 1)'], {}), '(1, maxXdim + 1)\n', (6402, 6418), True, 'import numpy as np\n'), ((8880, 8906), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\n', (8890, 8906), True, 'import matplotlib.pylab as plt\n'), ((9001, 9054), 'matplotlib.pylab.legend', 'plt.legend', (['[self.method]'], {'fontsize': '(9)', 'framealpha': '(0.2)'}), '([self.method], fontsize=9, framealpha=0.2)\n', (9011, 9054), True, 'import matplotlib.pylab as plt\n'), ((9061, 9096), 'matplotlib.pylab.xlabel', 'plt.xlabel', (['"""Latent Dimensionality"""'], {}), "('Latent Dimensionality')\n", (9071, 9096), True, 'import matplotlib.pylab as plt\n'), ((9105, 9124), 'matplotlib.pylab.ylabel', 'plt.ylabel', (['"""Error"""'], {}), "('Error')\n", (9115, 9124), True, 'import matplotlib.pylab as plt\n'), ((9133, 9183), 'matplotlib.pylab.title', 'plt.title', (['"""Latent Dimension vs. Prediction Error"""'], {}), "('Latent Dimension vs. Prediction Error')\n", (9142, 9183), True, 'import matplotlib.pylab as plt\n'), ((9192, 9214), 'matplotlib.pylab.grid', 'plt.grid', ([], {'which': '"""both"""'}), "(which='both')\n", (9200, 9214), True, 'import matplotlib.pylab as plt\n'), ((9223, 9241), 'matplotlib.pylab.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9239, 9241), True, 'import matplotlib.pylab as plt\n'), ((12741, 12754), 'numpy.float64', 'np.float64', (['F'], {}), '(F)\n', (12751, 12754), True, 'import numpy as np\n'), ((12774, 12787), 'numpy.float64', 'np.float64', (['G'], {}), '(G)\n', (12784, 12787), True, 'import numpy as np\n'), ((12838, 12853), 'numpy.max', 'np.max', (['F[:, i]'], {}), '(F[:, i])\n', (12844, 12853), True, 'import numpy as np\n'), ((12932, 12947), 'numpy.max', 'np.max', (['G[:, i]'], {}), '(G[:, i])\n', (12938, 12947), True, 'import numpy as np\n'), ((12997, 13014), 'scipy.linalg.orth', 'sp.linalg.orth', (['F'], {}), '(F)\n', (13011, 13014), True, 'import scipy as sp\n'), ((13035, 13052), 'scipy.linalg.orth', 'sp.linalg.orth', (['G'], {}), '(G)\n', (13049, 13052), True, 'import scipy as sp\n'), ((13154, 13164), 'numpy.diag', 'np.diag', (['s'], {}), '(s)\n', (13161, 13164), True, 'import numpy as np\n'), ((13227, 13237), 'numpy.diag', 'np.diag', (['s'], {}), '(s)\n', (13234, 13237), True, 'import numpy as np\n'), ((13264, 13276), 'numpy.arccos', 'np.arccos', (['s'], {}), '(s)\n', (13273, 13276), True, 'import numpy as np\n'), ((14212, 14223), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (14220, 14223), True, 'import numpy as np\n'), ((14257, 14272), 'numpy.asarray', 'np.asarray', (['[x]'], {}), '([x])\n', (14267, 14272), True, 'import numpy as np\n'), ((15707, 15775), 'funs.learning.MStepObservationCost', 'learning.MStepObservationCost', (['vecCd', 'xdim', 'ydim', 'experiment', 'infRes'], {}), '(vecCd, xdim, ydim, experiment, infRes)\n', (15736, 15775), True, 'import funs.learning as learning\n'), ((15804, 15877), 'funs.learning.MStepObservationCost_grad', 'learning.MStepObservationCost_grad', (['vecCd', 'xdim', 'ydim', 'experiment', 'infRes'], {}), '(vecCd, xdim, ydim, experiment, infRes)\n', (15838, 15877), True, 'import funs.learning as learning\n'), ((16078, 16096), 'numpy.diag', 'np.diag', (['invHessCd'], {}), '(invHessCd)\n', (16085, 16096), True, 'import numpy as np\n'), ((19001, 19065), 'numpy.zeros', 'np.zeros', (['[experiment.ydim, experiment.T * experiment.numTrials]'], {}), '([experiment.ydim, experiment.T * experiment.numTrials])\n', (19009, 19065), True, 'import numpy as np\n'), ((19280, 19294), 'numpy.cov', 'np.cov', (['spikes'], {}), '(spikes)\n', (19286, 19294), True, 'import numpy as np\n'), ((19707, 19720), 'numpy.log', 'np.log', (['meanY'], {}), '(meanY)\n', (19713, 19720), True, 'import numpy as np\n'), ((19758, 19777), 'numpy.linalg.eig', 'np.linalg.eig', (['lamb'], {}), '(lamb)\n', (19771, 19777), True, 'import numpy as np\n'), ((21098, 21133), 'numpy.reshape', 'np.reshape', (['vecCd', '[xdim + 1, ydim]'], {}), '(vecCd, [xdim + 1, ydim])\n', (21108, 21133), True, 'import numpy as np\n'), ((24460, 24478), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (24476, 24478), False, 'import sys\n'), ((24634, 24652), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (24650, 24652), False, 'import sys\n'), ((24791, 24809), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (24807, 24809), False, 'import sys\n'), ((24941, 24959), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (24957, 24959), False, 'import sys\n'), ((25092, 25110), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (25108, 25110), False, 'import sys\n'), ((25522, 25547), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (25536, 25547), True, 'import numpy as np\n'), ((30198, 30249), 'scipy.optimize.curve_fit', 'op.curve_fit', (['func', 'means', 'variances'], {'maxfev': '(100000)'}), '(func, means, variances, maxfev=100000)\n', (30210, 30249), True, 'import scipy.optimize as op\n'), ((30361, 30398), 'matplotlib.pylab.subplots', 'plt.subplots', ([], {'ncols': '(1)', 'figsize': '(4, 4)'}), '(ncols=1, figsize=(4, 4))\n', (30373, 30398), True, 'import matplotlib.pylab as plt\n'), ((31386, 31404), 'matplotlib.pylab.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (31402, 31404), True, 'import matplotlib.pylab as plt\n'), ((31509, 31528), 'numpy.zeros', 'np.zeros', (['self.ydim'], {}), '(self.ydim)\n', (31517, 31528), True, 'import numpy as np\n'), ((31997, 32047), 'matplotlib.pylab.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'sharex': '(True)', 'figsize': '(5, 4)'}), '(nrows=2, sharex=True, figsize=(5, 4))\n', (32009, 32047), True, 'import matplotlib.pylab as plt\n'), ((32565, 32583), 'matplotlib.pylab.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (32581, 32583), True, 'import matplotlib.pylab as plt\n'), ((32625, 32648), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(2)', '(2)'], {}), '(2, 2)\n', (32642, 32648), True, 'import matplotlib.gridspec as gridspec\n'), ((32664, 32685), 'matplotlib.pylab.subplot', 'plt.subplot', (['gs[0, 0]'], {}), '(gs[0, 0])\n', (32675, 32685), True, 'import matplotlib.pylab as plt\n'), ((32700, 32721), 'matplotlib.pylab.subplot', 'plt.subplot', (['gs[1, 0]'], {}), '(gs[1, 0])\n', (32711, 32721), True, 'import matplotlib.pylab as plt\n'), ((32736, 32757), 'matplotlib.pylab.subplot', 'plt.subplot', (['gs[:, 1]'], {}), '(gs[:, 1])\n', (32747, 32757), True, 'import matplotlib.pylab as plt\n'), ((33255, 33273), 'matplotlib.pylab.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (33271, 33273), True, 'import matplotlib.pylab as plt\n'), ((33377, 33401), 'scipy.io.loadmat', 'sio.loadmat', (['datfilename'], {}), '(datfilename)\n', (33388, 33401), True, 'import scipy.io as sio\n'), ((33439, 33491), 'numpy.shape', 'np.shape', (["dataPPGPFA['dataPPGPFA'][0, 0]['spkcount']"], {}), "(dataPPGPFA['dataPPGPFA'][0, 0]['spkcount'])\n", (33447, 33491), True, 'import numpy as np\n'), ((572, 598), 'numpy.linalg.det', 'np.linalg.det', (['((X + Y) / 2)'], {}), '((X + Y) / 2)\n', (585, 598), True, 'import numpy as np\n'), ((2091, 2119), 'numpy.floor', 'np.floor', (['(trialDur / binSize)'], {}), '(trialDur / binSize)\n', (2099, 2119), True, 'import numpy as np\n'), ((2367, 2395), 'numpy.floor', 'np.floor', (['(trialDur / binSize)'], {}), '(trialDur / binSize)\n', (2375, 2395), True, 'import numpy as np\n'), ((4428, 4447), 'numpy.zeros', 'np.zeros', (['[ydim, T]'], {}), '([ydim, T])\n', (4436, 4447), True, 'import numpy as np\n'), ((5386, 5405), 'numpy.zeros', 'np.zeros', (['[ydim, T]'], {}), '([ydim, T])\n', (5394, 5405), True, 'import numpy as np\n'), ((8704, 8719), 'numpy.argmin', 'np.argmin', (['errs'], {}), '(errs)\n', (8713, 8719), True, 'import numpy as np\n'), ((8923, 8953), 'numpy.arange', 'np.arange', (['(1)', '(self.maxXdim + 1)'], {}), '(1, self.maxXdim + 1)\n', (8932, 8953), True, 'import numpy as np\n'), ((10808, 10838), 'numpy.delete', 'np.delete', (["params['C']", 'nrn', '(0)'], {}), "(params['C'], nrn, 0)\n", (10817, 10838), True, 'import numpy as np\n'), ((10858, 10888), 'numpy.delete', 'np.delete', (["params['d']", 'nrn', '(0)'], {}), "(params['d'], nrn, 0)\n", (10867, 10888), True, 'import numpy as np\n'), ((11287, 11307), 'numpy.linalg.inv', 'np.linalg.inv', (['K_big'], {}), '(K_big)\n', (11300, 11307), True, 'import numpy as np\n'), ((11369, 11412), 'numpy.delete', 'np.delete', (["experiment.data[tr]['Y']", 'nrn', '(0)'], {}), "(experiment.data[tr]['Y'], nrn, 0)\n", (11378, 11412), True, 'import numpy as np\n'), ((11589, 11842), 'scipy.optimize.fmin_ncg', 'op.fmin_ncg', ([], {'f': 'inference.negLogPosteriorUnNorm', 'x0': 'xInit', 'fprime': 'inference.negLogPosteriorUnNorm_grad', 'fhess': 'inference.negLogPosteriorUnNorm_hess', 'args': '(ybar, C_big, d_big, K_bigInv, xdim, experiment.ydim - 1)', 'disp': '(False)', 'full_output': '(True)'}), '(f=inference.negLogPosteriorUnNorm, x0=xInit, fprime=inference.\n negLogPosteriorUnNorm_grad, fhess=inference.negLogPosteriorUnNorm_hess,\n args=(ybar, C_big, d_big, K_bigInv, xdim, experiment.ydim - 1), disp=\n False, full_output=True)\n', (11600, 11842), True, 'import scipy.optimize as op\n'), ((11981, 12021), 'numpy.reshape', 'np.reshape', (['res[0]', '[xdim, experiment.T]'], {}), '(res[0], [xdim, experiment.T])\n', (11991, 12021), True, 'import numpy as np\n'), ((14945, 14978), 'statsmodels.tools.numdiff._get_epsilon', 'nd._get_epsilon', (['x', '(3)', 'epsilon', 'n'], {}), '(x, 3, epsilon, n)\n', (14960, 14978), True, 'import statsmodels.tools.numdiff as nd\n'), ((16191, 16210), 'numpy.asarray', 'np.asarray', (['seenIdx'], {}), '(seenIdx)\n', (16201, 16210), True, 'import numpy as np\n'), ((19239, 19257), 'numpy.mean', 'np.mean', (['spikes', '(1)'], {}), '(spikes, 1)\n', (19246, 19257), True, 'import numpy as np\n'), ((19792, 19809), 'numpy.argsort', 'np.argsort', (['evals'], {}), '(evals)\n', (19802, 19809), True, 'import numpy as np\n'), ((21255, 21264), 'numpy.eye', 'np.eye', (['T'], {}), '(T)\n', (21261, 21264), True, 'import numpy as np\n'), ((21288, 21319), 'numpy.ndarray.flatten', 'np.ndarray.flatten', (["params['d']"], {}), "(params['d'])\n", (21306, 21319), True, 'import numpy as np\n'), ((21320, 21330), 'numpy.ones', 'np.ones', (['T'], {}), '(T)\n', (21327, 21330), True, 'import numpy as np\n'), ((29196, 29215), 'numpy.mean', 'np.mean', (['self.avgFR'], {}), '(self.avgFR)\n', (29203, 29215), True, 'import numpy as np\n'), ((31201, 31371), 'matplotlib.pylab.legend', 'plt.legend', (['[\'Neuron/Trial\', \'x=y\', """$f(x) = ax^b$\na=%.2f,b=%.2f""" % (self.curve_p[0\n ], self.curve_p[1])]'], {'frameon': '(False)', 'framealpha': '(0)', 'fontsize': '(10)', 'loc': '"""best"""'}), '([\'Neuron/Trial\', \'x=y\', """$f(x) = ax^b$\na=%.2f,b=%.2f""" % (\n self.curve_p[0], self.curve_p[1])], frameon=False, framealpha=0,\n fontsize=10, loc=\'best\')\n', (31211, 31371), True, 'import matplotlib.pylab as plt\n'), ((31674, 31699), 'numpy.sum', 'np.sum', (["self.data[i]['Y']"], {}), "(self.data[i]['Y'])\n", (31680, 31699), True, 'import numpy as np\n'), ((34163, 34189), 'scipy.io.loadmat', 'sio.loadmat', (['paramfilename'], {}), '(paramfilename)\n', (34174, 34189), True, 'import scipy.io as sio\n'), ((34263, 34306), 'numpy.ndarray.flatten', 'np.ndarray.flatten', (["initParams['tau'][0][0]"], {}), "(initParams['tau'][0][0])\n", (34281, 34306), True, 'import numpy as np\n'), ((34361, 34402), 'numpy.ndarray.flatten', 'np.ndarray.flatten', (["initParams['d'][0][0]"], {}), "(initParams['d'][0][0])\n", (34379, 34402), True, 'import numpy as np\n'), ((808, 821), 'numpy.diag', 'np.diag', (['lamb'], {}), '(lamb)\n', (815, 821), True, 'import numpy as np\n'), ((2441, 2467), 'numpy.floor', 'np.floor', (['(totalNumBins / T)'], {}), '(totalNumBins / T)\n', (2449, 2467), True, 'import numpy as np\n'), ((2860, 2904), 'numpy.histogram', 'np.histogram', (['times[-1].values', 'totalNumBins'], {}), '(times[-1].values, totalNumBins)\n', (2872, 2904), True, 'import numpy as np\n'), ((4508, 4559), 'numpy.sum', 'np.sum', (['raster[:, t * binSize:(t + 1) * binSize]', '(1)'], {}), '(raster[:, t * binSize:(t + 1) * binSize], 1)\n', (4514, 4559), True, 'import numpy as np\n'), ((5466, 5517), 'numpy.sum', 'np.sum', (['raster[:, t * binSize:(t + 1) * binSize]', '(1)'], {}), '(raster[:, t * binSize:(t + 1) * binSize], 1)\n', (5472, 5517), True, 'import numpy as np\n'), ((6576, 6713), 'funs.engine.PPGPFAfit', 'engine.PPGPFAfit', ([], {'experiment': 'trainingSet', 'initParams': 'initParams', 'inferenceMethod': 'inferenceMethod', 'EMmode': '"""Batch"""', 'maxEMiter': 'maxEMiter'}), "(experiment=trainingSet, initParams=initParams,\n inferenceMethod=inferenceMethod, EMmode='Batch', maxEMiter=maxEMiter)\n", (6592, 6713), True, 'import funs.engine as engine\n'), ((7009, 7204), 'funs.engine.PPGPFAfit', 'engine.PPGPFAfit', ([], {'experiment': 'trainingSet', 'initParams': 'initParams', 'inferenceMethod': 'inferenceMethod', 'EMmode': '"""Online"""', 'onlineParamUpdateMethod': '"""diag"""', 'maxEMiter': 'maxEMiter', 'batchSize': 'batchSize'}), "(experiment=trainingSet, initParams=initParams,\n inferenceMethod=inferenceMethod, EMmode='Online',\n onlineParamUpdateMethod='diag', maxEMiter=maxEMiter, batchSize=batchSize)\n", (7025, 7204), True, 'import funs.engine as engine\n'), ((7551, 7746), 'funs.engine.PPGPFAfit', 'engine.PPGPFAfit', ([], {'experiment': 'trainingSet', 'initParams': 'initParams', 'inferenceMethod': 'inferenceMethod', 'EMmode': '"""Online"""', 'onlineParamUpdateMethod': '"""hess"""', 'maxEMiter': 'maxEMiter', 'batchSize': 'batchSize'}), "(experiment=trainingSet, initParams=initParams,\n inferenceMethod=inferenceMethod, EMmode='Online',\n onlineParamUpdateMethod='hess', maxEMiter=maxEMiter, batchSize=batchSize)\n", (7567, 7746), True, 'import funs.engine as engine\n'), ((8093, 8288), 'funs.engine.PPGPFAfit', 'engine.PPGPFAfit', ([], {'experiment': 'trainingSet', 'initParams': 'initParams', 'inferenceMethod': 'inferenceMethod', 'EMmode': '"""Online"""', 'onlineParamUpdateMethod': '"""grad"""', 'maxEMiter': 'maxEMiter', 'batchSize': 'batchSize'}), "(experiment=trainingSet, initParams=initParams,\n inferenceMethod=inferenceMethod, EMmode='Online',\n onlineParamUpdateMethod='grad', maxEMiter=maxEMiter, batchSize=batchSize)\n", (8109, 8288), True, 'import funs.engine as engine\n'), ((11449, 11500), 'numpy.reshape', 'np.reshape', (['y', '((experiment.ydim - 1) * experiment.T)'], {}), '(y, (experiment.ydim - 1) * experiment.T)\n', (11459, 11500), True, 'import numpy as np\n'), ((11538, 11572), 'numpy.zeros', 'np.zeros', (['[xdim * experiment.T, 1]'], {}), '([xdim * experiment.T, 1])\n', (11546, 11572), True, 'import numpy as np\n'), ((12135, 12244), 'numpy.dot', 'np.dot', (["(experiment.data[tr]['Y'][nrn] - y_pred_mode_nrn)", "(experiment.data[tr]['Y'][nrn] - y_pred_mode_nrn)"], {}), "(experiment.data[tr]['Y'][nrn] - y_pred_mode_nrn, experiment.data[tr]\n ['Y'][nrn] - y_pred_mode_nrn)\n", (12141, 12244), True, 'import numpy as np\n'), ((17194, 17212), 'numpy.linalg.det', 'np.linalg.det', (['cov'], {}), '(cov)\n', (17207, 17212), True, 'import numpy as np\n'), ((17514, 17535), 'numpy.linalg.det', 'np.linalg.det', (['invcov'], {}), '(invcov)\n', (17527, 17535), True, 'import numpy as np\n'), ((18807, 18827), 'numpy.random.rand', 'np.random.rand', (['xdim'], {}), '(xdim)\n', (18821, 18827), True, 'import numpy as np\n'), ((19668, 19690), 'numpy.outer', 'np.outer', (['meanY', 'meanY'], {}), '(meanY, meanY)\n', (19676, 19690), True, 'import numpy as np\n'), ((20632, 20647), 'numpy.asarray', 'np.asarray', (['[d]'], {}), '([d])\n', (20642, 20647), True, 'import numpy as np\n'), ((29857, 29891), 'numpy.mean', 'np.mean', (["self.data[tr]['Y'][yd, :]"], {}), "(self.data[tr]['Y'][yd, :])\n", (29864, 29891), True, 'import numpy as np\n'), ((29926, 29959), 'numpy.var', 'np.var', (["self.data[tr]['Y'][yd, :]"], {}), "(self.data[tr]['Y'][yd, :])\n", (29932, 29959), True, 'import numpy as np\n'), ((31620, 31648), 'numpy.sum', 'np.sum', (["self.data[i]['Y']", '(1)'], {}), "(self.data[i]['Y'], 1)\n", (31626, 31648), True, 'import numpy as np\n'), ((1120, 1142), 'numpy.exp', 'np.exp', (['(lamb[i, j] / 2)'], {}), '(lamb[i, j] / 2)\n', (1126, 1142), True, 'import numpy as np\n'), ((4861, 4883), 'numpy.sum', 'np.sum', (['self.raster', '(1)'], {}), '(self.raster, 1)\n', (4867, 4883), True, 'import numpy as np\n'), ((5819, 5841), 'numpy.sum', 'np.sum', (['self.raster', '(1)'], {}), '(self.raster, 1)\n', (5825, 5841), True, 'import numpy as np\n'), ((18709, 18735), 'numpy.random.rand', 'np.random.rand', (['ydim', 'xdim'], {}), '(ydim, xdim)\n', (18723, 18735), True, 'import numpy as np\n'), ((18759, 18780), 'numpy.random.randn', 'np.random.randn', (['ydim'], {}), '(ydim)\n', (18774, 18780), True, 'import numpy as np\n'), ((20191, 20211), 'numpy.random.rand', 'np.random.rand', (['xdim'], {}), '(xdim)\n', (20205, 20211), True, 'import numpy as np\n'), ((21830, 21923), 'numpy.exp', 'np.exp', (["(-0.5 * ((T[i] * binSize - T[j] * binSize) ** 2 / (params['tau'][xd] * 1000\n ) ** 2))"], {}), "(-0.5 * ((T[i] * binSize - T[j] * binSize) ** 2 / (params['tau'][xd] *\n 1000) ** 2))\n", (21836, 21923), True, 'import numpy as np\n'), ((30520, 30538), 'numpy.max', 'np.max', (['self.means'], {}), '(self.means)\n', (30526, 30538), True, 'import numpy as np\n'), ((30539, 30561), 'numpy.max', 'np.max', (['self.variances'], {}), '(self.variances)\n', (30545, 30561), True, 'import numpy as np\n'), ((30601, 30619), 'numpy.max', 'np.max', (['self.means'], {}), '(self.means)\n', (30607, 30619), True, 'import numpy as np\n'), ((30620, 30642), 'numpy.max', 'np.max', (['self.variances'], {}), '(self.variances)\n', (30626, 30642), True, 'import numpy as np\n'), ((30708, 30726), 'numpy.max', 'np.max', (['self.means'], {}), '(self.means)\n', (30714, 30726), True, 'import numpy as np\n'), ((30727, 30749), 'numpy.max', 'np.max', (['self.variances'], {}), '(self.variances)\n', (30733, 30749), True, 'import numpy as np\n'), ((30783, 30801), 'numpy.max', 'np.max', (['self.means'], {}), '(self.means)\n', (30789, 30801), True, 'import numpy as np\n'), ((30802, 30824), 'numpy.max', 'np.max', (['self.variances'], {}), '(self.variances)\n', (30808, 30824), True, 'import numpy as np\n'), ((31050, 31068), 'numpy.max', 'np.max', (['self.means'], {}), '(self.means)\n', (31056, 31068), True, 'import numpy as np\n'), ((31069, 31091), 'numpy.max', 'np.max', (['self.variances'], {}), '(self.variances)\n', (31075, 31091), True, 'import numpy as np\n'), ((1030, 1052), 'numpy.exp', 'np.exp', (['(lamb[i, i] / 2)'], {}), '(lamb[i, i] / 2)\n', (1036, 1052), True, 'import numpy as np\n'), ((19642, 19656), 'numpy.diag', 'np.diag', (['meanY'], {}), '(meanY)\n', (19649, 19656), True, 'import numpy as np\n'), ((25661, 25697), 'numpy.random.rand', 'np.random.rand', (['self.ydim', 'self.xdim'], {}), '(self.ydim, self.xdim)\n', (25675, 25697), True, 'import numpy as np\n'), ((26067, 26103), 'numpy.random.rand', 'np.random.rand', (['self.ydim', 'self.xdim'], {}), '(self.ydim, self.xdim)\n', (26081, 26103), True, 'import numpy as np\n'), ((17245, 17263), 'numpy.linalg.inv', 'np.linalg.inv', (['cov'], {}), '(cov)\n', (17258, 17263), True, 'import numpy as np\n'), ((17859, 17870), 'time.time', 'time.time', ([], {}), '()\n', (17868, 17870), False, 'import time\n'), ((19618, 19640), 'numpy.outer', 'np.outer', (['meanY', 'meanY'], {}), '(meanY, meanY)\n', (19626, 19640), True, 'import numpy as np\n'), ((25792, 25817), 'numpy.random.rand', 'np.random.rand', (['self.ydim'], {}), '(self.ydim)\n', (25806, 25817), True, 'import numpy as np\n'), ((25868, 25893), 'numpy.random.rand', 'np.random.rand', (['self.xdim'], {}), '(self.xdim)\n', (25882, 25893), True, 'import numpy as np\n'), ((26198, 26223), 'numpy.random.rand', 'np.random.rand', (['self.ydim'], {}), '(self.ydim)\n', (26212, 26223), True, 'import numpy as np\n'), ((26274, 26299), 'numpy.random.rand', 'np.random.rand', (['self.xdim'], {}), '(self.xdim)\n', (26288, 26299), True, 'import numpy as np\n'), ((26352, 26372), 'numpy.random.rand', 'np.random.rand', (['ydim'], {}), '(ydim)\n', (26366, 26372), True, 'import numpy as np\n'), ((28102, 28125), 'numpy.dot', 'np.dot', (["params['C']", 'X0'], {}), "(params['C'], X0)\n", (28108, 28125), True, 'import numpy as np\n'), ((26998, 27021), 'numpy.dot', 'np.dot', (["params['C']", 'X0'], {}), "(params['C'], X0)\n", (27004, 27021), True, 'import numpy as np\n'), ((27517, 27539), 'numpy.dot', 'np.dot', (["params['C']", 'X'], {}), "(params['C'], X)\n", (27523, 27539), True, 'import numpy as np\n'), ((28720, 28742), 'numpy.dot', 'np.dot', (["params['C']", 'X'], {}), "(params['C'], X)\n", (28726, 28742), True, 'import numpy as np\n')] |
import numpy as np
input_dir = '/datahouse/yurl/TalkingData/P3-resample/'
output_dir = '/datahouse/yurl/TalkingData/P3-resample/'
filename = 'test-10000-15-800-2-100-13'
def sample_encoder_decoder(arr, percent, mode='random'):
import math
n = int(math.ceil(len(arr) * percent))
# if n == 1:
# return [arr[0]]
# else:
# gap = min(len(arr) - 1, len(arr) // (n - 1))
if mode == 'random':
en_inds = [i for i in range(len(arr))]
np.random.seed(int(2018 * percent))
if len(en_inds) > 0:
en_inds = np.random.choice(en_inds, n, replace=False)
en_inds.sort()
de_inds = [i for i in range(len(arr)) if i not in en_inds]
np.random.seed(int(2018 * percent))
if len(de_inds) > 0:
de_inds = np.random.choice(de_inds, min(200, len(arr) - n), replace=False)
de_inds.sort()
encoder_data = [arr[i] for i in en_inds]
decoder_data = [arr[i] for i in de_inds]
return encoder_data, decoder_data
trajectory = [x.rstrip() for x in open(input_dir + filename)]
for p in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]:
print(p)
en_file = open(output_dir + filename + '-' + str(p) + '-' + 'encoder', 'w')
de_file = open(output_dir + filename + '-' + str(p) + '-' + 'decoder', 'w')
for x in trajectory:
encoder, decoder = sample_encoder_decoder(x.split('|'), p, 'random')
if len(encoder) > 0 and len(decoder) > 0:
en_file.write('|'.join(encoder))
en_file.write('\n')
de_file.write('|'.join(decoder))
de_file.write('\n')
en_file.close()
de_file.close()
| [
"numpy.random.choice"
] | [((533, 576), 'numpy.random.choice', 'np.random.choice', (['en_inds', 'n'], {'replace': '(False)'}), '(en_inds, n, replace=False)\n', (549, 576), True, 'import numpy as np\n')] |
import random
import numpy as np
def display_cave(matrix):
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
char = "#" if matrix[i][j] == WALL else "."
print(char, end='')
print()
# the cave size
shape = (15,30)
# walls will be 0
# floors will be 1
WALL = 0
FLOOR = 1
fill_prob = 0.25
new_map = np.ones(shape)
for i in range(shape[0]):
for j in range(shape[1]):
choice = random.uniform(0, 1)
new_map[i][j] = WALL if choice < fill_prob else FLOOR
# run for given generations
generations = 5
for generation in range(generations):
for i in range(shape[0]):
for j in range(shape[1]):
# get the number of walls 1 away from each index
# get the number of walls 2 away from each index
submap = new_map[max(i-1, 0):min(i+2, new_map.shape[0]),max(j-1, 0):min(j+2, new_map.shape[1])]
wallcount_1away = len(np.where(submap.flatten() == WALL)[0])
submap = new_map[max(i-2, 0):min(i+3, new_map.shape[0]),max(j-2, 0):min(j+3, new_map.shape[1])]
wallcount_2away = len(np.where(submap.flatten() == WALL)[0])
# this consolidates walls
# for first five generations build a scaffolding of walls
if generation < 5:
# if looking 1 away in all directions you see 5 or more walls
# consolidate this point into a wall, if that doesnt happpen
# and if looking 2 away in all directions you see less than
# 7 walls, add a wall, this consolidates and adds walls
if wallcount_1away >= 5 or wallcount_2away <= 7:
new_map[i][j] = WALL
else:
new_map[i][j] = FLOOR
# this consolidates open space, fills in standalone walls,
# after generation 5 consolidate walls and increase walking space
# if there are more than 5 walls nearby make that point a wall,
# otherwise add a floor
else:
# if looking 1 away in all direction you see 5 walls
# consolidate this point into a wall,
if wallcount_1away >= 5:
new_map[i][j] = WALL
else:
new_map[i][j] = FLOOR
display_cave(new_map) | [
"numpy.ones",
"random.uniform"
] | [((379, 393), 'numpy.ones', 'np.ones', (['shape'], {}), '(shape)\n', (386, 393), True, 'import numpy as np\n'), ((470, 490), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (484, 490), False, 'import random\n')] |
import os
import torch
import time
import contextlib
import copy
import numpy as np
from . import nest
# from src.utils.logging import INFO, WARN
__all__ = [
'batch_open',
'GlobalNames',
'Timer',
'Collections',
'build_vocab_shortlist',
'to_gpu',
'should_trigger_by_steps',
'Saver',
'BestKSaver'
]
def argsort(seq, reverse=False):
numbered_seq = [(i, e) for i, e in enumerate(seq)]
sorted_seq = sorted(numbered_seq, key=lambda p: p[1], reverse=reverse)
return [p[0] for p in sorted_seq]
# ================================================================================== #
# File I/O Utils
@contextlib.contextmanager
def batch_open(refs, mode='r'):
handlers = []
if not isinstance(refs, (list, tuple)):
refs = [refs]
for f in refs:
handlers.append(open(f, mode))
yield handlers
for h in handlers:
h.close()
class GlobalNames:
# learning rate variable name
MY_LEARNING_RATE_NAME = "learning_rate"
MY_CHECKPOINIS_PREFIX = ".ckpt"
MY_BEST_MODEL_SUFFIX = ".best"
MY_COLLECTIONS_SUFFIX = ".collections.pkl"
MY_MODEL_ARCHIVES_SUFFIX = ".archives.pkl"
USE_GPU = False
SEED = 314159
IS_MASTER = True
DIST_RANK = 0
time_format = '%Y-%m-%d %H:%M:%S'
class Timer(object):
def __init__(self):
self.t0 = 0
def tic(self):
self.t0 = time.time()
def toc(self, format='m:s', return_seconds=False):
t1 = time.time()
if return_seconds is True:
return t1 - self.t0
if format == 's':
return '{0:d}'.format(t1 - self.t0)
m, s = divmod(t1 - self.t0, 60)
if format == 'm:s':
return '%d:%02d' % (m, s)
h, m = divmod(m, 60)
return '%d:%02d:%02d' % (h, m, s)
class Collections(object):
"""Collections for logs during training.
Usually we add loss and valid metrics to some collections after some steps.
"""
_MY_COLLECTIONS_NAME = "my_collections"
def __init__(self, kv_stores=None, name=None):
self._kv_stores = kv_stores if kv_stores is not None else {}
if name is None:
name = Collections._MY_COLLECTIONS_NAME
self._name = name
def add_to_collection(self, key, value):
"""
Add value to collection
:type key: str
:param key: Key of the collection
:param value: The value which is appended to the collection
"""
if key not in self._kv_stores:
self._kv_stores[key] = [value]
else:
self._kv_stores[key].append(value)
def get_collection(self, key, default=[]):
"""
Get the collection given a key
:type key: str
:param key: Key of the collection
"""
if key not in self._kv_stores:
return default
else:
return self._kv_stores[key]
def state_dict(self):
return self._kv_stores
def load_state_dict(self, state_dict):
self._kv_stores = copy.deepcopy(state_dict)
def build_vocab_shortlist(shortlist):
shortlist_ = nest.flatten(shortlist)
shortlist_ = sorted(list(set(shortlist_)))
shortlist_np = np.array(shortlist_).astype('int64')
map_to_shortlist = dict([(wid, sid) for sid, wid in enumerate(shortlist_np)])
map_from_shortlist = dict([(item[1], item[0]) for item in map_to_shortlist.items()])
return shortlist_np, map_to_shortlist, map_from_shortlist
def to_gpu(*inputs):
return list(map(lambda x: x.cuda(), inputs))
def _min_cond_to_trigger(global_step, n_epoch, min_step=-1):
"""
If min_step is an integer within (0,10]
global_step is the minimum number of epochs to trigger action.
Otherwise it is the minimum number of steps.
"""
if min_step > 0 and min_step <= 50:
if n_epoch >= min_step:
return True
else:
return False
else:
if global_step >= min_step:
return True
else:
return False
def should_trigger_by_steps(global_step,
n_epoch,
every_n_step,
min_step=-1,
debug=False):
"""
When to trigger bleu evaluation.
"""
# Debug mode
if not GlobalNames.IS_MASTER:
return False
if debug:
return True
# Not setting condition
if every_n_step <= 0:
return False
if _min_cond_to_trigger(global_step=global_step, n_epoch=n_epoch, min_step=min_step):
if np.mod(global_step, every_n_step) == 0:
return True
else:
return False
class Saver(object):
""" Saver to save and restore objects.
Saver only accept objects which contain two method: ```state_dict``` and ```load_state_dict```
"""
def __init__(self, save_prefix, num_max_keeping=1):
self.save_prefix = save_prefix.rstrip(".")
save_dir = os.path.dirname(self.save_prefix)
if not os.path.exists(save_dir):
os.mkdir(save_dir)
self.save_dir = save_dir
if os.path.exists(self.save_prefix):
with open(self.save_prefix) as f:
save_list = f.readlines()
save_list = [line.strip() for line in save_list]
else:
save_list = []
self.save_list = save_list
self.num_max_keeping = num_max_keeping
@staticmethod
def savable(obj):
if hasattr(obj, "state_dict") and hasattr(obj, "load_state_dict"):
return True
else:
return False
def save(self, global_step, **kwargs):
state_dict = dict()
for key, obj in kwargs.items():
if self.savable(obj):
state_dict[key] = obj.state_dict() if not hasattr(obj, "module") else obj.module.state_dict()
saveto_path = '{0}.{1}'.format(self.save_prefix, global_step)
torch.save(state_dict, saveto_path)
self.save_list.append(os.path.basename(saveto_path))
if len(self.save_list) > self.num_max_keeping:
out_of_date_state_dict = self.save_list.pop(0)
os.remove(os.path.join(self.save_dir, out_of_date_state_dict))
with open(self.save_prefix, "w") as f:
f.write("\n".join(self.save_list))
def load_latest(self, **kwargs):
if len(self.save_list) == 0:
return
latest_path = os.path.join(self.save_dir, self.save_list[-1])
from torch.serialization import default_restore_location
state_dict = torch.load(latest_path, map_location=torch.device("cpu"))
for name, obj in kwargs.items():
if self.savable(obj):
if name not in state_dict:
if GlobalNames.IS_MASTER:
print("Warning: {0} has no content saved!".format(name))
else:
if GlobalNames.IS_MASTER:
print("Loading {0}".format(name))
if hasattr(obj, "module"):
obj.module.load_state_dict(state_dict[name])
else:
obj.load_state_dict(state_dict[name])
class BestKSaver(object):
""" Saving best k checkpoints with some metric.
`BestKSaver` will save checkpoints with largest k values of metric. If two checkpoints have the same
value of metric, the latest checkpoint will be saved.
"""
def __init__(self, save_prefix, num_max_keeping=1):
self.save_prefix = save_prefix.rstrip(".")
save_dir = os.path.dirname(self.save_prefix)
if not os.path.exists(save_dir):
os.mkdir(save_dir)
self.save_dir = save_dir
if os.path.exists(self.save_prefix):
with open(self.save_prefix) as f:
save_list = f.readlines()
save_names = [line.strip().split(",")[0] for line in save_list]
save_metrics = [float(line.strip().split(",")[1]) for line in save_list]
else:
save_names = []
save_metrics = []
self.save_names = save_names
self.save_metrics = save_metrics
self.num_max_keeping = num_max_keeping
@property
def num_saved(self):
return len(self.save_names)
@property
def min_save_metric(self):
if len(self.save_metrics) == 0:
return - 1e-5 # pseudo minimum value, no metric can be less than this
else:
return min(self.save_metrics)
@staticmethod
def savable(obj):
if hasattr(obj, "state_dict") and hasattr(obj, "load_state_dict"):
return True
else:
return False
def get_all_ckpt_path(self):
"""Get all the path of checkpoints contains by"""
return [os.path.join(self.save_dir, path) for path in self.save_names]
def save(self, global_step, metric, **kwargs):
# Less than minimum metric value, do not save
if metric < self.min_save_metric:
return
state_dict = dict()
for key, obj in kwargs.items():
if self.savable(obj):
state_dict[key] = obj.state_dict() if not hasattr(obj, "module") else obj.module.state_dict()
saveto_path = '{0}.{1}'.format(self.save_prefix, global_step)
torch.save(state_dict, saveto_path)
if self.num_saved == 0:
new_save_names = [os.path.basename(saveto_path), ]
new_save_metrics = [metric, ]
else:
# new metric less than i-1 th checkpoint
insert_pos = 0
for i in range(len(self.save_metrics)):
if metric >= self.save_metrics[i]:
insert_pos = i
break
new_save_names = self.save_names[:insert_pos] + [os.path.basename(saveto_path), ] \
+ self.save_names[insert_pos:]
new_save_metrics = self.save_metrics[:insert_pos] + [metric, ] + self.save_metrics[insert_pos:]
if len(new_save_names) > self.num_max_keeping:
out_of_date_name = new_save_names[-1]
os.remove(os.path.join(self.save_dir, out_of_date_name))
new_save_names = new_save_names[:-1]
new_save_metrics = new_save_metrics[:-1]
self.save_names = new_save_names
self.save_metrics = new_save_metrics
with open(self.save_prefix, "w") as f:
for ii in range(len(self.save_names)):
f.write("{0},{1}\n".format(self.save_names[ii], self.save_metrics[ii]))
def load_latest(self, **kwargs):
if len(self.save_names) == 0:
return
latest_path = os.path.join(self.save_dir, self.save_names[-1])
state_dict = torch.load(latest_path, map_location=torch.device("cpu"))
for name, obj in kwargs.items():
if self.savable(obj):
if name not in state_dict:
if GlobalNames.IS_MASTER:
print("Warning: {0} has no content saved!".format(name))
else:
if GlobalNames.IS_MASTER:
print("Loading {0}".format(name))
if hasattr(obj, "module"):
obj.module.load_state_dict(state_dict[name])
else:
obj.load_state_dict(state_dict[name])
def clean_all_checkpoints(self):
# remove all the checkpoint files
for ckpt_path in self.get_all_ckpt_path():
try:
os.remove(ckpt_path)
except:
continue
try:
os.remove(self.save_prefix)
except:
pass
# rest save list
self.save_names = []
self.save_metrics = []
def calculate_parameter_stats(model):
raw_params = sum([p.numel() for n, p in model.state_dict().items()])
params_total = sum([p.numel() for n, p in model.named_parameters()])
params_with_embedding = sum(
[p.numel() for n, p in model.named_parameters() if
n.find('embedding') == -1])
return raw_params, params_total, params_with_embedding
| [
"os.mkdir",
"copy.deepcopy",
"os.remove",
"os.path.basename",
"os.path.dirname",
"os.path.exists",
"numpy.mod",
"time.time",
"torch.save",
"numpy.array",
"torch.device",
"os.path.join"
] | [((1402, 1413), 'time.time', 'time.time', ([], {}), '()\n', (1411, 1413), False, 'import time\n'), ((1483, 1494), 'time.time', 'time.time', ([], {}), '()\n', (1492, 1494), False, 'import time\n'), ((3055, 3080), 'copy.deepcopy', 'copy.deepcopy', (['state_dict'], {}), '(state_dict)\n', (3068, 3080), False, 'import copy\n'), ((5010, 5043), 'os.path.dirname', 'os.path.dirname', (['self.save_prefix'], {}), '(self.save_prefix)\n', (5025, 5043), False, 'import os\n'), ((5163, 5195), 'os.path.exists', 'os.path.exists', (['self.save_prefix'], {}), '(self.save_prefix)\n', (5177, 5195), False, 'import os\n'), ((5987, 6022), 'torch.save', 'torch.save', (['state_dict', 'saveto_path'], {}), '(state_dict, saveto_path)\n', (5997, 6022), False, 'import torch\n'), ((6488, 6535), 'os.path.join', 'os.path.join', (['self.save_dir', 'self.save_list[-1]'], {}), '(self.save_dir, self.save_list[-1])\n', (6500, 6535), False, 'import os\n'), ((7638, 7671), 'os.path.dirname', 'os.path.dirname', (['self.save_prefix'], {}), '(self.save_prefix)\n', (7653, 7671), False, 'import os\n'), ((7791, 7823), 'os.path.exists', 'os.path.exists', (['self.save_prefix'], {}), '(self.save_prefix)\n', (7805, 7823), False, 'import os\n'), ((9386, 9421), 'torch.save', 'torch.save', (['state_dict', 'saveto_path'], {}), '(state_dict, saveto_path)\n', (9396, 9421), False, 'import torch\n'), ((10753, 10801), 'os.path.join', 'os.path.join', (['self.save_dir', 'self.save_names[-1]'], {}), '(self.save_dir, self.save_names[-1])\n', (10765, 10801), False, 'import os\n'), ((3230, 3250), 'numpy.array', 'np.array', (['shortlist_'], {}), '(shortlist_)\n', (3238, 3250), True, 'import numpy as np\n'), ((4604, 4637), 'numpy.mod', 'np.mod', (['global_step', 'every_n_step'], {}), '(global_step, every_n_step)\n', (4610, 4637), True, 'import numpy as np\n'), ((5060, 5084), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (5074, 5084), False, 'import os\n'), ((5098, 5116), 'os.mkdir', 'os.mkdir', (['save_dir'], {}), '(save_dir)\n', (5106, 5116), False, 'import os\n'), ((6054, 6083), 'os.path.basename', 'os.path.basename', (['saveto_path'], {}), '(saveto_path)\n', (6070, 6083), False, 'import os\n'), ((7688, 7712), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (7702, 7712), False, 'import os\n'), ((7726, 7744), 'os.mkdir', 'os.mkdir', (['save_dir'], {}), '(save_dir)\n', (7734, 7744), False, 'import os\n'), ((8862, 8895), 'os.path.join', 'os.path.join', (['self.save_dir', 'path'], {}), '(self.save_dir, path)\n', (8874, 8895), False, 'import os\n'), ((11715, 11742), 'os.remove', 'os.remove', (['self.save_prefix'], {}), '(self.save_prefix)\n', (11724, 11742), False, 'import os\n'), ((6222, 6273), 'os.path.join', 'os.path.join', (['self.save_dir', 'out_of_date_state_dict'], {}), '(self.save_dir, out_of_date_state_dict)\n', (6234, 6273), False, 'import os\n'), ((6659, 6678), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (6671, 6678), False, 'import torch\n'), ((9485, 9514), 'os.path.basename', 'os.path.basename', (['saveto_path'], {}), '(saveto_path)\n', (9501, 9514), False, 'import os\n'), ((10211, 10256), 'os.path.join', 'os.path.join', (['self.save_dir', 'out_of_date_name'], {}), '(self.save_dir, out_of_date_name)\n', (10223, 10256), False, 'import os\n'), ((10861, 10880), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (10873, 10880), False, 'import torch\n'), ((11624, 11644), 'os.remove', 'os.remove', (['ckpt_path'], {}), '(ckpt_path)\n', (11633, 11644), False, 'import os\n'), ((9880, 9909), 'os.path.basename', 'os.path.basename', (['saveto_path'], {}), '(saveto_path)\n', (9896, 9909), False, 'import os\n')] |
import numpy as np
import cvgutils.Viz as viz
import matplotlib.pyplot as plt
import cv2
import cvgutils.Linalg as lin
if __name__ == "__main__":
p = np.linspace(0,2*np.pi,100)
x = np.cos(p)
y = np.sin(p)
f,t = lin.xyz2pt(x,y,0)
# f = np.arctan2(y,x)
# f[f<0] += 2*np.pi
im = viz.scatter(p,f)
im = viz.get_img_from_fig(im)
plt.close()
imxy = viz.scatter(x,y)
imxy = viz.get_img_from_fig(imxy)
cv2.imwrite('renderout/atan.png',np.concatenate((im,imxy),axis=0))
| [
"cvgutils.Viz.scatter",
"cvgutils.Linalg.xyz2pt",
"matplotlib.pyplot.close",
"numpy.sin",
"numpy.cos",
"numpy.linspace",
"cvgutils.Viz.get_img_from_fig",
"numpy.concatenate"
] | [((154, 184), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(100)'], {}), '(0, 2 * np.pi, 100)\n', (165, 184), True, 'import numpy as np\n'), ((189, 198), 'numpy.cos', 'np.cos', (['p'], {}), '(p)\n', (195, 198), True, 'import numpy as np\n'), ((207, 216), 'numpy.sin', 'np.sin', (['p'], {}), '(p)\n', (213, 216), True, 'import numpy as np\n'), ((227, 246), 'cvgutils.Linalg.xyz2pt', 'lin.xyz2pt', (['x', 'y', '(0)'], {}), '(x, y, 0)\n', (237, 246), True, 'import cvgutils.Linalg as lin\n'), ((304, 321), 'cvgutils.Viz.scatter', 'viz.scatter', (['p', 'f'], {}), '(p, f)\n', (315, 321), True, 'import cvgutils.Viz as viz\n'), ((330, 354), 'cvgutils.Viz.get_img_from_fig', 'viz.get_img_from_fig', (['im'], {}), '(im)\n', (350, 354), True, 'import cvgutils.Viz as viz\n'), ((359, 370), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (368, 370), True, 'import matplotlib.pyplot as plt\n'), ((382, 399), 'cvgutils.Viz.scatter', 'viz.scatter', (['x', 'y'], {}), '(x, y)\n', (393, 399), True, 'import cvgutils.Viz as viz\n'), ((410, 436), 'cvgutils.Viz.get_img_from_fig', 'viz.get_img_from_fig', (['imxy'], {}), '(imxy)\n', (430, 436), True, 'import cvgutils.Viz as viz\n'), ((474, 508), 'numpy.concatenate', 'np.concatenate', (['(im, imxy)'], {'axis': '(0)'}), '((im, imxy), axis=0)\n', (488, 508), True, 'import numpy as np\n')] |
import torch
import numpy as np
import models.model as model
import config as c
from utils.eval_functions import err_3dpe_parallel
from utils.data_utils import reinsert_root_joint_torch, root_center_poses
import data.data_h36m as data
from scipy.cluster.vq import kmeans
print("Program is running on: ", c.device)
print("EVALUATING EXPERIMENT: ", c.experiment_name, "\n")
actions = ['Directions', 'Discussion', 'Eating', 'Greeting', 'Phoning', 'Photo', 'Posing', 'Purchases', 'Sitting',
'SittingDown', 'Smoking', 'Waiting', 'WalkDog', 'WalkTogether', 'Walking']
# load model
inn = model.poseINN()
inn.to(c.device)
inn.load(c.load_model_name, c.device)
inn.eval()
# Protocol-I
final_errors_z0_p1 = []
final_errors_mean_p1 = []
final_errors_best_p1 = []
final_errors_worst_p1 = []
final_errors_median_p1 = []
# Protocol-II
final_errors_z0_p2 = []
final_errors_mean_p2 = []
final_errors_best_p2 = []
final_errors_worst_p2 = []
final_errors_median_p2 = []
final_hypo_stddev = torch.zeros((3, 17))
quick_eval_stride = 16 # at dataset creation, every 4th frame is used => evaluate on every 64th frame
c.batch_size = 512
n_hypo = 200
std_dev = 1.0
# can select "mode poses" via k-means (see appendix of paper)
K_MEANS = False
n_clusters = 10
if K_MEANS:
f = open(c.result_dir + "eval_" + c.m_name + "_withKmeans.txt", 'w')
else:
f = open(c.result_dir + "eval_" + c.m_name + ".txt", 'w')
f.write("Evaluated on every %d-th frame with %d different hypotheses\nand standard dev of %.2f.\n\n\n" %
(quick_eval_stride*4, n_hypo, std_dev))
def eval_hypo_stddev(poses_3d):
# poses_3d.shape == (n_hypo, bs, 3, 17)
# compute var over hypos and sum over poses for correct mean estimation over all poses in dataset
return torch.sum(torch.std(poses_3d, dim=0), dim=0).cpu()
for action_idx, action in enumerate(actions):
test_dataset = data.H36MDataset(c.test_file, quick_eval=True,
quick_eval_stride=quick_eval_stride,
actions=[action], train_set=False)
loader = torch.utils.data.DataLoader(test_dataset, batch_size=c.batch_size, shuffle=False, drop_last=False)
n_poses = len(test_dataset)
total_err_z0_p1 = 0
total_err_mean_p1 = 0
total_err_worst_p1 = 0
total_err_best_p1 = 0
total_err_median_p1 = 0
total_err_z0_p2 = 0
total_err_mean_p2 = 0
total_err_worst_p2 = 0
total_err_best_p2 = 0
total_err_median_p2 = 0
hypo_stddev = torch.zeros((3, 17))
for batch_idx, sample in enumerate(loader):
x = sample['poses_3d']
y_gt = sample['p2d_hrnet']
cond = sample['gauss_fits']
bs = x.shape[0]
# 2D to 3D mapping (reverse path)
z0 = torch.zeros((bs, c.ndim_z), device=c.device)
y_z0 = torch.cat((z0, y_gt), dim=1)
with torch.no_grad():
poses_3d_z0 = inn.reverse(y_z0, cond)
poses_3d_z0 = reinsert_root_joint_torch(poses_3d_z0)
poses_3d_z0 = root_center_poses(poses_3d_z0) * 1000
x_gt = sample['p3d_gt']
total_err_z0_p1 += torch.sum(torch.mean(torch.sqrt(torch.sum((x_gt.view(bs, 3, 17)
- poses_3d_z0.view(bs, 3, 17)) ** 2,
dim=1)), dim=1)).item()
x_cpu = x_gt.cpu()
poses_3d_z0 = poses_3d_z0.cpu()
# protocol II
total_err_z0_p2 += err_3dpe_parallel(x_cpu, poses_3d_z0)
# sample multiple z
z_all = std_dev * torch.randn(n_hypo, bs, c.ndim_z, device=c.device)
y_gt = y_gt[None, :].repeat(n_hypo, 1, 1)
y_rand = torch.cat((z_all, y_gt), dim=2)
y_rand = y_rand.view(-1, c.ndim_y + c.ndim_z)
cond = cond[None].repeat(n_hypo, 1, 1).view(-1, inn.cond_in_size)
with torch.no_grad():
poses_3d_pred = inn.reverse(y_rand, cond)
poses_3d_pred = reinsert_root_joint_torch(poses_3d_pred)
poses_3d_pred = root_center_poses(poses_3d_pred) * 1000
poses_3d_pred = poses_3d_pred.view(n_hypo, bs, 3, 17)
if K_MEANS:
# reduce n_hypos to n_clusters
poses_3d_pred = poses_3d_pred.view(n_hypo, bs, 3*17).cpu().numpy()
poses_3d_km_centers = np.zeros((n_clusters, bs, 3*17), dtype=np.float32)
for idx in range(bs):
codebook, distortion = kmeans(poses_3d_pred[:, idx], k_or_guess=n_clusters)
poses_3d_km_centers[:, idx] = codebook
poses_3d_pred = torch.from_numpy(poses_3d_km_centers).view(n_clusters, bs, 3, 17).cuda()
# compute variance in x, y and z direction
hypo_stddev += eval_hypo_stddev(poses_3d_pred)
errors_proto1 = torch.mean(torch.sqrt(torch.sum((x_gt.view(bs, 3, 17)
- poses_3d_pred) ** 2, dim=2)), dim=2)
# procrustes is faster on cpu
poses_3d_pred = poses_3d_pred.cpu()
x_gt = x_gt.cpu()
if K_MEANS:
x_gt = x_gt.repeat(n_clusters, 1)
else:
x_gt = x_gt.repeat(n_hypo, 1)
errors_proto2 = err_3dpe_parallel(x_gt, poses_3d_pred.clone(), return_sum=False).view(-1, bs)
print("Evaluated on batch %d of action %s" % (batch_idx + 1, action))
# finished evaluating a single batch, need to compute hypo statistics per gt pose!
# best hypos
values, _ = torch.min(errors_proto1, dim=0)
total_err_best_p1 += torch.sum(values).item()
total_err_mean_p1 += torch.sum(torch.mean(errors_proto1, dim=0))
total_err_mean_p2 += torch.sum(torch.mean(errors_proto2, dim=0))
# worst hypos
values, _ = torch.max(errors_proto1, dim=0)
total_err_worst_p1 += torch.sum(values).item()
# median hypos
values, _ = torch.median(errors_proto1, dim=0)
total_err_median_p1 += torch.sum(values).item()
# Protocol-II:
# best hypos
values, _ = torch.min(errors_proto2, dim=0)
total_err_best_p2 += torch.sum(values).item()
# worst hypos
values, _ = torch.max(errors_proto2, dim=0)
total_err_worst_p2 += torch.sum(values).item()
# median hypos
values, _ = torch.median(errors_proto2, dim=0)
total_err_median_p2 += torch.sum(values).item()
# write result for single action to file:
f.write("Action: %s\n" % action)
f.write("3D Protocol-I z_0: %.2f\n" % (total_err_z0_p1 / n_poses))
f.write("3D Protocol-I best hypo: %.2f\n" % (total_err_best_p1 / n_poses))
f.write("3D Protocol-I median hypo: %.2f\n" % (total_err_median_p1 / n_poses))
f.write("3D Protocol-I mean hypo: %.2f\n" % (total_err_mean_p1 / n_poses))
f.write("3D Protocol-I worst hypo: %.2f\n" % (total_err_worst_p1 / n_poses))
f.write("3D Protocol-II z_0: %.2f\n" % (total_err_z0_p2 / n_poses))
f.write("3D Protocol-II best hypo: %.2f\n" % (total_err_best_p2 / n_poses))
f.write("3D Protocol-II median hypo: %.2f\n" % (total_err_median_p2 / n_poses))
f.write("3D Protocol-II mean hypo: %.2f\n" % (total_err_mean_p2 / n_poses))
f.write("3D Protocol-II worst hypo: %.2f\n" % (total_err_worst_p2 / n_poses))
f.write("\n\n")
final_errors_z0_p1.append(total_err_z0_p1 / n_poses)
final_errors_mean_p1.append(total_err_mean_p1 / n_poses)
final_errors_best_p1.append(total_err_best_p1 / n_poses)
final_errors_worst_p1.append(total_err_worst_p1 / n_poses)
final_errors_median_p1.append(total_err_median_p1 / n_poses)
final_errors_z0_p2.append(total_err_z0_p2 / n_poses)
final_errors_mean_p2.append(total_err_mean_p2 / n_poses)
final_errors_best_p2.append(total_err_best_p2 / n_poses)
final_errors_worst_p2.append(total_err_worst_p2 / n_poses)
final_errors_median_p2.append(total_err_median_p2 / n_poses)
final_hypo_stddev += (hypo_stddev / n_poses)
avg_z0_p1 = sum(final_errors_z0_p1) / len(final_errors_z0_p1)
avg_mean_p1 = sum(final_errors_mean_p1) / len(final_errors_mean_p1)
avg_best_p1 = sum(final_errors_best_p1) / len(final_errors_best_p1)
avg_worst_p1 = sum(final_errors_worst_p1) / len(final_errors_worst_p1)
avg_median_p1 = sum(final_errors_median_p1) / len(final_errors_median_p1)
avg_z0_p2 = sum(final_errors_z0_p2) / len(final_errors_z0_p2)
avg_mean_p2 = sum(final_errors_mean_p2) / len(final_errors_mean_p2)
avg_best_p2 = sum(final_errors_best_p2) / len(final_errors_best_p2)
avg_worst_p2 = sum(final_errors_worst_p2) / len(final_errors_worst_p2)
avg_median_p2 = sum(final_errors_median_p2) / len(final_errors_median_p2)
# results averaged over all actions
f.write("Average: \n")
f.write("3D Protocol-I z_0: %.2f\n" % avg_z0_p1)
f.write("3D Protocol-I best hypo: %.2f\n" % avg_best_p1)
f.write("3D Protocol-I median hypo: %.2f\n" % avg_median_p1)
f.write("3D Protocol-I mean hypo: %.2f\n" % avg_mean_p1)
f.write("3D Protocol-I worst hypo: %.2f\n" % avg_worst_p1)
f.write("3D Protocol-II z_0: %.2f\n" % avg_z0_p2)
f.write("3D Protocol-II best hypo: %.2f\n" % avg_best_p2)
f.write("3D Protocol-II median hypo: %.2f\n" % avg_median_p2)
f.write("3D Protocol-II mean hypo: %.2f\n" % avg_mean_p2)
f.write("3D Protocol-II worst hypo: %.2f\n" % avg_worst_p2)
print("\nAverage:")
print("3D Protocol-I z_0: %.2f" % avg_z0_p1)
print("3D Protocol-I best hypo: %.2f" % avg_best_p1)
print("3D Protocol-I median hypo: %.2f" % avg_median_p1)
print("3D Protocol-I mean hypo: %.2f" % avg_mean_p1)
print("3D Protocol-I worst hypo: %.2f\n" % avg_worst_p1)
print("3D Protocol-II z_0: %.2f" % avg_z0_p2)
print("3D Protocol-II best hypo: %.2f" % avg_best_p2)
print("3D Protocol-II median hypo: %.2f" % avg_median_p2)
print("3D Protocol-II mean hypo: %.2f" % avg_mean_p2)
print("3D Protocol-II worst hypo: %.2f" % avg_worst_p2)
std_dev_in_mm = final_hypo_stddev/len(actions)
# standard deviation in mm per dimension and per joint:
print("\nstd dev per joint and dim in mm:")
f.write("\n\n")
f.write("std dev per joint and dim in mm:\n")
for i in range(std_dev_in_mm.shape[1]):
print("joint %d: std_x=%.2f, std_y=%.2f, std_z=%.2f" % (i, std_dev_in_mm[0, i], std_dev_in_mm[1, i],
std_dev_in_mm[2, i]))
f.write("joint %d: std_x=%.2f, std_y=%.2f, std_z=%.2f\n" % (i, std_dev_in_mm[0, i], std_dev_in_mm[1, i],
std_dev_in_mm[2, i]))
std_dev_means = torch.mean(std_dev_in_mm, dim=1)
print("mean: std_x=%.2f, std_y=%.2f, std_z=%.2f" % (std_dev_means[0], std_dev_means[1], std_dev_means[2]))
f.write("mean: std_x=%.2f, std_y=%.2f, std_z=%.2f\n" % (std_dev_means[0], std_dev_means[1], std_dev_means[2]))
| [
"data.data_h36m.H36MDataset",
"utils.eval_functions.err_3dpe_parallel",
"torch.cat",
"torch.randn",
"torch.std",
"torch.no_grad",
"torch.median",
"torch.utils.data.DataLoader",
"models.model.poseINN",
"utils.data_utils.reinsert_root_joint_torch",
"torch.zeros",
"utils.data_utils.root_center_po... | [((597, 612), 'models.model.poseINN', 'model.poseINN', ([], {}), '()\n', (610, 612), True, 'import models.model as model\n'), ((991, 1011), 'torch.zeros', 'torch.zeros', (['(3, 17)'], {}), '((3, 17))\n', (1002, 1011), False, 'import torch\n'), ((10460, 10492), 'torch.mean', 'torch.mean', (['std_dev_in_mm'], {'dim': '(1)'}), '(std_dev_in_mm, dim=1)\n', (10470, 10492), False, 'import torch\n'), ((1873, 1996), 'data.data_h36m.H36MDataset', 'data.H36MDataset', (['c.test_file'], {'quick_eval': '(True)', 'quick_eval_stride': 'quick_eval_stride', 'actions': '[action]', 'train_set': '(False)'}), '(c.test_file, quick_eval=True, quick_eval_stride=\n quick_eval_stride, actions=[action], train_set=False)\n', (1889, 1996), True, 'import data.data_h36m as data\n'), ((2078, 2181), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': 'c.batch_size', 'shuffle': '(False)', 'drop_last': '(False)'}), '(test_dataset, batch_size=c.batch_size, shuffle=\n False, drop_last=False)\n', (2105, 2181), False, 'import torch\n'), ((2493, 2513), 'torch.zeros', 'torch.zeros', (['(3, 17)'], {}), '((3, 17))\n', (2504, 2513), False, 'import torch\n'), ((2745, 2789), 'torch.zeros', 'torch.zeros', (['(bs, c.ndim_z)'], {'device': 'c.device'}), '((bs, c.ndim_z), device=c.device)\n', (2756, 2789), False, 'import torch\n'), ((2805, 2833), 'torch.cat', 'torch.cat', (['(z0, y_gt)'], {'dim': '(1)'}), '((z0, y_gt), dim=1)\n', (2814, 2833), False, 'import torch\n'), ((2937, 2975), 'utils.data_utils.reinsert_root_joint_torch', 'reinsert_root_joint_torch', (['poses_3d_z0'], {}), '(poses_3d_z0)\n', (2962, 2975), False, 'from utils.data_utils import reinsert_root_joint_torch, root_center_poses\n'), ((3477, 3514), 'utils.eval_functions.err_3dpe_parallel', 'err_3dpe_parallel', (['x_cpu', 'poses_3d_z0'], {}), '(x_cpu, poses_3d_z0)\n', (3494, 3514), False, 'from utils.eval_functions import err_3dpe_parallel\n'), ((3688, 3719), 'torch.cat', 'torch.cat', (['(z_all, y_gt)'], {'dim': '(2)'}), '((z_all, y_gt), dim=2)\n', (3697, 3719), False, 'import torch\n'), ((3958, 3998), 'utils.data_utils.reinsert_root_joint_torch', 'reinsert_root_joint_torch', (['poses_3d_pred'], {}), '(poses_3d_pred)\n', (3983, 3998), False, 'from utils.data_utils import reinsert_root_joint_torch, root_center_poses\n'), ((5462, 5493), 'torch.min', 'torch.min', (['errors_proto1'], {'dim': '(0)'}), '(errors_proto1, dim=0)\n', (5471, 5493), False, 'import torch\n'), ((5738, 5769), 'torch.max', 'torch.max', (['errors_proto1'], {'dim': '(0)'}), '(errors_proto1, dim=0)\n', (5747, 5769), False, 'import torch\n'), ((5869, 5903), 'torch.median', 'torch.median', (['errors_proto1'], {'dim': '(0)'}), '(errors_proto1, dim=0)\n', (5881, 5903), False, 'import torch\n'), ((6024, 6055), 'torch.min', 'torch.min', (['errors_proto2'], {'dim': '(0)'}), '(errors_proto2, dim=0)\n', (6033, 6055), False, 'import torch\n'), ((6153, 6184), 'torch.max', 'torch.max', (['errors_proto2'], {'dim': '(0)'}), '(errors_proto2, dim=0)\n', (6162, 6184), False, 'import torch\n'), ((6284, 6318), 'torch.median', 'torch.median', (['errors_proto2'], {'dim': '(0)'}), '(errors_proto2, dim=0)\n', (6296, 6318), False, 'import torch\n'), ((2847, 2862), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2860, 2862), False, 'import torch\n'), ((2998, 3028), 'utils.data_utils.root_center_poses', 'root_center_poses', (['poses_3d_z0'], {}), '(poses_3d_z0)\n', (3015, 3028), False, 'from utils.data_utils import reinsert_root_joint_torch, root_center_poses\n'), ((3570, 3620), 'torch.randn', 'torch.randn', (['n_hypo', 'bs', 'c.ndim_z'], {'device': 'c.device'}), '(n_hypo, bs, c.ndim_z, device=c.device)\n', (3581, 3620), False, 'import torch\n'), ((3862, 3877), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3875, 3877), False, 'import torch\n'), ((4023, 4055), 'utils.data_utils.root_center_poses', 'root_center_poses', (['poses_3d_pred'], {}), '(poses_3d_pred)\n', (4040, 4055), False, 'from utils.data_utils import reinsert_root_joint_torch, root_center_poses\n'), ((4302, 4354), 'numpy.zeros', 'np.zeros', (['(n_clusters, bs, 3 * 17)'], {'dtype': 'np.float32'}), '((n_clusters, bs, 3 * 17), dtype=np.float32)\n', (4310, 4354), True, 'import numpy as np\n'), ((5588, 5620), 'torch.mean', 'torch.mean', (['errors_proto1'], {'dim': '(0)'}), '(errors_proto1, dim=0)\n', (5598, 5620), False, 'import torch\n'), ((5661, 5693), 'torch.mean', 'torch.mean', (['errors_proto2'], {'dim': '(0)'}), '(errors_proto2, dim=0)\n', (5671, 5693), False, 'import torch\n'), ((1765, 1791), 'torch.std', 'torch.std', (['poses_3d'], {'dim': '(0)'}), '(poses_3d, dim=0)\n', (1774, 1791), False, 'import torch\n'), ((4426, 4478), 'scipy.cluster.vq.kmeans', 'kmeans', (['poses_3d_pred[:, idx]'], {'k_or_guess': 'n_clusters'}), '(poses_3d_pred[:, idx], k_or_guess=n_clusters)\n', (4432, 4478), False, 'from scipy.cluster.vq import kmeans\n'), ((5523, 5540), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (5532, 5540), False, 'import torch\n'), ((5800, 5817), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (5809, 5817), False, 'import torch\n'), ((5935, 5952), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (5944, 5952), False, 'import torch\n'), ((6085, 6102), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (6094, 6102), False, 'import torch\n'), ((6215, 6232), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (6224, 6232), False, 'import torch\n'), ((6350, 6367), 'torch.sum', 'torch.sum', (['values'], {}), '(values)\n', (6359, 6367), False, 'import torch\n'), ((4562, 4599), 'torch.from_numpy', 'torch.from_numpy', (['poses_3d_km_centers'], {}), '(poses_3d_km_centers)\n', (4578, 4599), False, 'import torch\n')] |
"""Dataset class for dSprites
ref)
https://github.com/google-research/disentanglement_lib/blob/master/disentanglement_lib/data/ground_truth/dsprites.py
"""
from typing import Optional
import pathlib
import numpy as np
import torch
from .base_data import BaseDataset
class DSpritesDataset(BaseDataset):
"""DSprites dataset.
The data set was originally introduced in "beta-VAE: Learning Basic Visual
Concepts with a Constrained Variational Framework" and can be downloaded
from https://github.com/deepmind/dsprites-dataset.
The ground-truth factors of variation are (in the default setting):
0 - shape (3 different values)
1 - scale (6 different values)
2 - orientation (40 different values)
3 - position x (32 different values)
4 - position y (32 different values)
Args:
root (str): Path to root directory of data.
filename (str, optional): File name of dataset.
"""
def __init__(self, root: str, filename: Optional[str] = None):
super().__init__()
# Load pre-downloaded dataset
filename = "dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz" \
if filename is None else filename
path = pathlib.Path(root, filename)
with np.load(path, encoding="latin1", allow_pickle=True) as dataset:
data = torch.tensor(dataset["imgs"])
targets = torch.tensor(dataset["latents_classes"][:, 1:])
self.data = data
self.targets = targets
self.factor_sizes = [3, 6, 40, 32, 32]
def __getitem__(self, index):
# Reshape dataset (channel, height, width)
# and change dtype uint8 -> float32
return self.data[index].unsqueeze(0).float(), self.targets[index]
def __len__(self):
return self.data.size(0)
| [
"pathlib.Path",
"torch.tensor",
"numpy.load"
] | [((1206, 1234), 'pathlib.Path', 'pathlib.Path', (['root', 'filename'], {}), '(root, filename)\n', (1218, 1234), False, 'import pathlib\n'), ((1248, 1299), 'numpy.load', 'np.load', (['path'], {'encoding': '"""latin1"""', 'allow_pickle': '(True)'}), "(path, encoding='latin1', allow_pickle=True)\n", (1255, 1299), True, 'import numpy as np\n'), ((1331, 1360), 'torch.tensor', 'torch.tensor', (["dataset['imgs']"], {}), "(dataset['imgs'])\n", (1343, 1360), False, 'import torch\n'), ((1383, 1430), 'torch.tensor', 'torch.tensor', (["dataset['latents_classes'][:, 1:]"], {}), "(dataset['latents_classes'][:, 1:])\n", (1395, 1430), False, 'import torch\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.
"""Tests for scf.scf."""
import os
import tempfile
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
import jax
import numpy as np
from pyscf.lib import parameters
import tensorflow.compat.v1 as tf
from symbolic_functionals.syfes.scf import scf
from symbolic_functionals.syfes.symbolic import xc_functionals
from symbolic_functionals.syfes.xc import mgga
from symbolic_functionals.syfes.xc import utils
from symbolic_functionals.syfes.xc import xc
jax.config.update('jax_enable_x64', True)
class SCFTest(parameterized.TestCase):
def setUp(self):
super().setUp()
parameters.TMPDIR = tempfile.mkdtemp(dir=flags.FLAGS.test_tmpdir)
def test_parse_xyz(self):
xyz_path = os.path.join(flags.FLAGS.test_tmpdir, 'test.xyz')
with tf.io.gfile.GFile(xyz_path, 'w') as f:
f.write('\n0 1\nO 0. 0. 0.\nH 0. -0.757 0.587\nH 0. 0.757 0.587\n')
atom, charge, spin = scf.parse_xyz(xyz_path)
self.assertLen(atom.split(';'), 3)
self.assertEqual(charge, 0)
self.assertEqual(spin, 0)
# expected values for Etot, Exc and Exx are computed by external PySCF
@parameterized.parameters(
('pbe,pbe', 0, 0, (17812,), (6, 17812), {
'Etot': -1.1601348451265638,
'Exc': -0.6899737187913197,
'Exx': -0.6583555393862027,
'Exxlr': 0.0,
'Enlc': 0.0
}),
('pbe,pbe', -1, 1, (20048,), (2, 6, 20048), {
'Etot': -1.0336723063997342,
'Exc': -0.8723776781828819,
'Exx': -0.8141180655850809,
'Exxlr': 0.0,
'Enlc': 0.0
}),
('wb97m_v', 0, 0, (17812,), (6, 17812), {
'Etot': -1.1537971220466094,
'Exc': -0.6829720417857192,
'Exx': -0.6577521311181448,
'Exxlr': -0.29729171800068577,
'Enlc': 0.00891190761270658
}),
('wb97m_v', -1, 1, (20048,), (2, 6, 20048), {
'Etot': -1.007161017404796,
'Exc': -0.8544883116165207,
'Exx': -0.8220018420576689,
'Exxlr': -0.40928226576050875,
'Enlc': 0.012704771979755908
}),
)
def test_scf_calculation_with_pyscf(self, xc_name, charge, spin,
expected_weights_shape,
expected_rho_shape, expected_energies):
res = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc=xc_name,
basis='def2svpd')
self.assertCountEqual(
list(res.keys()),
scf.SCF_SCALAR_RESULTS + ['rho', 'weights'])
self.assertTrue(res['converged'])
self.assertEqual(res['weights'].shape, expected_weights_shape)
self.assertEqual(res['rho'].shape, expected_rho_shape)
for energy in ['Etot', 'Exc', 'Exx', 'Exxlr', 'Enlc']:
np.testing.assert_allclose(res[energy], expected_energies[energy])
@parameterized.parameters(
('lda', 'lda_x,lda_c_pw', 0, 0),
('lda', 'lda_x,lda_c_pw', -1, 1),
('pbe', 'pbe,pbe', 0, 0),
('pbe', 'pbe,pbe', -1, 1),
('b97', 'hyb_gga_xc_b97', 0, 0),
('b97', 'hyb_gga_xc_b97', -1, 1),
('wb97x_v', 'wb97x_v', 0, 0),
('wb97x_v', 'wb97x_v', -1, 1),
('b97m_v', 'b97m_v', 0, 0),
('b97m_v', 'b97m_v', -1, 1),
('wb97m_v', 'wb97m_v', 0, 0),
('wb97m_v', 'wb97m_v', -1, 1),
)
def test_scf_calculation_with_custom_xc_default_params(
self, xc_name, xc_name_libxc, charge, spin):
hybrid_coeff, rsh_params = utils.get_hybrid_rsh_params(xc_name)
res_libxc = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc=xc_name_libxc,
basis='def2svpd')
res_custom = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc=xc_name,
xc_fun=xc.make_eval_xc(xc_name),
hybrid_coeff=hybrid_coeff,
rsh_params=rsh_params,
basis='def2svpd')
for energy in ['Etot', 'Exc', 'Exx', 'Exxlr', 'Enlc']:
self.assertAlmostEqual(res_libxc[energy], res_custom[energy], delta=2e-6)
@parameterized.parameters((0, 0), (-1, 1),)
def test_scf_calculation_with_custom_xc_custom_params(self, charge, spin):
hybrid_coeff, rsh_params = utils.get_hybrid_rsh_params('b97m_v')
res_libxc = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc='b97m_v',
basis='def2svpd')
res_custom = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc='b97m_v',
xc_fun=xc.make_eval_xc('wb97m_v', params=mgga.B97MV_PARAMS),
hybrid_coeff=hybrid_coeff,
rsh_params=rsh_params,
basis='def2svpd')
for energy in ['Etot', 'Exc', 'Exx', 'Exxlr', 'Enlc']:
self.assertAlmostEqual(res_libxc[energy], res_custom[energy], delta=2e-6)
@parameterized.parameters((0, 0), (-1, 1),)
def test_scf_calculation_with_symbolic_functional(self, charge, spin):
hybrid_coeff, rsh_params = utils.get_hybrid_rsh_params('wb97m_v')
res_libxc = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc='wb97m_v',
basis='def2svpd')
res_custom = scf.run_scf_for_mol(
atom='H 0. 0. 0.;H 0. 0. 0.74',
charge=charge,
spin=spin,
xc='wb97m_v',
xc_fun=xc_functionals.wb97mv_short.make_eval_xc(
omega=rsh_params[0],
**xc_functionals.WB97MV_PARAMETERS_UTRANSFORM),
hybrid_coeff=hybrid_coeff,
rsh_params=rsh_params,
basis='def2svpd')
for energy in ['Etot', 'Exc', 'Exx', 'Exxlr', 'Enlc']:
self.assertAlmostEqual(res_libxc[energy], res_custom[energy], delta=2e-6)
if __name__ == '__main__':
absltest.main()
| [
"absl.testing.absltest.main",
"tensorflow.compat.v1.io.gfile.GFile",
"symbolic_functionals.syfes.xc.xc.make_eval_xc",
"symbolic_functionals.syfes.symbolic.xc_functionals.wb97mv_short.make_eval_xc",
"symbolic_functionals.syfes.xc.utils.get_hybrid_rsh_params",
"symbolic_functionals.syfes.scf.scf.run_scf_for... | [((1105, 1146), 'jax.config.update', 'jax.config.update', (['"""jax_enable_x64"""', '(True)'], {}), "('jax_enable_x64', True)\n", (1122, 1146), False, 'import jax\n'), ((1745, 2518), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["('pbe,pbe', 0, 0, (17812,), (6, 17812), {'Etot': -1.1601348451265638, 'Exc':\n -0.6899737187913197, 'Exx': -0.6583555393862027, 'Exxlr': 0.0, 'Enlc': 0.0}\n )", "('pbe,pbe', -1, 1, (20048,), (2, 6, 20048), {'Etot': -1.0336723063997342,\n 'Exc': -0.8723776781828819, 'Exx': -0.8141180655850809, 'Exxlr': 0.0,\n 'Enlc': 0.0})", "('wb97m_v', 0, 0, (17812,), (6, 17812), {'Etot': -1.1537971220466094, 'Exc':\n -0.6829720417857192, 'Exx': -0.6577521311181448, 'Exxlr': -\n 0.29729171800068577, 'Enlc': 0.00891190761270658})", "('wb97m_v', -1, 1, (20048,), (2, 6, 20048), {'Etot': -1.007161017404796,\n 'Exc': -0.8544883116165207, 'Exx': -0.8220018420576689, 'Exxlr': -\n 0.40928226576050875, 'Enlc': 0.012704771979755908})"], {}), "(('pbe,pbe', 0, 0, (17812,), (6, 17812), {'Etot': -\n 1.1601348451265638, 'Exc': -0.6899737187913197, 'Exx': -\n 0.6583555393862027, 'Exxlr': 0.0, 'Enlc': 0.0}), ('pbe,pbe', -1, 1, (\n 20048,), (2, 6, 20048), {'Etot': -1.0336723063997342, 'Exc': -\n 0.8723776781828819, 'Exx': -0.8141180655850809, 'Exxlr': 0.0, 'Enlc': \n 0.0}), ('wb97m_v', 0, 0, (17812,), (6, 17812), {'Etot': -\n 1.1537971220466094, 'Exc': -0.6829720417857192, 'Exx': -\n 0.6577521311181448, 'Exxlr': -0.29729171800068577, 'Enlc': \n 0.00891190761270658}), ('wb97m_v', -1, 1, (20048,), (2, 6, 20048), {\n 'Etot': -1.007161017404796, 'Exc': -0.8544883116165207, 'Exx': -\n 0.8220018420576689, 'Exxlr': -0.40928226576050875, 'Enlc': \n 0.012704771979755908}))\n", (1769, 2518), False, 'from absl.testing import parameterized\n'), ((3500, 3913), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["('lda', 'lda_x,lda_c_pw', 0, 0)", "('lda', 'lda_x,lda_c_pw', -1, 1)", "('pbe', 'pbe,pbe', 0, 0)", "('pbe', 'pbe,pbe', -1, 1)", "('b97', 'hyb_gga_xc_b97', 0, 0)", "('b97', 'hyb_gga_xc_b97', -1, 1)", "('wb97x_v', 'wb97x_v', 0, 0)", "('wb97x_v', 'wb97x_v', -1, 1)", "('b97m_v', 'b97m_v', 0, 0)", "('b97m_v', 'b97m_v', -1, 1)", "('wb97m_v', 'wb97m_v', 0, 0)", "('wb97m_v', 'wb97m_v', -1, 1)"], {}), "(('lda', 'lda_x,lda_c_pw', 0, 0), ('lda',\n 'lda_x,lda_c_pw', -1, 1), ('pbe', 'pbe,pbe', 0, 0), ('pbe', 'pbe,pbe', \n -1, 1), ('b97', 'hyb_gga_xc_b97', 0, 0), ('b97', 'hyb_gga_xc_b97', -1, \n 1), ('wb97x_v', 'wb97x_v', 0, 0), ('wb97x_v', 'wb97x_v', -1, 1), (\n 'b97m_v', 'b97m_v', 0, 0), ('b97m_v', 'b97m_v', -1, 1), ('wb97m_v',\n 'wb97m_v', 0, 0), ('wb97m_v', 'wb97m_v', -1, 1))\n", (3524, 3913), False, 'from absl.testing import parameterized\n'), ((4738, 4779), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['(0, 0)', '(-1, 1)'], {}), '((0, 0), (-1, 1))\n', (4762, 4779), False, 'from absl.testing import parameterized\n'), ((5544, 5585), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['(0, 0)', '(-1, 1)'], {}), '((0, 0), (-1, 1))\n', (5568, 5585), False, 'from absl.testing import parameterized\n'), ((6456, 6471), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (6469, 6471), False, 'from absl.testing import absltest\n'), ((1252, 1297), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'dir': 'flags.FLAGS.test_tmpdir'}), '(dir=flags.FLAGS.test_tmpdir)\n', (1268, 1297), False, 'import tempfile\n'), ((1342, 1391), 'os.path.join', 'os.path.join', (['flags.FLAGS.test_tmpdir', '"""test.xyz"""'], {}), "(flags.FLAGS.test_tmpdir, 'test.xyz')\n", (1354, 1391), False, 'import os\n'), ((1542, 1565), 'symbolic_functionals.syfes.scf.scf.parse_xyz', 'scf.parse_xyz', (['xyz_path'], {}), '(xyz_path)\n', (1555, 1565), False, 'from symbolic_functionals.syfes.scf import scf\n'), ((2942, 3056), 'symbolic_functionals.syfes.scf.scf.run_scf_for_mol', 'scf.run_scf_for_mol', ([], {'atom': '"""H 0. 0. 0.;H 0. 0. 0.74"""', 'charge': 'charge', 'spin': 'spin', 'xc': 'xc_name', 'basis': '"""def2svpd"""'}), "(atom='H 0. 0. 0.;H 0. 0. 0.74', charge=charge, spin=\n spin, xc=xc_name, basis='def2svpd')\n", (2961, 3056), False, 'from symbolic_functionals.syfes.scf import scf\n'), ((4108, 4144), 'symbolic_functionals.syfes.xc.utils.get_hybrid_rsh_params', 'utils.get_hybrid_rsh_params', (['xc_name'], {}), '(xc_name)\n', (4135, 4144), False, 'from symbolic_functionals.syfes.xc import utils\n'), ((4161, 4281), 'symbolic_functionals.syfes.scf.scf.run_scf_for_mol', 'scf.run_scf_for_mol', ([], {'atom': '"""H 0. 0. 0.;H 0. 0. 0.74"""', 'charge': 'charge', 'spin': 'spin', 'xc': 'xc_name_libxc', 'basis': '"""def2svpd"""'}), "(atom='H 0. 0. 0.;H 0. 0. 0.74', charge=charge, spin=\n spin, xc=xc_name_libxc, basis='def2svpd')\n", (4180, 4281), False, 'from symbolic_functionals.syfes.scf import scf\n'), ((4889, 4926), 'symbolic_functionals.syfes.xc.utils.get_hybrid_rsh_params', 'utils.get_hybrid_rsh_params', (['"""b97m_v"""'], {}), "('b97m_v')\n", (4916, 4926), False, 'from symbolic_functionals.syfes.xc import utils\n'), ((4943, 5058), 'symbolic_functionals.syfes.scf.scf.run_scf_for_mol', 'scf.run_scf_for_mol', ([], {'atom': '"""H 0. 0. 0.;H 0. 0. 0.74"""', 'charge': 'charge', 'spin': 'spin', 'xc': '"""b97m_v"""', 'basis': '"""def2svpd"""'}), "(atom='H 0. 0. 0.;H 0. 0. 0.74', charge=charge, spin=\n spin, xc='b97m_v', basis='def2svpd')\n", (4962, 5058), False, 'from symbolic_functionals.syfes.scf import scf\n'), ((5691, 5729), 'symbolic_functionals.syfes.xc.utils.get_hybrid_rsh_params', 'utils.get_hybrid_rsh_params', (['"""wb97m_v"""'], {}), "('wb97m_v')\n", (5718, 5729), False, 'from symbolic_functionals.syfes.xc import utils\n'), ((5746, 5862), 'symbolic_functionals.syfes.scf.scf.run_scf_for_mol', 'scf.run_scf_for_mol', ([], {'atom': '"""H 0. 0. 0.;H 0. 0. 0.74"""', 'charge': 'charge', 'spin': 'spin', 'xc': '"""wb97m_v"""', 'basis': '"""def2svpd"""'}), "(atom='H 0. 0. 0.;H 0. 0. 0.74', charge=charge, spin=\n spin, xc='wb97m_v', basis='def2svpd')\n", (5765, 5862), False, 'from symbolic_functionals.syfes.scf import scf\n'), ((1401, 1433), 'tensorflow.compat.v1.io.gfile.GFile', 'tf.io.gfile.GFile', (['xyz_path', '"""w"""'], {}), "(xyz_path, 'w')\n", (1418, 1433), True, 'import tensorflow.compat.v1 as tf\n'), ((3429, 3495), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['res[energy]', 'expected_energies[energy]'], {}), '(res[energy], expected_energies[energy])\n', (3455, 3495), True, 'import numpy as np\n'), ((4476, 4500), 'symbolic_functionals.syfes.xc.xc.make_eval_xc', 'xc.make_eval_xc', (['xc_name'], {}), '(xc_name)\n', (4491, 4500), False, 'from symbolic_functionals.syfes.xc import xc\n'), ((5254, 5306), 'symbolic_functionals.syfes.xc.xc.make_eval_xc', 'xc.make_eval_xc', (['"""wb97m_v"""'], {'params': 'mgga.B97MV_PARAMS'}), "('wb97m_v', params=mgga.B97MV_PARAMS)\n", (5269, 5306), False, 'from symbolic_functionals.syfes.xc import xc\n'), ((6059, 6172), 'symbolic_functionals.syfes.symbolic.xc_functionals.wb97mv_short.make_eval_xc', 'xc_functionals.wb97mv_short.make_eval_xc', ([], {'omega': 'rsh_params[0]'}), '(omega=rsh_params[0], **\n xc_functionals.WB97MV_PARAMETERS_UTRANSFORM)\n', (6099, 6172), False, 'from symbolic_functionals.syfes.symbolic import xc_functionals\n')] |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import argparse
import copy
import math
import random
import sys
import time
import numpy as np
import multiprocessing as mp
max_time = 0
start_time = time.time()
distance = []
capacity = 0
depot = 0
dem = []
seed = 0
table_all = []
def arg_analysis():
parser = argparse.ArgumentParser(description="deal with args")
parser.add_argument("file_name")
parser.add_argument("-t", type=int, default=60)
parser.add_argument("-s", type=int, default=time.time())
args = parser.parse_args()
return args.file_name, args.t, args.s
def read_file(file_name):
with open(file_name, 'r+') as file:
name = file.readline().split()[2]
vertices = int(file.readline().split()[2])
depot = int(file.readline().split()[2])
required_edges = int(file.readline().split()[3])
non_required_edges = int(file.readline().split()[3])
vehicles = int(file.readline().split()[2])
capacity = int(file.readline().split()[2])
total = int(file.readline().split()[6])
file.readline()
graph = 99999 * np.ones((vertices + 1, vertices + 1),
dtype=np.int32)
demands = []
while True:
now = file.readline()
if now == "END":
break
nodes = now.split()
node1 = int(nodes[0])
node2 = int(nodes[1])
cost = int(nodes[2])
demand = int(nodes[3])
graph[node1][node2] = cost
graph[node2][node1] = cost
if demand != 0:
demands.append((node1, node2, cost, demand))
demands.append((node2, node1, cost, demand))
distance = floyd(graph)
demands = np.array(demands)
demands = demands.tolist()
return depot, capacity, demands, distance
def floyd(graph):
n = len(graph)
for k in range(1, n):
graph[k][k] = 0
for i in range(1, n):
for j in range(1, n):
if graph[i][j] > graph[i][k] + graph[k][j]:
graph[i][j] = graph[i][k] + graph[k][j]
return graph
def get_init(demands, weight):
# copy_demand = copy.deepcopy(demands)
# a1, b1, c1 = path_scanning(copy_demand, 0)
population = []
do_time = 0
# if max_time > 120:
if weight[0] > 0.05:
do_time = 0
else:
do_time = 0.5 * max_time
for i in [1, 2]:
copy_demand = copy.deepcopy(demands)
a2, b2, c2 = path_scanning(copy_demand, i)
population.append((a2, b2, c2))
# cho = random.randint(0, 8)
cho = 0
global table
# table.add(get_hash(b1))
# table.add(get_hash(b2))
# cho = 0
# cho=0
if cho < 0:
cho = 0
while time.time() - start_time < do_time:
a = 1
copy_demand = copy.deepcopy(demands)
a, b, c = path_scanning_random(copy_demand)
population.append((a, b, c))
# table.add(get_hash(b))
list = sorted(population, key=lambda p: p[0])
# if random.random()<0.5:
# list.insert(0,population[0])
if cho >= len(list) - 1:
cho = 0
# return population[0]
two_opt(population[0][1], population[0][2])
two_opt(list[0][1], list[0][2])
two_opt(list[cho][1], list[cho][2])
if weight[0] > 0.05:
return population[0]
if list[cho][0] > 1.05 * list[0][0]:
return list[0]
else:
return list[cho]
def get_hash(routes):
h = 0
for route in routes:
for task in route:
h = (31 * h + task[0]) % 1000000007
return h
def path_scanning(demands, ch):
ans = []
total_cost = 0
routes = []
remain = []
while len(demands) != 0:
ans.append(0)
route = []
route_full_info = []
load = 0
o = depot
route_cost = 0
while True:
candidates = []
for d in demands:
if d[3] + load <= capacity:
candidates.append(d)
if len(candidates) == 0:
break
find_min = False
choose = []
# if load < capacity / 2:
# m = -9999999
# else:
m = 9999999
find_min = True
for task in candidates:
cost = distance[o][task[0]] + task[2]
if ch == 1:
cost0 = distance[o][task[0]]
else:
cost0 = distance[o][task[0]] / task[3]
if find_min and cost0 < m or (not find_min and cost > m):
m = cost0
choose = task
route.append((choose[0], choose[1]))
route_full_info.append(choose)
demands.remove(choose)
demands.remove([choose[1], choose[0], choose[2], choose[3]])
route_cost += distance[o][choose[0]] + choose[2]
# print(f"{o} to {choose[0]} , cost {distance[o][choose[0]]}")
# print(f"{choose[0]} to {choose[1]} , cost {choose[2]}")
load += choose[3]
o = choose[1]
# total_cost += distance[o][depot]
route_cost += distance[o][depot]
total_cost += route_cost
# print(f"{o} to {depot} , cost {distance[o][depot]}")
ans.extend(route)
remain.append([capacity - load, route_cost])
# if o != depot:
# ans.append((o, depot))
ans.append(0)
routes.append(route_full_info)
# total_cost = flip(routes, total_cost)
return total_cost, routes, remain
def path_scanning_random(demands):
ans = []
total_cost = 0
routes = []
remain = []
while len(demands) != 0:
ans.append(0)
route = []
route_full_info = []
load = 0
o = depot
route_cost = 0
while True:
candidates = []
for d in demands:
if d[3] + load <= capacity:
candidates.append(d)
if len(candidates) == 0:
break
find_min = False
choose = []
# if load < capacity / 2:
# m = -9999999
# else:
m = 9999999
choose_list = []
find_min = True
for task in candidates:
cost = distance[o][task[0]]
if cost == m:
choose_list.append(task)
if find_min and cost < m or (not find_min and cost > m):
m = cost
choose_list = [task]
# elif float(cost) < float(1.01 * m) and random.random() < 0.4:
# choose_list.append(task)
# elif float(cost) < float(1.03 * m) and random.random() < 0.2:
# choose_list.append(task)
# elif float(cost) < float(1.08 * m) and random.random() < 0.1:
# choose_list.append(task)
# elif float(cost) < float(1.1 * m) and random.random() < 0.05:
# choose_list.append(task)
r = random.randint(0, len(choose_list) - 1)
choose = choose_list[r]
route.append((choose[0], choose[1]))
route_full_info.append(choose)
demands.remove(choose)
demands.remove([choose[1], choose[0], choose[2], choose[3]])
route_cost += distance[o][choose[0]] + choose[2]
# print(f"{o} to {choose[0]} , cost {distance[o][choose[0]]}")
# print(f"{choose[0]} to {choose[1]} , cost {choose[2]}")
load += choose[3]
o = choose[1]
# total_cost += distance[o][depot]
route_cost += distance[o][depot]
total_cost += route_cost
# print(f"{o} to {depot} , cost {distance[o][depot]}")
ans.extend(route)
remain.append([capacity - load, route_cost])
# if o != depot:
# ans.append((o, depot))
ans.append(0)
routes.append(route_full_info)
# total_cost = flip(routes, total_cost)
return total_cost, routes, remain
def flip1(ans, cost):
for i in range(len(ans)):
if ans[i] != 0:
if i == 0:
start = depot
elif ans[i - 1] == 0:
start = depot
else:
start = ans[i - 1][1]
if i == len(ans) - 1:
end = depot
elif ans[i + 1] == 0:
end = depot
else:
end = ans[i + 1][0]
det = -distance[start][ans[i][0]] - distance[ans[i][1]][end] + distance[end][ans[i][0]] + \
distance[ans[i][1]][start]
if det < 0:
cost += det
ans[i] = ans[i][1], ans[i][0]
return cost
def flip(routes, cost, remain):
for j in range(len(routes)):
route = routes[j]
for i in range(len(route)):
if i == 0:
start = depot
else:
start = route[i - 1][1]
if i == len(route) - 1:
end = depot
else:
end = route[i + 1][0]
det = -distance[start][route[i][0]] - distance[route[i][1]][end] + distance[end][route[i][0]] + \
distance[route[i][1]][start]
if det < 0:
cost += det
route[i] = [route[i][1], route[i][0], route[i][2], route[i][3]]
remain[j][1] += det
return cost
def recombine(routes, remain):
r1, r2 = 0, 0
while True:
r1 = random.randint(0, len(routes) - 1)
r2 = random.randint(0, len(routes) - 1)
if r1 != r2:
break
route1 = routes[r1]
route2 = routes[r2]
count = 0
while True:
r3 = random.randint(0, len(route1) - 1)
r4 = random.randint(0, len(route2) - 1)
new_route1 = route1[:r3] + route2[r4:]
new_route2 = route2[:r4] + route1[r3:]
new_demand1 = np.sum(new_route1, axis=0)[3]
new_demand2 = np.sum(new_route2, axis=0)[3]
count += 1
if (new_demand1 <= capacity and new_demand2 <= capacity) or count > len(route1) + len(route2):
break
if count > len(new_route1) + len(new_route2):
return 0
if r3 == 0:
start1 = depot
else:
start1 = route1[r3 - 1][1]
if r3 == len(route1) - 1:
end1 = depot
else:
end1 = route1[r3 + 1][0]
if r3 == 0:
start1 = depot
else:
start1 = route1[r3 - 1][1]
if r3 == len(route1) - 1:
end1 = depot
else:
end1 = route1[r3 + 1][0]
new_cost1 = cal_new_cost(new_route1)
new_cost2 = cal_new_cost(new_route2)
old_cost1 = remain[r1][1]
old_cost2 = remain[r2][1]
routes[r1] = new_route1
routes[r2] = new_route2
remain[r1][1] = new_cost1
remain[r2][1] = new_cost2
remain[r1][0] = capacity - new_demand1
remain[r2][0] = capacity - new_demand2
# print(new_cost1 + new_cost2 - old_cost1 - old_cost2)
return new_cost1 + new_cost2 - old_cost1 - old_cost2
def simulated_annealing(routes, cost, remain, weight, see):
global table
T = 10000
cool_rate = 0.001
best_routes = routes
best_cost = cost
best_remain = remain
times = 0
repeat = 0
# print(f"----{cost}")
while time.time() - start_time < max_time - 1:
times += 1
last_cost = cost
copy_routes = copy.deepcopy(routes)
copy_remain = copy.deepcopy(remain)
new_cost = cost
while time.time() - start_time < max_time - 1:
last_cost = cost
copy_routes = copy.deepcopy(routes)
copy_remain = copy.deepcopy(remain)
choice = random.random()
# before = time.time()
if choice < weight[0]:
new_cost = cost + self_single_insertion(copy_routes, copy_remain)
elif choice < weight[1]:
new_cost = cost + cross_single_insertion(copy_routes, copy_remain)
elif choice < weight[2]:
new_cost = cost + swap(copy_routes, copy_remain)
elif choice < weight[3]:
new_cost = cost + cross_double_insertion(copy_routes, copy_remain)
else:
new_cost = cost + recombine(copy_routes, copy_remain)
new_cost = flip(copy_routes, new_cost, copy_remain)
# ha = get_hash(copy_routes)
# if ha not in table:
# table.add(ha)
# break
break
if acceptance_probability(cost, new_cost, T, see) > random.random():
# ha = get_hash(copy_routes)
# if ha not in table:
# table.add(ha)
# cost = two_opt(copy_routes, copy_remain)
# else:
cost = new_cost
# print(cost)
# print(acceptance_probability(best_cost, new_cost, T))
routes = copy_routes
remain = copy_remain
if cost < best_cost:
best_cost = cost
best_remain = remain
best_routes = routes
if cost == last_cost:
repeat += 1
if cost > 1.2 * best_cost:
T = 10000
cost = best_cost
routes = best_routes
remain = best_remain
if repeat > 100:
T = 10000
repeat = 0
T *= 1 - cool_rate
# print(time.time()-before)
# print(times)
return best_routes, best_cost, best_remain
def self_single_insertion(routes, remain):
r = random.randint(0, len(routes) - 1)
route = routes[r]
n = len(route)
tid = random.randint(0, n - 1)
if tid == 0:
old_start = depot
else:
old_start = route[tid - 1][1]
if tid == n - 1:
old_end = depot
else:
old_end = route[tid + 1][0]
task = route[tid]
route.remove(task)
idx = random.randint(0, n - 1)
route.insert(idx, task)
if idx == 0:
new_start = depot
else:
new_start = route[idx - 1][1]
if idx == n - 1:
new_end = depot
else:
new_end = route[idx + 1][0]
change = distance[old_start][old_end] - distance[new_start][new_end] + distance[new_start][task[0]] + \
distance[task[1]][new_end] - distance[old_start][task[0]] - distance[task[1]][old_end]
# print(f"new:{distance[old_start][task[0]]-distance[task[1]][old_end]}")
# print(f"true:{cal_new_cost(route)}")
# print(change+remain[r][1])
# change=0
# old_cost = remain[r][1]
remain[r][1] += change
return change
def cross_single_insertion(routes, remain):
r = random.randint(0, len(routes) - 1)
route = routes[r]
tid = random.randint(0, len(route) - 1)
task = route[tid]
demand = task[3]
candidates = []
for i in range(len(routes)):
if i != r and remain[i][0] >= demand:
candidates.append(i)
if len(candidates) == 0:
return 0
r2 = random.randint(0, len(candidates) - 1)
route2 = routes[candidates[r2]]
if tid == 0:
old_start = depot
else:
old_start = route[tid - 1][1]
if tid == len(route) - 1:
old_end = depot
else:
old_end = route[tid + 1][0]
idx = random.randint(0, len(route2))
route2.insert(idx, task)
route.remove(task)
if idx == 0:
new_start = depot
else:
new_start = route2[idx - 1][1]
if idx == len(route2) - 1:
new_end = depot
else:
new_end = route2[idx + 1][0]
change1 = distance[old_start][old_end] - distance[old_start][task[0]] - distance[task[1]][old_end] - task[2]
change2 = -distance[new_start][new_end] + distance[new_start][task[0]] + distance[task[1]][new_end] + task[2]
if len(route) == 0:
routes.remove(route)
remain[r][0] += demand
remain[candidates[r2]][0] -= demand
remain[r][1] += change1
remain[candidates[r2]][1] += change2
# if change2 + change1 < 0:
# print(change1 + change2)
if len(route) == 0:
remain.pop(r)
return change1 + change2
def cross_double_insertion(routes, remain):
r = random.randint(0, len(routes) - 1)
route = routes[r]
if len(route) < 2:
return 0
tid = random.randint(0, len(route) - 2)
task = route[tid]
task2 = route[tid + 1]
demand = task[3] + task2[3]
candidates = []
for i in range(len(routes)):
if i != r and remain[i][0] >= demand:
candidates.append(i)
if len(candidates) == 0:
return 0
r2 = random.randint(0, len(candidates) - 1)
route2 = routes[candidates[r2]]
if tid == 0:
old_start = depot
else:
old_start = route[tid - 1][1]
if tid == len(route) - 2:
old_end = depot
else:
old_end = route[tid + 2][0]
idx = random.randint(0, len(route2))
route2.insert(idx, task)
route2.insert(idx + 1, task2)
route.remove(task)
route.remove(task2)
if idx == 0:
new_start = depot
else:
new_start = route2[idx - 1][1]
if idx == len(route2) - 2:
new_end = depot
else:
new_end = route2[idx + 2][0]
#
# old_cost1 = remain[r][1]
# old_cost2 = remain[candidates[r2]][1]
if len(route) == 0:
# new_cost1 = cal_new_cost(route)
# else:
routes.remove(route)
# new_cost1 = 0
change1 = distance[old_start][old_end] - distance[old_start][task[0]] - distance[task2[1]][old_end] - task[2] - \
task2[2] - distance[task[1]][task2[0]]
change2 = -distance[new_start][new_end] + distance[new_start][task[0]] + distance[task2[1]][new_end] + task[2] + \
task2[2] + distance[task[1]][task2[0]]
remain[r][0] += demand
remain[candidates[r2]][0] -= demand
remain[r][1] += change1
remain[candidates[r2]][1] += change2
# print(f"true{cal_new_cost(route)}, {remain[r][1]}")
if len(route) == 0:
remain.pop(r)
return change1 + change2
def acceptance_probability(old, new, T, see):
if new < old:
return 1.0
else:
# print((old - new) / T)
return math.exp((old - new) * see / T)
def cal_new_cost(route):
new_cost = 0
new_cost += distance[depot][route[0][0]]
for i in range(0, len(route)):
if i == 0:
start = depot
else:
start = route[i - 1][1]
if i == len(route) - 1:
end = depot
else:
end = route[i + 1][0]
new_cost += distance[route[i][1]][end] + route[i][2]
return new_cost
def get_ans(routes):
ans = []
for route in routes:
ans.append(0)
for task in route:
ans.append((task[0], task[1]))
ans.append(0)
return ans
def two_opt(routes, remain):
total = 0
for i in range(len(routes)):
route = routes[i]
min = remain[i][1]
best_route = route
n = len(route)
for a in range(0, n - 1):
for b in range(a + 2, n):
copy_route = copy.deepcopy(route)
cost = reverse(copy_route, a, b)
if cost < min:
# print(det)
best_route = copy_route
min = cost
remain[i][1] = cost
routes[i] = best_route
total += min
# print(total)
return total
def reverse(route, a, b):
# r = 0
# count = 0
# global rv_total
# global rv_ok
# rv_total += 1
# while True:
# r = random.randint(0, len(routes) - 1)
# route = routes[r]
# if len(route) >= 2 or count > 5:
# break
# else:
# count += 1
# if count > 5:
# return 0
# a, b = 0, 0
# count = 0
# while True:
# a = random.randint(0, len(route) - 1)
# b = random.randint(0, len(route) - 1)
# if abs(a - b) > 1 and a>0 and b>0:
# break
# else:
# count += 1
# if count > 5:
# return 0
# print("before")
# print(len(route))
# if a < b:
# print(route)
# print((a,b))
# print(route)
# print(route[a:b])
# print(route[b - 1:a - 1:-1])
# else:
# route[b:a] = route[a - 1:b - 1:-1]
# print("after")
# print(len(route))
# print(route)
# n_cost = cal_new_cost(route)
# old_cost = remain[r][1]
# remain[r][1] = n_cost
# if n_cost - old_cost < 0:
# # print(f"reverse: {n_cost - old_cost}")
# rv_ok += 1
# if a == 0:
# start = depot
# else:
# start = route[a - 1][1]
# if b == len(route):
# end = depot
# else:
# end = route[b][0]
# change = distance[route[a][1]][end] + distance[start][route[b - 1][0]] - distance[start][route[a][0]] - \
# distance[route[b - 1][1]][end]
# old = cal_new_cost(route)
# # print(a,b)
# # print(route)
route[a:b] = reversed(route[a:b])
# print(route)
new = cal_new_cost(route)
# print(f"old{old}")
# print(f"new{new - change}")
return new
def swap(routes, remain):
r1, r2 = 0, 0
while True:
r1 = random.randint(0, len(routes) - 1)
r2 = random.randint(0, len(routes) - 1)
if r1 != r2:
break
route1 = routes[r1]
route2 = routes[r2]
count = 0
while True:
r3 = random.randint(0, len(route1) - 1)
r4 = random.randint(0, len(route2) - 1)
temp1 = route2[r4]
temp2 = route1[r3]
if r3 == 0:
old_start = depot
else:
old_start = route1[r3 - 1][1]
if r3 == len(route1) - 1:
old_end = depot
else:
old_end = route1[r3 + 1][0]
if r4 == 0:
new_start = depot
else:
new_start = route2[r4 - 1][1]
if r4 == len(route2) - 1:
new_end = depot
else:
new_end = route2[r4 + 1][0]
new_demand1 = capacity - remain[r1][0] - temp2[3] + temp1[3]
new_demand2 = capacity - remain[r2][0] - temp1[3] + temp2[3]
# print(count)
count += 1
if (new_demand1 <= capacity and new_demand2 <= capacity) or count > len(route1) + len(route2):
break
new_route1 = route1[:r3] + [temp1] + route1[r3 + 1:]
new_route2 = route2[:r4] + [temp2] + route2[r4 + 1:]
if count > len(new_route1) + len(new_route2):
return 0
change1 = distance[old_start][temp1[0]] + distance[temp1[1]][old_end] + temp1[2] - distance[old_start][temp2[0]] - \
distance[temp2[1]][old_end] - temp2[2]
change2 = distance[new_start][temp2[0]] + distance[temp2[1]][new_end] + temp2[2] - distance[new_start][temp1[0]] - \
distance[temp1[1]][new_end] - temp1[2]
# new_cost1 = cal_new_cost(new_route1)
# new_cost2 = cal_new_cost(new_route2)
#
# if new_cost2 != remain[r2][1] + change2:
# print("cnm")
#
# print(f"true:{new_cost2}")
# print(remain[r2][1] + change2)
# old_cost1 = remain[r1][1]
# old_cost2 = remain[r2][1]
routes[r1] = new_route1
routes[r2] = new_route2
remain[r1][1] += change1
remain[r2][1] += change2
remain[r1][0] = capacity - new_demand1
remain[r2][0] = capacity - new_demand2
# print(new_cost1 + new_cost2 - old_cost1 - old_cost2)
return change2 + change1
def solver(s, weight):
file_name, termination, see = arg_analysis()
# print(termination)
# random.seed(seed)
global seed
seed = see
global max_time
max_time = termination
de, cap, dem, dis = read_file(file_name)
global depot
depot = de
global capacity
capacity = cap
global distance
distance = dis
global table
table = set()
demands = dem
random.seed(s)
total, routes, remain = get_init(demands, weight)
total = flip(routes, total, remain)
two_opt(routes, remain)
if weight[0] > 0.05:
see = random.randint(10000, 12000)
else:
see = random.randint(8000, 10000)
best_r, best_c, best_re = simulated_annealing(routes, total, remain, weight, see)
t_cost = 0
for route in best_r:
t_cost += cal_new_cost(route)
# print(f"weitht: {weight} , cost:{t_cost}, see{see}")
ans = get_ans(best_r)
return ans, t_cost
class Pro(mp.Process):
def __init__(self, q1, q2):
mp.Process.__init__(self, target=self.start)
self.q1 = q1
self.q2 = q2
self.exit = mp.Event()
def run(self):
while True:
s, weight = self.q1.get()
r, c = solver(s, weight)
self.q2.put((r, c))
# print(time.time() - start_time)
if __name__ == "__main__":
num = 8
# print(mp.cpu_count())
see = [random.randint(0, 10), seed, random.randint(11, 99), random.randint(100, 999), random.randint(1000, 9999),
random.randint(10000, 99999),
random.randint(100000, 500000), random.randint(500000, 9999999), random.randint(0, 10), seed,
random.randint(11, 99), random.randint(100, 999),
random.randint(1000, 9999), random.randint(10000, 99999),
random.randint(100000, 500000), random.randint(500000, 9999999), random.randint(0, 10), seed,
random.randint(11, 99), random.randint(100, 999), random.randint(1000, 9999),
random.randint(10000, 99999),
random.randint(100000, 500000), random.randint(500000, 9999999), random.randint(0, 10), seed,
random.randint(11, 99), random.randint(100, 999),
random.randint(1000, 9999), random.randint(10000, 99999),
random.randint(100000, 500000), random.randint(500000, 9999999)]
# single cross swap double recombine
weight = [[0.2, 0.5, 0.7, 0.85], [0.05, 0.4, 0.6, 0.7], [0.05, 0.4, 0.6, 0.7], [0.2, 0.5, 0.7, 0.85],
[0.2, 0.5, 0.7, 0.85], [0.05, 0.4, 0.6, 0.7], [0.05, 0.4, 0.6, 0.7], [0.2, 0.5, 0.7, 0.85],
[0, 0.35, 0.9, 0.95], [0.5, 0.8, 0.95, 0.95], [0, 0, 0, 1],
[1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 0], [0.3, 0.8, 0.8, 0.9], [0.15, 0.35, 0.9, 0.95],
[0.3, 0.6, 0.8, 0.9], [0.5, 0.8, 0.9, 0.95], [0.2, 0.7, 0.85, 0.95],
[0.1, 0.3, 0.8, 0.9], [0.1, 0.25, 0.4, 0.9], [0.15, 0.3, 0.4, 0.5], [0.2, 0.4, 0.6, 0.8],
[0, 0.35, 0.9, 0.95], [0.5, 0.8, 0.95, 0.95], [0, 0, 0, 1],
[1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 0], [0.3, 0.8, 0.8, 0.9]]
# best_r, best_c = simulated_annealing(routes, total, remain)
pro = []
for i in range(num):
pro.append(Pro(mp.Queue(), mp.Queue()))
pro[i].start()
pro[i].q1.put((see[i], weight[i]))
result = []
for i in range(num):
result.append(pro[i].q2.get())
list = sorted(result, key=lambda p: p[1])
ans = list[0][0]
cost = list[0][1]
# print(time.time()-start_time)
print("s " + str(ans).replace("[", "").replace("]", "").replace(" ", ""))
print("q " + str(cost))
# print(time.time() - start_time)
for p in pro:
p.terminate()
| [
"copy.deepcopy",
"math.exp",
"numpy.sum",
"random.randint",
"argparse.ArgumentParser",
"numpy.ones",
"time.time",
"random.random",
"numpy.array",
"random.seed",
"multiprocessing.Queue",
"multiprocessing.Event",
"multiprocessing.Process.__init__"
] | [((348, 359), 'time.time', 'time.time', ([], {}), '()\n', (357, 359), False, 'import time\n'), ((465, 518), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""deal with args"""'}), "(description='deal with args')\n", (488, 518), False, 'import argparse\n'), ((13881, 13905), 'random.randint', 'random.randint', (['(0)', '(n - 1)'], {}), '(0, n - 1)\n', (13895, 13905), False, 'import random\n'), ((14145, 14169), 'random.randint', 'random.randint', (['(0)', '(n - 1)'], {}), '(0, n - 1)\n', (14159, 14169), False, 'import random\n'), ((24053, 24067), 'random.seed', 'random.seed', (['s'], {}), '(s)\n', (24064, 24067), False, 'import random\n'), ((1927, 1944), 'numpy.array', 'np.array', (['demands'], {}), '(demands)\n', (1935, 1944), True, 'import numpy as np\n'), ((2634, 2656), 'copy.deepcopy', 'copy.deepcopy', (['demands'], {}), '(demands)\n', (2647, 2656), False, 'import copy\n'), ((3012, 3034), 'copy.deepcopy', 'copy.deepcopy', (['demands'], {}), '(demands)\n', (3025, 3034), False, 'import copy\n'), ((11640, 11661), 'copy.deepcopy', 'copy.deepcopy', (['routes'], {}), '(routes)\n', (11653, 11661), False, 'import copy\n'), ((11684, 11705), 'copy.deepcopy', 'copy.deepcopy', (['remain'], {}), '(remain)\n', (11697, 11705), False, 'import copy\n'), ((18384, 18415), 'math.exp', 'math.exp', (['((old - new) * see / T)'], {}), '((old - new) * see / T)\n', (18392, 18415), False, 'import math\n'), ((24229, 24257), 'random.randint', 'random.randint', (['(10000)', '(12000)'], {}), '(10000, 12000)\n', (24243, 24257), False, 'import random\n'), ((24282, 24309), 'random.randint', 'random.randint', (['(8000)', '(10000)'], {}), '(8000, 10000)\n', (24296, 24309), False, 'import random\n'), ((24648, 24692), 'multiprocessing.Process.__init__', 'mp.Process.__init__', (['self'], {'target': 'self.start'}), '(self, target=self.start)\n', (24667, 24692), True, 'import multiprocessing as mp\n'), ((24755, 24765), 'multiprocessing.Event', 'mp.Event', ([], {}), '()\n', (24763, 24765), True, 'import multiprocessing as mp\n'), ((25040, 25061), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (25054, 25061), False, 'import random\n'), ((25069, 25091), 'random.randint', 'random.randint', (['(11)', '(99)'], {}), '(11, 99)\n', (25083, 25091), False, 'import random\n'), ((25093, 25117), 'random.randint', 'random.randint', (['(100)', '(999)'], {}), '(100, 999)\n', (25107, 25117), False, 'import random\n'), ((25119, 25145), 'random.randint', 'random.randint', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (25133, 25145), False, 'import random\n'), ((25158, 25186), 'random.randint', 'random.randint', (['(10000)', '(99999)'], {}), '(10000, 99999)\n', (25172, 25186), False, 'import random\n'), ((25199, 25229), 'random.randint', 'random.randint', (['(100000)', '(500000)'], {}), '(100000, 500000)\n', (25213, 25229), False, 'import random\n'), ((25231, 25262), 'random.randint', 'random.randint', (['(500000)', '(9999999)'], {}), '(500000, 9999999)\n', (25245, 25262), False, 'import random\n'), ((25264, 25285), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (25278, 25285), False, 'import random\n'), ((25304, 25326), 'random.randint', 'random.randint', (['(11)', '(99)'], {}), '(11, 99)\n', (25318, 25326), False, 'import random\n'), ((25328, 25352), 'random.randint', 'random.randint', (['(100)', '(999)'], {}), '(100, 999)\n', (25342, 25352), False, 'import random\n'), ((25365, 25391), 'random.randint', 'random.randint', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (25379, 25391), False, 'import random\n'), ((25393, 25421), 'random.randint', 'random.randint', (['(10000)', '(99999)'], {}), '(10000, 99999)\n', (25407, 25421), False, 'import random\n'), ((25434, 25464), 'random.randint', 'random.randint', (['(100000)', '(500000)'], {}), '(100000, 500000)\n', (25448, 25464), False, 'import random\n'), ((25466, 25497), 'random.randint', 'random.randint', (['(500000)', '(9999999)'], {}), '(500000, 9999999)\n', (25480, 25497), False, 'import random\n'), ((25499, 25520), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (25513, 25520), False, 'import random\n'), ((25539, 25561), 'random.randint', 'random.randint', (['(11)', '(99)'], {}), '(11, 99)\n', (25553, 25561), False, 'import random\n'), ((25563, 25587), 'random.randint', 'random.randint', (['(100)', '(999)'], {}), '(100, 999)\n', (25577, 25587), False, 'import random\n'), ((25589, 25615), 'random.randint', 'random.randint', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (25603, 25615), False, 'import random\n'), ((25628, 25656), 'random.randint', 'random.randint', (['(10000)', '(99999)'], {}), '(10000, 99999)\n', (25642, 25656), False, 'import random\n'), ((25669, 25699), 'random.randint', 'random.randint', (['(100000)', '(500000)'], {}), '(100000, 500000)\n', (25683, 25699), False, 'import random\n'), ((25701, 25732), 'random.randint', 'random.randint', (['(500000)', '(9999999)'], {}), '(500000, 9999999)\n', (25715, 25732), False, 'import random\n'), ((25734, 25755), 'random.randint', 'random.randint', (['(0)', '(10)'], {}), '(0, 10)\n', (25748, 25755), False, 'import random\n'), ((25774, 25796), 'random.randint', 'random.randint', (['(11)', '(99)'], {}), '(11, 99)\n', (25788, 25796), False, 'import random\n'), ((25798, 25822), 'random.randint', 'random.randint', (['(100)', '(999)'], {}), '(100, 999)\n', (25812, 25822), False, 'import random\n'), ((25835, 25861), 'random.randint', 'random.randint', (['(1000)', '(9999)'], {}), '(1000, 9999)\n', (25849, 25861), False, 'import random\n'), ((25863, 25891), 'random.randint', 'random.randint', (['(10000)', '(99999)'], {}), '(10000, 99999)\n', (25877, 25891), False, 'import random\n'), ((25904, 25934), 'random.randint', 'random.randint', (['(100000)', '(500000)'], {}), '(100000, 500000)\n', (25918, 25934), False, 'import random\n'), ((25936, 25967), 'random.randint', 'random.randint', (['(500000)', '(9999999)'], {}), '(500000, 9999999)\n', (25950, 25967), False, 'import random\n'), ((656, 667), 'time.time', 'time.time', ([], {}), '()\n', (665, 667), False, 'import time\n'), ((1268, 1321), 'numpy.ones', 'np.ones', (['(vertices + 1, vertices + 1)'], {'dtype': 'np.int32'}), '((vertices + 1, vertices + 1), dtype=np.int32)\n', (1275, 1321), True, 'import numpy as np\n'), ((2940, 2951), 'time.time', 'time.time', ([], {}), '()\n', (2949, 2951), False, 'import time\n'), ((10173, 10199), 'numpy.sum', 'np.sum', (['new_route1'], {'axis': '(0)'}), '(new_route1, axis=0)\n', (10179, 10199), True, 'import numpy as np\n'), ((10225, 10251), 'numpy.sum', 'np.sum', (['new_route2'], {'axis': '(0)'}), '(new_route2, axis=0)\n', (10231, 10251), True, 'import numpy as np\n'), ((11532, 11543), 'time.time', 'time.time', ([], {}), '()\n', (11541, 11543), False, 'import time\n'), ((11840, 11861), 'copy.deepcopy', 'copy.deepcopy', (['routes'], {}), '(routes)\n', (11853, 11861), False, 'import copy\n'), ((11888, 11909), 'copy.deepcopy', 'copy.deepcopy', (['remain'], {}), '(remain)\n', (11901, 11909), False, 'import copy\n'), ((11931, 11946), 'random.random', 'random.random', ([], {}), '()\n', (11944, 11946), False, 'import random\n'), ((12802, 12817), 'random.random', 'random.random', ([], {}), '()\n', (12815, 12817), False, 'import random\n'), ((11744, 11755), 'time.time', 'time.time', ([], {}), '()\n', (11753, 11755), False, 'import time\n'), ((19292, 19312), 'copy.deepcopy', 'copy.deepcopy', (['route'], {}), '(route)\n', (19305, 19312), False, 'import copy\n'), ((26895, 26905), 'multiprocessing.Queue', 'mp.Queue', ([], {}), '()\n', (26903, 26905), True, 'import multiprocessing as mp\n'), ((26907, 26917), 'multiprocessing.Queue', 'mp.Queue', ([], {}), '()\n', (26915, 26917), True, 'import multiprocessing as mp\n')] |
#!/bin/python
import argparse
from osgeo import gdal
import numpy as np
import os
parser = argparse.ArgumentParser()
parser.add_argument('infile', type=str, help='Input file')
parser.add_argument('outfile', type=str, help='Output file')
parser.add_argument('--scale', type=int, nargs=4, default=[0, 32767, 1, 255], help='like scale for gdal_translate')
parser.add_argument('--nodata', type=int, default=0, help='new nodata')
parser.add_argument('--exp', type=str, default="1.00", help='exponent for power-law stretch, or log for logarithmic stretch')
args = parser.parse_args()
SrcMin, SrcMax, DstMin, DstMax = args.scale
ds = gdal.Open(args.infile, gdal.GA_ReadOnly)
xoffset, px_w, rot1, yoffset, rot2, px_h = ds.GetGeoTransform()
bd = ds.GetRasterBand(1)
nd = bd.GetNoDataValue()
A = bd.ReadAsArray().astype(np.float32)
A[A==-32768]=np.nan
A=A/18*25
print("min,max,mean,std", np.nanmin(A), np.nanmax(A), np.nanmean(A), np.nanstd(A))
if args.exp=='log':
B = np.log2( 1 + (A-SrcMin) / (SrcMax-SrcMin)) * (DstMax-DstMin) + DstMin
else:
B = (DstMax-DstMin) * np.power( (A-SrcMin) / (SrcMax-SrcMin), float(args.exp)) + DstMin
B[A<SrcMin] = DstMin
B[A>SrcMax] = DstMax
B[A==nd] = args.nodata
drv = gdal.GetDriverByName('GTiff')
outfile=args.outfile
ods = drv.Create(outfile, B.shape[1], B.shape[0], bands=1, eType=gdal.GDT_Byte, options=['COMPRESS=LZW','BIGTIFF=YES'])
ods.GetRasterBand(1).WriteArray(B)
ods.GetRasterBand(1).SetNoDataValue(args.nodata)
ods.GetRasterBand(1).ComputeStatistics(True)
ods.SetGeoTransform(ds.GetGeoTransform())
ods.SetProjection(ds.GetProjection())
ods = None
ds = None
| [
"argparse.ArgumentParser",
"numpy.log2",
"numpy.nanstd",
"numpy.nanmin",
"osgeo.gdal.Open",
"osgeo.gdal.GetDriverByName",
"numpy.nanmax",
"numpy.nanmean"
] | [((92, 117), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (115, 117), False, 'import argparse\n'), ((631, 671), 'osgeo.gdal.Open', 'gdal.Open', (['args.infile', 'gdal.GA_ReadOnly'], {}), '(args.infile, gdal.GA_ReadOnly)\n', (640, 671), False, 'from osgeo import gdal\n'), ((1205, 1234), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""GTiff"""'], {}), "('GTiff')\n", (1225, 1234), False, 'from osgeo import gdal\n'), ((884, 896), 'numpy.nanmin', 'np.nanmin', (['A'], {}), '(A)\n', (893, 896), True, 'import numpy as np\n'), ((898, 910), 'numpy.nanmax', 'np.nanmax', (['A'], {}), '(A)\n', (907, 910), True, 'import numpy as np\n'), ((912, 925), 'numpy.nanmean', 'np.nanmean', (['A'], {}), '(A)\n', (922, 925), True, 'import numpy as np\n'), ((927, 939), 'numpy.nanstd', 'np.nanstd', (['A'], {}), '(A)\n', (936, 939), True, 'import numpy as np\n'), ((967, 1012), 'numpy.log2', 'np.log2', (['(1 + (A - SrcMin) / (SrcMax - SrcMin))'], {}), '(1 + (A - SrcMin) / (SrcMax - SrcMin))\n', (974, 1012), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 16:27:27 2018
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
import math
from sklearn.metrics import mean_squared_error
from keras.models import Model
from keras.layers import Input
import keras.backend as K
from keras.callbacks import LearningRateScheduler
from keras import optimizers
#from keras import regularizers
from data_creation import create_dataset, read_data
from dual_attention import first_attention, second_attention
def scheduler(epoch):
# every 20 epochs, lr reduced to 20%
if epoch % 20 == 0 and epoch != 0:
lr = K.get_value(model.optimizer.lr)
K.set_value(model.optimizer.lr, lr * 0.2)
print("lr changed to {}".format(lr * 0.2))
return K.get_value(model.optimizer.lr)
np.random.seed(8)
path = 'full_non_padding.csv'
#sample the data for every 20 minutes to reduce the amount of data
sample_step = 5
#apple, adobe, amazon,microsoft,netflix
in_column = (1,2,11,62,67)
out_column = 67
for i in range(np.size(in_column)):
in_column = list(in_column)
label_column = 0
if in_column[i] == out_column:
label_column = i
break
data = read_data(path, sample_step, in_column)
data_attention = np.reshape(data[:,label_column] ,(-1, 1))
#create dataset
numFeature = np.size(data,1) #n
#Time steps (window size)
T = 20
#cells number in encoder
m = 64
#cells number in decoder
p = 64
# prepare inputs
sig, mu, trainX, trainY, testX, testY = create_dataset(data,\
numStepTrain = 0.7, window_size = T, label_column = label_column)
train_label = np.reshape(trainY[:, -1], (-1, 1))
test_label = np.reshape(testY[:, -1], (-1, 1))
h_init = np.zeros((trainX.shape[0], m))
s_init = np.zeros((trainX.shape[0], m))
hd_init = np.zeros((trainX.shape[0], p))
sd_init = np.zeros((trainX.shape[0], p))
# define input variables
In1 = Input(shape = (trainX.shape[1], trainX.shape[2])) #(None, T, m)
Iny = Input(shape = (trainY.shape[1],)) #(None, T)
h0 = Input(shape = (m,)) #(None, m)
s0 = Input(shape = (m,))
hd0 = Input(shape = (p,)) #(None, m)
sd0 = Input(shape = (p,))
#attention 1st stage --- encoder
H = first_attention(In1, h0, s0, m, T, numFeature) #(None, T, m)
#attention 2nd stage
Y = second_attention(H, Iny, hd0, sd0, m, p, T)
reduce_lr = LearningRateScheduler(scheduler)
#build model
model = Model(inputs = [In1, Iny, h0, s0, hd0, sd0], outputs = Y)
optimizer = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mean_squared_error', optimizer = optimizer)
#model.summary()
model.fit([trainX, trainY, h_init, s_init, hd_init, sd_init], train_label, epochs=120, batch_size=128, \
callbacks=[reduce_lr], verbose=1, shuffle=False)
trainPredict = model.predict([trainX, trainY, h_init, s_init, hd_init, sd_init])
testPredict = model.predict([testX, testY, h_init, s_init, hd_init, sd_init])
trainPredict = trainPredict * sig + mu
train_label = train_label * sig + mu
testPredict = testPredict * sig + mu
test_label = test_label * sig + mu
# calculate root mean squared error
trainScore = math.sqrt(mean_squared_error(train_label, trainPredict))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(test_label, testPredict))
print('Test Score: %.2f RMSE' % (testScore))
trainPredictPlot = np.empty_like(data_attention)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[T : len(trainPredict) + T, :] = trainPredict
# shift test predictions for plotting
testPredictPlot = np.empty_like(data_attention)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict) + T : len(data_attention), :] = testPredict
# plot baseline and predictions
plt.figure(1,figsize=(12,9))
plt.plot(data_attention, label = 'ground truth')
plt.plot(trainPredictPlot, label = 'train prediction')
plt.plot(testPredictPlot, label = 'test prediction')
plt.legend()
plt.show()
plt.figure(1, figsize=(12, 9))
plt.plot(test_label, label = 'test target')
plt.plot(testPredict, label = 'prediction')
plt.legend()
plt.show()
| [
"numpy.random.seed",
"keras.backend.set_value",
"keras.models.Model",
"matplotlib.pyplot.figure",
"keras.callbacks.LearningRateScheduler",
"keras.layers.Input",
"numpy.empty_like",
"dual_attention.second_attention",
"numpy.reshape",
"sklearn.metrics.mean_squared_error",
"numpy.size",
"matplotl... | [((827, 844), 'numpy.random.seed', 'np.random.seed', (['(8)'], {}), '(8)\n', (841, 844), True, 'import numpy as np\n'), ((1236, 1275), 'data_creation.read_data', 'read_data', (['path', 'sample_step', 'in_column'], {}), '(path, sample_step, in_column)\n', (1245, 1275), False, 'from data_creation import create_dataset, read_data\n'), ((1294, 1336), 'numpy.reshape', 'np.reshape', (['data[:, label_column]', '(-1, 1)'], {}), '(data[:, label_column], (-1, 1))\n', (1304, 1336), True, 'import numpy as np\n'), ((1367, 1383), 'numpy.size', 'np.size', (['data', '(1)'], {}), '(data, 1)\n', (1374, 1383), True, 'import numpy as np\n'), ((1548, 1633), 'data_creation.create_dataset', 'create_dataset', (['data'], {'numStepTrain': '(0.7)', 'window_size': 'T', 'label_column': 'label_column'}), '(data, numStepTrain=0.7, window_size=T, label_column=label_column\n )\n', (1562, 1633), False, 'from data_creation import create_dataset, read_data\n'), ((1678, 1712), 'numpy.reshape', 'np.reshape', (['trainY[:, -1]', '(-1, 1)'], {}), '(trainY[:, -1], (-1, 1))\n', (1688, 1712), True, 'import numpy as np\n'), ((1727, 1760), 'numpy.reshape', 'np.reshape', (['testY[:, -1]', '(-1, 1)'], {}), '(testY[:, -1], (-1, 1))\n', (1737, 1760), True, 'import numpy as np\n'), ((1771, 1801), 'numpy.zeros', 'np.zeros', (['(trainX.shape[0], m)'], {}), '((trainX.shape[0], m))\n', (1779, 1801), True, 'import numpy as np\n'), ((1812, 1842), 'numpy.zeros', 'np.zeros', (['(trainX.shape[0], m)'], {}), '((trainX.shape[0], m))\n', (1820, 1842), True, 'import numpy as np\n'), ((1854, 1884), 'numpy.zeros', 'np.zeros', (['(trainX.shape[0], p)'], {}), '((trainX.shape[0], p))\n', (1862, 1884), True, 'import numpy as np\n'), ((1896, 1926), 'numpy.zeros', 'np.zeros', (['(trainX.shape[0], p)'], {}), '((trainX.shape[0], p))\n', (1904, 1926), True, 'import numpy as np\n'), ((1962, 2009), 'keras.layers.Input', 'Input', ([], {'shape': '(trainX.shape[1], trainX.shape[2])'}), '(shape=(trainX.shape[1], trainX.shape[2]))\n', (1967, 2009), False, 'from keras.layers import Input\n'), ((2041, 2072), 'keras.layers.Input', 'Input', ([], {'shape': '(trainY.shape[1],)'}), '(shape=(trainY.shape[1],))\n', (2046, 2072), False, 'from keras.layers import Input\n'), ((2116, 2133), 'keras.layers.Input', 'Input', ([], {'shape': '(m,)'}), '(shape=(m,))\n', (2121, 2133), False, 'from keras.layers import Input\n'), ((2192, 2209), 'keras.layers.Input', 'Input', ([], {'shape': '(m,)'}), '(shape=(m,))\n', (2197, 2209), False, 'from keras.layers import Input\n'), ((2219, 2236), 'keras.layers.Input', 'Input', ([], {'shape': '(p,)'}), '(shape=(p,))\n', (2224, 2236), False, 'from keras.layers import Input\n'), ((2295, 2312), 'keras.layers.Input', 'Input', ([], {'shape': '(p,)'}), '(shape=(p,))\n', (2300, 2312), False, 'from keras.layers import Input\n'), ((2356, 2402), 'dual_attention.first_attention', 'first_attention', (['In1', 'h0', 's0', 'm', 'T', 'numFeature'], {}), '(In1, h0, s0, m, T, numFeature)\n', (2371, 2402), False, 'from dual_attention import first_attention, second_attention\n'), ((2457, 2500), 'dual_attention.second_attention', 'second_attention', (['H', 'Iny', 'hd0', 'sd0', 'm', 'p', 'T'], {}), '(H, Iny, hd0, sd0, m, p, T)\n', (2473, 2500), False, 'from dual_attention import first_attention, second_attention\n'), ((2530, 2562), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', (['scheduler'], {}), '(scheduler)\n', (2551, 2562), False, 'from keras.callbacks import LearningRateScheduler\n'), ((2586, 2639), 'keras.models.Model', 'Model', ([], {'inputs': '[In1, Iny, h0, s0, hd0, sd0]', 'outputs': 'Y'}), '(inputs=[In1, Iny, h0, s0, hd0, sd0], outputs=Y)\n', (2591, 2639), False, 'from keras.models import Model\n'), ((2657, 2723), 'keras.optimizers.Adam', 'optimizers.Adam', ([], {'lr': '(0.001)', 'beta_1': '(0.9)', 'beta_2': '(0.999)', 'epsilon': '(1e-08)'}), '(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)\n', (2672, 2723), False, 'from keras import optimizers\n'), ((3584, 3613), 'numpy.empty_like', 'np.empty_like', (['data_attention'], {}), '(data_attention)\n', (3597, 3613), True, 'import numpy as np\n'), ((3768, 3797), 'numpy.empty_like', 'np.empty_like', (['data_attention'], {}), '(data_attention)\n', (3781, 3797), True, 'import numpy as np\n'), ((3943, 3973), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(12, 9)'}), '(1, figsize=(12, 9))\n', (3953, 3973), True, 'import matplotlib.pyplot as plt\n'), ((3973, 4019), 'matplotlib.pyplot.plot', 'plt.plot', (['data_attention'], {'label': '"""ground truth"""'}), "(data_attention, label='ground truth')\n", (3981, 4019), True, 'import matplotlib.pyplot as plt\n'), ((4023, 4075), 'matplotlib.pyplot.plot', 'plt.plot', (['trainPredictPlot'], {'label': '"""train prediction"""'}), "(trainPredictPlot, label='train prediction')\n", (4031, 4075), True, 'import matplotlib.pyplot as plt\n'), ((4079, 4129), 'matplotlib.pyplot.plot', 'plt.plot', (['testPredictPlot'], {'label': '"""test prediction"""'}), "(testPredictPlot, label='test prediction')\n", (4087, 4129), True, 'import matplotlib.pyplot as plt\n'), ((4133, 4145), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4143, 4145), True, 'import matplotlib.pyplot as plt\n'), ((4147, 4157), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4155, 4157), True, 'import matplotlib.pyplot as plt\n'), ((4159, 4189), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(12, 9)'}), '(1, figsize=(12, 9))\n', (4169, 4189), True, 'import matplotlib.pyplot as plt\n'), ((4191, 4232), 'matplotlib.pyplot.plot', 'plt.plot', (['test_label'], {'label': '"""test target"""'}), "(test_label, label='test target')\n", (4199, 4232), True, 'import matplotlib.pyplot as plt\n'), ((4236, 4277), 'matplotlib.pyplot.plot', 'plt.plot', (['testPredict'], {'label': '"""prediction"""'}), "(testPredict, label='prediction')\n", (4244, 4277), True, 'import matplotlib.pyplot as plt\n'), ((4281, 4293), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4291, 4293), True, 'import matplotlib.pyplot as plt\n'), ((4295, 4305), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4303, 4305), True, 'import matplotlib.pyplot as plt\n'), ((792, 823), 'keras.backend.get_value', 'K.get_value', (['model.optimizer.lr'], {}), '(model.optimizer.lr)\n', (803, 823), True, 'import keras.backend as K\n'), ((1065, 1083), 'numpy.size', 'np.size', (['in_column'], {}), '(in_column)\n', (1072, 1083), True, 'import numpy as np\n'), ((3353, 3398), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['train_label', 'trainPredict'], {}), '(train_label, trainPredict)\n', (3371, 3398), False, 'from sklearn.metrics import mean_squared_error\n'), ((3471, 3514), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['test_label', 'testPredict'], {}), '(test_label, testPredict)\n', (3489, 3514), False, 'from sklearn.metrics import mean_squared_error\n'), ((645, 676), 'keras.backend.get_value', 'K.get_value', (['model.optimizer.lr'], {}), '(model.optimizer.lr)\n', (656, 676), True, 'import keras.backend as K\n'), ((686, 727), 'keras.backend.set_value', 'K.set_value', (['model.optimizer.lr', '(lr * 0.2)'], {}), '(model.optimizer.lr, lr * 0.2)\n', (697, 727), True, 'import keras.backend as K\n')] |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from .colors import label_color
def draw_box(image, box, color, thickness=2):
""" Draws a box on an image with a given color.
# Arguments
image : The image to draw on.
box : A list of 4 elements (x1, y1, x2, y2).
color : The color of the box.
thickness : The thickness of the lines to draw a box with.
"""
b = np.array(box).astype(int)
cv2.rectangle(image, (b[0], b[1]), (b[2], b[3]), color, thickness, cv2.LINE_AA)
end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1
def draw_landmarks(image, landmarks, color = label_color(0), thickness=2):
""" Draws a landmarks on an image with a given color.
# Arguments
image : The image to draw on.
landmarks : A list of (68,2) elements.
color : The color of the box.
thickness : The thickness of the lines to draw a box with.
"""
b = np.array(landmarks).astype(np.int32)
for i in range(b.shape[0]):
st = b[i]
cv2.circle(image, (st[0], st[1]), thickness, color,-1)
if i in end_list:
continue
ed = b[i + 1]
cv2.line(image, (st[0], st[1]), (ed[0], ed[1]), (255, 255, 255), 1)
def draw_caption(image, box, caption):
""" Draws a caption above the box in an image.
# Arguments
image : The image to draw on.
box : A list of 4 elements (x1, y1, x2, y2).
caption : String containing the text to draw.
"""
b = np.array(box).astype(int)
cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 2)
cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 2)
def draw_boxes(image, boxes, color, thickness=2):
""" Draws boxes on an image with a given color.
# Arguments
image : The image to draw on.
boxes : A [N, 4] matrix (x1, y1, x2, y2).
color : The color of the boxes.
thickness : The thickness of the lines to draw boxes with.
"""
for b in boxes:
draw_box(image, b, color, thickness=thickness)
def draw_detections(image, detections, color=None, generator=None):
""" Draws detections in an image.
# Arguments
image : The image to draw on.
detections : A [N, 4 + num_classes] matrix (x1, y1, x2, y2, cls_1, cls_2, ...).
color : The color of the boxes. By default the color from keras_retinanet.utils.colors.label_color will be used.
generator : (optional) Generator which can map label to class name.
"""
for d in detections:
label = np.argmax(d[4:])
c = color if color is not None else label_color(label)
score = d[4 + label]
caption = (generator.label_to_name(label) if generator else str(label)) + ': {0:.2f}'.format(score)
draw_caption(image, d, caption)
draw_box(image, d, color=c)
def draw_annotations(image, annotations, color=(0, 255, 0), generator=None):
""" Draws annotations in an image.
# Arguments
image : The image to draw on.
annotations : A [N, 5] matrix (x1, y1, x2, y2, label).
color : The color of the boxes. By default the color from keras_retinanet.utils.colors.label_color will be used.
generator : (optional) Generator which can map label to class name.
"""
for a in annotations:
label = a[4]
c = color if color is not None else label_color(label)
caption = '{}'.format(generator.label_to_name(label) if generator else label)
draw_caption(image, a, caption)
draw_box(image, a, color=c)
def show_3d_point(data,color=None):
import matplotlib.colors
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
if len(data)>1000:
colormap = plt.get_cmap("rainbow")
else:
colormap = plt.get_cmap("winter")
if color is not None:
ax.scatter(data[:,0], data[:,1], data[:,2], c=color/255.0 ,marker='.',alpha=0.5)
else:
norm = matplotlib.colors.Normalize(vmin=min(data[:, 2]), vmax=max(data[:, 2]))
ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colormap(norm(data[:, 2])), marker='.', alpha=0.5)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
#ax.axis('off')
plt.show()
def show_3d_mesh(data):
from scipy.interpolate import griddata
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y = np.meshgrid(data[:,0], data[:,1])
Z = griddata(data[:,0:2],data[:,2],(X,Y),method='nearest')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
| [
"cv2.line",
"numpy.meshgrid",
"cv2.putText",
"matplotlib.pyplot.show",
"scipy.interpolate.griddata",
"cv2.circle",
"numpy.argmax",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.figure",
"numpy.array",
"cv2.rectangle"
] | [((524, 603), 'cv2.rectangle', 'cv2.rectangle', (['image', '(b[0], b[1])', '(b[2], b[3])', 'color', 'thickness', 'cv2.LINE_AA'], {}), '(image, (b[0], b[1]), (b[2], b[3]), color, thickness, cv2.LINE_AA)\n', (537, 603), False, 'import cv2\n'), ((618, 676), 'numpy.array', 'np.array', (['[17, 22, 27, 42, 48, 31, 36, 68]'], {'dtype': 'np.int32'}), '([17, 22, 27, 42, 48, 31, 36, 68], dtype=np.int32)\n', (626, 676), True, 'import numpy as np\n'), ((1681, 1779), 'cv2.putText', 'cv2.putText', (['image', 'caption', '(b[0], b[1] - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(255, 255, 255)', '(2)'], {}), '(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (\n 255, 255, 255), 2)\n', (1692, 1779), False, 'import cv2\n'), ((1780, 1874), 'cv2.putText', 'cv2.putText', (['image', 'caption', '(b[0], b[1] - 10)', 'cv2.FONT_HERSHEY_PLAIN', '(1)', '(255, 0, 0)', '(2)'], {}), '(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (\n 255, 0, 0), 2)\n', (1791, 1874), False, 'import cv2\n'), ((3959, 3971), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3969, 3971), True, 'import matplotlib.pyplot as plt\n'), ((4569, 4579), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4577, 4579), True, 'import matplotlib.pyplot as plt\n'), ((4662, 4674), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4672, 4674), True, 'import matplotlib.pyplot as plt\n'), ((4735, 4770), 'numpy.meshgrid', 'np.meshgrid', (['data[:, 0]', 'data[:, 1]'], {}), '(data[:, 0], data[:, 1])\n', (4746, 4770), True, 'import numpy as np\n'), ((4778, 4838), 'scipy.interpolate.griddata', 'griddata', (['data[:, 0:2]', 'data[:, 2]', '(X, Y)'], {'method': '"""nearest"""'}), "(data[:, 0:2], data[:, 2], (X, Y), method='nearest')\n", (4786, 4838), False, 'from scipy.interpolate import griddata\n'), ((4978, 4988), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4986, 4988), True, 'import matplotlib.pyplot as plt\n'), ((1161, 1216), 'cv2.circle', 'cv2.circle', (['image', '(st[0], st[1])', 'thickness', 'color', '(-1)'], {}), '(image, (st[0], st[1]), thickness, color, -1)\n', (1171, 1216), False, 'import cv2\n'), ((1297, 1364), 'cv2.line', 'cv2.line', (['image', '(st[0], st[1])', '(ed[0], ed[1])', '(255, 255, 255)', '(1)'], {}), '(image, (st[0], st[1]), (ed[0], ed[1]), (255, 255, 255), 1)\n', (1305, 1364), False, 'import cv2\n'), ((2817, 2833), 'numpy.argmax', 'np.argmax', (['d[4:]'], {}), '(d[4:])\n', (2826, 2833), True, 'import numpy as np\n'), ((4064, 4087), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""rainbow"""'], {}), "('rainbow')\n", (4076, 4087), True, 'import matplotlib.pyplot as plt\n'), ((4119, 4141), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""winter"""'], {}), "('winter')\n", (4131, 4141), True, 'import matplotlib.pyplot as plt\n'), ((493, 506), 'numpy.array', 'np.array', (['box'], {}), '(box)\n', (501, 506), True, 'import numpy as np\n'), ((1063, 1082), 'numpy.array', 'np.array', (['landmarks'], {}), '(landmarks)\n', (1071, 1082), True, 'import numpy as np\n'), ((1650, 1663), 'numpy.array', 'np.array', (['box'], {}), '(box)\n', (1658, 1663), True, 'import numpy as np\n')] |
import numpy as np
from ya_glm.opt.concave_penalty import scad_prox, mcp_prox
def gen_thresh(values, pen_val, thresh='hard', thresh_kws={}):
"""
Applies a generalized thresholding operator to an array.
Parameters
----------
values: array-like
The values to threshold.
pen_val: float
Amount of shrinkage.
kind: str
Which kind of thresholding operator to use. Must be one of ['soft', 'hard']
kws: dict
Optional key word arguments to pass into thresholding operator.
Output
------
values_thresholded: array-like
"""
if thresh is None:
return values
if thresh == 'hard':
out = hard_thresh(values=values, pen_val=pen_val)
elif thresh == 'soft':
out = soft_thresh(values=values, pen_val=pen_val)
elif thresh == 'adpt_lasso':
out = adpt_lasso_thresh(values=values, pen_val=pen_val,
**thresh_kws)
elif thresh == 'scad':
out = scad_prox(values=values, pen_val=pen_val,
**thresh_kws)
elif thresh == 'mcp':
out = mcp_prox(values=values, pen_val=pen_val,
**thresh_kws)
elif callable(thresh):
return thresh(values=values, pen_val=pen_val, **thresh_kws)
else:
raise ValueError("Bad input to 'thresh' {}".format(thresh))
return out
def hard_thresh(values, pen_val):
"""
Hard thresholding opeator.
Parameters
----------
values: array-like
The values to threshold.
pen_val: float
The cutoff value.
Output
------
pen_values: array-like
The values after hard threshodling.
"""
values = np.array(values)
out = np.zeros_like(values)
non_zero_mask = abs(values) > pen_val
out[non_zero_mask] = values[non_zero_mask]
return out
def soft_thresh(values, pen_val):
"""
Soft thresholding opeator.
Parameters
----------
values: array-like
The values to threshold.
pen_val: float
The cutoff value.
Output
------
pen_values: array-like
The values after soft threshodling.
"""
values = np.array(values)
return np.sign(values) * np.clip(abs(values) - pen_val,
a_min=0, a_max=np.inf)
def adpt_lasso_thresh(values, pen_val, eta=1):
"""
Adaptive Lasso based generalized thresholding operator e.g. see (4) from (Rothman et al, 2009).
Parameters
----------
values: array-like
The values to threshold.
pen_val: float
The cutoff value.
eta: float
TODO
Output
------
pen_values: array-like
The values after threshodling.
"""
values = np.array(values)
pen_vals_trans = (1.0 / abs(values)) ** eta
pen_vals_trans *= pen_val ** (eta + 1)
return np.sign(values) * np.clip(abs(values) - pen_vals_trans,
a_min=0, a_max=np.inf)
| [
"numpy.zeros_like",
"ya_glm.opt.concave_penalty.mcp_prox",
"ya_glm.opt.concave_penalty.scad_prox",
"numpy.array",
"numpy.sign"
] | [((1715, 1731), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (1723, 1731), True, 'import numpy as np\n'), ((1742, 1763), 'numpy.zeros_like', 'np.zeros_like', (['values'], {}), '(values)\n', (1755, 1763), True, 'import numpy as np\n'), ((2191, 2207), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (2199, 2207), True, 'import numpy as np\n'), ((2757, 2773), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (2765, 2773), True, 'import numpy as np\n'), ((2219, 2234), 'numpy.sign', 'np.sign', (['values'], {}), '(values)\n', (2226, 2234), True, 'import numpy as np\n'), ((2878, 2893), 'numpy.sign', 'np.sign', (['values'], {}), '(values)\n', (2885, 2893), True, 'import numpy as np\n'), ((1002, 1057), 'ya_glm.opt.concave_penalty.scad_prox', 'scad_prox', ([], {'values': 'values', 'pen_val': 'pen_val'}), '(values=values, pen_val=pen_val, **thresh_kws)\n', (1011, 1057), False, 'from ya_glm.opt.concave_penalty import scad_prox, mcp_prox\n'), ((1123, 1177), 'ya_glm.opt.concave_penalty.mcp_prox', 'mcp_prox', ([], {'values': 'values', 'pen_val': 'pen_val'}), '(values=values, pen_val=pen_val, **thresh_kws)\n', (1131, 1177), False, 'from ya_glm.opt.concave_penalty import scad_prox, mcp_prox\n')] |
# --- Day 8: Two-Factor Authentication ---
# https://adventofcode.com/2016/day/8
import numpy
import re
import time
simple = False
verbose = 1
if simple:
# noinspection SpellCheckingInspection
data = ['rect 3x2', 'rotate column x=1 by 1', 'rotate row y=0 by 4', 'rotate column x=1 by 1']
size = {'x': 7, 'y': 3}
else:
file = open('08_input.txt', 'r')
data = file.read().splitlines()
size = {'x': 50, 'y': 6}
def main():
start_time = time.time()
rect = re.compile(r'rect (\d+)x(\d+)', flags=re.IGNORECASE)
rota = re.compile(r'rotate \w+ (\w)=(\d+) by (\d+)', flags=re.IGNORECASE)
kp = numpy.full((size['y'], size['x']), False)
if verbose > 2:
print('data:\n{}'.format(data))
if simple:
print(kp)
# part 1
for row in data:
if verbose > 1:
print(row)
inst = rect.match(row)
if inst:
kp[0:int(inst.group(2)), 0:int(inst.group(1))] = True
inst = rota.match(row)
if inst:
if inst.group(1) == 'x':
kp[:, int(inst.group(2))] = numpy.roll(kp[:, int(inst.group(2))], int(inst.group(3)))
else:
kp[int(inst.group(2))] = numpy.roll(kp[int(inst.group(2))], int(inst.group(3)), axis=0)
print('part 1: lit pixels {}'.format(kp.sum()))
middle_time = time.time()
print("part 1 time elapsed: {} seconds".format(middle_time - start_time))
# part 2
for row in kp:
for col in row:
if col:
print('#', end='')
else:
print(' ', end='')
print('')
end_time = time.time()
print("part 2 time elapsed: {} seconds".format(end_time - middle_time))
if __name__ == '__main__':
main()
| [
"numpy.full",
"re.compile",
"time.time"
] | [((485, 496), 'time.time', 'time.time', ([], {}), '()\n', (494, 496), False, 'import time\n'), ((511, 564), 're.compile', 're.compile', (['"""rect (\\\\d+)x(\\\\d+)"""'], {'flags': 're.IGNORECASE'}), "('rect (\\\\d+)x(\\\\d+)', flags=re.IGNORECASE)\n", (521, 564), False, 'import re\n'), ((576, 645), 're.compile', 're.compile', (['"""rotate \\\\w+ (\\\\w)=(\\\\d+) by (\\\\d+)"""'], {'flags': 're.IGNORECASE'}), "('rotate \\\\w+ (\\\\w)=(\\\\d+) by (\\\\d+)', flags=re.IGNORECASE)\n", (586, 645), False, 'import re\n'), ((653, 694), 'numpy.full', 'numpy.full', (["(size['y'], size['x'])", '(False)'], {}), "((size['y'], size['x']), False)\n", (663, 694), False, 'import numpy\n'), ((1387, 1398), 'time.time', 'time.time', ([], {}), '()\n', (1396, 1398), False, 'import time\n'), ((1688, 1699), 'time.time', 'time.time', ([], {}), '()\n', (1697, 1699), False, 'import time\n')] |
import re
import numpy
# Wells Path/Deviation file reader
def read_dev_file(filename):
# -----
# Pre-calc for lines counting and arrays pre-init
file = open(filename)
lines_count = -1 # minus data names line
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
line = line.lstrip()
if len(line) > 0: # skipping empty line
if line[0] != '#': # skipping comment line
lines_count += 1
file.close()
# ---
# Actual reading
file = open(filename)
header_line_founded = False
dev_dict = {}
names = []
current_data_line = 0
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
line = line.lstrip()
if len(line) > 0: # skipping empty line
if line[0] != '#': # skipping comment line
line = re.sub(r'\n','',line) # remove \n
line = line.lstrip() # remove whitespaces from the beginning
values = re.split(r'[ \t]+', line) # split line in tokens by spaces and tabs
if header_line_founded == False:
names = values
for name in values:
# dev_dict[name] = numpy.array([])
dev_dict[name] = numpy.zeros(lines_count)
header_line_founded = True
else:
for k in xrange(len(values)):
dev_dict [ names[k] ][current_data_line] = float(values[k])
current_data_line += 1
return dev_dict
| [
"numpy.zeros",
"re.sub",
"re.split"
] | [((862, 885), 're.sub', 're.sub', (['"""\\\\n"""', '""""""', 'line'], {}), "('\\\\n', '', line)\n", (868, 885), False, 'import re\n'), ((981, 1006), 're.split', 're.split', (['"""[ \\\\t]+"""', 'line'], {}), "('[ \\\\t]+', line)\n", (989, 1006), False, 'import re\n'), ((1209, 1233), 'numpy.zeros', 'numpy.zeros', (['lines_count'], {}), '(lines_count)\n', (1220, 1233), False, 'import numpy\n')] |
from rich import print
from pyembroidery import *
from svgpathtools import svg2paths, wsvg
import numpy as np
OUTPUT_PES = "pes_tests/"
OUTPUT_SVG = "svg_tests/"
INPUT_SVG = "tests_input/"
class Embryoid:
def __init__(self):
self.pattern = EmbPattern()
def save_svg(self, fname=OUTPUT_SVG + "design.svg"):
write_svg(self.pattern, fname)
def save_pes(self, fname=OUTPUT_PES + "design.pes"):
write_pes(self.pattern, fname)
def add_stitch_block(self, block):
self.pattern.add_block(block)
def block_from_coords(self, coords):
block = []
for coord in coords:
block.append((coord[0], coord[1]))
self.pattern.add_block(block, "teal")
def parse_svg(self, fname):
paths, attributes = svg2paths(fname)
print(paths)
print(attributes)
for path in paths:
block = []
for segment in path._segments:
block.append((segment.start.real, segment.start.imag))
block.append((path._segments[0].start.real, path._segments[0].start.imag))
self.pattern.add_block(block, "teal")
def solid_block(x_len=100, y_len=100, num_stitches=20):
stitches = []
stitches_y_coords = np.linspace(0, y_len, num_stitches)
for stitch_y in stitches_y_coords:
stitches.append((0, stitch_y))
stitches.append((x_len, stitch_y))
return stitches
def parse(fname, outname):
e = Embryoid()
e.parse_svg(INPUT_SVG + fname)
e.save_svg(outname + ".svg")
e.save_pes(outname + ".pes")
if __name__ == "__main__":
from embroiderTurtle import hilbert
e = Embryoid()
e.block_from_coords([*hilbert()])
e.save_pes("hilbert.pes")
e.save_svg("hilbert.svg")
print(*hilbert())
# parse("convo.svg", "convo")
# e = Embryoid()
# e.add_stitch_block(solid_block())
# e.save_svg("block_test.svg")
# e.save_pes("block_test.pes")
| [
"svgpathtools.svg2paths",
"rich.print",
"embroiderTurtle.hilbert",
"numpy.linspace"
] | [((1250, 1285), 'numpy.linspace', 'np.linspace', (['(0)', 'y_len', 'num_stitches'], {}), '(0, y_len, num_stitches)\n', (1261, 1285), True, 'import numpy as np\n'), ((785, 801), 'svgpathtools.svg2paths', 'svg2paths', (['fname'], {}), '(fname)\n', (794, 801), False, 'from svgpathtools import svg2paths, wsvg\n'), ((810, 822), 'rich.print', 'print', (['paths'], {}), '(paths)\n', (815, 822), False, 'from rich import print\n'), ((831, 848), 'rich.print', 'print', (['attributes'], {}), '(attributes)\n', (836, 848), False, 'from rich import print\n'), ((1775, 1784), 'embroiderTurtle.hilbert', 'hilbert', ([], {}), '()\n', (1782, 1784), False, 'from embroiderTurtle import hilbert\n'), ((1692, 1701), 'embroiderTurtle.hilbert', 'hilbert', ([], {}), '()\n', (1699, 1701), False, 'from embroiderTurtle import hilbert\n')] |
from pgfutils import save, setup_figure
setup_figure(width=1, height=1)
import base64
from pathlib import Path
import tempfile
from matplotlib import pyplot as plt
import numpy as np
t = np.linspace(0, 10, 201)
s = np.sin(2 * np.pi * 0.5 * t)
with open(Path(tempfile.gettempdir()) / "test_nonproject.png", "wb") as f:
img = (
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlse"
"KgAAAABJRU5ErkJggg=="
)
f.write(base64.b64decode(img))
plt.plot(t, s)
save()
| [
"pgfutils.setup_figure",
"matplotlib.pyplot.plot",
"tempfile.gettempdir",
"pgfutils.save",
"base64.b64decode",
"numpy.sin",
"numpy.linspace"
] | [((42, 73), 'pgfutils.setup_figure', 'setup_figure', ([], {'width': '(1)', 'height': '(1)'}), '(width=1, height=1)\n', (54, 73), False, 'from pgfutils import save, setup_figure\n'), ((193, 216), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(201)'], {}), '(0, 10, 201)\n', (204, 216), True, 'import numpy as np\n'), ((221, 248), 'numpy.sin', 'np.sin', (['(2 * np.pi * 0.5 * t)'], {}), '(2 * np.pi * 0.5 * t)\n', (227, 248), True, 'import numpy as np\n'), ((497, 511), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 's'], {}), '(t, s)\n', (505, 511), True, 'from matplotlib import pyplot as plt\n'), ((512, 518), 'pgfutils.save', 'save', ([], {}), '()\n', (516, 518), False, 'from pgfutils import save, setup_figure\n'), ((473, 494), 'base64.b64decode', 'base64.b64decode', (['img'], {}), '(img)\n', (489, 494), False, 'import base64\n'), ((265, 286), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (284, 286), False, 'import tempfile\n')] |
#!/usr/bin/env python
# coding: utf-8
from numpy import exp, dot, random, array
"""Python code for simple Artificial Neural Network with one hidden layer"""
def initialize_weights():
# Generate random numbers
random.seed(1)
# Assign random weights to a 3 x 1 matrix
synaptic_weights = random.uniform(low=-1, high=1, size=(3, 1))
return synaptic_weights
def sigmoid(x):
return 1 / (1 + exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def train(inputs, expected_output, synaptic_weights, bias, learning_rate, training_iterations):
for epoch in range(training_iterations):
# Forward pass -- Pass the training set through the network.
predicted_output = learn(inputs, synaptic_weights, bias)
# Backaward pass
# Calculate the error
error = sigmoid_derivative(predicted_output) * (expected_output - predicted_output)
# Adjust the weights and bias by a factor
weight_factor = dot(inputs.T, error) * learning_rate
bias_factor = error * learning_rate
# Update the synaptic weights
synaptic_weights += weight_factor
# Update the bias
bias += bias_factor
if ((epoch % 1000) == 0):
print("Epoch", epoch)
print("Predicted Output = ", predicted_output.T)
print("Expected Output = ", expected_output.T)
print()
return synaptic_weights
def learn(inputs, synaptic_weights, bias):
return sigmoid(dot(inputs, synaptic_weights) + bias)
if __name__ == "__main__":
# Initialize random weights for the network
synaptic_weights = initialize_weights()
# The training set
inputs = array([[0, 1, 1],
[1, 0, 0],
[1, 0, 1]])
# Target set
expected_output = array([[1, 0, 1]]).T
# Test set
test = array([1, 0, 1])
# Train the neural network
trained_weights = train(inputs, expected_output, synaptic_weights, bias=0.001, learning_rate=0.98,
training_iterations=1000000)
# Test the neural network with a test example
accuracy = (learn(test, trained_weights, bias=0.01)) * 100
print("accuracy =", accuracy[0], "%")
| [
"numpy.random.uniform",
"numpy.random.seed",
"numpy.array",
"numpy.exp",
"numpy.dot"
] | [((221, 235), 'numpy.random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (232, 235), False, 'from numpy import exp, dot, random, array\n'), ((306, 349), 'numpy.random.uniform', 'random.uniform', ([], {'low': '(-1)', 'high': '(1)', 'size': '(3, 1)'}), '(low=-1, high=1, size=(3, 1))\n', (320, 349), False, 'from numpy import exp, dot, random, array\n'), ((1691, 1731), 'numpy.array', 'array', (['[[0, 1, 1], [1, 0, 0], [1, 0, 1]]'], {}), '([[0, 1, 1], [1, 0, 0], [1, 0, 1]])\n', (1696, 1731), False, 'from numpy import exp, dot, random, array\n'), ((1860, 1876), 'numpy.array', 'array', (['[1, 0, 1]'], {}), '([1, 0, 1])\n', (1865, 1876), False, 'from numpy import exp, dot, random, array\n'), ((1812, 1830), 'numpy.array', 'array', (['[[1, 0, 1]]'], {}), '([[1, 0, 1]])\n', (1817, 1830), False, 'from numpy import exp, dot, random, array\n'), ((416, 423), 'numpy.exp', 'exp', (['(-x)'], {}), '(-x)\n', (419, 423), False, 'from numpy import exp, dot, random, array\n'), ((977, 997), 'numpy.dot', 'dot', (['inputs.T', 'error'], {}), '(inputs.T, error)\n', (980, 997), False, 'from numpy import exp, dot, random, array\n'), ((1495, 1524), 'numpy.dot', 'dot', (['inputs', 'synaptic_weights'], {}), '(inputs, synaptic_weights)\n', (1498, 1524), False, 'from numpy import exp, dot, random, array\n')] |
from sklearn.datasets import fetch_openml
from sklearn.linear_model import SGDClassifier
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mnist = fetch_openml('mnist_784', version=1)
mnist.keys()
x, y = mnist["data"], mnist["target"]
x.shape
y.shape
y = y.astype(np.uint8)
some_digit = x[0]
some_digit_image = some_digit.reshape(28,28)
plt.imshow(some_digit_image, cmap = mpl.cm.binary, interpolation="nearest")
plt.axis("off")
plt.show()
x_train, x_test, y_train, y_test = x[:60000], x[60000:], y[:60000], y[60000:]
sgd_clf = SGDClassifier(random_state=42)
sgd_clf.fit(x_train, y_train)
sgd_clf.predict([some_digit])
#dividing the data into different folds
from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_index, test_index in skfolds.split(x_train, y_train):
clone_clf = clone(sgd_clf)
x_train_folds = x_train[train_index]
y_train_folds = y_train[train_index]
x_test_folds = x_train[test_index]
y_test_folds = y_train[test_index]
clone_clf.fit(x_train_folds, y_train_folds)
y_pred = clone_clf.predict(x_test_folds)
n_correct = sum(y_pred == y_test_folds)
print(n_correct / len(y_pred))
from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, x_train, y_train, cv=3, scoring="accuracy")
from sklearn.model_selection import cross_val_predict
y_train_predict = cross_val_predict(sgd_clf, x_train, y_train, cv=3)
from sklearn.metrics import confusion_matrix
confusion_matrix(y_train, y_train_predict)
# Wont work for multi class
# from sklearn.metrics import precision_score, recall_score, f1_score
# precision_score(y_train, y_train_predict)
# recall_score(y_train, y_train_predict)
# f1_score(y_train, y_train_predict)
# y_scores = sgd_clf.decision_function([some_digit])
# #ROC Curve score
# # Wont work for multi class
# from sklearn.metrics import roc_curve
# fpr, tpr, thresholds = roc_curve(y_train, y_scores)
# def plot_roc_curve(fpr, tpr, label=None):
# plt.plot(fpr, tpr, linewidth=2, label=label)
# plt.plot([0,1], [0,1], 'k--')
# plt.axis([0,1], [0,1])
# plt.xlabel('False Positive Rate')
# plt.ylabel('True Positive Rate')
# plot_roc_curve(fpr, tpr)
# plt.show()
#checking the ROC and the area under the curve score
#from sklearn.metrics import roc_auc_score
#roc_auc_score(y_train, y_score)
#trying the random forest classifier
from sklearn.ensemble import RandomForestClassifier
forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, x_train, y_train, cv=3, method="predict_proba")
y_scores_forest = y_probas_forest[:, 1]
# Wont work with multi class classifier
# fpr_forest, tpr_forest, threshold_forest = roc_curve(y_train, y_score_forest)
# plt.plot(fpr, tpr, "b:", label="SGD")
# plot_roc_curve(fpr_forest, tpr_forest, "Random_forest")
# plt.legend(loc="lower right")
# plt.show()
# roc_auc_score(y_train, y_scores_forest)
#another try
#Understanding the SGD results
some_digit_scores = sgd_clf.decision_function([some_digit])
np.argmax(some_digit_scores)
sgd_clf.classes_
forest_clf.fit(x_train, y_train)
forest_clf.predict([some_digit])
forest_clf.predict_proba([some_digit])
cross_val_score(sgd_clf, x_train, y_train, cv=3, scoring='accuracy')
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(x_train.astype(np.float64))
cross_val_score(sgd_clf, x_train_scaled, y_train, cv=3, scoring="accuracy")
y_train_pred = cross_val_predict(sgd_clf, x_train_scaled, y_train, cv=3)
conf_mtx = confusion_matrix(y_train, y_train_pred)
plt.matshow(conf_mtx, cmap=plt.cm.gray)
plt.show()
#Dividing the value in the confusion matrix by the number of images in the corresponding class
row_sums = conf_mtx.sum(axis=1, keepdims=True)
norm_conf_mx = conf_mtx / row_sums
np.fill_diagonal(norm_conf_mx, 0)
plt.matshow(norm_conf_mx, cmap=plt.cm.gray)
plt.show()
from sklearn.metrics import classification_report
clf_report = classification_report(y_train, y_train_predict, target_names=target_names)
print(clf_report)
| [
"sklearn.ensemble.RandomForestClassifier",
"numpy.fill_diagonal",
"matplotlib.pyplot.show",
"sklearn.preprocessing.StandardScaler",
"sklearn.linear_model.SGDClassifier",
"numpy.argmax",
"matplotlib.pyplot.imshow",
"sklearn.model_selection.cross_val_score",
"matplotlib.pyplot.matshow",
"matplotlib.... | [((176, 212), 'sklearn.datasets.fetch_openml', 'fetch_openml', (['"""mnist_784"""'], {'version': '(1)'}), "('mnist_784', version=1)\n", (188, 212), False, 'from sklearn.datasets import fetch_openml\n'), ((371, 444), 'matplotlib.pyplot.imshow', 'plt.imshow', (['some_digit_image'], {'cmap': 'mpl.cm.binary', 'interpolation': '"""nearest"""'}), "(some_digit_image, cmap=mpl.cm.binary, interpolation='nearest')\n", (381, 444), True, 'import matplotlib.pyplot as plt\n'), ((447, 462), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (455, 462), True, 'import matplotlib.pyplot as plt\n'), ((463, 473), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (471, 473), True, 'import matplotlib.pyplot as plt\n'), ((564, 594), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {'random_state': '(42)'}), '(random_state=42)\n', (577, 594), False, 'from sklearn.linear_model import SGDClassifier\n'), ((791, 835), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(3)', 'random_state': '(42)'}), '(n_splits=3, random_state=42)\n', (806, 835), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((1323, 1391), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['sgd_clf', 'x_train', 'y_train'], {'cv': '(3)', 'scoring': '"""accuracy"""'}), "(sgd_clf, x_train, y_train, cv=3, scoring='accuracy')\n", (1338, 1391), False, 'from sklearn.model_selection import cross_val_score\n'), ((1466, 1516), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['sgd_clf', 'x_train', 'y_train'], {'cv': '(3)'}), '(sgd_clf, x_train, y_train, cv=3)\n', (1483, 1516), False, 'from sklearn.model_selection import cross_val_predict\n'), ((1564, 1606), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_train', 'y_train_predict'], {}), '(y_train, y_train_predict)\n', (1580, 1606), False, 'from sklearn.metrics import confusion_matrix\n'), ((2545, 2584), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'random_state': '(42)'}), '(random_state=42)\n', (2567, 2584), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2603, 2680), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['forest_clf', 'x_train', 'y_train'], {'cv': '(3)', 'method': '"""predict_proba"""'}), "(forest_clf, x_train, y_train, cv=3, method='predict_proba')\n", (2620, 2680), False, 'from sklearn.model_selection import cross_val_predict\n'), ((3136, 3164), 'numpy.argmax', 'np.argmax', (['some_digit_scores'], {}), '(some_digit_scores)\n', (3145, 3164), True, 'import numpy as np\n'), ((3289, 3357), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['sgd_clf', 'x_train', 'y_train'], {'cv': '(3)', 'scoring': '"""accuracy"""'}), "(sgd_clf, x_train, y_train, cv=3, scoring='accuracy')\n", (3304, 3357), False, 'from sklearn.model_selection import cross_val_score\n'), ((3418, 3434), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3432, 3434), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3501, 3576), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['sgd_clf', 'x_train_scaled', 'y_train'], {'cv': '(3)', 'scoring': '"""accuracy"""'}), "(sgd_clf, x_train_scaled, y_train, cv=3, scoring='accuracy')\n", (3516, 3576), False, 'from sklearn.model_selection import cross_val_score\n'), ((3593, 3650), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['sgd_clf', 'x_train_scaled', 'y_train'], {'cv': '(3)'}), '(sgd_clf, x_train_scaled, y_train, cv=3)\n', (3610, 3650), False, 'from sklearn.model_selection import cross_val_predict\n'), ((3662, 3701), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_train', 'y_train_pred'], {}), '(y_train, y_train_pred)\n', (3678, 3701), False, 'from sklearn.metrics import confusion_matrix\n'), ((3703, 3742), 'matplotlib.pyplot.matshow', 'plt.matshow', (['conf_mtx'], {'cmap': 'plt.cm.gray'}), '(conf_mtx, cmap=plt.cm.gray)\n', (3714, 3742), True, 'import matplotlib.pyplot as plt\n'), ((3743, 3753), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3751, 3753), True, 'import matplotlib.pyplot as plt\n'), ((3933, 3966), 'numpy.fill_diagonal', 'np.fill_diagonal', (['norm_conf_mx', '(0)'], {}), '(norm_conf_mx, 0)\n', (3949, 3966), True, 'import numpy as np\n'), ((3967, 4010), 'matplotlib.pyplot.matshow', 'plt.matshow', (['norm_conf_mx'], {'cmap': 'plt.cm.gray'}), '(norm_conf_mx, cmap=plt.cm.gray)\n', (3978, 4010), True, 'import matplotlib.pyplot as plt\n'), ((4011, 4021), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4019, 4021), True, 'import matplotlib.pyplot as plt\n'), ((4087, 4161), 'sklearn.metrics.classification_report', 'classification_report', (['y_train', 'y_train_predict'], {'target_names': 'target_names'}), '(y_train, y_train_predict, target_names=target_names)\n', (4108, 4161), False, 'from sklearn.metrics import classification_report\n'), ((917, 931), 'sklearn.base.clone', 'clone', (['sgd_clf'], {}), '(sgd_clf)\n', (922, 931), False, 'from sklearn.base import clone\n')] |
#!/usr/bin/env python
import numpy as np
import scipy as sp
import collections
def scalar_len(a):
"""
Return
"""
if isinstance(a, collections.Iterable):
return len(a)
else:
return 1
def complex_polarToCartesian(r, theta):
"""
Convert a polar representation of a complex number to a cartesian
representation.
Can be used with a numpy array allowing for block conversions
Example Usage:
results = complex_polarToCartesian(1.4142, 0.7854)
results approx. 1+1j
"""
return r * np.exp(theta*1j)
def complex_cartesianToPolar(x):
"""
Convert a cartesian representation of a complex number to a polar
representation.
Can be used with a numpy array allowing for block conversions
Example Usage:
results = complex_cartesianToPolar(1 + 1j)
results approx. (1.4142, 0.7854)
"""
return (np.abs(x), np.angle(x))
def stereoToMono(audio_samples):
"""
Takes in an 2d array of stereo samples and returns a mono numpy
array of dtype np.int16.
"""
LEFT = 0
RIGHT = 1
channels = scalar_len(audio_samples[0])
if channels == 1:
mono_samples = np.asarray(audio_samples,
dtype=np.int16)
elif channels == 2:
mono_samples = np.asarray(
[(sample[RIGHT] + sample[LEFT])/2 for sample in audio_samples],
dtype=np.int16
)
else:
raise Exception("Must be mono or stereo")
return mono_samples
| [
"numpy.angle",
"numpy.asarray",
"numpy.abs",
"numpy.exp"
] | [((566, 586), 'numpy.exp', 'np.exp', (['(theta * 1.0j)'], {}), '(theta * 1.0j)\n', (572, 586), True, 'import numpy as np\n'), ((921, 930), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (927, 930), True, 'import numpy as np\n'), ((932, 943), 'numpy.angle', 'np.angle', (['x'], {}), '(x)\n', (940, 943), True, 'import numpy as np\n'), ((1209, 1250), 'numpy.asarray', 'np.asarray', (['audio_samples'], {'dtype': 'np.int16'}), '(audio_samples, dtype=np.int16)\n', (1219, 1250), True, 'import numpy as np\n'), ((1312, 1410), 'numpy.asarray', 'np.asarray', (['[((sample[RIGHT] + sample[LEFT]) / 2) for sample in audio_samples]'], {'dtype': 'np.int16'}), '([((sample[RIGHT] + sample[LEFT]) / 2) for sample in\n audio_samples], dtype=np.int16)\n', (1322, 1410), True, 'import numpy as np\n')] |
import os
import json
import numpy as np
from bert_serving.client import BertClient
class WordEmbedding():
"""A class that implements some basic functionalities over word embeddings.
"""
def __init__(self, lang, dim):
"""Initializes a new :class:`Embedding` with for language ``lang``.
:param lang: Language of this embedding.
:type lang: str
:param dim: Word vector size (dimension).
:type dim: int
"""
self.lang = lang
self.dim = dim
self.embeddings = []
self.id2word = {}
self.word2id = {}
self.index = None
def get_word_emb(self, word):
"""Gets embedding for a given ``word``.
:param word: The word used to find the embedding.
:type word: str
:returns: the embedding for ``word``
:rtype: np.array
"""
try:
return self.embeddings[self.word2id[word]]
except:
return None
def load_from_file(self, path, nmax=None):
"""Loads vectors from .vec file to memory.
:param path: Path for the .vec file.
:type path: str
:param nmax: Maximum number of vectors to be loaded.
:type nmax: int
"""
with open(path, 'r', encoding='utf-8', newline='\n', errors='ignore') as fp:
if not nmax:
nmax, _ = next(fp).split()
nmax = int(nmax)
np_vecs = np.empty([nmax, self.dim], dtype=np.float32)
for i, line in enumerate(fp):
if i == nmax:
break
word, vec = line.rstrip().split(' ', 1)
np_vecs[i] = np.fromstring(vec, dtype=np.float32, sep=' ')
self.word2id[word] = i
self.id2word[i] = word
# Normalization
np_vecs = np_vecs / np.linalg.norm(np_vecs, 2, 1)[:, None]
self.embeddings = np_vecs
def save_to_file(self, path):
"""Save embeddings from memory to .vec file.
:param path: Path for the output .vec file.
:type path: str
"""
with open(path, "w") as fp:
fp.write(f'{len(self.embeddings)} {self.dim}\n')
fp.writelines(
f'{v} {" ".join(str(x) for x in self.embeddings[k])}\n'
for k,v in self.id2word.items()
)
def infer_vector(self):
"""Abstract method to infer the vector representation of a text."""
raise NotImplementedError("This method should be implemented by subclasses")
class MuseWordEmbedding(WordEmbedding):
"""A class that implements some basic functionalities over fastText MUSE word
embeddings.
"""
def infer_vector(self, text, ignore_unk=False):
"""Infers a vector for ``text``. When its value contains more than one
token, the string is split and an average of each token embedding is
returned. When ``ignore_unk`` is True, this function returns the average of
the known tokens of ``text``, when it is False, if any of the tokens are
unknown, the function returns None.
:param text: String that the vector will be inferred.
:type text: str
:param ignore_unk: If unknown tokens should be taken into consideration.
:type ignore_unk: bool
:returns: A vector for ``text`` or ``None`` if one of its token is unknown.
:rtype: np.array
"""
word_embs = []
for word in text.split():
if word in self.word2id:
word_embs.append(self.get_word_emb(word))
elif not ignore_unk:
return None
else:
return np.mean(word_embs, axis=0) if len(word_embs) > 0 else None
class BertWordEmbedding(WordEmbedding):
"""A class that implements some basic functionalities over BERT word
embeddings.
"""
def __init__(self, lang, dim):
super().__init__(lang, dim)
self.bc = None
def get_client(self):
"""Instantiates and returns the BERT server client of this instance. The
instantiated client will be cached for subsequent calls.
:returns: ``class:BertClient`` of this instance.
:rtype: ``class:BertClient``
"""
if self.bc is None:
self.bc = BertClient()
return self.bc
def load_from_vocab(self, words):
"""Loads vectors from a list of words. When this method is used the vectors
for each word are first inferred from the remote BERT server.
:param words: List of words in the vocabulary.
:type words: list[str]
"""
bc = self.get_client()
np_vecs = bc.encode(words)
for i, word in enumerate(words):
self.word2id[word] = i
self.id2word[i] = word
# Normalization
np_vecs = np_vecs / np.linalg.norm(np_vecs, 2, 1)[:, None]
self.embeddings = np_vecs
def infer_vector(self, text):
"""Infers a vector for ``text``.
:param text: String that the vector will be inferred.
:type text: str
:returns: A vector for ``text`` or ``None`` if one of its token is unknown.
:rtype: np.array
"""
bc = self.get_client()
return bc.encode([text])[0]
class LUEmbedding(WordEmbedding):
"""A class that implements some basic functionalities for LU embeddings.
"""
def load_from_file(self, path, nmax=None):
with open(path, 'r') as fp:
data = json.load(fp)
vecs = []
for i, (k, v) in enumerate(data.items()):
self.word2id[k] = i
self.id2word[i] = k
vecs.append(v)
self.embeddings = np.concatenate(vecs).reshape((-1, self.dim))
class SearchIndex:
def __init__(self, vecs, words, dim):
"""Initializes a new :class:`SearchIndex` for vectors ``vecs`` with
dimension ``dim`` and words ``words``.
:param vecs: List of vectors.
:type vecs: list[np.array]
:param words: String representation of ``vecs``.
:type words: list[str]
:param dim: Vector size.
:type dim: int
"""
self.id2word = {}
self.word2id = {}
for i, w in enumerate(words):
self.id2word[i] = w
self.word2id[w] = i
import faiss
index = faiss.IndexFlatIP(dim)
index.add(np.array(vecs).astype(np.float32))
self.index = index
def get_knn(self, vec, K=5):
"""Returns the indices of the ``K`` nearest neighbors of ``vec`` in the
:class:`Embedding` space.
:param vec: The vector to get its neighbors
:type vec: np.array
:param K: Number of neighbors to search.
:type K: int
:returns: Indices of ``K`` nearest vectors of ``vec```
:rtype: np.array
"""
D, I = self.index.search(vec.astype(np.float32).reshape(1, -1), K)
return D[0], I[0]
| [
"json.load",
"numpy.empty",
"faiss.IndexFlatIP",
"numpy.mean",
"numpy.linalg.norm",
"numpy.array",
"bert_serving.client.BertClient",
"numpy.fromstring",
"numpy.concatenate"
] | [((5411, 5433), 'faiss.IndexFlatIP', 'faiss.IndexFlatIP', (['dim'], {}), '(dim)\n', (5428, 5433), False, 'import faiss\n'), ((1217, 1261), 'numpy.empty', 'np.empty', (['[nmax, self.dim]'], {'dtype': 'np.float32'}), '([nmax, self.dim], dtype=np.float32)\n', (1225, 1261), True, 'import numpy as np\n'), ((3655, 3667), 'bert_serving.client.BertClient', 'BertClient', ([], {}), '()\n', (3665, 3667), False, 'from bert_serving.client import BertClient\n'), ((4695, 4708), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (4704, 4708), False, 'import json\n'), ((1388, 1433), 'numpy.fromstring', 'np.fromstring', (['vec'], {'dtype': 'np.float32', 'sep': '""" """'}), "(vec, dtype=np.float32, sep=' ')\n", (1401, 1433), True, 'import numpy as np\n'), ((1529, 1558), 'numpy.linalg.norm', 'np.linalg.norm', (['np_vecs', '(2)', '(1)'], {}), '(np_vecs, 2, 1)\n', (1543, 1558), True, 'import numpy as np\n'), ((3102, 3128), 'numpy.mean', 'np.mean', (['word_embs'], {'axis': '(0)'}), '(word_embs, axis=0)\n', (3109, 3128), True, 'import numpy as np\n'), ((4128, 4157), 'numpy.linalg.norm', 'np.linalg.norm', (['np_vecs', '(2)', '(1)'], {}), '(np_vecs, 2, 1)\n', (4142, 4157), True, 'import numpy as np\n'), ((4860, 4880), 'numpy.concatenate', 'np.concatenate', (['vecs'], {}), '(vecs)\n', (4874, 4880), True, 'import numpy as np\n'), ((5446, 5460), 'numpy.array', 'np.array', (['vecs'], {}), '(vecs)\n', (5454, 5460), True, 'import numpy as np\n')] |
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the BSD license. See the accompanying LICENSE file
# or read the terms at https://opensource.org/licenses/BSD-3-Clause.
from __future__ import absolute_import, print_function, division
import numpy as np
import random
import tensorflow as tf
import deepmedic.neuralnet.ops as ops
try:
from sys import maxint as MAX_INT
except ImportError:
# python3 compatibility
from sys import maxsize as MAX_INT
#################################################################
# Layer Types #
#################################################################
# >> Any operation that has "trainable" parameters is a layer.
#
class Layer(object):
def apply(self, input, mode):
# mode: "train" or "infer"
raise NotImplementedError()
def trainable_params(self):
raise NotImplementedError()
def params_for_L1_L2_reg(self):
return []
def rec_field(self, rf_at_inp, stride_rf_at_inp):
# stride_rf_at_inp: [str-x, str-y, str-z
# stride of the rec field at prev layer wrt cnn's inp
# Returns: receptive field [x,y,z] of neurons in this input, and ...
# stride of rf wrt input-image when shifting between 2 consequtive neurons in this layer
return rf_at_inp, stride_rf_at_inp
def calc_outp_dims_given_inp(self, inp_dims):
return inp_dims
def calc_inp_dims_given_outp(self, outp_dims):
return outp_dims
class PoolingLayer(Layer):
def __init__(self, window_size, strides, pad_mode, pool_mode):
# window_size: [wx, wy, wz]
# strides: [sx, sy, sz]
# mode: 'MAX' or 'AVG'
# mirror_pad: [mirrorPad-x,-y,-z]
self._window_size = window_size
self._strides = strides
self._pad_mode = pad_mode
self._pool_mode = pool_mode
def apply(self, input, _):
# input dimensions: (batch, fms, r, c, z)
return ops.pool_3d(input, self._window_size, self._strides, self._pad_mode, self._pool_mode)
def trainable_params(self):
return []
def _n_padding(self):
# Returns [padx,pady,padz], how much pad would have been added to preserve dimensions ('SAME' or 'MIRROR').
return [0,0,0] if self._pad_mode == 'VALID' else [self._window_size[d] - 1 for d in range(3)]
def rec_field(self):
raise NotImplementedError()
def calc_outp_dims_given_inp(self, inp_dims): # Same as conv.
padding = self._n_padding()
if np.any([inp_dims[d] + padding[d] < self._window_size[d] for d in range(3)]):
return [0,0,0]
else:
return [1 + (inp_dims[d] + padding[d] - self._window_size[d]) // self._strides[d] for d in range(3)]
def calc_inp_dims_given_outp(self, outp_dims):
assert np.all([outp_dims[d] > 0 for d in range(3)])
padding = self._n_padding()
return [(outp_dims[d]-1)*self._strides[d] + self._window_size[d] - padding[d] for d in range(3)]
class ConvolutionalLayer(Layer):
def __init__(self, fms_in, fms_out, conv_kernel_dims, init_method, pad_mode, rng):
# filter_shape of dimensions: list/np.array: [#FMs in this layer, #FMs in input, kern-dim-x, kern-dim-y, kern-dim-z]
std_init = self._get_std_init(init_method, fms_in, fms_out, conv_kernel_dims)
w_init = np.asarray(rng.normal(loc=0.0, scale=std_init, size=[fms_out, fms_in] + conv_kernel_dims), dtype='float32')
self._w = tf.Variable(w_init, dtype="float32", name="W") # w shape: [#FMs of this layer, #FMs of Input, x, y, z]
self._strides = [1,1,1]
self._pad_mode = pad_mode
def _get_std_init(self, init_method, fms_in, fms_out, conv_kernel_dims):
if init_method[0] == "normal" :
std_init = init_method[1] # commonly 0.01 from Krizhevski
elif init_method[0] == "fanIn" :
var_scale = init_method[1] # 2 for init ala Delving into Rectifier, 1 for SNN.
std_init = np.sqrt(var_scale/np.prod([fms_in] + conv_kernel_dims))
return std_init
def apply(self, input, mode):
return ops.conv_3d(input, self._w, self._pad_mode)
def trainable_params(self):
return [self._w]
def params_for_L1_L2_reg(self):
return self.trainable_params()
def _n_padding(self):
# Returns [padx,pady,padz], how much pad would have been added to preserve dimensions ('SAME' or 'MIRROR').
return [0,0,0] if self._pad_mode == 'VALID' else [self._w.shape.as_list()[2+d] - 1 for d in range(3)]
def rec_field(self, rf_at_inp, stride_rf_at_inp):
rf_out = [rf_at_inp[d] + (self._w.shape.as_list()[2+d]-1)*stride_rf_at_inp[d] for d in range(3)]
stride_rf = [stride_rf_at_inp[d]*self._strides[d] for d in range(3)]
return rf_out, stride_rf
def calc_outp_dims_given_inp(self, inp_dims):
padding = self._n_padding()
if np.any([inp_dims[d] + padding[d] < self._w.shape.as_list()[2+d] for d in range(3)]):
return [0,0,0]
else:
return [1 + (inp_dims[d] + padding[d] - self._w.shape.as_list()[2+d]) // self._strides[d] for d in range(3)]
def calc_inp_dims_given_outp(self, outp_dims):
assert np.all([outp_dims[d] > 0 for d in range(3)])
padding = self._n_padding()
return [(outp_dims[d]-1)*self._strides[d] + self._w.shape.as_list()[2+d] - padding[d] for d in range(3)]
class LowRankConvolutionalLayer(ConvolutionalLayer):
# Behaviour: Create W, set self._W, set self._params, convolve, return ouput and outputShape.
# The created filters are either 1-dimensional (rank=1) or 2-dim (rank=2), depending on the self._rank
# If 1-dim: rSubconv is the input convolved with the row-1dimensional filter.
# If 2-dim: rSubconv is the input convolved with the RC-2D filter, cSubconv with CZ-2D filter, zSubconv with ZR-2D filter.
def __init__(self, fms_in, fms_out, conv_kernel_dims, init_method, pad_mode, rng) :
self._conv_kernel_dims = conv_kernel_dims # For _crop_sub_outputs_same_dims_and_concat(). Could be done differently?
std_init = self._get_std_init(init_method, fms_in, fms_out, conv_kernel_dims)
x_subfilter_shape = [fms_out//3, fms_in, conv_kernel_dims[0], 1 if self._rank == 1 else conv_kernel_dims[1], 1]
w_init = np.asarray(rng.normal(loc=0.0, scale=std_init, size=x_subfilter_shape), dtype='float32')
self._w_x = tf.Variable(w_init, dtype="float32", name="w_x")
y_subfilter_shape = [fms_out//3, fms_in, 1, conv_kernel_dims[1], 1 if self._rank == 1 else conv_kernel_dims[2]]
w_init = np.asarray(rng.normal(loc=0.0, scale=std_init, size=y_subfilter_shape), dtype='float32')
self._w_y = tf.Variable(w_init, dtype="float32", name="w_y")
n_fms_left = fms_out - 2*(fms_out//3) # Cause of possibly inexact integer division.
z_subfilter_shape = [n_fms_left, fms_in, 1 if self._rank == 1 else conv_kernel_dims[0], 1, conv_kernel_dims[2]]
w_init = np.asarray(rng.normal(loc=0.0, scale=std_init, size=z_subfilter_shape), dtype='float32')
self._w_z = tf.Variable(w_init, dtype="float32", name="w_z")
self._strides = [1,1,1]
self._pad_mode = pad_mode
def trainable_params(self):
return [self._w_x, self._w_y, self._w_z] # Note: these tensors have different shapes! Treat carefully.
def params_for_L1_L2_reg(self):
return self.trainable_params()
def apply(self, input, mode):
out_x = ops.conv_3d(input, self._w_x, self._pad_mode)
out_y = ops.conv_3d(input, self._w_y, self._pad_mode)
out_z = ops.conv_3d(input, self._w_z, self._pad_mode)
# concatenate together.
out = self._crop_sub_outputs_same_dims_and_concat(out_x, out_y, out_z)
return out
def _crop_sub_outputs_same_dims_and_concat(self, tens_x, tens_y, tens_z):
assert (tens_x.shape[0] == tens_y.shape[0]) and (tens_y.shape[0] == tens_z.shape[0]) # batch-size
conv_tens_shape = [tens_x.shape[0],
tens_x.shape[1] + tens_y.shape[1] + tens_z.shape[1],
tens_x.shape[2],
tens_y.shape[3],
tens_z.shape[4]
]
x_crop_slice = slice( (self._conv_kernel_dims[0]-1)//2, (self._conv_kernel_dims[0]-1)//2 + conv_tens_shape[2] )
y_crop_slice = slice( (self._conv_kernel_dims[1]-1)//2, (self._conv_kernel_dims[1]-1)//2 + conv_tens_shape[3] )
z_crop_slice = slice( (self._conv_kernel_dims[2]-1)//2, (self._conv_kernel_dims[2]-1)//2 + conv_tens_shape[4] )
tens_x_crop = tens_x[:,:, :, y_crop_slice if self._rank == 1 else slice(0, MAX_INT), z_crop_slice ]
tens_y_crop = tens_y[:,:, x_crop_slice, :, z_crop_slice if self._rank == 1 else slice(0, MAX_INT) ]
tens_z_crop = tens_z[:,:, x_crop_slice if self._rank == 1 else slice(0, MAX_INT), y_crop_slice, : ]
conc_tens = tf.concat([tens_x_crop, tens_y_crop, tens_z_crop], axis=1) #concatenate the FMs
return conc_tens
def _n_padding(self):
# Returns [padx,pady,padz], how much pad would have been added to preserve dimensions ('SAME' or 'MIRROR').
if self._pad_mode == 'VALID':
padding = [0,0,0]
else:
padding = [self._w_x.shape[2] - 1, self._w_y.shape[3] - 1, self._w_z.shape[4] - 1]
return padding
def rec_field(self, rf_at_inp, stride_rf_at_inp):
rf_out = [rf_at_inp[0] + (self._w_x.shape[2]-1)*stride_rf_at_inp[0],
rf_at_inp[1] + (self._w_y.shape[3]-1)*stride_rf_at_inp[1],
rf_at_inp[2] + (self._w_z.shape[4]-1)*stride_rf_at_inp[2]]
stride_rf = [stride_rf_at_inp[d]*self._strides[d] for d in range(3)]
return rf_out, stride_rf
def calc_outp_dims_given_inp(self, inp_dims):
padding = self._n_padding()
if np.any([inp_dims[d] + padding[d] < self._w.shape.as_list()[2+d] for d in range(3)]):
return [0,0,0]
else:
return [1 + (inp_dims[0] + padding[0] - self._w_x.shape.as_list()[2]) // self._strides[0],
1 + (inp_dims[1] + padding[1] - self._w_y.shape.as_list()[3]) // self._strides[1],
1 + (inp_dims[2] + padding[2] - self._w_z.shape.as_list()[4]) // self._strides[2]]
def calc_inp_dims_given_outp(self, outp_dims):
assert np.all([outp_dims[d] > 0 for d in range(3)])
padding = self._n_padding()
return [(outp_dims[0]-1)*self._strides[0] + self._w_x.shape.as_list()[2] - padding[0],
(outp_dims[1]-1)*self._strides[1] + self._w_y.shape.as_list()[3] - padding[1],
(outp_dims[2]-1)*self._strides[2] + self._w_z.shape.as_list()[4] - padding[2]]
class DropoutLayer(Layer):
def __init__(self, dropout_rate, rng):
self._keep_prob = 1 - dropout_rate
self._rng = rng
def apply(self, input, mode):
if self._keep_prob > 0.999: #Dropout below 0.001 I take it as if there is no dropout. To avoid float problems with drop == 0.0
return input
if mode == "train":
random_tensor = self._keep_prob
random_tensor += tf.random.uniform(shape=tf.shape(input), minval=0., maxval=1., seed=self._rng.randint(999999), dtype="float32")
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
dropout_mask = tf.floor(random_tensor)
output = input * dropout_mask
elif mode == "infer":
output = input * self._keep_prob
else:
raise NotImplementedError()
return output
def trainable_params(self):
return []
class BiasLayer(Layer):
def __init__(self, n_channels):
self._b = tf.Variable(np.zeros((n_channels), dtype = 'float32'), name="b")
def apply(self, input, _):
# self._b.shape[0] should already be input.shape[1] number of input channels.
return input + tf.reshape(self._b, shape=[1,input.shape[1],1,1,1])
def trainable_params(self):
return [self._b]
class BatchNormLayer(Layer):
# Order of functions:
# __init__ -> apply(train) --> get_update_ops_for_bn_moving_avg -> update_arrays_of_bn_moving_avg -> apply(infer)
def __init__(self, moving_avg_length, n_channels):
self._moving_avg_length = moving_avg_length # integer. The number of iterations (batches) over which to compute a moving average.
self._g = tf.Variable( np.ones( (n_channels), dtype='float32'), name="gBn" )
self._b = tf.Variable( np.zeros( (n_channels), dtype='float32'), name="bBn" )
#for moving average:
self._array_mus_for_moving_avg = tf.Variable( np.zeros( (moving_avg_length, n_channels), dtype='float32' ), name="muBnsForRollingAverage" )
self._array_vars_for_moving_avg = tf.Variable( np.ones( (moving_avg_length, n_channels), dtype='float32' ), name="varBnsForRollingAverage" )
self._new_mu_batch = tf.Variable(np.zeros( (n_channels), dtype='float32'), name="sharedNewMu_B") # Value will be assigned every training-iteration.
self._new_var_batch = tf.Variable(np.ones( (n_channels), dtype='float32'), name="sharedNewVar_B")
# Create ops for updating the matrices with the bn inference stats.
self._tf_plchld_int32 = tf.compat.v1.placeholder( dtype="int32", name="tf_plchld_int32") # convenience for tf.assign
self._op_update_mtrx_bn_inf_mu = tf.compat.v1.assign( self._array_mus_for_moving_avg[self._tf_plchld_int32], self._new_mu_batch ) # Cant it just take tensor? self._latest_mu_batch?
self._op_update_mtrx_bn_inf_var = tf.compat.v1.assign( self._array_vars_for_moving_avg[self._tf_plchld_int32], self._new_var_batch )
self._latest_mu_batch = None # I think this is useless
self._latest_var_batch = None # I think this is useless
self._idx_where_moving_avg_is = 0 #Index in the rolling-average matrices of the layers, of the entry to update in the next batch.
def trainable_params(self):
return [self._g, self._b]
def apply(self, input, mode, e1 = np.finfo(np.float32).tiny):
# mode: String in ["train", "infer"]
n_channs = input.shape[1]
if mode == "train":
self._new_mu_batch_t, self._new_var_batch_t = tf.nn.moments(input, axes=[0,2,3,4])
mu = self._new_mu_batch_t
var = self._new_var_batch_t
elif mode == "infer":
mu = tf.reduce_mean(self._array_mus_for_moving_avg, axis=0)
var = tf.reduce_mean(self._array_vars_for_moving_avg, axis=0)
else:
raise NotImplementedError()
# Reshape for broadcast.
g_resh = tf.reshape(self._g, shape=[1,n_channs,1,1,1])
b_resh = tf.reshape(self._b, shape=[1,n_channs,1,1,1])
mu = tf.reshape(mu, shape=[1,n_channs,1,1,1])
var = tf.reshape(var, shape=[1,n_channs,1,1,1])
# Normalize
norm_inp = (input - mu ) / tf.sqrt(var + e1) # e1 should come OUT of the sqrt!
norm_inp = g_resh * norm_inp + b_resh
# Returns mu_batch, var_batch to update the moving average afterwards (during training)
return norm_inp
def get_update_ops_for_bn_moving_avg(self) : # I think this is utterly useless.
# This function or something similar should stay, even if I clean the BN rolling average.
return [ tf.compat.v1.assign( ref=self._new_mu_batch, value=self._new_mu_batch_t, validate_shape=True ),
tf.compat.v1.assign( ref=self._new_var_batch, value=self._new_var_batch_t, validate_shape=True ) ]
def update_arrays_of_bn_moving_avg(self, sessionTf):
sessionTf.run( fetches=self._op_update_mtrx_bn_inf_mu, feed_dict={self._tf_plchld_int32: self._idx_where_moving_avg_is} )
sessionTf.run( fetches=self._op_update_mtrx_bn_inf_var, feed_dict={self._tf_plchld_int32: self._idx_where_moving_avg_is} )
self._idx_where_moving_avg_is = (self._idx_where_moving_avg_is + 1) % self._moving_avg_length
def get_act_layer(act_str, n_fms_in):
if act_str == "linear" : # -1 stands for "no nonlinearity". Used for input layers of the pathway.
return IdentityLayer()
elif act_str == "relu" :
return ReluLayer()
elif act_str == "prelu" :
return PreluLayer(n_fms_in)
elif act_str == "elu" :
return EluLayer()
elif act_str == "selu" :
return SeluLayer()
class PreluLayer(Layer):
def __init__(self, n_channels, alpha=0.01):
self._a = tf.Variable(np.ones((n_channels), dtype='float32')*alpha, name="aPrelu")
def apply(self, input, _):
# input is a tensor of shape (batchSize, FMs, r, c, z)
return ops.prelu(input, tf.reshape(self._a, shape=[1,input.shape[1],1,1,1]) )
def trainable_params(self):
return [self._a]
class IdentityLayer(Layer):
def apply(self, input, _): return input
def trainable_params(self): return []
class ReluLayer(Layer):
def apply(self, input, _): return ops.relu(input)
def trainable_params(self): return []
class EluLayer(Layer):
def apply(self, input, _): return ops.elu(input)
def trainable_params(self): return []
class SeluLayer(Layer):
def apply(self, input, _): return ops.selu(input)
def trainable_params(self): return []
| [
"tensorflow.reshape",
"numpy.ones",
"tensorflow.compat.v1.assign",
"tensorflow.floor",
"tensorflow.Variable",
"tensorflow.sqrt",
"deepmedic.neuralnet.ops.pool_3d",
"numpy.prod",
"deepmedic.neuralnet.ops.relu",
"tensorflow.nn.moments",
"tensorflow.compat.v1.placeholder",
"tensorflow.concat",
... | [((2221, 2311), 'deepmedic.neuralnet.ops.pool_3d', 'ops.pool_3d', (['input', 'self._window_size', 'self._strides', 'self._pad_mode', 'self._pool_mode'], {}), '(input, self._window_size, self._strides, self._pad_mode, self.\n _pool_mode)\n', (2232, 2311), True, 'import deepmedic.neuralnet.ops as ops\n'), ((3795, 3841), 'tensorflow.Variable', 'tf.Variable', (['w_init'], {'dtype': '"""float32"""', 'name': '"""W"""'}), "(w_init, dtype='float32', name='W')\n", (3806, 3841), True, 'import tensorflow as tf\n'), ((4462, 4505), 'deepmedic.neuralnet.ops.conv_3d', 'ops.conv_3d', (['input', 'self._w', 'self._pad_mode'], {}), '(input, self._w, self._pad_mode)\n', (4473, 4505), True, 'import deepmedic.neuralnet.ops as ops\n'), ((6889, 6937), 'tensorflow.Variable', 'tf.Variable', (['w_init'], {'dtype': '"""float32"""', 'name': '"""w_x"""'}), "(w_init, dtype='float32', name='w_x')\n", (6900, 6937), True, 'import tensorflow as tf\n'), ((7197, 7245), 'tensorflow.Variable', 'tf.Variable', (['w_init'], {'dtype': '"""float32"""', 'name': '"""w_y"""'}), "(w_init, dtype='float32', name='w_y')\n", (7208, 7245), True, 'import tensorflow as tf\n'), ((7598, 7646), 'tensorflow.Variable', 'tf.Variable', (['w_init'], {'dtype': '"""float32"""', 'name': '"""w_z"""'}), "(w_init, dtype='float32', name='w_z')\n", (7609, 7646), True, 'import tensorflow as tf\n'), ((8021, 8066), 'deepmedic.neuralnet.ops.conv_3d', 'ops.conv_3d', (['input', 'self._w_x', 'self._pad_mode'], {}), '(input, self._w_x, self._pad_mode)\n', (8032, 8066), True, 'import deepmedic.neuralnet.ops as ops\n'), ((8084, 8129), 'deepmedic.neuralnet.ops.conv_3d', 'ops.conv_3d', (['input', 'self._w_y', 'self._pad_mode'], {}), '(input, self._w_y, self._pad_mode)\n', (8095, 8129), True, 'import deepmedic.neuralnet.ops as ops\n'), ((8147, 8192), 'deepmedic.neuralnet.ops.conv_3d', 'ops.conv_3d', (['input', 'self._w_z', 'self._pad_mode'], {}), '(input, self._w_z, self._pad_mode)\n', (8158, 8192), True, 'import deepmedic.neuralnet.ops as ops\n'), ((9524, 9582), 'tensorflow.concat', 'tf.concat', (['[tens_x_crop, tens_y_crop, tens_z_crop]'], {'axis': '(1)'}), '([tens_x_crop, tens_y_crop, tens_z_crop], axis=1)\n', (9533, 9582), True, 'import tensorflow as tf\n'), ((14048, 14111), 'tensorflow.compat.v1.placeholder', 'tf.compat.v1.placeholder', ([], {'dtype': '"""int32"""', 'name': '"""tf_plchld_int32"""'}), "(dtype='int32', name='tf_plchld_int32')\n", (14072, 14111), True, 'import tensorflow as tf\n'), ((14183, 14281), 'tensorflow.compat.v1.assign', 'tf.compat.v1.assign', (['self._array_mus_for_moving_avg[self._tf_plchld_int32]', 'self._new_mu_batch'], {}), '(self._array_mus_for_moving_avg[self._tf_plchld_int32],\n self._new_mu_batch)\n', (14202, 14281), True, 'import tensorflow as tf\n'), ((14374, 14474), 'tensorflow.compat.v1.assign', 'tf.compat.v1.assign', (['self._array_vars_for_moving_avg[self._tf_plchld_int32]', 'self._new_var_batch'], {}), '(self._array_vars_for_moving_avg[self._tf_plchld_int32],\n self._new_var_batch)\n', (14393, 14474), True, 'import tensorflow as tf\n'), ((15497, 15546), 'tensorflow.reshape', 'tf.reshape', (['self._g'], {'shape': '[1, n_channs, 1, 1, 1]'}), '(self._g, shape=[1, n_channs, 1, 1, 1])\n', (15507, 15546), True, 'import tensorflow as tf\n'), ((15561, 15610), 'tensorflow.reshape', 'tf.reshape', (['self._b'], {'shape': '[1, n_channs, 1, 1, 1]'}), '(self._b, shape=[1, n_channs, 1, 1, 1])\n', (15571, 15610), True, 'import tensorflow as tf\n'), ((15625, 15669), 'tensorflow.reshape', 'tf.reshape', (['mu'], {'shape': '[1, n_channs, 1, 1, 1]'}), '(mu, shape=[1, n_channs, 1, 1, 1])\n', (15635, 15669), True, 'import tensorflow as tf\n'), ((15684, 15729), 'tensorflow.reshape', 'tf.reshape', (['var'], {'shape': '[1, n_channs, 1, 1, 1]'}), '(var, shape=[1, n_channs, 1, 1, 1])\n', (15694, 15729), True, 'import tensorflow as tf\n'), ((17928, 17943), 'deepmedic.neuralnet.ops.relu', 'ops.relu', (['input'], {}), '(input)\n', (17936, 17943), True, 'import deepmedic.neuralnet.ops as ops\n'), ((18052, 18066), 'deepmedic.neuralnet.ops.elu', 'ops.elu', (['input'], {}), '(input)\n', (18059, 18066), True, 'import deepmedic.neuralnet.ops as ops\n'), ((18180, 18195), 'deepmedic.neuralnet.ops.selu', 'ops.selu', (['input'], {}), '(input)\n', (18188, 18195), True, 'import deepmedic.neuralnet.ops as ops\n'), ((12072, 12095), 'tensorflow.floor', 'tf.floor', (['random_tensor'], {}), '(random_tensor)\n', (12080, 12095), True, 'import tensorflow as tf\n'), ((12462, 12499), 'numpy.zeros', 'np.zeros', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (12470, 12499), True, 'import numpy as np\n'), ((12670, 12725), 'tensorflow.reshape', 'tf.reshape', (['self._b'], {'shape': '[1, input.shape[1], 1, 1, 1]'}), '(self._b, shape=[1, input.shape[1], 1, 1, 1])\n', (12680, 12725), True, 'import tensorflow as tf\n'), ((13196, 13232), 'numpy.ones', 'np.ones', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (13203, 13232), True, 'import numpy as np\n'), ((13282, 13319), 'numpy.zeros', 'np.zeros', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (13290, 13319), True, 'import numpy as np\n'), ((13422, 13480), 'numpy.zeros', 'np.zeros', (['(moving_avg_length, n_channels)'], {'dtype': '"""float32"""'}), "((moving_avg_length, n_channels), dtype='float32')\n", (13430, 13480), True, 'import numpy as np\n'), ((13572, 13629), 'numpy.ones', 'np.ones', (['(moving_avg_length, n_channels)'], {'dtype': '"""float32"""'}), "((moving_avg_length, n_channels), dtype='float32')\n", (13579, 13629), True, 'import numpy as np\n'), ((13716, 13753), 'numpy.zeros', 'np.zeros', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (13724, 13753), True, 'import numpy as np\n'), ((13874, 13910), 'numpy.ones', 'np.ones', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (13881, 13910), True, 'import numpy as np\n'), ((14876, 14896), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (14884, 14896), True, 'import numpy as np\n'), ((15083, 15122), 'tensorflow.nn.moments', 'tf.nn.moments', (['input'], {'axes': '[0, 2, 3, 4]'}), '(input, axes=[0, 2, 3, 4])\n', (15096, 15122), True, 'import tensorflow as tf\n'), ((15784, 15801), 'tensorflow.sqrt', 'tf.sqrt', (['(var + e1)'], {}), '(var + e1)\n', (15791, 15801), True, 'import tensorflow as tf\n'), ((16228, 16324), 'tensorflow.compat.v1.assign', 'tf.compat.v1.assign', ([], {'ref': 'self._new_mu_batch', 'value': 'self._new_mu_batch_t', 'validate_shape': '(True)'}), '(ref=self._new_mu_batch, value=self._new_mu_batch_t,\n validate_shape=True)\n', (16247, 16324), True, 'import tensorflow as tf\n'), ((16341, 16439), 'tensorflow.compat.v1.assign', 'tf.compat.v1.assign', ([], {'ref': 'self._new_var_batch', 'value': 'self._new_var_batch_t', 'validate_shape': '(True)'}), '(ref=self._new_var_batch, value=self._new_var_batch_t,\n validate_shape=True)\n', (16360, 16439), True, 'import tensorflow as tf\n'), ((17616, 17671), 'tensorflow.reshape', 'tf.reshape', (['self._a'], {'shape': '[1, input.shape[1], 1, 1, 1]'}), '(self._a, shape=[1, input.shape[1], 1, 1, 1])\n', (17626, 17671), True, 'import tensorflow as tf\n'), ((15249, 15303), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['self._array_mus_for_moving_avg'], {'axis': '(0)'}), '(self._array_mus_for_moving_avg, axis=0)\n', (15263, 15303), True, 'import tensorflow as tf\n'), ((15323, 15378), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['self._array_vars_for_moving_avg'], {'axis': '(0)'}), '(self._array_vars_for_moving_avg, axis=0)\n', (15337, 15378), True, 'import tensorflow as tf\n'), ((17424, 17460), 'numpy.ones', 'np.ones', (['n_channels'], {'dtype': '"""float32"""'}), "(n_channels, dtype='float32')\n", (17431, 17460), True, 'import numpy as np\n'), ((11885, 11900), 'tensorflow.shape', 'tf.shape', (['input'], {}), '(input)\n', (11893, 11900), True, 'import tensorflow as tf\n'), ((4342, 4378), 'numpy.prod', 'np.prod', (['([fms_in] + conv_kernel_dims)'], {}), '([fms_in] + conv_kernel_dims)\n', (4349, 4378), True, 'import numpy as np\n')] |
import os
import sys
import random
import shutil
import cv2
import time
import math
import pprint
import numpy as np
import pandas as pd
from tensorboardX import SummaryWriter
from dataset import Dataset, BatchGenerator
import tensorflow as tf
from utils.experiments import LabelSmoother
from utils.tools import AverageMeter, Logger
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, Callback
class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, d_model=256, warmup_steps=4000):
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps = warmup_steps
self.current_lr = 0.0
def __call__(self, step):
arg1 = tf.math.rsqrt(step)
arg2 = step * (self.warmup_steps ** -1.5)
result = tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)
self.current_lr = result.numpy()
return result
def evaluate_single_epoch(config, model, dataloader, criterion, log_val, epoch, writer, dataset_size):
batch_time = AverageMeter()
losses = AverageMeter()
scores = AverageMeter()
eval_loss = tf.keras.metrics.Mean(name='eval_loss')
eval_accuracy = tf.keras.metrics.BinaryAccuracy(name='eval_accuracy')
end = time.time()
for i, (images, labels) in enumerate(dataloader):
preds = model(images)
loss = criterion(labels, preds)
eval_loss(loss)
loss_mean = eval_loss.result().numpy()
losses.update(loss_mean, 1)
eval_accuracy(labels, preds)
score = eval_accuracy.result().numpy()
scores.update(score, 1)
batch_time.update(time.time() - end)
end = time.time()
if i % config.PRINT_EVERY == 0:
print('[%2d/%2d] time: %.2f, loss: %.6f, score: %.4f'
% (i, dataset_size, batch_time.sum, loss_mean, score))
del images, labels, preds
## end of epoch. break..
if i > dataset_size / config.EVAL.BATCH_SIZE: break
writer.add_scalar('val/loss', losses.avg, epoch)
writer.add_scalar('val/score', scores.avg, epoch)
log_val.write('[%d/%d] loss: %.6f, score: %.4f\n'
% (epoch, config.TRAIN.NUM_EPOCHS, losses.avg, scores.avg))
print('average loss over VAL epoch: %f' % losses.avg)
return scores.avg, losses.avg
def train_single_epoch(config, model, dataloader, criterion, optimizer, log_train, epoch, writer, dataset_size):
batch_time = AverageMeter()
losses = AverageMeter()
scores = AverageMeter()
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.BinaryAccuracy(name='train_accuracy')
end = time.time()
for i, (images, labels) in enumerate(dataloader):
with tf.GradientTape() as grad_tape:
preds = model(images)
loss = criterion(labels, preds)
gradients = grad_tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# preds = tf.sigmoid(logits)
train_loss(loss)
train_accuracy(labels, preds)
losses.update(train_loss.result().numpy(), 1)
scores.update(train_accuracy.result().numpy(), 1)
batch_time.update(time.time() - end)
end = time.time()
dataloader_len = dataset_size / config.TRAIN.BATCH_SIZE
if i % 100 == 0:
print("[%d/%d][%d/%d] time: %.2f, loss: %.6f, score: %.4f, lr: %f"
% (epoch, config.TRAIN.NUM_EPOCHS, i, dataloader_len, batch_time.sum, train_loss.result().numpy(),
train_accuracy.result().numpy(),
optimizer.learning_rate.numpy()))
if i == 0:
iteration = dataloader_len * epoch + i
annotated_images = utils.tools.annotate_to_images(images, labels, preds.numpy())
for idx, annotated_image in enumerate(annotated_images):
writer.add_image('train/image_{}_class_{}'.format(int(idx / 8), idx % 8), annotated_image, iteration)
del images, labels, preds
## end of epoch. break..
if i > dataset_size / config.TRAIN.BATCH_SIZE: break
writer.add_scalar('train/score', scores.avg, epoch)
writer.add_scalar('train/loss', losses.avg, epoch)
writer.add_scalar('train/lr', optimizer.learning_rate.numpy(), epoch)
log_train.write('[%d/%d] loss: %.6f, score: %.4f, lr: %f\n'
% (epoch, config.TRAIN.NUM_EPOCHS, losses.avg, scores.avg, optimizer.learning_rate.numpy()))
print('average loss over TRAIN epoch: %f' % losses.avg)
def train(config, model, train_loader, test_loader, optimizer, log_train, log_val, start_epoch, best_score, best_loss,
writer, dataset_size, criterion):
if 1: # keras mode
## train phase..
metric = tf.keras.metrics.BinaryAccuracy()
checkpoint_all = ModelCheckpoint(
'checkpoints\\all_models.{epoch:02d}-{loss:.2f}.h5',
monitor='loss',
verbose=1,
save_best_only=False,
mode='auto',
period=1
)
model.compile(optimizer=optimizer, loss=dice_loss, metrics=['accuracy'])
model.fit_generator(generator=train_loader, steps_per_epoch=len(train_loader), epochs=config.TRAIN.NUM_EPOCHS,
verbose=1,
validation_data=test_loader,
max_queue_size=10,
workers=config.TRAIN.NUM_WORKERS,
use_multiprocessing=False,
callbacks=[checkpoint_all])
## use_multiprocessing=True.. get erorr i don't know..
else: # pytorch style mode
for epoch in range(start_epoch, config.TRAIN.NUM_EPOCHS):
# ## TODO set a loss function..
train_single_epoch(config, model, train_loader, criterion, optimizer, log_train, epoch, writer,
dataset_size[0])
test_score, test_loss = evaluate_single_epoch(config, model, test_loader, criterion, log_val, epoch, writer,
dataset_size[1])
print('Total Test Score: %.4f, Test Loss: %.4f' % (test_score, test_loss))
#
if test_score > best_score:
best_score = test_score
print('Test score Improved! Save checkpoint')
model.save_weights(str(epoch) + "_" + str(best_score) + "_model.h5")
# utils.checkpoint.save_checkpoint(config, model, epoch, test_score, test_loss)
def run(config):
## TODO change to get model
sm.set_framework('tf.keras') ## segmentation_model 2.0 support feature..
backbone = 'mobilenetv2'
model = sm.Unet(backbone, input_shape=(256, 256, 3), encoder_weights=None,
activation='sigmoid') # activation='identity')#, decoder_attention_type='scse') # 'imagenet')
model.summary()
## TODO optimizer change
# optimizer = tf.keras.optimizers.Adam(learning_rate_schedule)#learning_rate=config.OPTIMIZER.LR) #get_optimizer(config, model.parameters())
optimizer = tf.keras.optimizers.Adam(
learning_rate=config.OPTIMIZER.LR) # config.OPTIMIZER.LR) #get_optimizer(config, model.parameters())
##loss ##
criterion = FocalLoss() # DiceLoss()#tf.keras.losses.BinaryCrossentropy()
checkpoint = None
# checkpoint = utils.checkpoint.get_initial_checkpoint(config)
if checkpoint is not None:
last_epoch, score, loss = utils.checkpoint.load_checkpoint(config, model, checkpoint)
# utils.checkpoint.load_checkpoint_legacy(config, model, checkpoint)
else:
print('[*] no checkpoint found')
last_epoch, score, loss = -1, -1, float('inf')
print('last epoch:{} score:{:.4f} loss:{:.4f}'.format(last_epoch, score, loss))
# optimizer.param_groups[0]['initial_lr'] = config.OPTIMIZER.LR
writer = SummaryWriter(os.path.join(config.TRAIN_DIR + config.RECIPE, 'logs'))
log_train = Logger()
log_val = Logger()
log_train.open(os.path.join(config.TRAIN_DIR + config.RECIPE, 'log_train.txt'), mode='a')
log_val.open(os.path.join(config.TRAIN_DIR + config.RECIPE, 'log_val.txt'), mode='a')
train_loader = BatchGenerator(config, 'train', config.TRAIN.BATCH_SIZE, None)
# train_dataset = Dataset(config, 'train', None)
# train_loader = train_dataset.DataGenerator(config.DATA_DIR, batch_size=config.TRAIN.BATCH_SIZE, shuffle = True)
train_datasize = len(train_loader) # train_dataset.get_length()
# val_dataset = Dataset(config, 'val', None)
# val_loader = val_dataset.DataGenerator(config.DATA_DIR, batch_size=config.TRAIN.BATCH_SIZE, shuffle=False)
val_loader = BatchGenerator(config, 'val', config.EVAL.BATCH_SIZE, None)
val_datasize = len(val_loader) # val_dataset.get_length()
### TODO: add transform
train(config, model, train_loader, val_loader, optimizer, log_train, log_val, last_epoch + 1, score, loss, writer,
(train_datasize, val_datasize), criterion)
model.save_weights("model.h5")
def seed_everything():
seed = 2019
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
def main():
import warnings
warnings.filterwarnings("ignore")
print('start training.')
seed_everything()
ymls = ['configs/fastscnn_mv3_sj_add_data_1024.yml']
for yml in ymls:
config = utils.config.load(yml)
os.environ["CUDA_VISIBLE_DEVICES"] = '0,1' # config.GPU
prepare_train_directories(config)
pprint.pprint(config, indent=2)
utils.config.save_config(yml, config.TRAIN_DIR + config.RECIPE)
run(config)
print('success!')
if __name__ == '__main__':
main()
| [
"tensorflow.random.set_seed",
"dataset.BatchGenerator",
"numpy.random.seed",
"warnings.filterwarnings",
"tensorflow.keras.metrics.Mean",
"tensorflow.keras.callbacks.ModelCheckpoint",
"time.time",
"utils.tools.Logger",
"utils.tools.AverageMeter",
"tensorflow.cast",
"tensorflow.keras.optimizers.Ad... | [((1143, 1157), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (1155, 1157), False, 'from utils.tools import AverageMeter, Logger\n'), ((1171, 1185), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (1183, 1185), False, 'from utils.tools import AverageMeter, Logger\n'), ((1199, 1213), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (1211, 1213), False, 'from utils.tools import AverageMeter, Logger\n'), ((1230, 1269), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""eval_loss"""'}), "(name='eval_loss')\n", (1251, 1269), True, 'import tensorflow as tf\n'), ((1290, 1343), 'tensorflow.keras.metrics.BinaryAccuracy', 'tf.keras.metrics.BinaryAccuracy', ([], {'name': '"""eval_accuracy"""'}), "(name='eval_accuracy')\n", (1321, 1343), True, 'import tensorflow as tf\n'), ((1354, 1365), 'time.time', 'time.time', ([], {}), '()\n', (1363, 1365), False, 'import time\n'), ((2560, 2574), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2572, 2574), False, 'from utils.tools import AverageMeter, Logger\n'), ((2588, 2602), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2600, 2602), False, 'from utils.tools import AverageMeter, Logger\n'), ((2616, 2630), 'utils.tools.AverageMeter', 'AverageMeter', ([], {}), '()\n', (2628, 2630), False, 'from utils.tools import AverageMeter, Logger\n'), ((2649, 2689), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""train_loss"""'}), "(name='train_loss')\n", (2670, 2689), True, 'import tensorflow as tf\n'), ((2711, 2765), 'tensorflow.keras.metrics.BinaryAccuracy', 'tf.keras.metrics.BinaryAccuracy', ([], {'name': '"""train_accuracy"""'}), "(name='train_accuracy')\n", (2742, 2765), True, 'import tensorflow as tf\n'), ((2776, 2787), 'time.time', 'time.time', ([], {}), '()\n', (2785, 2787), False, 'import time\n'), ((7276, 7335), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'config.OPTIMIZER.LR'}), '(learning_rate=config.OPTIMIZER.LR)\n', (7300, 7335), True, 'import tensorflow as tf\n'), ((8156, 8164), 'utils.tools.Logger', 'Logger', ([], {}), '()\n', (8162, 8164), False, 'from utils.tools import AverageMeter, Logger\n'), ((8179, 8187), 'utils.tools.Logger', 'Logger', ([], {}), '()\n', (8185, 8187), False, 'from utils.tools import AverageMeter, Logger\n'), ((8391, 8453), 'dataset.BatchGenerator', 'BatchGenerator', (['config', '"""train"""', 'config.TRAIN.BATCH_SIZE', 'None'], {}), "(config, 'train', config.TRAIN.BATCH_SIZE, None)\n", (8405, 8453), False, 'from dataset import Dataset, BatchGenerator\n'), ((8875, 8934), 'dataset.BatchGenerator', 'BatchGenerator', (['config', '"""val"""', 'config.EVAL.BATCH_SIZE', 'None'], {}), "(config, 'val', config.EVAL.BATCH_SIZE, None)\n", (8889, 8934), False, 'from dataset import Dataset, BatchGenerator\n'), ((9281, 9298), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (9292, 9298), False, 'import random\n'), ((9348, 9368), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (9362, 9368), True, 'import numpy as np\n'), ((9373, 9397), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (9391, 9397), True, 'import tensorflow as tf\n'), ((9436, 9469), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (9459, 9469), False, 'import warnings\n'), ((661, 694), 'tensorflow.cast', 'tf.cast', (['self.d_model', 'tf.float32'], {}), '(self.d_model, tf.float32)\n', (668, 694), True, 'import tensorflow as tf\n'), ((813, 832), 'tensorflow.math.rsqrt', 'tf.math.rsqrt', (['step'], {}), '(step)\n', (826, 832), True, 'import tensorflow as tf\n'), ((1776, 1787), 'time.time', 'time.time', ([], {}), '()\n', (1785, 1787), False, 'import time\n'), ((3388, 3399), 'time.time', 'time.time', ([], {}), '()\n', (3397, 3399), False, 'import time\n'), ((4927, 4960), 'tensorflow.keras.metrics.BinaryAccuracy', 'tf.keras.metrics.BinaryAccuracy', ([], {}), '()\n', (4958, 4960), True, 'import tensorflow as tf\n'), ((4987, 5131), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['"""checkpoints\\\\all_models.{epoch:02d}-{loss:.2f}.h5"""'], {'monitor': '"""loss"""', 'verbose': '(1)', 'save_best_only': '(False)', 'mode': '"""auto"""', 'period': '(1)'}), "('checkpoints\\\\all_models.{epoch:02d}-{loss:.2f}.h5',\n monitor='loss', verbose=1, save_best_only=False, mode='auto', period=1)\n", (5002, 5131), False, 'from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, Callback\n'), ((8084, 8138), 'os.path.join', 'os.path.join', (['(config.TRAIN_DIR + config.RECIPE)', '"""logs"""'], {}), "(config.TRAIN_DIR + config.RECIPE, 'logs')\n", (8096, 8138), False, 'import os\n'), ((8207, 8270), 'os.path.join', 'os.path.join', (['(config.TRAIN_DIR + config.RECIPE)', '"""log_train.txt"""'], {}), "(config.TRAIN_DIR + config.RECIPE, 'log_train.txt')\n", (8219, 8270), False, 'import os\n'), ((8299, 8360), 'os.path.join', 'os.path.join', (['(config.TRAIN_DIR + config.RECIPE)', '"""log_val.txt"""'], {}), "(config.TRAIN_DIR + config.RECIPE, 'log_val.txt')\n", (8311, 8360), False, 'import os\n'), ((9757, 9788), 'pprint.pprint', 'pprint.pprint', (['config'], {'indent': '(2)'}), '(config, indent=2)\n', (9770, 9788), False, 'import pprint\n'), ((900, 927), 'tensorflow.math.rsqrt', 'tf.math.rsqrt', (['self.d_model'], {}), '(self.d_model)\n', (913, 927), True, 'import tensorflow as tf\n'), ((930, 957), 'tensorflow.math.minimum', 'tf.math.minimum', (['arg1', 'arg2'], {}), '(arg1, arg2)\n', (945, 957), True, 'import tensorflow as tf\n'), ((2855, 2872), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (2870, 2872), True, 'import tensorflow as tf\n'), ((1743, 1754), 'time.time', 'time.time', ([], {}), '()\n', (1752, 1754), False, 'import time\n'), ((3355, 3366), 'time.time', 'time.time', ([], {}), '()\n', (3364, 3366), False, 'import time\n')] |
# Example command:
# python /scratch/imb/Xiao/HEMnet/HEMnet/train.py -b /scratch/imb/Xiao/HE_test/10x/ -t train_dataset_10x_19_12_19_strict_Reinhard/tiles_10x/ -l valid_Reinhard/tiles_10x -o HEMnet_14_01_2020 -g 2 -e 10 -s -m vgg16 -a 64 -v
import argparse
import numpy as np
import os
import time
from pathlib import Path
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.utils import class_weight
from model import HEMnetModel
def get_class_weights(generator):
class_weights = class_weight.compute_class_weight(
'balanced',
np.unique(generator.classes),
generator.classes)
return class_weights
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--base_dir', type = Path,
help = 'Base Directory')
parser.add_argument('-t', '--train_dir', type = Path,
help = 'Directory containing training input tiles - relative to base directory')
parser.add_argument('-l', '--valid_dir', type=Path,
help='Directory containing validation input tiles - relative to base directory')
parser.add_argument('-o', '--out_dir', type = Path, default=Path(),
help = 'Output Directory - relative to base directory')
parser.add_argument('-m', '--cnn_base', type=str, default="xception",
help='pre-trained convolutional neural network base')
parser.add_argument('-g', '--num_gpus', type=int, default=2,
help='Number of GPUs for training model')
parser.add_argument('-e', '--epochs', type=int, default=100,
help='Number of epochs for training model')
parser.add_argument('-a', '--batch_size', type=int, default=32,
help='Number of tiles for each batch')
parser.add_argument('-s', '--save_model', action = 'store_true',
help = 'save model weights')
parser.add_argument('-v', '--verbosity', action = 'store_true',
help = 'Increase output verbosity')
parser.add_argument('-w', '--transfer_learning', action='store_true',
help='Use CNN base pre-trained from ImageNet')
parser.add_argument('-f', '--fine_tuning', action='store_true',
help='Fine-tuning pre-trained model')
args = parser.parse_args()
####################
# Paths and Inputs #
####################
# Paths
BASE_PATH = args.base_dir
TRAIN_INPUT_PATH = BASE_PATH.joinpath(args.train_dir)
VALID_INPUT_PATH = BASE_PATH.joinpath(args.valid_dir)
OUTPUT_PATH = BASE_PATH.joinpath(args.out_dir)
# User selectable parameters
SAVE_MODEL = args.save_model
CNN_BASE = args.cnn_base
NUM_GPUS = args.num_gpus
EPOCHS = args.epochs
BATCH_SIZE = args.batch_size
TRANSFER_LEARNING = args.transfer_learning
FINE_TUNING = args.fine_tuning
VERBOSE = args.verbosity
# Verbose functions
if VERBOSE:
verbose_print = lambda *args: print(*args)
verbose_save_img = lambda img, path, img_type: img.save(path, img_type)
verbose_save_fig = lambda fig, path, dpi=300: fig.savefig(path, dpi=dpi)
else:
verbose_print = lambda *args: None
verbose_save_img = lambda *args: None
verbose_save_fig = lambda *args: None
HEMnet = HEMnetModel(cnn_base=CNN_BASE,
num_gpus=NUM_GPUS,
transfer_learning=TRANSFER_LEARNING,
fine_tuning=FINE_TUNING)
input_size = (HEMnet.get_input_shape()[0], HEMnet.get_input_shape()[1])
train_datagen = ImageDataGenerator(rescale=1. / 255,
rotation_range=360,
horizontal_flip=True,
vertical_flip=True,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2)
train_generator = train_datagen.flow_from_directory(TRAIN_INPUT_PATH,
classes=['cancer', 'non-cancer'],
target_size=input_size,
batch_size=BATCH_SIZE,
class_mode='binary',
shuffle=True)
valid_datagen = ImageDataGenerator(rescale=1./255)
valid_generator = valid_datagen.flow_from_directory(VALID_INPUT_PATH,
classes=['cancer', 'non-cancer'],
target_size=input_size,
batch_size=BATCH_SIZE,
class_mode='binary',
shuffle=True)
HEMnet.train(train_generator, valid_generator, EPOCHS)
OUTPUT_PATH = OUTPUT_PATH.joinpath('training_results')
os.makedirs(OUTPUT_PATH, exist_ok=True)
HEMnet.save_training_results(OUTPUT_PATH)
if SAVE_MODEL:
model_save_path = OUTPUT_PATH.joinpath("trained_model.h5")
HEMnet.save_model(model_save_path)
| [
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"model.HEMnetModel",
"os.makedirs",
"argparse.ArgumentParser",
"pathlib.Path",
"numpy.unique"
] | [((704, 729), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (727, 729), False, 'import argparse\n'), ((3409, 3525), 'model.HEMnetModel', 'HEMnetModel', ([], {'cnn_base': 'CNN_BASE', 'num_gpus': 'NUM_GPUS', 'transfer_learning': 'TRANSFER_LEARNING', 'fine_tuning': 'FINE_TUNING'}), '(cnn_base=CNN_BASE, num_gpus=NUM_GPUS, transfer_learning=\n TRANSFER_LEARNING, fine_tuning=FINE_TUNING)\n', (3420, 3525), False, 'from model import HEMnetModel\n'), ((3693, 3881), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)', 'rotation_range': '(360)', 'horizontal_flip': '(True)', 'vertical_flip': '(True)', 'width_shift_range': '(0.2)', 'height_shift_range': '(0.2)', 'shear_range': '(0.2)', 'zoom_range': '(0.2)'}), '(rescale=1.0 / 255, rotation_range=360, horizontal_flip=\n True, vertical_flip=True, width_shift_range=0.2, height_shift_range=0.2,\n shear_range=0.2, zoom_range=0.2)\n', (3711, 3881), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((4635, 4672), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), '(rescale=1.0 / 255)\n', (4653, 4672), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((5264, 5303), 'os.makedirs', 'os.makedirs', (['OUTPUT_PATH'], {'exist_ok': '(True)'}), '(OUTPUT_PATH, exist_ok=True)\n', (5275, 5303), False, 'import os\n'), ((579, 607), 'numpy.unique', 'np.unique', (['generator.classes'], {}), '(generator.classes)\n', (588, 607), True, 'import numpy as np\n'), ((1224, 1230), 'pathlib.Path', 'Path', ([], {}), '()\n', (1228, 1230), False, 'from pathlib import Path\n')] |
"""
Copyright 2019 Akvelon Inc.
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 time
import os
import pandas as pd
import numpy as np
from pathlib import Path
import tensorflow as tf
from sklearn.preprocessing import RobustScaler
from sklearn.externals import joblib
import matplotlib.pyplot as plt
from tensorflow import keras
class PredictorTrainer:
DATA_PATH = 'data/training.csv'
MODEL_PATH = 'data/models/'
SCALER_PATH = 'data/models/scaler.pkl'
TRAINED_MODEL_PATH = 'data/models/fee-predictor-model.h5'
BATCH_SIZE = 256
TRAIN_STEPS = 10
TRAIN_DATA_PERCENT = 0.9
def __init__(self, batch_size=BATCH_SIZE, train_steps=TRAIN_STEPS):
self.initialize_scaler()
def initialize_scaler(self):
path = Path(PredictorTrainer.SCALER_PATH)
if not path.is_file():
print('Scaler model not found. Initializing.')
#self.scaler = MinMaxScaler(feature_range=(0, 1))
self.scaler = RobustScaler()
data = self.load_data()
self.scaler.fit(data.values[:, 1:])
path.parent.mkdir(parents=True, exist_ok=True)
joblib.dump(self.scaler, PredictorTrainer.SCALER_PATH)
print('Scaler initialized and saved.')
else:
print('Found scaler model. Loading.')
self.scaler = joblib.load(PredictorTrainer.SCALER_PATH)
print('Scaler loaded.')
def scale_data(self, data):
return self.scaler.transform(data)
# splits the data onto training and test set
def split_data(self, data, n):
train_start = 0
train_end = int(np.floor(0.8 * n))
test_start = train_end + 1
test_end = n
return data[train_start:train_end], data[test_start:test_end]
# loads the file with default data
def load_file(self):
return pd.read_csv(PredictorTrainer.DATA_PATH)
# there are helper fields in data, this function left only ones which needed to train the model
def get_learning_data(self, dataframe):
return dataframe.drop(['block_median_fee_per_byte', 'block_id'], axis='columns')
# sometimes fee_per_byte is enormous, so we take care of having the normal one here
def filter_out_outliners(self, dataframe):
return dataframe.query('fee_per_byte < block_median_fee_per_byte')
# do all transformation needed to get info suitable for training
def load_data(self):
data = self.load_file()
data = self.filter_out_outliners(data)
return self.get_learning_data(data)
def train(self):
data = self.load_data()
n = data.shape[0]
data = data.values
data_train, data_test = self.split_data(data, n)
x_train = self.scale_data(data_train[:, 1:])
y_train = data_train[:, 0]
x_test = self.scale_data(data_test[:, 1:])
y_test = data_test[:, 0]
model = keras.Sequential([
keras.layers.Dense(3, kernel_initializer='normal', input_dim=3),
keras.layers.Dense(1024, kernel_initializer='normal'),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(512, kernel_initializer='normal'),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(256, kernel_initializer='normal'),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(128, kernel_initializer='normal'),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(64, kernel_initializer='normal',),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(32, kernel_initializer='normal'),
keras.layers.PReLU(),
keras.layers.Dropout(0.1),
keras.layers.Dense(1, kernel_initializer='normal')
])
model.compile(optimizer='adam',
loss=tf.losses.huber_loss)
model.fit(x_train, y_train, epochs=10, batch_size=250)
model.save(PredictorTrainer.TRAINED_MODEL_PATH)
def load_model(self, model_name):
return keras.models.load_model(model_name, custom_objects={'huber_loss': tf.losses.huber_loss})
def evaluate_block(self, model_name, test_file):
model = self.load_model(model_name)
data_raw = pd.read_csv(test_file)
min_fee = data_raw[['fee_per_byte']].min().values[0]
median_fee = data_raw[['block_median_fee_per_byte']].values[0][0]
data = data_raw.query('confirmation_speed == 0')
data = self.get_learning_data(data)
data_y = data[:, 0]
data_x = self.scale_data(data[:, 1:])
predicted = model.predict(data_x).flatten()
hit = np.where(predicted > min_fee)[0].size
out = np.where(predicted > median_fee)[0].size
total_good = np.where((min_fee < predicted) & (predicted < median_fee))[0].size
print('hit', hit)
print('out', out)
print('total_good', total_good)
total_fee_loss = 0
sizes = data_raw.query('confirmation_speed == 0')[['vsize']].values.flatten()
for i in range(0, data_y.size):
total_fee_loss += sizes[i] * (data_y[i] - predicted[i])
print('total_fee_loss', total_fee_loss)
return
# evaluates the model predictions and write down values to file for further analisys
def evaluate(self):
# idea is to check how well we predict fee so that transaction were added to the first block after they appear in mempool
model = self.load_model(PredictorTrainer.TRAINED_MODEL_PATH)
data_raw = self.load_file()
# looking for blocks which wasn't used during training so that get legitimate result
# the first step is get training set the same way as we did this during training session
data = self.filter_out_outliners(data_raw)
data_train, data_test = self.split_data(data, data.shape[0])
data_train_blocks = set(data_train['block_id'].values.flatten()) # block ids which were used during training
all_blocks = set(data_raw['block_id'].values.flatten()) # all block ids in our data
block_indexes_to_evaluate = list(all_blocks.difference(data_train_blocks)) # this difference are block ids which wasn't used by training process
data = data_raw[(data_raw['block_id'].isin(block_indexes_to_evaluate))] # filter the data which wasn't used in training so we can use it to evaluate
data = data.query('confirmation_speed == 0') # we looking only for results where transaction were added to the first next block after it added to mempool
#collecting the statistics
output = pd.DataFrame(columns=['block_id', 'min_fee', 'median_fee', 'predicted_mean_fee', 'predicted_median_fee'])
for name, group in data.groupby('block_id'):
min_fee = group['fee_per_byte'].min()
median_fee = group['fee_per_byte'].median()
learning_data = self.get_learning_data(group)
x_test = self.scale_data(learning_data.values[:, 1:])
y_predicted = model.predict(x_test).flatten()
predicted_mean_fee = float(np.mean(y_predicted))
predicted_median_fee = float(np.median(y_predicted))
output = output.append({
'block_id': name,
'min_fee': min_fee,
'median_fee': median_fee,
'predicted_mean_fee': predicted_mean_fee,
'predicted_median_fee': predicted_median_fee
}, ignore_index=True)
output.to_csv(os.path.join(PredictorTrainer.MODEL_PATH, 'evaluation_output.csv'))
def predict(self, predict, expected, model_name):
predict_scaled = self.scale_data(predict)[:, 1:]
sess, x, y, out = self.load_model(os.path.join(PredictorTrainer.MODEL_PATH, model_name))
predictions = sess.run(out, feed_dict={x: predict_scaled})
template = 'Prediction is "{}", expected "{}"\n'
output = []
i = 0
for pred, expec in zip(predictions[0, :], expected):
inversed = self.scaler.inverse_transform(np.array([[pred, predict[i][1], predict[i][2], predict[i][3]]]))
pred = inversed[0, 0]
print(template.format(pred, expec))
output.append(
{'mempool_megabytes': predict[i][1], 'mempool_tx_count': predict[i][2],
'confirmation_speed': predict[i][3],
'prediction': pred})
i += 1
return output
| [
"pandas.DataFrame",
"sklearn.externals.joblib.dump",
"tensorflow.keras.models.load_model",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"pandas.read_csv",
"sklearn.preprocessing.RobustScaler",
"numpy.floor",
"numpy.median",
"tensorflow.keras.layers.PReLU",
"pathlib.Path",
... | [((1313, 1347), 'pathlib.Path', 'Path', (['PredictorTrainer.SCALER_PATH'], {}), '(PredictorTrainer.SCALER_PATH)\n', (1317, 1347), False, 'from pathlib import Path\n'), ((2439, 2478), 'pandas.read_csv', 'pd.read_csv', (['PredictorTrainer.DATA_PATH'], {}), '(PredictorTrainer.DATA_PATH)\n', (2450, 2478), True, 'import pandas as pd\n'), ((4865, 4958), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['model_name'], {'custom_objects': "{'huber_loss': tf.losses.huber_loss}"}), "(model_name, custom_objects={'huber_loss': tf.losses\n .huber_loss})\n", (4888, 4958), False, 'from tensorflow import keras\n'), ((5027, 5049), 'pandas.read_csv', 'pd.read_csv', (['test_file'], {}), '(test_file)\n', (5038, 5049), True, 'import pandas as pd\n'), ((7502, 7611), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['block_id', 'min_fee', 'median_fee', 'predicted_mean_fee',\n 'predicted_median_fee']"}), "(columns=['block_id', 'min_fee', 'median_fee',\n 'predicted_mean_fee', 'predicted_median_fee'])\n", (7514, 7611), True, 'import pandas as pd\n'), ((1537, 1551), 'sklearn.preprocessing.RobustScaler', 'RobustScaler', ([], {}), '()\n', (1549, 1551), False, 'from sklearn.preprocessing import RobustScaler\n'), ((1737, 1791), 'sklearn.externals.joblib.dump', 'joblib.dump', (['self.scaler', 'PredictorTrainer.SCALER_PATH'], {}), '(self.scaler, PredictorTrainer.SCALER_PATH)\n', (1748, 1791), False, 'from sklearn.externals import joblib\n'), ((1938, 1979), 'sklearn.externals.joblib.load', 'joblib.load', (['PredictorTrainer.SCALER_PATH'], {}), '(PredictorTrainer.SCALER_PATH)\n', (1949, 1979), False, 'from sklearn.externals import joblib\n'), ((2209, 2226), 'numpy.floor', 'np.floor', (['(0.8 * n)'], {}), '(0.8 * n)\n', (2217, 2226), True, 'import numpy as np\n'), ((8363, 8429), 'os.path.join', 'os.path.join', (['PredictorTrainer.MODEL_PATH', '"""evaluation_output.csv"""'], {}), "(PredictorTrainer.MODEL_PATH, 'evaluation_output.csv')\n", (8375, 8429), False, 'import os\n'), ((8617, 8670), 'os.path.join', 'os.path.join', (['PredictorTrainer.MODEL_PATH', 'model_name'], {}), '(PredictorTrainer.MODEL_PATH, model_name)\n', (8629, 8670), False, 'import os\n'), ((3593, 3656), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(3)'], {'kernel_initializer': '"""normal"""', 'input_dim': '(3)'}), "(3, kernel_initializer='normal', input_dim=3)\n", (3611, 3656), False, 'from tensorflow import keras\n'), ((3661, 3714), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1024)'], {'kernel_initializer': '"""normal"""'}), "(1024, kernel_initializer='normal')\n", (3679, 3714), False, 'from tensorflow import keras\n'), ((3696, 3716), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (3714, 3716), False, 'from tensorflow import keras\n'), ((3736, 3761), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (3756, 3761), False, 'from tensorflow import keras\n'), ((3803, 3855), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(512)'], {'kernel_initializer': '"""normal"""'}), "(512, kernel_initializer='normal')\n", (3821, 3855), False, 'from tensorflow import keras\n'), ((3838, 3858), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (3856, 3858), False, 'from tensorflow import keras\n'), ((3878, 3903), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (3898, 3903), False, 'from tensorflow import keras\n'), ((3945, 3997), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(256)'], {'kernel_initializer': '"""normal"""'}), "(256, kernel_initializer='normal')\n", (3963, 3997), False, 'from tensorflow import keras\n'), ((3980, 4000), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (3998, 4000), False, 'from tensorflow import keras\n'), ((4020, 4045), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (4040, 4045), False, 'from tensorflow import keras\n'), ((4087, 4139), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(128)'], {'kernel_initializer': '"""normal"""'}), "(128, kernel_initializer='normal')\n", (4105, 4139), False, 'from tensorflow import keras\n'), ((4122, 4142), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (4140, 4142), False, 'from tensorflow import keras\n'), ((4162, 4187), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (4182, 4187), False, 'from tensorflow import keras\n'), ((4229, 4280), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(64)'], {'kernel_initializer': '"""normal"""'}), "(64, kernel_initializer='normal')\n", (4247, 4280), False, 'from tensorflow import keras\n'), ((4264, 4284), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (4282, 4284), False, 'from tensorflow import keras\n'), ((4304, 4329), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (4324, 4329), False, 'from tensorflow import keras\n'), ((4370, 4421), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(32)'], {'kernel_initializer': '"""normal"""'}), "(32, kernel_initializer='normal')\n", (4388, 4421), False, 'from tensorflow import keras\n'), ((4405, 4425), 'tensorflow.keras.layers.PReLU', 'keras.layers.PReLU', ([], {}), '()\n', (4423, 4425), False, 'from tensorflow import keras\n'), ((4445, 4470), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.1)'], {}), '(0.1)\n', (4465, 4470), False, 'from tensorflow import keras\n'), ((4508, 4558), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'kernel_initializer': '"""normal"""'}), "(1, kernel_initializer='normal')\n", (4526, 4558), False, 'from tensorflow import keras\n'), ((5446, 5475), 'numpy.where', 'np.where', (['(predicted > min_fee)'], {}), '(predicted > min_fee)\n', (5454, 5475), True, 'import numpy as np\n'), ((5502, 5534), 'numpy.where', 'np.where', (['(predicted > median_fee)'], {}), '(predicted > median_fee)\n', (5510, 5534), True, 'import numpy as np\n'), ((5578, 5636), 'numpy.where', 'np.where', (['((min_fee < predicted) & (predicted < median_fee))'], {}), '((min_fee < predicted) & (predicted < median_fee))\n', (5586, 5636), True, 'import numpy as np\n'), ((7933, 7953), 'numpy.mean', 'np.mean', (['y_predicted'], {}), '(y_predicted)\n', (7940, 7953), True, 'import numpy as np\n'), ((7997, 8019), 'numpy.median', 'np.median', (['y_predicted'], {}), '(y_predicted)\n', (8006, 8019), True, 'import numpy as np\n'), ((8956, 9019), 'numpy.array', 'np.array', (['[[pred, predict[i][1], predict[i][2], predict[i][3]]]'], {}), '([[pred, predict[i][1], predict[i][2], predict[i][3]]])\n', (8964, 9019), True, 'import numpy as np\n')] |
import binascii
import logging
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from typing import Callable, Iterable, List, Tuple
import numpy as np
from .common import S_BOX, State
from .key_expension import get_first_key
SQUARE_ROUNDS = 4
REVERSED_S_BOX = {v: k for k, v in S_BOX.items()}
def crack_key(encrypt_ds: Callable[[Iterable[State]], List[State]], rounds: int = SQUARE_ROUNDS) -> bytes:
last_key = crack_last_key(encrypt_ds)
logging.info(f"[+] Found last key: {binascii.hexlify(last_key).decode()}")
cracked_key = get_first_key(last_key, rounds + 1)
return cracked_key
def crack_last_key(encrypt_ds: Callable[[Iterable[State]], List[State]]) -> bytes:
last_bytes = [0] * 16
positions = list(range(16))
logging.info("Gathering encrypted delta set...")
encrypted_ds = gather_encrypted_delta_sets(encrypt_ds)
position_guesser = partial(guess_position, encrypted_ds)
logging.info("Cracking key...")
with ProcessPoolExecutor() as executor:
for position, found_byte in zip(positions, executor.map(position_guesser, positions)):
last_bytes[position] = found_byte
logging.info("Finished cracking key")
return bytes(last_bytes)
def gather_encrypted_delta_sets(encrypt_ds: Callable[[Iterable[State]], List[State]]) -> Iterable[Iterable[State]]:
encrypted_ds = []
for inactive_value in range(0x10):
logging.debug(f"[ ] Encrypting delta set {hex(inactive_value)}...")
ds = get_delta_set(inactive_value)
encrypted_ds.append(encrypt_ds(ds))
return encrypted_ds
def guess_position(encrypted_delta_sets: Iterable[Iterable[State]], position: int) -> int:
position_in_state = (position % 4, position // 4)
for encrypted_delta_set in encrypted_delta_sets:
correct_guesses = []
for guess in range(0x100):
reversed_bytes = reverse_state(guess, position_in_state, encrypted_delta_set)
if is_guess_correct(reversed_bytes):
correct_guesses.append(guess)
if len(correct_guesses) == 1:
break
else:
raise RuntimeError(f"Could not find byte for position {position}")
return correct_guesses[0]
def reverse_state(guess: int, position: Tuple[int, int], encrypted_ds: Iterable[State]) -> List[int]:
r = []
i, j = position
for s in encrypted_ds:
before_add_round_key = s[i, j] ^ guess
before_sub_byte = REVERSED_S_BOX[before_add_round_key]
r.append(before_sub_byte)
return r
def is_guess_correct(reversed_bytes: Iterable[int]) -> bool:
r = 0
for i in reversed_bytes:
r ^= i
return r == 0
def get_delta_set(inactive_value: int) -> List[State]:
base_state = np.full((4, 4), inactive_value)
delta_set = []
for i in range(256):
state = base_state.copy()
state[0, 0] = i
delta_set.append(state)
return delta_set
| [
"numpy.full",
"functools.partial",
"binascii.hexlify",
"concurrent.futures.ProcessPoolExecutor",
"logging.info"
] | [((781, 829), 'logging.info', 'logging.info', (['"""Gathering encrypted delta set..."""'], {}), "('Gathering encrypted delta set...')\n", (793, 829), False, 'import logging\n'), ((912, 949), 'functools.partial', 'partial', (['guess_position', 'encrypted_ds'], {}), '(guess_position, encrypted_ds)\n', (919, 949), False, 'from functools import partial\n'), ((954, 985), 'logging.info', 'logging.info', (['"""Cracking key..."""'], {}), "('Cracking key...')\n", (966, 985), False, 'import logging\n'), ((1175, 1212), 'logging.info', 'logging.info', (['"""Finished cracking key"""'], {}), "('Finished cracking key')\n", (1187, 1212), False, 'import logging\n'), ((2756, 2787), 'numpy.full', 'np.full', (['(4, 4)', 'inactive_value'], {}), '((4, 4), inactive_value)\n', (2763, 2787), True, 'import numpy as np\n'), ((995, 1016), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {}), '()\n', (1014, 1016), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((518, 544), 'binascii.hexlify', 'binascii.hexlify', (['last_key'], {}), '(last_key)\n', (534, 544), False, 'import binascii\n')] |
import pandas as pd
import numpy as np
import os
import plotly.graph_objects as go
from scipy.spatial import Delaunay
import pymatgen.core as mg
from pymatgen.ext.matproj import MPRester
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN
import itertools
from itertools import product
from bokeh.sampledata.periodic_table import elements
import networkx as nx
import matplotlib.pyplot as plt
from .element_color_schemes import ElementColorSchemes
pmg = MPRester("UP0x1rTAXR52g7pi")
elcolor = dict(zip(elements["atomic number"].values, elements["CPK"].values))
class Structure():
def __init__(self, structure_dirpath="structures/"):
self.structure_dirpath = structure_dirpath
self.element_colors = ElementColorSchemes.get_element_color_schemes()
def set_sig_fig(self, val):
try:
return '{:.3g}'.format(float(val))
except:
return val
def get_structure(self, mpid, is_primitive, scale, structure=""):
if structure == "":
structure_tmp = pmg.get_structure_by_material_id(mpid)
else:
structure_tmp = structure.copy()
sa_structure = SpacegroupAnalyzer(structure_tmp)
#print(sa_structure.get_space_group_symbol())
if is_primitive:
#structure = structure.get_primitive_structure()
structure = sa_structure.get_primitive_standard_structure()
structure.make_supercell([scale, scale, scale])
else:
#structure = structure.get_primitive_structure().get_reduced_structure()
structure = sa_structure.get_refined_structure()
structure.make_supercell([scale, scale, scale])
return structure
def get_mpdata_from_composition(self, composition):
properties = ["task_id", "pretty_formula", "spacegroup.symbol", "formation_energy_per_atom", "e_above_hull", "band_gap"]
mpdata = pmg.query(criteria=composition, properties=properties)
df_mpdata = pd.DataFrame(mpdata)
df_mpdata = df_mpdata.rename(columns={"task_id": "mpid"})
df_mpdata = df_mpdata.applymap(self.set_sig_fig)
df_mpdata = df_mpdata.sort_values("e_above_hull")
return df_mpdata
def my_round(self, val, digit=2):
p = 10 ** digit
return (val * p * 2 + 1) // 2 / p
def get_round(self, arr,digit=2):
res = np.array([self.my_round(val,digit) for val in arr])
return res
def get_delaunay_ctn(self, mpid="mp-19717", scale=1, is_primitive=False, structure=""):
structure_tmp = self.get_structure(mpid, is_primitive, scale, structure=structure)
structure_tmp.make_supercell([5, 5, 5])
xyz_list = [site["xyz"] for site in structure_tmp.as_dict()["sites"]] # Information on each site in the crystal structure
label_list = [site["label"] for site in structure_tmp.as_dict()["sites"]]
matrix = structure_tmp.lattice.matrix
a, b, c = self.get_round(structure_tmp.lattice.abc)
tri = Delaunay(xyz_list)
simplices_all = tri.simplices
points_all = tri.points
tol = 0.05 #Error in atomic coordinates[angstrom]
include_idxs = []
for i, point in enumerate(points_all):
abc_mat = self.get_round(structure_tmp.lattice.get_vector_along_lattice_directions(point))
if (abc_mat[0]>=(a*2/5)-tol) and (abc_mat[1]>=(b*2/5)-tol) and (abc_mat[2]>=(c*2/5)-tol) and (abc_mat[0]<=(a*3/5)+tol) and (abc_mat[1]<=(b*3/5)+tol) and (abc_mat[2]<=(c*3/5)+tol):
include_idxs.append(i)
ijklist = []
pidxs = []
for tet in simplices_all:
if len(set(tet)&set(include_idxs)) > 0:
tet = np.sort(tet)
i = tet[0]
j = tet[1]
k = tet[2]
w = tet[3]
ijklist.append((i, j, k, w))
pidxs.extend((i, j, k, w))
pidxs = list(set(pidxs))
atom_idx_dict = dict(zip(set(np.array(label_list)), range(len(set(np.array(label_list))))))
viz_points = []
atoms_radius = []
atoms_color = []
atom_idxs = []
atom_species = []
pidx_dict = {}
for i, pidx in enumerate(np.sort(pidxs)):
viz_points.append(points_all[pidx])
if mg.Element(label_list[pidx]).atomic_radius != None:
atoms_radius.append(mg.Element(label_list[pidx]).atomic_radius*(10/scale))
else:
atoms_radius.append(10/scale)
#atoms_color.append(elements[elements["symbol"]==label_list[pidx]]["CPK"].values[0])
atoms_color.append(self.element_colors["VESTA"][label_list[pidx]])
atom_idxs.append(atom_idx_dict[label_list[pidx]])
atom_species.append(label_list[pidx])
pidx_dict[pidx] = i
viz_ijk = []
for ijk in ijklist:
ijk_tmp = []
for tmp in ijk:
ijk_tmp.append(pidx_dict[tmp])
viz_ijk.append(tuple(ijk_tmp))
pts = np.array(viz_points)
ijk = np.array(list(set(viz_ijk)))
return {"pts": pts, "ijk": ijk, "matrix":matrix, "atom_species": atom_species, "atoms_radius": atoms_radius, "atoms_color": atoms_color, "atom_idxs": atom_idxs}
def get_delaunay_ctn_multipro(self, mpid, is_primitive, scale, structure):
delaunay_dict = {}
delaunay_data = list(self.get_delaunay_ctn(mpid=mpid, is_primitive=is_primitive, scale=scale, structure=structure).values())
delaunay_dict[mpid] = delaunay_data
return delaunay_dict
def get_delaunay_cfn(self, mpid="mp-19717", scale=1, is_primitive=False, structure=""):
structure_tmp = self.get_structure(mpid, is_primitive, scale, structure=structure)
structure_tmp.make_supercell([5, 5, 5])
xyz_list = [site["xyz"] for site in structure_tmp.as_dict()["sites"]] # Information on each site in the crystal structure
label_list = [site["label"] for site in structure_tmp.as_dict()["sites"]]
matrix = structure_tmp.lattice.matrix
a, b, c = self.get_round(structure_tmp.lattice.abc)
tri = Delaunay(xyz_list)
simplices_all = tri.simplices
points_all = tri.points
tol = 0.05 #Error in atomic coordinates[angstrom]
include_idxs = []
for i, point in enumerate(points_all):
abc_mat = self.get_round(structure_tmp.lattice.get_vector_along_lattice_directions(point))
if (abc_mat[0]>=(a*2/5)-tol) and (abc_mat[1]>=(b*2/5)-tol) and (abc_mat[2]>=(c*2/5)-tol) and (abc_mat[0]<=(a*3/5)+tol) and (abc_mat[1]<=(b*3/5)+tol) and (abc_mat[2]<=(c*3/5)+tol):
include_idxs.append(i)
ijklist = []
pidxs = []
for tet in simplices_all:
if len(set(tet)&set(include_idxs)) > 0:
for comb in itertools.combinations(tet, 3):
comb = np.sort(comb)
i = comb[0]
j = comb[1]
k = comb[2]
ijklist.append((i, j, k))
pidxs.extend((i, j, k))
pidxs = list(set(pidxs))
atom_idx_dict = dict(zip(set(np.array(label_list)), range(len(set(np.array(label_list))))))
viz_points = []
atoms_radius = []
atoms_color = []
atom_idxs = []
atom_species = []
pidx_dict = {}
for i, pidx in enumerate(np.sort(pidxs)):
viz_points.append(points_all[pidx])
if mg.Element(label_list[pidx]).atomic_radius != None:
atoms_radius.append(mg.Element(label_list[pidx]).atomic_radius*(10/scale))
else:
atoms_radius.append(10/scale)
#atoms_color.append(elements[elements["symbol"]==label_list[pidx]]["CPK"].values[0])
atoms_color.append(self.element_colors["VESTA"][label_list[pidx]])
atom_idxs.append(atom_idx_dict[label_list[pidx]])
atom_species.append(label_list[pidx])
pidx_dict[pidx] = i
viz_ijk = []
for ijk in ijklist:
ijk_tmp = []
for tmp in ijk:
ijk_tmp.append(pidx_dict[tmp])
viz_ijk.append(tuple(ijk_tmp))
pts = np.array(viz_points)
ijk = np.array(list(set(viz_ijk)))
return {"pts": pts, "ijk": ijk, "matrix":matrix, "atom_species": atom_species, "atoms_radius": atoms_radius, "atoms_color": atoms_color, "atom_idxs": atom_idxs}
def get_delaunay_multipro(self, mpid, is_primitive, scale, structure):
delaunay_dict = {}
delaunay_data = list(self.get_delaunay_cfn(mpid=mpid, is_primitive=is_primitive, scale=scale, structure=structure).values())
delaunay_dict[mpid] = delaunay_data
return delaunay_dict
def show_delaunay(self, mpid="mp-19717", scale=1, is_primitive=False, structure=""):
pts, ijk, matrix, atom_species, atoms_radius, atoms_color, atom_idxs = self.get_delaunay_cfn(mpid=mpid, scale=scale, is_primitive=is_primitive, structure=structure).values()
x, y, z = pts.T
i, j, k = ijk.T
xyz = list(product([2/5,3/5], repeat=3))
xyz = [np.dot(np.array(xyz_tmp),matrix) for xyz_tmp in xyz]
xx,yy,zz = np.array([xyz[0],xyz[1],xyz[3],xyz[2],xyz[0]
,xyz[4],xyz[5],xyz[1]
,xyz[3],xyz[7],xyz[5]
,xyz[5],xyz[7],xyz[6],xyz[4]
,xyz[6],xyz[2]]).T
fig = go.Figure(data=[go.Mesh3d(x=np.array(x), y=np.array(y), z=np.array(z),
color='lightblue',
opacity=0.2,
flatshading=True,
contour=dict(show=False),
hoverinfo="text",
i = i,
j = j,
k = k),
go.Scatter3d(x=x, y=y, z=z, mode='markers',
#hoverinfo="text",
#hovertext=atom_species,
marker=dict(
size=atoms_radius,
color=atoms_color,
opacity=0.8
)
),
go.Scatter3d(x=xx,
y=yy,
z=zz,
#hoverinfo="text",
mode='lines',
name='',
line=dict(color= 'rgb(70,70,70)', width=2))]
)
fig.update_layout(
margin=dict(l=0, r=0, t=10, b=0),
autosize=False,
width=700,
height=700,
scene=dict(
xaxis=dict(showgrid=False, showbackground=True, showticklabels=False, title="x"),
yaxis=dict(showgrid=False, showbackground=True ,showticklabels=False, title="y"),
zaxis=dict(showgrid=False, showbackground=True, showticklabels=False, title="z")
)
)
fig.update_scenes(camera_projection=dict(type="orthographic"))
fig.show()
def get_delaunay_to_offformat(self, mpid="mp-19717", scale=1, is_primitive=False, structure="", nodes=False):
pts, ijks, _, atom_species, _, _, _ = self.get_delaunay_cfn(mpid=mpid, scale=scale, is_primitive=is_primitive, structure=structure).values()
offtext = "OFF\n"
offtext += str(len(pts)) + " " + str(len(ijks)) + " 0\n"
for pt in pts:
offtext += " ".join(map(str, pt)) + "\n"
for ijk in ijks:
offtext += str(len(ijk)) + " " + " ".join(map(str, ijk)) + "\n"
if nodes:
offtext += "\n".join(map(str, atom_species))
if not os.path.exists(self.structure_dirpath):
os.mkdir(self.structure_dirpath)
if not os.path.exists(self.structure_dirpath+"mp_delaunay_offformat/"):
os.mkdir(self.structure_dirpath+"mp_delaunay_offformat/")
# Refactor: Add naming process when mpid is missing
with open(self.structure_dirpath+"mp_delaunay_offformat/"+mpid+".off", mode='w') as f:
f.write(offtext)
return offtext
def get_delaunay_to_objformat(self, mpid="mp-19717", scale=1, is_primitive=False, structure=""):
pts, ijks, _, atom_species, _, _, _ = self.get_delaunay_cfn(mpid=mpid, scale=scale, is_primitive=is_primitive, structure=structure).values()
objtext ="####\n#\n# OBJ File Generated by Pyklab\n#\n####\n"+ \
"# Object "+mpid+".obj\n"+ \
"#\n# Vertices: "+str(len(pts))+"\n"+ \
"# Faces: "+str(len(ijks))+"\n#\n####\n"
for pt in pts:
objtext += "v " + " ".join(map(str, pt)) + "\n"
objtext += "\n"
for ijk in ijks:
ijk = map(lambda x: x+1, ijk)
objtext += "f " + " ".join(map(str, ijk)) + "\n"
objtext += "\n# End of File"
if not os.path.exists(self.structure_dirpath):
os.mkdir(self.structure_dirpath)
if not os.path.exists(self.structure_dirpath+"mp_delaunay_objformat/"):
os.mkdir(self.structure_dirpath+"mp_delaunay_objformat/")
# Refactor: Add naming process when mpid is missing
with open(self.structure_dirpath+"mp_delaunay_objformat/"+mpid+".obj", mode='w') as f:
f.write(objtext)
return objtext
def create_crystal_graph(self, structure, graphtype="IsayevNN"):
#https://pymatgen.org/pymatgen.analysis.local_env.html
#IsayevNN: https://www.nature.com/articles/ncomms15679.pdf
if graphtype == "IsayevNN":
nn = IsayevNN(cutoff=6, allow_pathological=True)
elif graphtype == "MinimumDistanceNN":
nn = MinimumDistanceNN(cutoff=5)
elif graphtype == "CrystalNN":
nn = CrystalNN()
elif graphtype == "CutOffDictNN":
nn = CutOffDictNN()
elif graphtype == "EconNN":
nn = EconNN()
elif graphtype == "JmolNN":
nn = JmolNN()
elif graphtype == "MinimumOKeeffeNN":
nn = MinimumOKeeffeNN()
elif graphtype == "MinimumVIRENN":
nn = MinimumVIRENN()
elif graphtype == "VoronoiNN":
nn = VoronoiNN()
originalsites = {}
originalsites_inv = {}
for site in structure.sites:
originalsites[site] = nn._get_original_site(structure, site)
originalsites_inv[nn._get_original_site(structure, site)] = site
nodes = {} # ノードの初期化
edges = {} # エッジの初期化
adj = [] # 隣接行列の初期化
weights = [] # 重み行列の初期化
distances = [] # 原子間距離行列の初期化
# 元の各サイト
for i, basesite in enumerate(nn.get_all_nn_info(structure)):
orisite1 = originalsites_inv[i]
nodes[i] = orisite1.as_dict()["species"][0]["element"]
sitenum = structure.num_sites # 元の結晶構造のサイト数
adj.append([0]*sitenum) # 隣接行列の初期化
weights.append([0]*sitenum) # 重み行列の初期化
distances.append([0]*sitenum) # 原子間距離行列の初期化
# uniquesite = []
# 各隣接サイト
for neighbor in basesite:
# 隣接サイトと同一の元サイトの探索
# for orisite2 in list(originalsites.keys()):
for orisite2 in list(originalsites.keys())[i+1:]:
# https://pymatgen.org/pymatgen.core.sites.html
# 同一サイトであるか判定
if neighbor["site"].is_periodic_image(orisite2):
adj[i][originalsites[orisite2]] += 1
weights[i][originalsites[orisite2]] += neighbor["weight"]
distances[i][originalsites[orisite2]] += orisite1.distance(neighbor["site"])
edges.setdefault(i, [])
edges[i].append(originalsites[orisite2])
break
return nodes, edges, adj, weights, distances
def view_graph(self, graph, node2atom):
g_nodes = [mg.Composition(node).elements[0].symbol for node in graph.nodes]
pos = nx.spring_layout(graph) # ,k=10)
if len(graph.edges) > 0:
edge_labels = {}
u, v, d = np.array(list(graph.edges(data=True))).T
sites = list(zip(u, v))
for st in sites:
edge_labels.setdefault(st, 0)
edge_labels[st] += 1
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels, font_size=5)
else:
print("No edges")
nx.draw_networkx(graph, pos, font_size=5, width=0.5, node_color=[elcolor[node2atom[node]] for node in g_nodes],
node_size=[mg.Element(node).atomic_radius*100 for node in g_nodes])
def visualize_crystal_graph(self, nodes, edges, distances):
G = nx.MultiGraph()
node2atom = {}
atomcount = {}
renamenodes = {}
for siteidx, el in nodes.items():
atomcount.setdefault(el, 0)
atomcount[el] += 1
renamenodes[siteidx] = el + str(atomcount[el])
G.add_node(renamenodes[siteidx])
node2atom[el] = mg.Element(el).number
for siteidx, edge in edges.items():
for i, e in enumerate(edge):
G.add_edge(renamenodes[siteidx], renamenodes[e], length=distances[siteidx][e])
fig = plt.figure(figsize=(3, 3), dpi=300, facecolor='w', edgecolor='k')
ax = fig.add_subplot(1, 1, 1)
# Remove axis ticks
ax.tick_params(labelbottom="off", bottom="off")
ax.tick_params(labelleft="off", left="off")
# Remove labels
ax.set_xticklabels([])
# Remove axis
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['left'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['bottom'].set_visible(False)
plt.grid(False)
self.view_graph(G, node2atom)
plt.show()
def check_edges(self, adj, searchlist, connects):
new_searchlist = []
for sl in searchlist:
connects[sl] = 1
save_idxs = np.array(connects)^np.array([1]*len(adj))
idxs = np.array(adj[sl]>0, dtype=int)
searchidx = idxs & save_idxs
new_searchlist.extend(np.where(np.array(searchidx) > 0)[0])
new_searchlist = list(set(new_searchlist))
if len(new_searchlist) <= 0:
return np.sum(connects) == len(adj)
return self.check_edges(adj, new_searchlist, connects)
def is_cg_mpid(self, mpid, structure_tmp, is_primitive, scale, graphtype):
try:
structure = self.get_structure(mpid,is_primitive, scale,structure_tmp)
_, _, adj, _, _ = self.create_crystal_graph(structure, graphtype)
adj = np.array(adj)+np.array(adj).T
if len(adj) > 1:
connect_idxs = [0]*len(adj)
startnode = [0]
if self.check_edges(adj, startnode, connect_idxs):
return True, mpid
else:
return False, mpid
else:
return False, mpid
except:
return False, mpid
def get_space_group_number(self, mpid, structure_tmp):
return SpacegroupAnalyzer(structure_tmp).get_space_group_number()
def get_crystal_system_number(self, mpid, structure_tmp):
cs_dict = {'trigonal': 0,
'monoclinic': 1,
'tetragonal': 2,
'triclinic': 3,
'cubic': 4,
'orthorhombic': 5,
'hexagonal': 6}
return cs_dict[SpacegroupAnalyzer(structure_tmp).get_crystal_system()] | [
"os.mkdir",
"numpy.sum",
"networkx.MultiGraph",
"matplotlib.pyplot.figure",
"pymatgen.analysis.local_env.MinimumDistanceNN",
"matplotlib.pyplot.gca",
"networkx.draw_networkx_edge_labels",
"pymatgen.ext.matproj.MPRester",
"pymatgen.analysis.local_env.CrystalNN",
"scipy.spatial.Delaunay",
"pandas.... | [((615, 643), 'pymatgen.ext.matproj.MPRester', 'MPRester', (['"""UP0x1rTAXR52g7pi"""'], {}), "('UP0x1rTAXR52g7pi')\n", (623, 643), False, 'from pymatgen.ext.matproj import MPRester\n'), ((1310, 1343), 'pymatgen.symmetry.analyzer.SpacegroupAnalyzer', 'SpacegroupAnalyzer', (['structure_tmp'], {}), '(structure_tmp)\n', (1328, 1343), False, 'from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n'), ((2139, 2159), 'pandas.DataFrame', 'pd.DataFrame', (['mpdata'], {}), '(mpdata)\n', (2151, 2159), True, 'import pandas as pd\n'), ((3164, 3182), 'scipy.spatial.Delaunay', 'Delaunay', (['xyz_list'], {}), '(xyz_list)\n', (3172, 3182), False, 'from scipy.spatial import Delaunay\n'), ((5242, 5262), 'numpy.array', 'np.array', (['viz_points'], {}), '(viz_points)\n', (5250, 5262), True, 'import numpy as np\n'), ((6357, 6375), 'scipy.spatial.Delaunay', 'Delaunay', (['xyz_list'], {}), '(xyz_list)\n', (6365, 6375), False, 'from scipy.spatial import Delaunay\n'), ((8495, 8515), 'numpy.array', 'np.array', (['viz_points'], {}), '(viz_points)\n', (8503, 8515), True, 'import numpy as np\n'), ((16717, 16740), 'networkx.spring_layout', 'nx.spring_layout', (['graph'], {}), '(graph)\n', (16733, 16740), True, 'import networkx as nx\n'), ((17453, 17468), 'networkx.MultiGraph', 'nx.MultiGraph', ([], {}), '()\n', (17466, 17468), True, 'import networkx as nx\n'), ((18003, 18068), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3, 3)', 'dpi': '(300)', 'facecolor': '"""w"""', 'edgecolor': '"""k"""'}), "(figsize=(3, 3), dpi=300, facecolor='w', edgecolor='k')\n", (18013, 18068), True, 'import matplotlib.pyplot as plt\n'), ((18538, 18553), 'matplotlib.pyplot.grid', 'plt.grid', (['(False)'], {}), '(False)\n', (18546, 18553), True, 'import matplotlib.pyplot as plt\n'), ((18601, 18611), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18609, 18611), True, 'import matplotlib.pyplot as plt\n'), ((4419, 4433), 'numpy.sort', 'np.sort', (['pidxs'], {}), '(pidxs)\n', (4426, 4433), True, 'import numpy as np\n'), ((7672, 7686), 'numpy.sort', 'np.sort', (['pidxs'], {}), '(pidxs)\n', (7679, 7686), True, 'import numpy as np\n'), ((9395, 9428), 'itertools.product', 'product', (['[2 / 5, 3 / 5]'], {'repeat': '(3)'}), '([2 / 5, 3 / 5], repeat=3)\n', (9402, 9428), False, 'from itertools import product\n'), ((9513, 9663), 'numpy.array', 'np.array', (['[xyz[0], xyz[1], xyz[3], xyz[2], xyz[0], xyz[4], xyz[5], xyz[1], xyz[3],\n xyz[7], xyz[5], xyz[5], xyz[7], xyz[6], xyz[4], xyz[6], xyz[2]]'], {}), '([xyz[0], xyz[1], xyz[3], xyz[2], xyz[0], xyz[4], xyz[5], xyz[1],\n xyz[3], xyz[7], xyz[5], xyz[5], xyz[7], xyz[6], xyz[4], xyz[6], xyz[2]])\n', (9521, 9663), True, 'import numpy as np\n'), ((12348, 12386), 'os.path.exists', 'os.path.exists', (['self.structure_dirpath'], {}), '(self.structure_dirpath)\n', (12362, 12386), False, 'import os\n'), ((12400, 12432), 'os.mkdir', 'os.mkdir', (['self.structure_dirpath'], {}), '(self.structure_dirpath)\n', (12408, 12432), False, 'import os\n'), ((12448, 12513), 'os.path.exists', 'os.path.exists', (["(self.structure_dirpath + 'mp_delaunay_offformat/')"], {}), "(self.structure_dirpath + 'mp_delaunay_offformat/')\n", (12462, 12513), False, 'import os\n'), ((12525, 12584), 'os.mkdir', 'os.mkdir', (["(self.structure_dirpath + 'mp_delaunay_offformat/')"], {}), "(self.structure_dirpath + 'mp_delaunay_offformat/')\n", (12533, 12584), False, 'import os\n'), ((13566, 13604), 'os.path.exists', 'os.path.exists', (['self.structure_dirpath'], {}), '(self.structure_dirpath)\n', (13580, 13604), False, 'import os\n'), ((13618, 13650), 'os.mkdir', 'os.mkdir', (['self.structure_dirpath'], {}), '(self.structure_dirpath)\n', (13626, 13650), False, 'import os\n'), ((13666, 13731), 'os.path.exists', 'os.path.exists', (["(self.structure_dirpath + 'mp_delaunay_objformat/')"], {}), "(self.structure_dirpath + 'mp_delaunay_objformat/')\n", (13680, 13731), False, 'import os\n'), ((13743, 13802), 'os.mkdir', 'os.mkdir', (["(self.structure_dirpath + 'mp_delaunay_objformat/')"], {}), "(self.structure_dirpath + 'mp_delaunay_objformat/')\n", (13751, 13802), False, 'import os\n'), ((14262, 14305), 'pymatgen.analysis.local_env.IsayevNN', 'IsayevNN', ([], {'cutoff': '(6)', 'allow_pathological': '(True)'}), '(cutoff=6, allow_pathological=True)\n', (14270, 14305), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((17036, 17114), 'networkx.draw_networkx_edge_labels', 'nx.draw_networkx_edge_labels', (['graph', 'pos'], {'edge_labels': 'edge_labels', 'font_size': '(5)'}), '(graph, pos, edge_labels=edge_labels, font_size=5)\n', (17064, 17114), True, 'import networkx as nx\n'), ((18839, 18871), 'numpy.array', 'np.array', (['(adj[sl] > 0)'], {'dtype': 'int'}), '(adj[sl] > 0, dtype=int)\n', (18847, 18871), True, 'import numpy as np\n'), ((3877, 3889), 'numpy.sort', 'np.sort', (['tet'], {}), '(tet)\n', (3884, 3889), True, 'import numpy as np\n'), ((7076, 7106), 'itertools.combinations', 'itertools.combinations', (['tet', '(3)'], {}), '(tet, 3)\n', (7098, 7106), False, 'import itertools\n'), ((9447, 9464), 'numpy.array', 'np.array', (['xyz_tmp'], {}), '(xyz_tmp)\n', (9455, 9464), True, 'import numpy as np\n'), ((14370, 14397), 'pymatgen.analysis.local_env.MinimumDistanceNN', 'MinimumDistanceNN', ([], {'cutoff': '(5)'}), '(cutoff=5)\n', (14387, 14397), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((17785, 17799), 'pymatgen.core.Element', 'mg.Element', (['el'], {}), '(el)\n', (17795, 17799), True, 'import pymatgen.core as mg\n'), ((18778, 18796), 'numpy.array', 'np.array', (['connects'], {}), '(connects)\n', (18786, 18796), True, 'import numpy as np\n'), ((19103, 19119), 'numpy.sum', 'np.sum', (['connects'], {}), '(connects)\n', (19109, 19119), True, 'import numpy as np\n'), ((19476, 19489), 'numpy.array', 'np.array', (['adj'], {}), '(adj)\n', (19484, 19489), True, 'import numpy as np\n'), ((19952, 19985), 'pymatgen.symmetry.analyzer.SpacegroupAnalyzer', 'SpacegroupAnalyzer', (['structure_tmp'], {}), '(structure_tmp)\n', (19970, 19985), False, 'from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n'), ((4176, 4196), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (4184, 4196), True, 'import numpy as np\n'), ((4499, 4527), 'pymatgen.core.Element', 'mg.Element', (['label_list[pidx]'], {}), '(label_list[pidx])\n', (4509, 4527), True, 'import pymatgen.core as mg\n'), ((7135, 7148), 'numpy.sort', 'np.sort', (['comb'], {}), '(comb)\n', (7142, 7148), True, 'import numpy as np\n'), ((7429, 7449), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7437, 7449), True, 'import numpy as np\n'), ((7752, 7780), 'pymatgen.core.Element', 'mg.Element', (['label_list[pidx]'], {}), '(label_list[pidx])\n', (7762, 7780), True, 'import pymatgen.core as mg\n'), ((14454, 14465), 'pymatgen.analysis.local_env.CrystalNN', 'CrystalNN', ([], {}), '()\n', (14463, 14465), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((19490, 19503), 'numpy.array', 'np.array', (['adj'], {}), '(adj)\n', (19498, 19503), True, 'import numpy as np\n'), ((20300, 20333), 'pymatgen.symmetry.analyzer.SpacegroupAnalyzer', 'SpacegroupAnalyzer', (['structure_tmp'], {}), '(structure_tmp)\n', (20318, 20333), False, 'from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n'), ((14525, 14539), 'pymatgen.analysis.local_env.CutOffDictNN', 'CutOffDictNN', ([], {}), '()\n', (14537, 14539), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((16638, 16658), 'pymatgen.core.Composition', 'mg.Composition', (['node'], {}), '(node)\n', (16652, 16658), True, 'import pymatgen.core as mg\n'), ((18328, 18337), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18335, 18337), True, 'import matplotlib.pyplot as plt\n'), ((18381, 18390), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18388, 18390), True, 'import matplotlib.pyplot as plt\n'), ((18433, 18442), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18440, 18442), True, 'import matplotlib.pyplot as plt\n'), ((18484, 18493), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (18491, 18493), True, 'import matplotlib.pyplot as plt\n'), ((4213, 4233), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (4221, 4233), True, 'import numpy as np\n'), ((4587, 4615), 'pymatgen.core.Element', 'mg.Element', (['label_list[pidx]'], {}), '(label_list[pidx])\n', (4597, 4615), True, 'import pymatgen.core as mg\n'), ((7466, 7486), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7474, 7486), True, 'import numpy as np\n'), ((7840, 7868), 'pymatgen.core.Element', 'mg.Element', (['label_list[pidx]'], {}), '(label_list[pidx])\n', (7850, 7868), True, 'import pymatgen.core as mg\n'), ((9772, 9783), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (9780, 9783), True, 'import numpy as np\n'), ((9787, 9798), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (9795, 9798), True, 'import numpy as np\n'), ((9802, 9813), 'numpy.array', 'np.array', (['z'], {}), '(z)\n', (9810, 9813), True, 'import numpy as np\n'), ((14593, 14601), 'pymatgen.analysis.local_env.EconNN', 'EconNN', ([], {}), '()\n', (14599, 14601), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((17319, 17335), 'pymatgen.core.Element', 'mg.Element', (['node'], {}), '(node)\n', (17329, 17335), True, 'import pymatgen.core as mg\n'), ((18954, 18973), 'numpy.array', 'np.array', (['searchidx'], {}), '(searchidx)\n', (18962, 18973), True, 'import numpy as np\n'), ((14655, 14663), 'pymatgen.analysis.local_env.JmolNN', 'JmolNN', ([], {}), '()\n', (14661, 14663), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((14727, 14745), 'pymatgen.analysis.local_env.MinimumOKeeffeNN', 'MinimumOKeeffeNN', ([], {}), '()\n', (14743, 14745), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((14806, 14821), 'pymatgen.analysis.local_env.MinimumVIRENN', 'MinimumVIRENN', ([], {}), '()\n', (14819, 14821), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n'), ((14878, 14889), 'pymatgen.analysis.local_env.VoronoiNN', 'VoronoiNN', ([], {}), '()\n', (14887, 14889), False, 'from pymatgen.analysis.local_env import IsayevNN, MinimumDistanceNN, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumOKeeffeNN, MinimumVIRENN, VoronoiNN\n')] |
"""
----------------------------------------------------------------------------------------
Copyright (c) 2020 - see AUTHORS file
This file is part of the ARTHuS software.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU Affero General Public License as published by the Free Software Foundation,
either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this
program. If not, see < [ https://www.gnu.org/licenses/ | https://www.gnu.org/licenses/ ] >.
----------------------------------------------------------------------------------------
"""
import os
import cv2
import glob
import torch
import natsort
import numpy as np
from tqdm import tqdm
import utils.filterOperations as filterOperations
from arguments_benchmark import args
def load_from_folder(directory, normalized=True, device="cpu", append_original=None, append_mask=None, append_border=None):
# Get all file names
filename_list_original = natsort.natsorted(glob.glob(directory + "/original_*.png"))
filename_list_masks = natsort.natsorted(glob.glob(directory + "/mask_*.png"))
if append_mask == None or append_original == None:
append_original = list()
append_mask = list()
pbar = tqdm(total = len(filename_list_original))
for file_original, file_mask in zip(filename_list_original, filename_list_masks):
tmp_image = cv2.imread(file_original, cv2.IMREAD_COLOR)
tmp_label = cv2.imread(file_mask, cv2.IMREAD_GRAYSCALE)
if append_border is not None:
append_border.append(borderMask(tmp_label, int(args.border[0]), int(args.border[1])))
torch_image = torch.from_numpy(tmp_image).to(device).type(torch.float).transpose(0,2).transpose(1,2)
torch_label = torch.from_numpy(tmp_label).to(device).type(torch.float)
torch_label = 1-(torch_label/255)
torch_label = torch_label.type(torch.long).unsqueeze_(0)
if normalized:
torch_image = ((torch_image*2)/255) -1
append_original.append(torch_image.unsqueeze_(0).to("cpu"))
append_mask.append(torch_label.to("cpu"))
pbar.update(1)
pbar.close()
return append_original, append_mask, append_border
def compute_weights(labels):
total = 0
total_foreground = 0
for label in labels:
total_foreground += torch.sum(label == 0).to("cpu").numpy()
total += label.size()[1] * label.size()[2]
percentage = total_foreground/total
weights = torch.Tensor(2)
weights[0] = 1/percentage
weights[1] = 1/(1-percentage)
return weights
class ConfusionMatrix:
def __init__(self, device):
self.TP = 0
self.FP = 0
self.FN = 0
self.TN = 0
self.ones = None
self.zeros = None
self.device = device
def evaluate(self, mask, groundtruth):
if self.ones is None or self.zeros is None:
self.update(groundtruth.size()[0], groundtruth.size()[1])
self.ones = self.ones.to(self.device)
self.zeros = self.zeros.to(self.device)
TP_mask = torch.where((mask == 1) & (groundtruth == 1), self.ones, self.zeros)
FP_mask = torch.where((mask == 1) & (groundtruth == 0), self.ones, self.zeros)
FN_mask = torch.where((mask == 0) & (groundtruth == 1), self.ones, self.zeros)
TN_mask = torch.where((mask == 0) & (groundtruth == 0), self.ones, self.zeros)
self.TP += torch.sum(TP_mask)
self.FP += torch.sum(FP_mask)
self.FN += torch.sum(FN_mask)
self.TN += torch.sum(TN_mask)
self.ones = self.ones.to("cpu")
self.zeros = self.zeros.to("cpu")
def update(self, height, width):
self.ones = torch.ones((height, width), dtype=torch.float32)
self.zeros = torch.zeros((height, width), dtype=torch.float32)
def F1(self):
return ((2*self.TP)/(2*self.TP + self.FP + self.FN)).to("cpu").numpy()
def Jaccard(self):
return ((self.TP)/(self.TP + self.FP + self.FN)).to("cpu").numpy()
def Accuracy(self):
return ((self.TP + self.TN)/(self.TP + self.FP + self.FN + self.TN)).to("cpu").numpy()
def Precision(self):
return ((self.TP)/(self.TP + self.FP)).to("cpu").numpy()
def TPR(self):
return ((self.TP)/(self.TP + self.FN)).to("cpu").numpy()
def FPR(self):
return (1-((self.TN)/(self.TN+self.FP))).to("cpu").numpy()
def get_metrics(self):
return [self.F1(), self.Jaccard(), self.Precision(), self.TPR(), self.FPR(), self.Accuracy()]
def __str__(self):
print("Jaccard : ", self.Jaccard())
print("F1 : ", self.F1())
print("Precision :", self.Precision())
print("TPR : ", self.TPR())
print("FPR : ", self.FPR())
print("Accuracy : ", self.Accuracy())
print(self.TP, " - ", self.FP)
print(self.FN, " - ", self.TN)
return "-----"
def borderMask(mask, inner_border_size, outer_border_size):
mask_eroded = filterOperations.morphological_erosion(mask, 2*inner_border_size+1)
mask_dilated = filterOperations.morphological_dilation(mask, 2*outer_border_size+1)
border = mask_dilated - mask_eroded
out = np.abs(mask-0.5*border)
out_tensor = torch.from_numpy(out).type(torch.float)/255
return out_tensor | [
"torch.ones",
"torch.from_numpy",
"numpy.abs",
"utils.filterOperations.morphological_dilation",
"torch.where",
"cv2.imread",
"torch.Tensor",
"glob.glob",
"torch.zeros",
"torch.sum",
"utils.filterOperations.morphological_erosion"
] | [((2693, 2708), 'torch.Tensor', 'torch.Tensor', (['(2)'], {}), '(2)\n', (2705, 2708), False, 'import torch\n'), ((4925, 4996), 'utils.filterOperations.morphological_erosion', 'filterOperations.morphological_erosion', (['mask', '(2 * inner_border_size + 1)'], {}), '(mask, 2 * inner_border_size + 1)\n', (4963, 4996), True, 'import utils.filterOperations as filterOperations\n'), ((5009, 5081), 'utils.filterOperations.morphological_dilation', 'filterOperations.morphological_dilation', (['mask', '(2 * outer_border_size + 1)'], {}), '(mask, 2 * outer_border_size + 1)\n', (5048, 5081), True, 'import utils.filterOperations as filterOperations\n'), ((5122, 5149), 'numpy.abs', 'np.abs', (['(mask - 0.5 * border)'], {}), '(mask - 0.5 * border)\n', (5128, 5149), True, 'import numpy as np\n'), ((1326, 1366), 'glob.glob', 'glob.glob', (["(directory + '/original_*.png')"], {}), "(directory + '/original_*.png')\n", (1335, 1366), False, 'import glob\n'), ((1409, 1445), 'glob.glob', 'glob.glob', (["(directory + '/mask_*.png')"], {}), "(directory + '/mask_*.png')\n", (1418, 1445), False, 'import glob\n'), ((1700, 1743), 'cv2.imread', 'cv2.imread', (['file_original', 'cv2.IMREAD_COLOR'], {}), '(file_original, cv2.IMREAD_COLOR)\n', (1710, 1743), False, 'import cv2\n'), ((1758, 1801), 'cv2.imread', 'cv2.imread', (['file_mask', 'cv2.IMREAD_GRAYSCALE'], {}), '(file_mask, cv2.IMREAD_GRAYSCALE)\n', (1768, 1801), False, 'import cv2\n'), ((3204, 3272), 'torch.where', 'torch.where', (['((mask == 1) & (groundtruth == 1))', 'self.ones', 'self.zeros'], {}), '((mask == 1) & (groundtruth == 1), self.ones, self.zeros)\n', (3215, 3272), False, 'import torch\n'), ((3285, 3353), 'torch.where', 'torch.where', (['((mask == 1) & (groundtruth == 0))', 'self.ones', 'self.zeros'], {}), '((mask == 1) & (groundtruth == 0), self.ones, self.zeros)\n', (3296, 3353), False, 'import torch\n'), ((3366, 3434), 'torch.where', 'torch.where', (['((mask == 0) & (groundtruth == 1))', 'self.ones', 'self.zeros'], {}), '((mask == 0) & (groundtruth == 1), self.ones, self.zeros)\n', (3377, 3434), False, 'import torch\n'), ((3447, 3515), 'torch.where', 'torch.where', (['((mask == 0) & (groundtruth == 0))', 'self.ones', 'self.zeros'], {}), '((mask == 0) & (groundtruth == 0), self.ones, self.zeros)\n', (3458, 3515), False, 'import torch\n'), ((3532, 3550), 'torch.sum', 'torch.sum', (['TP_mask'], {}), '(TP_mask)\n', (3541, 3550), False, 'import torch\n'), ((3564, 3582), 'torch.sum', 'torch.sum', (['FP_mask'], {}), '(FP_mask)\n', (3573, 3582), False, 'import torch\n'), ((3596, 3614), 'torch.sum', 'torch.sum', (['FN_mask'], {}), '(FN_mask)\n', (3605, 3614), False, 'import torch\n'), ((3628, 3646), 'torch.sum', 'torch.sum', (['TN_mask'], {}), '(TN_mask)\n', (3637, 3646), False, 'import torch\n'), ((3768, 3816), 'torch.ones', 'torch.ones', (['(height, width)'], {'dtype': 'torch.float32'}), '((height, width), dtype=torch.float32)\n', (3778, 3816), False, 'import torch\n'), ((3832, 3881), 'torch.zeros', 'torch.zeros', (['(height, width)'], {'dtype': 'torch.float32'}), '((height, width), dtype=torch.float32)\n', (3843, 3881), False, 'import torch\n'), ((5160, 5181), 'torch.from_numpy', 'torch.from_numpy', (['out'], {}), '(out)\n', (5176, 5181), False, 'import torch\n'), ((2044, 2071), 'torch.from_numpy', 'torch.from_numpy', (['tmp_label'], {}), '(tmp_label)\n', (2060, 2071), False, 'import torch\n'), ((2558, 2579), 'torch.sum', 'torch.sum', (['(label == 0)'], {}), '(label == 0)\n', (2567, 2579), False, 'import torch\n'), ((1941, 1968), 'torch.from_numpy', 'torch.from_numpy', (['tmp_image'], {}), '(tmp_image)\n', (1957, 1968), False, 'import torch\n')] |
from typing import Union
from subsurface.structs import PointSet, TriSurf, LineSet, TetraMesh, StructuredGrid
from subsurface.structs.common import Common
from subsurface.structs.errors import PyVistaImportError
import numpy as np
try:
import pyvista as pv
except ImportError:
raise ImportError()
def pv_plot(meshes: list,
image_2d=False,
plotter_kwargs: dict = None,
add_mesh_kwargs: dict = None):
"""
Args:
meshes (List[pv.PolyData]):
image_2d (bool): If True convert plot to matplotlib imshow. This helps for visualizing
the plot in IDEs
plotter_kwargs (dict): pyvista.Plotter kwargs
add_mesh_kwargs (dict): pyvista.add_mesh kwargs
"""
plotter_kwargs = dict() if plotter_kwargs is None else plotter_kwargs
add_mesh_kwargs = dict() if add_mesh_kwargs is None else add_mesh_kwargs
p = pv.Plotter(**plotter_kwargs, off_screen=image_2d)
for m in meshes:
p.add_mesh(m, **add_mesh_kwargs)
if image_2d is False:
return p.show()
else:
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError('Matplotlib is necessary for generating a 2D image.')
img = p.plot(screenshot=True)
fig = plt.imshow(img[1])
plt.axis('off')
plt.show()
p.close()
return fig
def to_pyvista_points(point_set: PointSet):
"""Create pyvista.PolyData from PointSet
Args:
point_set (PointSet): Class for pointset based data structures.
Returns:
pv.PolyData
"""
poly = pv.PolyData(point_set.data.vertex)
poly.point_arrays.update(point_set.data.attributes_to_dict)
return poly
def to_pyvista_mesh(unstructured_element: Union[TriSurf]) -> pv.PolyData:
"""Create planar surface PolyData from unstructured element such as TriSurf
"""
nve = unstructured_element.data.n_vertex_per_element
vertices = unstructured_element.data.vertex
cells = np.c_[np.full(unstructured_element.data.n_elements, nve),
unstructured_element.data.cells]
mesh = pv.PolyData(vertices, cells)
mesh.cell_arrays.update(unstructured_element.data.attributes_to_dict)
mesh.point_arrays.update(unstructured_element.data.points_attributes)
return mesh
def to_pyvista_line(line_set: LineSet, as_tube=True, radius=None,
spline=False, n_interp_points=1000):
"""Create pyvista PolyData for 1D lines
Args:
line_set:
as_tube (bool):
radius (float): radius of the tube
spline: NotImplemented
n_interp_points: NotImplemented
Returns:
pv.PolyData
"""
nve = line_set.data.n_vertex_per_element
vertices = line_set.data.vertex
cells = np.c_[np.full(line_set.data.n_elements, nve),
line_set.data.cells]
if spline is False:
mesh = pv.PolyData()
mesh.points = vertices
mesh.lines = cells
else:
raise NotImplementedError
# mesh = pv.Spline(ver)
mesh.cell_arrays.update(line_set.data.attributes_to_dict)
if as_tube is True:
return mesh.tube(radius=radius)
else:
return mesh
def to_pyvista_tetra(tetra_mesh: TetraMesh):
"""Create pyvista.UnstructuredGrid"""
vertices = tetra_mesh.data.vertex
tets = tetra_mesh.data.cells
cells = np.c_[np.full(len(tets), 4), tets]
import vtk
ctypes = np.array([vtk.VTK_TETRA, ], np.int32)
mesh = pv.UnstructuredGrid(cells, ctypes, vertices)
mesh.cell_arrays.update(tetra_mesh.data.attributes_to_dict)
return mesh
def to_pyvista_grid(structured_grid: StructuredGrid, attribute: str):
ndim = structured_grid.ds.data[attribute].ndim
if ndim == 2:
meshgrid = structured_grid.meshgrid_2d(attribute)
elif ndim == 3:
meshgrid = structured_grid.meshgrid_3d
else:
raise AttributeError('The DataArray does not have valid dimensionality.')
mesh = pv.StructuredGrid(*meshgrid)
mesh.point_arrays.update({attribute: structured_grid.ds.data[attribute].values.ravel()})
return mesh | [
"numpy.full",
"matplotlib.pyplot.show",
"pyvista.StructuredGrid",
"matplotlib.pyplot.imshow",
"pyvista.UnstructuredGrid",
"pyvista.Plotter",
"matplotlib.pyplot.axis",
"numpy.array",
"pyvista.PolyData"
] | [((903, 952), 'pyvista.Plotter', 'pv.Plotter', ([], {'off_screen': 'image_2d'}), '(**plotter_kwargs, off_screen=image_2d)\n', (913, 952), True, 'import pyvista as pv\n'), ((1625, 1659), 'pyvista.PolyData', 'pv.PolyData', (['point_set.data.vertex'], {}), '(point_set.data.vertex)\n', (1636, 1659), True, 'import pyvista as pv\n'), ((2142, 2170), 'pyvista.PolyData', 'pv.PolyData', (['vertices', 'cells'], {}), '(vertices, cells)\n', (2153, 2170), True, 'import pyvista as pv\n'), ((3469, 3504), 'numpy.array', 'np.array', (['[vtk.VTK_TETRA]', 'np.int32'], {}), '([vtk.VTK_TETRA], np.int32)\n', (3477, 3504), True, 'import numpy as np\n'), ((3518, 3562), 'pyvista.UnstructuredGrid', 'pv.UnstructuredGrid', (['cells', 'ctypes', 'vertices'], {}), '(cells, ctypes, vertices)\n', (3537, 3562), True, 'import pyvista as pv\n'), ((4013, 4041), 'pyvista.StructuredGrid', 'pv.StructuredGrid', (['*meshgrid'], {}), '(*meshgrid)\n', (4030, 4041), True, 'import pyvista as pv\n'), ((1299, 1317), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img[1]'], {}), '(img[1])\n', (1309, 1317), True, 'import matplotlib.pyplot as plt\n'), ((1326, 1341), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1334, 1341), True, 'import matplotlib.pyplot as plt\n'), ((1350, 1360), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1358, 1360), True, 'import matplotlib.pyplot as plt\n'), ((2930, 2943), 'pyvista.PolyData', 'pv.PolyData', ([], {}), '()\n', (2941, 2943), True, 'import pyvista as pv\n'), ((2028, 2078), 'numpy.full', 'np.full', (['unstructured_element.data.n_elements', 'nve'], {}), '(unstructured_element.data.n_elements, nve)\n', (2035, 2078), True, 'import numpy as np\n'), ((2812, 2850), 'numpy.full', 'np.full', (['line_set.data.n_elements', 'nve'], {}), '(line_set.data.n_elements, nve)\n', (2819, 2850), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Union
import numpy
from draugr.torch_utilities import to_tensor
__author__ = "<NAME>"
import torch
__all__ = ["torch_advantage_estimate", "torch_compute_gae"]
def torch_advantage_estimate(
signal,
non_terminal,
value_estimate,
*,
discount_factor: float = 0.95,
tau: float = 0.97,
device: Union[str, torch.device] = "cpu",
normalise: bool = True,
divide_by_zero_safety: float = 1e-10,
):
"""
Computes advantages and discounted returns.
If the advantage is positive for an action, then it yielded a more positive signal than expected. And thus
expectations can be adjust to make actions more likely.
:param discount_factor:
:type discount_factor:
:param tau:
:type tau:
:return:
:rtype:
@param device:
@param tau:
@param discount_factor:
@param value_estimate:
@param non_terminal:
@param signal:
@param divide_by_zero_safety:
@param normalise:
"""
horizon_length, num_workers, *_ = signal.size()
advantages_out = torch.zeros_like(signal, device=device)
adv = torch.zeros(num_workers, device=device)
for t in reversed(range(horizon_length - 1)):
delta = (
signal[t]
+ value_estimate[t + 1] * discount_factor * non_terminal[t]
- value_estimate[t]
)
adv = adv * discount_factor * tau * non_terminal[t] + delta
advantages_out[t] = adv
if normalise:
advantages_out = (advantages_out - advantages_out.mean()) / (
advantages_out.std() + divide_by_zero_safety
)
return advantages_out
def torch_compute_gae(
signal,
non_terminal,
values,
*,
discount_factor=0.95,
gae_lambda=0.95,
device: Union[str, torch.device] = "cpu",
normalise_adv=True,
) -> torch.tensor:
"""
Computes discounted return and advantage
@param signal:
@param non_terminal:
@param values:
@param discount_factor:
@param gae_lambda:
@param device:
@param normalise:
@return:
"""
len_signal = len(signal)
assert len_signal == len(non_terminal) == len(values) - 1, (
f"{signal.shape}, {non_terminal.shape}, " f"{values.shape}"
)
ret = []
gae = 0
for step_i in reversed(range(len_signal)):
delta = (
signal[step_i]
+ discount_factor * values[step_i + 1] * non_terminal[step_i]
- values[step_i]
)
gae = delta + discount_factor * gae_lambda * non_terminal[step_i] * gae
ret.insert(0, gae + values[step_i])
ret = to_tensor(ret, device=device)
advantage = ret - values[:-1]
if normalise_adv:
advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-6)
return ret, advantage
if __name__ == "__main__":
def s():
numpy.random.seed(23)
size = (10, 3, 1)
a_size = (size[0] + 1, *size[1:])
signal = numpy.zeros(size)
non_terminal = numpy.ones(size)
value_estimate = numpy.random.random(a_size)
non_terminal[3, 0] = 0
non_terminal[8, 1] = 0
signal[-5:, :] = -1
signals = to_tensor(signal, device="cpu")
non_terminals = to_tensor(non_terminal, device="cpu")
value_estimates = to_tensor(value_estimate, device="cpu")
r, a = torch_compute_gae(signals, non_terminals, value_estimates)
print(r, a)
print(size, r.shape, a.shape)
s()
| [
"numpy.random.seed",
"torch.zeros_like",
"numpy.zeros",
"numpy.ones",
"numpy.random.random",
"torch.zeros",
"draugr.torch_utilities.to_tensor"
] | [((1035, 1074), 'torch.zeros_like', 'torch.zeros_like', (['signal'], {'device': 'device'}), '(signal, device=device)\n', (1051, 1074), False, 'import torch\n'), ((1085, 1124), 'torch.zeros', 'torch.zeros', (['num_workers'], {'device': 'device'}), '(num_workers, device=device)\n', (1096, 1124), False, 'import torch\n'), ((2549, 2578), 'draugr.torch_utilities.to_tensor', 'to_tensor', (['ret'], {'device': 'device'}), '(ret, device=device)\n', (2558, 2578), False, 'from draugr.torch_utilities import to_tensor\n'), ((2793, 2814), 'numpy.random.seed', 'numpy.random.seed', (['(23)'], {}), '(23)\n', (2810, 2814), False, 'import numpy\n'), ((2900, 2917), 'numpy.zeros', 'numpy.zeros', (['size'], {}), '(size)\n', (2911, 2917), False, 'import numpy\n'), ((2941, 2957), 'numpy.ones', 'numpy.ones', (['size'], {}), '(size)\n', (2951, 2957), False, 'import numpy\n'), ((2983, 3010), 'numpy.random.random', 'numpy.random.random', (['a_size'], {}), '(a_size)\n', (3002, 3010), False, 'import numpy\n'), ((3120, 3151), 'draugr.torch_utilities.to_tensor', 'to_tensor', (['signal'], {'device': '"""cpu"""'}), "(signal, device='cpu')\n", (3129, 3151), False, 'from draugr.torch_utilities import to_tensor\n'), ((3176, 3213), 'draugr.torch_utilities.to_tensor', 'to_tensor', (['non_terminal'], {'device': '"""cpu"""'}), "(non_terminal, device='cpu')\n", (3185, 3213), False, 'from draugr.torch_utilities import to_tensor\n'), ((3240, 3279), 'draugr.torch_utilities.to_tensor', 'to_tensor', (['value_estimate'], {'device': '"""cpu"""'}), "(value_estimate, device='cpu')\n", (3249, 3279), False, 'from draugr.torch_utilities import to_tensor\n')] |
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil -*-
# ROS imports
import roslib; roslib.load_manifest('freemovr_engine')
import rosbag
# standard Python stuff
import json
import numpy as np
import freemovr_engine.fixup_path as fixup_path
class Vec3:
def __init__(self,x=0, y=0, z=0):
self.x=x
self.y=y
self.z=z
def to_dict(self):
#this dict is usually used for serializing, and some libraries have trouble serializing
#numpy types (im looking at you ROS parameter server API)
return dict(x=float(self.x),y=float(self.y),z=float(self.z))
def point_dict_to_vec(d):
return Vec3(**d)
def range_0_2pi(angle):
"""put angle in range [0,2*pi]"""
# Given: np.fmod( -1, 3) == -1
pi2 = 2*np.pi
return np.fmod((np.fmod(angle,pi2) + pi2),pi2)
class ModelBase(object):
def get_relative_distance_to_first_surface(self, a, b):
"""return relative distance to surface from point a in direction of point b.
a is Nx3 array of points
b is Nx3 array of points
Given point A and point B, the vector S is B-A. Find t such
that tS + A is on the surface of the model.
return length N vector of relative distances
"""
raise NotImplementedError(
'derived class must provide implementation in %r'%self)
def get_first_surface(self, a, b):
"""return point on surface closest to point a in direction of point b.
a is Nx3 array of points
b is Nx3 array of points
return Nx3 array of points
"""
raise NotImplementedError(
'derived class must provide implementation in %r'%self)
def to_geom_dict(self):
raise NotImplementedError(
'derived class must provide implementation in %r'%self)
def get_center(self):
return self.center_arr
class Cylinder(ModelBase):
def __init__(self, base=None, axis=None, radius=None):
self.base = point_dict_to_vec(base)
self.axis = point_dict_to_vec(axis)
self.radius = radius
if self.base.x != 0 or self.base.y != 0 or self.base.z != 0:
raise NotImplementedError("not tested when cylinder not at origin")
if self.axis.x != 0 or self.axis.y != 0:
raise NotImplementedError("only right cylinder currently supported")
if self.axis.z <= 0:
raise NotImplementedError("only cylinder z>0 currently supported")
# keep in sync with DisplaySurfaceGeometry.cpp
self._radius = radius
self._matrix = np.eye(3) # currently we're forcing vertical cylinder, so this is OK
self._height = self.axis.z - self.base.z
self._base = np.expand_dims(np.array( (self.base.x, self.base.y, self.base.z) ),1)
self.center_arr = self._base[:,0] + np.array((0,0,self._height*0.5))
super(Cylinder,self).__init__()
def __repr__(self):
return 'Cylinder( base=%r, axis=%r, radius=%r )'%(self._base[:,0].tolist(), self.axis, self.radius )
def to_geom_dict(self):
return dict(
axis=self.axis.to_dict(),
base=self.base.to_dict(),
radius=float(self.radius),
model="cylinder")
def texcoord2worldcoord(self,tc):
# Parse inputs
tc = np.array(tc,copy=False)
assert tc.ndim==2
assert tc.shape[1]==2
tc = tc.T
# keep in sync with DisplaySurfaceGeometry.cpp
frac_theta = tc[0]
frac_height = tc[1]
angle = frac_theta * 2.0*np.pi + np.pi
c = np.cos(angle)
s = np.sin(angle)
r = self._radius
vec = np.vstack((c*r, s*r, frac_height*self._height))
result = np.dot( self._matrix, vec ) + self._base
return result.T
def worldcoord2texcoord(self,wc):
# Parse inputs
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
wc = wc.T
x,y,z = wc
x0 = x-self.base.x
y0 = y-self.base.y
z0 = z-self.base.z
angle = np.arctan2( y0, x0 )
height = z0
tc0 = range_0_2pi(angle-np.pi)/(2*np.pi)
tc1 = z0/self._height
result = np.vstack((tc0,tc1))
return result.T
def worldcoord2normal(self,wc):
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
wc = wc.T
x,y,z = wc
x0 = x-self.base.x
y0 = y-self.base.y
r = np.sqrt( x0**2 + y0**2 )
result = np.vstack( (x0/r, y0/r, z*0) )
return result.T
def get_relative_distance_to_first_surface(self, a, b):
# See ModelBase.get_relative_distance_to_first_surface for docstring
a = np.array(a,copy=False)
assert a.ndim==2
assert a.shape[1]==3
inshape = a.shape
b = np.array(b,copy=False)
assert b.ndim==2
assert b.shape[1]==3
assert b.shape==inshape
# Since our cylinder is upright, we project our line into 2D,
# solve for the intersection with the circle.
a = a.T
b = b.T
# Move so that cylinder base is at (0,0).
ax = a[0] - self.base.x
ay = a[1] - self.base.y
az = a[2] - self.base.z
bx = b[0] - self.base.x
by = b[1] - self.base.y
bz = b[2] - self.base.z
del a, b
# Now create vector between points a and b
sx = bx-ax
sy = by-ay
sz = bz-az
r = self.radius
old_settings = np.seterr(invalid='ignore') # we expect some nans below
# Solve for the intersections between line and circle (see sympy_line_circle.py for math)
t0 = (-ax*sx - ay*sy + (-ax**2*sy**2 + 2*ax*ay*sx*sy - ay**2*sx**2 + r**2*sx**2 + r**2*sy**2)**(0.5))/(sx**2 + sy**2)
t1 = (ax*sx + ay*sy + (-ax**2*sy**2 + 2*ax*ay*sx*sy - ay**2*sx**2 + r**2*sx**2 + r**2*sy**2)**(0.5))/(-sx**2 - sy**2)
tt = np.vstack((t0,t1))
np.seterr(**old_settings)
# We want t to be > 0 (in direction from camera center to
# point) but the closest one, so the smallest value meeting
# this criterion.
tt[tt <= 0] = np.nan # behind camera - invalid
# find Z coordinate of each intersection
zz = az+sz*tt
# intersections not on cylinder are invalid
tt[zz < 0] = np.nan
tt[zz > self.axis.z] = np.nan
tmin = np.nanmin(tt, axis=0) # find closest to camera
return tmin
get_relative_distance_to_first_surface.__doc__ = ModelBase.get_relative_distance_to_first_surface.__doc__ # inherit docstring
def get_first_surface(self,a,b):
# See ModelBase.get_first_surface for docstring
tmin = self.get_relative_distance_to_first_surface(a,b)
a = np.array(a,copy=False)
b = np.array(b,copy=False)
inshape = a.shape
a = a.T
b = b.T
# Move so that cylinder base is at (0,0).
ax = a[0] - self.base.x
ay = a[1] - self.base.y
az = a[2] - self.base.z
bx = b[0] - self.base.x
by = b[1] - self.base.y
bz = b[2] - self.base.z
del a, b
# Now create vector between points a and b
sx = bx-ax
sy = by-ay
sz = bz-az
x = ax+sx*tmin
y = ay+sy*tmin
z = az+sz*tmin
result = np.vstack((x,y,z)).T
assert result.shape==inshape
return result
get_first_surface.__doc__ = ModelBase.get_first_surface.__doc__ # inherit docstring
class Sphere(ModelBase):
def __init__(self, center=None, radius=None):
self.center = point_dict_to_vec(center)
self.radius = radius
# keep in sync with DisplaySurfaceGeometry.cpp
self._radius = radius
self._center = np.expand_dims(np.array( (self.center.x, self.center.y, self.center.z) ),1)
self.center_arr = self._center[:,0]
super(Sphere,self).__init__()
def __repr__(self):
return 'Sphere( center=%r, radius=%r )'%(self._center[:,0].tolist(), self.radius )
def to_geom_dict(self):
return dict(
center=self.center.to_dict(),
radius=float(self.radius),
model="sphere")
def texcoord2worldcoord(self,tc):
# Parse inputs
tc = np.array(tc,copy=False)
assert tc.ndim==2
assert tc.shape[1]==2
tc = tc.T
# keep in sync with DisplaySurfaceGeometry.cpp
frac_az = tc[0]
frac_el = tc[1]
az = frac_az * 2.0*np.pi # 0 - 2pi
el = frac_el*np.pi - np.pi/2 # -pi/2 - pi/2
ca = np.cos(az)
sa = np.sin(az)
ce = np.cos(el)
se = np.sin(el)
r = self._radius
vec = np.vstack((r*ca*ce, r*sa*ce, r*se))
result = vec + self._center
return result.T
def worldcoord2texcoord(self,wc):
# Parse inputs
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
wc = wc.T
x,y,z = wc
x0 = x-self.center.x
y0 = y-self.center.y
z0 = z-self.center.z
r = np.sqrt( x0**2 + y0**2 + z0**2 )
az = np.arctan2( y0, x0 )
el_rad = np.arcsin( z0/r )
el = el_rad / np.pi + 0.5
tc0 = range_0_2pi(az)/(2*np.pi)
tc1 = el
result = np.vstack((tc0,tc1))
return result.T
def worldcoord2normal(self,wc):
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
wc = wc.T
x,y,z = wc
x0 = x-self.center.x
y0 = y-self.center.y
z0 = z-self.center.z
r = np.sqrt( x0**2 + y0**2 + z0**2 )
result = np.vstack( (x0/r, y0/r, z0/r) )
return result.T
def get_relative_distance_to_first_surface(self, a, b):
# See ModelBase.get_relative_distance_to_first_surface for docstring
a = np.array(a,copy=False)
assert a.ndim==2
assert a.shape[1]==3
inshape = a.shape
b = np.array(b,copy=False)
assert b.ndim==2
assert b.shape[1]==3
assert b.shape==inshape
a = a.T
b = b.T
# Move so that sphere center is at (0,0).
ax = a[0] - self.center.x
ay = a[1] - self.center.y
az = a[2] - self.center.z
bx = b[0] - self.center.x
by = b[1] - self.center.y
bz = b[2] - self.center.z
del a, b
# Now create vector between points a and b
sx = bx-ax
sy = by-ay
sz = bz-az
r = self.radius
old_settings = np.seterr(invalid='ignore') # we expect some nans below
# Solve for the intersections between line and sphere (see sympy_line_sphere.py for math)
t0,t1 = [(ax*sx + ay*sy + az*sz + (-ax**2*sy**2 - ax**2*sz**2 + 2*ax*ay*sx*sy + 2*ax*az*sx*sz - ay**2*sx**2 - ay**2*sz**2 + 2*ay*az*sy*sz - az**2*sx**2 - az**2*sy**2 + r**2*sx**2 + r**2*sy**2 + r**2*sz**2)**(0.5))/(-sx**2 - sy**2 - sz**2), (-ax*sx - ay*sy - az*sz + (-ax**2*sy**2 - ax**2*sz**2 + 2*ax*ay*sx*sy + 2*ax*az*sx*sz - ay**2*sx**2 - ay**2*sz**2 + 2*ay*az*sy*sz - az**2*sx**2 - az**2*sy**2 + r**2*sx**2 + r**2*sy**2 + r**2*sz**2)**(0.5))/(sx**2 + sy**2 + sz**2)]
np.seterr(**old_settings)
tt = np.vstack((t0,t1))
# We want t to be > 0 (in direction from camera center to
# point) but the closest one, so the smallest value meeting
# this criterion.
tt[tt <= 0] = np.nan # behind camera - invalid
tmin = np.nanmin(tt, axis=0) # find closest to camera
return tmin
get_relative_distance_to_first_surface.__doc__ = ModelBase.get_relative_distance_to_first_surface.__doc__ # inherit docstring
def get_first_surface(self,a,b):
# See ModelBase.get_first_surface for docstring
tmin = self.get_relative_distance_to_first_surface(a,b)
a = np.array(a,copy=False)
inshape = a.shape
b = np.array(b,copy=False)
a = a.T
b = b.T
# Move so that sphere center is at (0,0).
ax = a[0] - self.center.x
ay = a[1] - self.center.y
az = a[2] - self.center.z
bx = b[0] - self.center.x
by = b[1] - self.center.y
bz = b[2] - self.center.z
del a, b
# Now create vector between points a and b
sx = bx-ax
sy = by-ay
sz = bz-az
x = ax+sx*tmin
y = ay+sy*tmin
z = az+sz*tmin
result = np.vstack((x+self.center.x,y+self.center.y,z+self.center.z)).T
assert result.shape==inshape
return result
get_first_surface.__doc__ = ModelBase.get_first_surface.__doc__ # inherit docstring
class PlanarRectangle(ModelBase):
def __init__(self, lowerleft=None, upperleft=None, lowerright=None):
self.left_lower_corner = point_dict_to_vec(lowerleft)
self.left_upper_corner = point_dict_to_vec(upperleft)
self.right_lower_corner = point_dict_to_vec(lowerright)
# keep in sync with DisplaySurfaceGeometry.cpp
self._left_lower_corner = np.array( (self.left_lower_corner.x,
self.left_lower_corner.y,
self.left_lower_corner.z),
dtype=np.float )
self._left_upper_corner = np.array( (self.left_upper_corner.x,
self.left_upper_corner.y,
self.left_upper_corner.z),
dtype=np.float )
self._right_lower_corner = np.array( (self.right_lower_corner.x,
self.right_lower_corner.y,
self.right_lower_corner.z),
dtype=np.float )
self._dir_u = self._right_lower_corner - self._left_lower_corner
self._dir_v = self._left_upper_corner - self._left_lower_corner
self.center_arr = self._left_lower_corner + 0.5*self._dir_u + 0.5*self._dir_v
self._normal = np.cross( self._dir_u, self._dir_v )
super(PlanarRectangle,self).__init__()
def __repr__(self):
return 'PlanarRectangle( lowerleft=%r, upperleft=%r, lowerright=%r )'%(
self._left_lower_corner[:,0].tolist(),
self._left_upper_corner[:,0].tolist(),
self._right_lower_corner[:,0].tolist(),
)
def to_geom_dict(self):
return dict(
lowerleft=self.left_lower_corner.to_dict(),
upperleft=self.left_upper_corner.to_dict(),
lowerright=self.right_lower_corner.to_dict(),
model="planar_rectangle")
def texcoord2worldcoord(self,tc):
# Parse inputs
tc = np.array(tc,copy=False)
assert tc.ndim==2
assert tc.shape[1]==2
tex_u,tex_v = tc.T
# keep in sync with DisplaySurfaceGeometry.cpp
self._dir_u[:,np.newaxis] * tex_u[np.newaxis]
self._dir_v[:,np.newaxis] * tex_v[np.newaxis]
result = self._left_lower_corner[:,np.newaxis] \
+ self._dir_u[:,np.newaxis] * tex_u[np.newaxis] \
+ self._dir_v[:,np.newaxis] * tex_v[np.newaxis]
return result.T
def worldcoord2texcoord(self,wc):
# Parse inputs
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
wc = wc.T
x,y,z = wc
x0 = x-self.left_lower_corner.x
y0 = y-self.left_lower_corner.y
z0 = z-self.left_lower_corner.z
wc = np.vstack((x0,y0,z0))
u = np.dot( self._dir_u, wc )
v = np.dot( self._dir_v, wc )
result = np.vstack((u,v))
return result.T
def worldcoord2normal(self,wc):
wc = np.array(wc,copy=False)
assert wc.ndim==2
assert wc.shape[1]==3
N = wc.shape[0]
one_sz = np.ones((1,N))
bad = np.isnan(wc[:,0])
result = (self._normal[:,np.newaxis]*one_sz).T
result[bad] = np.nan
return result
def get_relative_distance_to_first_surface(self, a, b):
# See ModelBase.get_relative_distance_to_first_surface for docstring
a = np.array(a,copy=False)
assert a.ndim==2
assert a.shape[1]==3
inshape = a.shape
b = np.array(b,copy=False)
assert b.ndim==2
assert b.shape[1]==3
assert b.shape==inshape
# See http://en.wikipedia.org/wiki/Line-plane_intersection
# especially the "Algebraic form" section.
# Create variables according to wikipedia notation linked above
l = b-a
l0 = a
n = self._normal
p0 = np.array( [self.left_lower_corner.x,
self.left_lower_corner.y,
self.left_lower_corner.z],
dtype=np.float)
# Now, do the math...
old_settings = np.seterr(invalid='ignore',divide='ignore') # we expect some nans below
d = np.dot((p0-l0),n)/np.dot(l,n)
d[np.isinf(d)] = np.nan # don't let infinity in
d[d<0] = np.nan # don't look backwards, either
np.seterr(**old_settings)
return d
get_relative_distance_to_first_surface.__doc__ = ModelBase.get_relative_distance_to_first_surface.__doc__ # inherit docstring
def get_first_surface(self,a,b):
# See ModelBase.get_first_surface for docstring
d = self.get_relative_distance_to_first_surface(a,b)
a = np.array(a,copy=False)
assert a.ndim==2
assert a.shape[1]==3
inshape = a.shape
b = np.array(b,copy=False)
assert b.ndim==2
assert b.shape[1]==3
assert b.shape==inshape
l = b-a
l0 = a
d = d[:,np.newaxis]
pt = d*l+l0
return pt
get_first_surface.__doc__ = ModelBase.get_first_surface.__doc__ # inherit docstring
def get_distance_between_point_and_ray( c, a, b ):
"""return distance between point c and ray from a in direction of point b.
c is Nx3 array of points
a is Nx3 array of points
b is Nx3 array of points
return Nx3 array of points
"""
c = np.array(c,copy=False)
assert c.ndim==2
assert c.shape[1]==3
inshape = c.shape
a = np.array(a,copy=False)
assert a.ndim==2
assert a.shape[1]==3
assert a.shape==inshape
b = np.array(b,copy=False)
assert b.ndim==2
assert b.shape[1]==3
assert b.shape==inshape
c = c.T
a = a.T
b = b.T
# Move so that sphere center is at (0,0).
ax = a[0] - c[0]
ay = a[1] - c[1]
az = a[2] - c[2]
bx = b[0] - c[0]
by = b[1] - c[1]
bz = b[2] - c[2]
del a, b
# Now create vector between points a and b
sx = bx-ax
sy = by-ay
sz = bz-az
# See sympy_line_point.py
t = -(ax*sx + ay*sy + az*sz)/(sx**2 + sy**2 + sz**2)
t = np.max(t,0) # get point a if t opposite from b
# find the point
x = ax+sx*t
y = ay+sy*t
z = az+sz*t
verts = np.vstack((x,y,z))
# now find the distance
dist = np.sqrt(np.sum((verts-c)**2,axis=0))
return dist
class Geometry:
def __init__(self, filename=None, geom_dict=None):
if filename and not geom_dict:
geom_dict = json.loads( open(filename).read() )
elif geom_dict and not filename:
pass
else:
raise Exception("must supply filename OR geometry dict (but not both)")
if geom_dict['model']=='cylinder':
self.model = Cylinder(base=geom_dict['base'],
axis=geom_dict['axis'],
radius=geom_dict['radius'])
elif geom_dict['model']=='sphere':
self.model = Sphere(center=geom_dict['center'],
radius=geom_dict['radius'])
elif geom_dict['model']=='planar_rectangle':
kwargs = geom_dict.copy()
del kwargs['model']
self.model = PlanarRectangle(**kwargs)
elif geom_dict['model']=='from_file':
import PyDisplaySurfaceArbitraryGeometry as pdsag
self.model = pdsag.ArbitraryGeometry(
filename=fixup_path.fixup_path( geom_dict['filename'] ),
precision=geom_dict.get('precision',1e-6))
else:
raise ValueError("unknown model type: %s"%geom_dict['model'])
def compute_for_camera_view(self, camera, what='world_coords'):
shape = (camera.height, camera.width)
y = np.expand_dims(np.arange(camera.height),1)
x = np.expand_dims(np.arange(camera.width),0)
XX, YY = np.broadcast_arrays(x, y)
assert XX.shape == shape
assert YY.shape == shape
XX = XX.flatten()
YY = YY.flatten()
distorted = np.vstack((XX,YY)).T
ray = camera.project_pixel_to_3d_ray(distorted,
distorted=True,
distance=1.0 )
camcenter = camera.camcenter_like(ray)
if what=='world_coords':
world_coords = self.model.get_first_surface(camcenter,ray)
rx, ry, rz = world_coords.T
# reshape into image-sized arrays
rx.shape = (camera.height, camera.width, 1)
ry.shape = (camera.height, camera.width, 1)
rz.shape = (camera.height, camera.width, 1)
output = np.concatenate((rx,ry,rz),axis=2)
assert output.shape == (camera.height, camera.width, 3)
elif what == 'texture_coords':
world_coords = self.model.get_first_surface(camcenter,ray)
texcoords = self.model.worldcoord2texcoord(world_coords)
tc0, tc1 = texcoords.T
# reshape into image-sized arrays
tc0.shape = (camera.height, camera.width, 1)
tc1.shape = (camera.height, camera.width, 1)
output = np.concatenate((tc0,tc1),axis=2)
assert output.shape == (camera.height, camera.width, 2)
elif what == 'distance':
distance = self.model.get_relative_distance_to_first_surface(camcenter,ray)
distance.shape = (camera.height, camera.width)
output = distance
elif what == 'incidence_angle':
world_coords = self.model.get_first_surface(camcenter,ray)
surface_normal = self.model.worldcoord2normal(world_coords)
projector_dir = -ray
dot_product = np.sum(projector_dir*surface_normal,axis=1)
angle = np.arccos(dot_product)
angle.shape = (camera.height, camera.width)
output = angle
return output
def angle_between_vectors(v1, v2):
dot = np.dot(v1, v2)
len_a = np.sqrt(np.dot(v1, v1))
len_b = np.sqrt(np.dot(v2, v2))
if len_a == 0 or len_b == 0:
return 0
return np.arccos(dot / (len_a * len_b))
def tcs_to_beachball(farr):
assert farr.ndim == 3
assert farr.shape[2] == 2
u = farr[:,:,0]
v = farr[:,:,1]
good = ~np.isnan( u )
assert np.allclose( good, ~np.isnan(v) )
assert np.all( u[good] >= 0 )
assert np.all( u[good] <= 1 )
assert np.all( v[good] >= 0 )
assert np.all( v[good] <= 1 )
hf = u*4 # horiz float
vf = v*2 # vert float
hi = np.floor( hf ) # horiz int (0,1,2,3)
hi[hi==4.0] = 3.0
vi = np.floor( vf ) # vert int (0,1)
vi[vi==2.0] = 1.0
iif = hi + 4*vi + 1 # (1,2,3,4,5,6,7,8)
ii = iif.astype( np.uint8 ) # nan -> 0
colors = np.array( [ (0,0,0), # black
(255,0,0), # red
(0,255,0), # green
(0, 0, 255), # blue
(255, 0, 255),
(255, 0, 255),
(255,0,0), # red
(0,255,0), # green
(0, 0, 255), # blue
])
bbim = colors[ ii ]
return bbim
| [
"numpy.arctan2",
"numpy.sum",
"numpy.floor",
"numpy.ones",
"numpy.isnan",
"numpy.sin",
"numpy.arange",
"roslib.load_manifest",
"numpy.arcsin",
"freemovr_engine.fixup_path.fixup_path",
"numpy.max",
"numpy.arccos",
"numpy.broadcast_arrays",
"numpy.fmod",
"numpy.cross",
"numpy.isinf",
"... | [((90, 129), 'roslib.load_manifest', 'roslib.load_manifest', (['"""freemovr_engine"""'], {}), "('freemovr_engine')\n", (110, 129), False, 'import roslib\n'), ((18247, 18270), 'numpy.array', 'np.array', (['c'], {'copy': '(False)'}), '(c, copy=False)\n', (18255, 18270), True, 'import numpy as np\n'), ((18347, 18370), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (18355, 18370), True, 'import numpy as np\n'), ((18453, 18476), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (18461, 18476), True, 'import numpy as np\n'), ((18964, 18976), 'numpy.max', 'np.max', (['t', '(0)'], {}), '(t, 0)\n', (18970, 18976), True, 'import numpy as np\n'), ((19093, 19113), 'numpy.vstack', 'np.vstack', (['(x, y, z)'], {}), '((x, y, z))\n', (19102, 19113), True, 'import numpy as np\n'), ((22796, 22810), 'numpy.dot', 'np.dot', (['v1', 'v2'], {}), '(v1, v2)\n', (22802, 22810), True, 'import numpy as np\n'), ((22944, 22976), 'numpy.arccos', 'np.arccos', (['(dot / (len_a * len_b))'], {}), '(dot / (len_a * len_b))\n', (22953, 22976), True, 'import numpy as np\n'), ((23186, 23206), 'numpy.all', 'np.all', (['(u[good] >= 0)'], {}), '(u[good] >= 0)\n', (23192, 23206), True, 'import numpy as np\n'), ((23220, 23240), 'numpy.all', 'np.all', (['(u[good] <= 1)'], {}), '(u[good] <= 1)\n', (23226, 23240), True, 'import numpy as np\n'), ((23254, 23274), 'numpy.all', 'np.all', (['(v[good] >= 0)'], {}), '(v[good] >= 0)\n', (23260, 23274), True, 'import numpy as np\n'), ((23288, 23308), 'numpy.all', 'np.all', (['(v[good] <= 1)'], {}), '(v[good] <= 1)\n', (23294, 23308), True, 'import numpy as np\n'), ((23375, 23387), 'numpy.floor', 'np.floor', (['hf'], {}), '(hf)\n', (23383, 23387), True, 'import numpy as np\n'), ((23443, 23455), 'numpy.floor', 'np.floor', (['vf'], {}), '(vf)\n', (23451, 23455), True, 'import numpy as np\n'), ((23600, 23733), 'numpy.array', 'np.array', (['[(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255), (255, 0, \n 255), (255, 0, 0), (0, 255, 0), (0, 0, 255)]'], {}), '([(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255),\n (255, 0, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255)])\n', (23608, 23733), True, 'import numpy as np\n'), ((2576, 2585), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (2582, 2585), True, 'import numpy as np\n'), ((3306, 3330), 'numpy.array', 'np.array', (['tc'], {'copy': '(False)'}), '(tc, copy=False)\n', (3314, 3330), True, 'import numpy as np\n'), ((3575, 3588), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (3581, 3588), True, 'import numpy as np\n'), ((3601, 3614), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (3607, 3614), True, 'import numpy as np\n'), ((3655, 3708), 'numpy.vstack', 'np.vstack', (['(c * r, s * r, frac_height * self._height)'], {}), '((c * r, s * r, frac_height * self._height))\n', (3664, 3708), True, 'import numpy as np\n'), ((3860, 3884), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (3868, 3884), True, 'import numpy as np\n'), ((4076, 4094), 'numpy.arctan2', 'np.arctan2', (['y0', 'x0'], {}), '(y0, x0)\n', (4086, 4094), True, 'import numpy as np\n'), ((4214, 4235), 'numpy.vstack', 'np.vstack', (['(tc0, tc1)'], {}), '((tc0, tc1))\n', (4223, 4235), True, 'import numpy as np\n'), ((4309, 4333), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (4317, 4333), True, 'import numpy as np\n'), ((4493, 4519), 'numpy.sqrt', 'np.sqrt', (['(x0 ** 2 + y0 ** 2)'], {}), '(x0 ** 2 + y0 ** 2)\n', (4500, 4519), True, 'import numpy as np\n'), ((4536, 4570), 'numpy.vstack', 'np.vstack', (['(x0 / r, y0 / r, z * 0)'], {}), '((x0 / r, y0 / r, z * 0))\n', (4545, 4570), True, 'import numpy as np\n'), ((4741, 4764), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (4749, 4764), True, 'import numpy as np\n'), ((4857, 4880), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (4865, 4880), True, 'import numpy as np\n'), ((5543, 5570), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (5552, 5570), True, 'import numpy as np\n'), ((5962, 5981), 'numpy.vstack', 'np.vstack', (['(t0, t1)'], {}), '((t0, t1))\n', (5971, 5981), True, 'import numpy as np\n'), ((5989, 6014), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_settings)\n', (5998, 6014), True, 'import numpy as np\n'), ((6439, 6460), 'numpy.nanmin', 'np.nanmin', (['tt'], {'axis': '(0)'}), '(tt, axis=0)\n', (6448, 6460), True, 'import numpy as np\n'), ((6807, 6830), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (6815, 6830), True, 'import numpy as np\n'), ((6842, 6865), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (6850, 6865), True, 'import numpy as np\n'), ((8321, 8345), 'numpy.array', 'np.array', (['tc'], {'copy': '(False)'}), '(tc, copy=False)\n', (8329, 8345), True, 'import numpy as np\n'), ((8633, 8643), 'numpy.cos', 'np.cos', (['az'], {}), '(az)\n', (8639, 8643), True, 'import numpy as np\n'), ((8657, 8667), 'numpy.sin', 'np.sin', (['az'], {}), '(az)\n', (8663, 8667), True, 'import numpy as np\n'), ((8682, 8692), 'numpy.cos', 'np.cos', (['el'], {}), '(el)\n', (8688, 8692), True, 'import numpy as np\n'), ((8706, 8716), 'numpy.sin', 'np.sin', (['el'], {}), '(el)\n', (8712, 8716), True, 'import numpy as np\n'), ((8758, 8803), 'numpy.vstack', 'np.vstack', (['(r * ca * ce, r * sa * ce, r * se)'], {}), '((r * ca * ce, r * sa * ce, r * se))\n', (8767, 8803), True, 'import numpy as np\n'), ((8929, 8953), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (8937, 8953), True, 'import numpy as np\n'), ((9146, 9182), 'numpy.sqrt', 'np.sqrt', (['(x0 ** 2 + y0 ** 2 + z0 ** 2)'], {}), '(x0 ** 2 + y0 ** 2 + z0 ** 2)\n', (9153, 9182), True, 'import numpy as np\n'), ((9193, 9211), 'numpy.arctan2', 'np.arctan2', (['y0', 'x0'], {}), '(y0, x0)\n', (9203, 9211), True, 'import numpy as np\n'), ((9231, 9248), 'numpy.arcsin', 'np.arcsin', (['(z0 / r)'], {}), '(z0 / r)\n', (9240, 9248), True, 'import numpy as np\n'), ((9358, 9379), 'numpy.vstack', 'np.vstack', (['(tc0, tc1)'], {}), '((tc0, tc1))\n', (9367, 9379), True, 'import numpy as np\n'), ((9453, 9477), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (9461, 9477), True, 'import numpy as np\n'), ((9670, 9706), 'numpy.sqrt', 'np.sqrt', (['(x0 ** 2 + y0 ** 2 + z0 ** 2)'], {}), '(x0 ** 2 + y0 ** 2 + z0 ** 2)\n', (9677, 9706), True, 'import numpy as np\n'), ((9721, 9756), 'numpy.vstack', 'np.vstack', (['(x0 / r, y0 / r, z0 / r)'], {}), '((x0 / r, y0 / r, z0 / r))\n', (9730, 9756), True, 'import numpy as np\n'), ((9927, 9950), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (9935, 9950), True, 'import numpy as np\n'), ((10043, 10066), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (10051, 10066), True, 'import numpy as np\n'), ((10617, 10644), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (10626, 10644), True, 'import numpy as np\n'), ((11258, 11283), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_settings)\n', (11267, 11283), True, 'import numpy as np\n'), ((11298, 11317), 'numpy.vstack', 'np.vstack', (['(t0, t1)'], {}), '((t0, t1))\n', (11307, 11317), True, 'import numpy as np\n'), ((11550, 11571), 'numpy.nanmin', 'np.nanmin', (['tt'], {'axis': '(0)'}), '(tt, axis=0)\n', (11559, 11571), True, 'import numpy as np\n'), ((11918, 11941), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (11926, 11941), True, 'import numpy as np\n'), ((11979, 12002), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (11987, 12002), True, 'import numpy as np\n'), ((13102, 13211), 'numpy.array', 'np.array', (['(self.left_lower_corner.x, self.left_lower_corner.y, self.left_lower_corner.z)'], {'dtype': 'np.float'}), '((self.left_lower_corner.x, self.left_lower_corner.y, self.\n left_lower_corner.z), dtype=np.float)\n', (13110, 13211), True, 'import numpy as np\n'), ((13377, 13486), 'numpy.array', 'np.array', (['(self.left_upper_corner.x, self.left_upper_corner.y, self.left_upper_corner.z)'], {'dtype': 'np.float'}), '((self.left_upper_corner.x, self.left_upper_corner.y, self.\n left_upper_corner.z), dtype=np.float)\n', (13385, 13486), True, 'import numpy as np\n'), ((13653, 13765), 'numpy.array', 'np.array', (['(self.right_lower_corner.x, self.right_lower_corner.y, self.\n right_lower_corner.z)'], {'dtype': 'np.float'}), '((self.right_lower_corner.x, self.right_lower_corner.y, self.\n right_lower_corner.z), dtype=np.float)\n', (13661, 13765), True, 'import numpy as np\n'), ((14155, 14189), 'numpy.cross', 'np.cross', (['self._dir_u', 'self._dir_v'], {}), '(self._dir_u, self._dir_v)\n', (14163, 14189), True, 'import numpy as np\n'), ((14845, 14869), 'numpy.array', 'np.array', (['tc'], {'copy': '(False)'}), '(tc, copy=False)\n', (14853, 14869), True, 'import numpy as np\n'), ((15395, 15419), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (15403, 15419), True, 'import numpy as np\n'), ((15646, 15669), 'numpy.vstack', 'np.vstack', (['(x0, y0, z0)'], {}), '((x0, y0, z0))\n', (15655, 15669), True, 'import numpy as np\n'), ((15680, 15703), 'numpy.dot', 'np.dot', (['self._dir_u', 'wc'], {}), '(self._dir_u, wc)\n', (15686, 15703), True, 'import numpy as np\n'), ((15718, 15741), 'numpy.dot', 'np.dot', (['self._dir_v', 'wc'], {}), '(self._dir_v, wc)\n', (15724, 15741), True, 'import numpy as np\n'), ((15761, 15778), 'numpy.vstack', 'np.vstack', (['(u, v)'], {}), '((u, v))\n', (15770, 15778), True, 'import numpy as np\n'), ((15852, 15876), 'numpy.array', 'np.array', (['wc'], {'copy': '(False)'}), '(wc, copy=False)\n', (15860, 15876), True, 'import numpy as np\n'), ((15974, 15989), 'numpy.ones', 'np.ones', (['(1, N)'], {}), '((1, N))\n', (15981, 15989), True, 'import numpy as np\n'), ((16003, 16021), 'numpy.isnan', 'np.isnan', (['wc[:, 0]'], {}), '(wc[:, 0])\n', (16011, 16021), True, 'import numpy as np\n'), ((16277, 16300), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (16285, 16300), True, 'import numpy as np\n'), ((16393, 16416), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (16401, 16416), True, 'import numpy as np\n'), ((16763, 16872), 'numpy.array', 'np.array', (['[self.left_lower_corner.x, self.left_lower_corner.y, self.left_lower_corner.z]'], {'dtype': 'np.float'}), '([self.left_lower_corner.x, self.left_lower_corner.y, self.\n left_lower_corner.z], dtype=np.float)\n', (16771, 16872), True, 'import numpy as np\n'), ((16995, 17039), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""', 'divide': '"""ignore"""'}), "(invalid='ignore', divide='ignore')\n", (17004, 17039), True, 'import numpy as np\n'), ((17228, 17253), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_settings)\n', (17237, 17253), True, 'import numpy as np\n'), ((17569, 17592), 'numpy.array', 'np.array', (['a'], {'copy': '(False)'}), '(a, copy=False)\n', (17577, 17592), True, 'import numpy as np\n'), ((17685, 17708), 'numpy.array', 'np.array', (['b'], {'copy': '(False)'}), '(b, copy=False)\n', (17693, 17708), True, 'import numpy as np\n'), ((19160, 19192), 'numpy.sum', 'np.sum', (['((verts - c) ** 2)'], {'axis': '(0)'}), '((verts - c) ** 2, axis=0)\n', (19166, 19192), True, 'import numpy as np\n'), ((20711, 20736), 'numpy.broadcast_arrays', 'np.broadcast_arrays', (['x', 'y'], {}), '(x, y)\n', (20730, 20736), True, 'import numpy as np\n'), ((22831, 22845), 'numpy.dot', 'np.dot', (['v1', 'v1'], {}), '(v1, v1)\n', (22837, 22845), True, 'import numpy as np\n'), ((22867, 22881), 'numpy.dot', 'np.dot', (['v2', 'v2'], {}), '(v2, v2)\n', (22873, 22881), True, 'import numpy as np\n'), ((23115, 23126), 'numpy.isnan', 'np.isnan', (['u'], {}), '(u)\n', (23123, 23126), True, 'import numpy as np\n'), ((789, 808), 'numpy.fmod', 'np.fmod', (['angle', 'pi2'], {}), '(angle, pi2)\n', (796, 808), True, 'import numpy as np\n'), ((2730, 2779), 'numpy.array', 'np.array', (['(self.base.x, self.base.y, self.base.z)'], {}), '((self.base.x, self.base.y, self.base.z))\n', (2738, 2779), True, 'import numpy as np\n'), ((2829, 2865), 'numpy.array', 'np.array', (['(0, 0, self._height * 0.5)'], {}), '((0, 0, self._height * 0.5))\n', (2837, 2865), True, 'import numpy as np\n'), ((3720, 3745), 'numpy.dot', 'np.dot', (['self._matrix', 'vec'], {}), '(self._matrix, vec)\n', (3726, 3745), True, 'import numpy as np\n'), ((7383, 7403), 'numpy.vstack', 'np.vstack', (['(x, y, z)'], {}), '((x, y, z))\n', (7392, 7403), True, 'import numpy as np\n'), ((7828, 7883), 'numpy.array', 'np.array', (['(self.center.x, self.center.y, self.center.z)'], {}), '((self.center.x, self.center.y, self.center.z))\n', (7836, 7883), True, 'import numpy as np\n'), ((12506, 12574), 'numpy.vstack', 'np.vstack', (['(x + self.center.x, y + self.center.y, z + self.center.z)'], {}), '((x + self.center.x, y + self.center.y, z + self.center.z))\n', (12515, 12574), True, 'import numpy as np\n'), ((17079, 17097), 'numpy.dot', 'np.dot', (['(p0 - l0)', 'n'], {}), '(p0 - l0, n)\n', (17085, 17097), True, 'import numpy as np\n'), ((17097, 17109), 'numpy.dot', 'np.dot', (['l', 'n'], {}), '(l, n)\n', (17103, 17109), True, 'import numpy as np\n'), ((17119, 17130), 'numpy.isinf', 'np.isinf', (['d'], {}), '(d)\n', (17127, 17130), True, 'import numpy as np\n'), ((20611, 20635), 'numpy.arange', 'np.arange', (['camera.height'], {}), '(camera.height)\n', (20620, 20635), True, 'import numpy as np\n'), ((20666, 20689), 'numpy.arange', 'np.arange', (['camera.width'], {}), '(camera.width)\n', (20675, 20689), True, 'import numpy as np\n'), ((20877, 20896), 'numpy.vstack', 'np.vstack', (['(XX, YY)'], {}), '((XX, YY))\n', (20886, 20896), True, 'import numpy as np\n'), ((21504, 21540), 'numpy.concatenate', 'np.concatenate', (['(rx, ry, rz)'], {'axis': '(2)'}), '((rx, ry, rz), axis=2)\n', (21518, 21540), True, 'import numpy as np\n'), ((23160, 23171), 'numpy.isnan', 'np.isnan', (['v'], {}), '(v)\n', (23168, 23171), True, 'import numpy as np\n'), ((22002, 22036), 'numpy.concatenate', 'np.concatenate', (['(tc0, tc1)'], {'axis': '(2)'}), '((tc0, tc1), axis=2)\n', (22016, 22036), True, 'import numpy as np\n'), ((22557, 22603), 'numpy.sum', 'np.sum', (['(projector_dir * surface_normal)'], {'axis': '(1)'}), '(projector_dir * surface_normal, axis=1)\n', (22563, 22603), True, 'import numpy as np\n'), ((22621, 22643), 'numpy.arccos', 'np.arccos', (['dot_product'], {}), '(dot_product)\n', (22630, 22643), True, 'import numpy as np\n'), ((20274, 20318), 'freemovr_engine.fixup_path.fixup_path', 'fixup_path.fixup_path', (["geom_dict['filename']"], {}), "(geom_dict['filename'])\n", (20295, 20318), True, 'import freemovr_engine.fixup_path as fixup_path\n')] |
from abc import ABC
from collections import namedtuple
from enum import IntEnum, auto
import numpy as np
import pygame as pg
pg.init()
font_style = pg.font.SysFont("bahnschrift", 13)
GameAction = namedtuple('GameAction', ['cell_id', 'dx', 'dy'])
def find_cell(game, xr, yr):
for cell in game.cells:
if cell.x == xr and cell.y == yr:
return cell
class AbstractGameObject(ABC):
def tick(self):
raise NotImplementedError()
class Game(AbstractGameObject):
WIDTH, HEIGHT = 1600, 900
def __init__(self, pop_size):
assert pop_size < Cell.H * Cell.W, "Population size too big"
self.pop_size = pop_size
self.RES = self.WIDTH, self.HEIGHT = Game.WIDTH, Game.HEIGHT
self.H_WIDTH, self.H_HEIGHT = self.WIDTH // 2, self.HEIGHT // 2
self.FPS = 10
self.screen = pg.display.set_mode(self.RES)
self.clock = pg.time.Clock()
self.cells_food = np.array([[CellFood(x, y) for x in range(Cell.W)] for y in range(Cell.H)])
self.cells = []
self.generate()
def draw(self):
self.screen.fill(pg.Color('black'))
self.draw_grid()
self.draw_food()
self.draw_cells()
def draw_grid(self):
for x in range(0, self.WIDTH, Cell.TILE):
pg.draw.line(self.screen, pg.Color('dimgray'), (x, 0), (x, self.HEIGHT))
for y in range(0, self.HEIGHT, Cell.TILE):
pg.draw.line(self.screen, pg.Color('dimgray'), (0, y), (self.WIDTH, y))
def _draw_tile(self, color, x, y):
pg.draw.rect(self.screen, pg.Color(color),
(x * Cell.TILE + 2, y * Cell.TILE + 2, Cell.TILE - 2, Cell.TILE - 2))
def draw_food(self):
for y in range(Cell.H):
for x in range(Cell.W):
if self.cells_food[y, x].magic:
pass
else:
self._draw_tile('forestgreen', x, y)
render_hp = font_style.render(f'{self.cells_food[y][x].count}', True, pg.Color('yellow'))
self.screen.blit(render_hp,
(x * Cell.TILE + Cell.TILE // 2 - render_hp.get_width() // 2 + 2,
y * Cell.TILE + Cell.TILE // 2 - render_hp.get_height() // 2 + 2))
def draw_cells(self):
for cell in self.cells:
if not cell.died:
self._draw_tile('red', cell.x, cell.y)
render_hp = font_style.render(f'{cell.hp}', True, pg.Color('yellow'))
self.screen.blit(render_hp,
(cell.x * Cell.TILE + Cell.TILE // 2 - render_hp.get_width()//2 + 2,
cell.y * Cell.TILE + Cell.TILE // 2 - render_hp.get_height()//2 + 2))
def run(self):
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
exit()
self.tick()
def generate(self):
self.cells = [Cell(0, 0, cell_id) for cell_id in range(self.pop_size)]
coords = [(x, y) for x in range(Cell.W) for y in range(Cell.H)]
np.random.shuffle(coords)
for i in range(self.pop_size):
self.cells[i].x = coords[i][0]
self.cells[i].y = coords[i][1]
for y in range(Cell.H):
for x in range(Cell.W):
self.cells_food[y, x].count = np.random.randint(0, 100)
self.cells_food[y, x].magic = False
x = coords[self.pop_size][0]
y = coords[self.pop_size][1]
self.cells_food[y, x].magic = False
def restart(self):
self.cells.clear()
self.generate()
def update(self, game_action: GameAction):
cell = self.cells[game_action.cell_id]
for other_cell in self.cells:
if cell.x + game_action.dx == other_cell.x and \
cell.y + game_action.dy == other_cell.y \
and other_cell.cell_id != cell.cell_id:
return False
cell.x += game_action.dx
cell.y += game_action.dy
cell.heal(self.cells_food[cell.y, cell.x].hit() // Cell.FOOD_DIV)
return True
def tick(self):
for cell in self.cells:
cell.tick()
for cell in self.cells_food.reshape(-1):
cell.tick()
self.display_tick()
def display_tick(self):
pg.display.set_caption(f"{self.clock.get_fps()}")
pg.display.flip()
self.clock.tick(self.FPS)
class CellType(IntEnum):
PEACEFUL = auto()
class Cell(AbstractGameObject):
TILE = 50
H = Game.HEIGHT // TILE
W = Game.WIDTH // TILE
HP_PER_TICK = -13
FOOD_PER_TICK = 40
FOOD_DIV = 2
MAX_HP = 100
MIN_HP = 0
def __init__(self, x, y, cell_id=None):
self.x, self.y = x, y
self.hp = np.random.randint(Cell.MIN_HP + Cell.MAX_HP // 2, Cell.MAX_HP)
self.type = CellType.PEACEFUL
self.cell_id = cell_id
self.hp_delta = 0
def tick(self):
delta = self.HP_PER_TICK
self.hp = max(self.hp + delta, Cell.MIN_HP)
def heal(self, count=None):
old_hp = self.hp
if count is None:
count = Cell.FOOD_PER_TICK // Cell.FOOD_DIV
self.hp = self.hp + count
self.hp_delta = self.hp - old_hp
return self.hp_delta
@property
def died(self):
return self.hp <= Cell.MIN_HP
@property
def alive(self):
return not self.died
class CellFood(AbstractGameObject):
MAX_COUNT = 40
MIN_COUNT = 0
TILE = Cell.TILE
HP_DAMAGE = Cell.FOOD_PER_TICK
FOOD_PER_TICK = 6
def __init__(self, x, y, count=None, magic=False):
self.x, self.y = x, y
if count is None:
count = np.random.randint(CellFood.MIN_COUNT, CellFood.MAX_COUNT)
self.count = count
self.min = np.random.randint(CellFood.MIN_COUNT, CellFood.MAX_COUNT // 3)
self.max = np.random.randint(self.min, CellFood.MAX_COUNT)
self.per_tick = np.random.randint(0, self.FOOD_PER_TICK)
self.magic = magic
def hit(self):
old_count = self.count
self.count = max(self.count - CellFood.HP_DAMAGE, self.min)
count = old_count - self.count
return count
def tick(self):
self.count = min(self.per_tick + self.count, self.max)
if __name__ == '__main__':
Game(50).run()
| [
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.Color",
"pygame.init",
"pygame.display.flip",
"numpy.random.randint",
"collections.namedtuple",
"enum.auto",
"pygame.time.Clock",
"numpy.random.shuffle"
] | [((127, 136), 'pygame.init', 'pg.init', ([], {}), '()\n', (134, 136), True, 'import pygame as pg\n'), ((150, 184), 'pygame.font.SysFont', 'pg.font.SysFont', (['"""bahnschrift"""', '(13)'], {}), "('bahnschrift', 13)\n", (165, 184), True, 'import pygame as pg\n'), ((200, 249), 'collections.namedtuple', 'namedtuple', (['"""GameAction"""', "['cell_id', 'dx', 'dy']"], {}), "('GameAction', ['cell_id', 'dx', 'dy'])\n", (210, 249), False, 'from collections import namedtuple\n'), ((4530, 4536), 'enum.auto', 'auto', ([], {}), '()\n', (4534, 4536), False, 'from enum import IntEnum, auto\n'), ((850, 879), 'pygame.display.set_mode', 'pg.display.set_mode', (['self.RES'], {}), '(self.RES)\n', (869, 879), True, 'import pygame as pg\n'), ((901, 916), 'pygame.time.Clock', 'pg.time.Clock', ([], {}), '()\n', (914, 916), True, 'import pygame as pg\n'), ((3121, 3146), 'numpy.random.shuffle', 'np.random.shuffle', (['coords'], {}), '(coords)\n', (3138, 3146), True, 'import numpy as np\n'), ((4436, 4453), 'pygame.display.flip', 'pg.display.flip', ([], {}), '()\n', (4451, 4453), True, 'import pygame as pg\n'), ((4831, 4893), 'numpy.random.randint', 'np.random.randint', (['(Cell.MIN_HP + Cell.MAX_HP // 2)', 'Cell.MAX_HP'], {}), '(Cell.MIN_HP + Cell.MAX_HP // 2, Cell.MAX_HP)\n', (4848, 4893), True, 'import numpy as np\n'), ((5868, 5930), 'numpy.random.randint', 'np.random.randint', (['CellFood.MIN_COUNT', '(CellFood.MAX_COUNT // 3)'], {}), '(CellFood.MIN_COUNT, CellFood.MAX_COUNT // 3)\n', (5885, 5930), True, 'import numpy as np\n'), ((5950, 5997), 'numpy.random.randint', 'np.random.randint', (['self.min', 'CellFood.MAX_COUNT'], {}), '(self.min, CellFood.MAX_COUNT)\n', (5967, 5997), True, 'import numpy as np\n'), ((6022, 6062), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.FOOD_PER_TICK'], {}), '(0, self.FOOD_PER_TICK)\n', (6039, 6062), True, 'import numpy as np\n'), ((1114, 1131), 'pygame.Color', 'pg.Color', (['"""black"""'], {}), "('black')\n", (1122, 1131), True, 'import pygame as pg\n'), ((1579, 1594), 'pygame.Color', 'pg.Color', (['color'], {}), '(color)\n', (1587, 1594), True, 'import pygame as pg\n'), ((2828, 2842), 'pygame.event.get', 'pg.event.get', ([], {}), '()\n', (2840, 2842), True, 'import pygame as pg\n'), ((5764, 5821), 'numpy.random.randint', 'np.random.randint', (['CellFood.MIN_COUNT', 'CellFood.MAX_COUNT'], {}), '(CellFood.MIN_COUNT, CellFood.MAX_COUNT)\n', (5781, 5821), True, 'import numpy as np\n'), ((1323, 1342), 'pygame.Color', 'pg.Color', (['"""dimgray"""'], {}), "('dimgray')\n", (1331, 1342), True, 'import pygame as pg\n'), ((1459, 1478), 'pygame.Color', 'pg.Color', (['"""dimgray"""'], {}), "('dimgray')\n", (1467, 1478), True, 'import pygame as pg\n'), ((3387, 3412), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (3404, 3412), True, 'import numpy as np\n'), ((2019, 2037), 'pygame.Color', 'pg.Color', (['"""yellow"""'], {}), "('yellow')\n", (2027, 2037), True, 'import pygame as pg\n'), ((2493, 2511), 'pygame.Color', 'pg.Color', (['"""yellow"""'], {}), "('yellow')\n", (2501, 2511), True, 'import pygame as pg\n')] |
# -*- coding: utf-8 -*-
"""
LAS file processing
"""
# !pip install rasterio
# !pip install laspy
import glob, os, zipfile
import numpy as np
import rasterio as rio
from rasterio import warp
import laspy
las_path = '007.zip'
L8_NLCD_path = 'L8_NLCD.zip'
def prep_file(las_path, L8_NLCD_path, siteID=6):
'''extract data and get las_list and the required tif file for L8_NLCD'''
# prep las
las_filename, ext = os.path.splitext(las_path)
with zipfile.ZipFile(las_path, 'r') as zip_ref:
zip_ref.extractall('./')
las_zips = [file for file in glob.glob(os.path.join(las_filename, "*.zip"))]
for zip_file in las_zips:
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall(os.path.join(las_filename))
las_list = [file for file in glob.glob(os.path.join(las_filename, "*.las"))]
# prep L8_NLCD
with zipfile.ZipFile(L8_NLCD_path, 'r') as zip_ref:
zip_ref.extractall('./')
L8_NLCD_tif = os.path.join('L8_NLCD', 'L8_NLCD_Site_ID_{}_LARGE.TIF'.format(siteID))
return las_list, L8_NLCD_tif
def get_elevation(lat, lon, las_list, las_crs=2881):
'''get elevation data around a given coor'''
src_crs = rio.crs.CRS.from_epsg(4326) # latlon crs
dst_crs = rio.crs.CRS.from_epsg(las_crs) # las file crs in epsg
xs = [lon]
ys = [lat]
coor_transformed = warp.transform(src_crs, dst_crs, xs, ys, zs=None)
x, y = coor_transformed[0][0], coor_transformed[1][0]
# search las files for (x, y)
z_avg = 0 # output 0 if missing
square_size = 10 # in NAD83(HARN), ~10 meters/feet?
for las_file in las_list:
inFile = laspy.file.File(las_file, mode = "r")
if inFile.header.min[0] < x and x < inFile.header.max[0] \
and inFile.header.min[1] < y and y < inFile.header.max[1]:
coor = np.vstack((inFile.x, inFile.y, inFile.z)).transpose()
# focus on a small square to calculate z
X_valid = np.logical_and((x-square_size//2 < coor[:,0]), (x+square_size//2 > coor[:,0]))
coor = coor[np.where(X_valid)]
Y_valid = np.logical_and((y-square_size//2 < coor[:,1]), (y+square_size//2 > coor[:,1]))
coor = coor[np.where(Y_valid)]
if len(coor[:,2]) == 0: # dealing with missing data
z_avg = 0
else:
z_avg = coor[:,2].mean()
inFile.close()
return z_avg
def classify_z(z):
cls = 0 # low-rise
if 15 < z and z <= 40:
cls = 1 # mid-rise
if z > 40:
cls = 2 # high-rise
return cls
def get_site_elevation(las_path, L8_NLCD_path, siteID=6, las_crs=2881):
'''get elevation data around a given siteID'''
las_list, L8_NLCD_tif = prep_file(las_path, L8_NLCD_path, siteID)
# image shape
x_max, y_max = 128, 128
elevation = np.zeros((x_max, y_max))
elevation_cls = elevation.copy()
with rio.open(L8_NLCD_tif) as src:
# for each pixel
for x in range(x_max):
for y in range(y_max):
lon, lat = src.xy(x, y)
z_avg = get_elevation(lat, lon, las_list, las_crs)
elevation[x, y] = z_avg
elevation_cls[x, y] = classify_z(z_avg)
return elevation, elevation_cls
t_start = time.time()
elevation, elevation_cls = get_site_elevation(las_path, L8_NLCD_path, siteID=6, las_crs=2881)
t_end = time.time()
print ("Time elapsed: {} s".format(t_end - t_start))
elevation[:5,:5]
elevation_cls[:5,:5]
| [
"rasterio.open",
"zipfile.ZipFile",
"laspy.file.File",
"numpy.logical_and",
"numpy.zeros",
"rasterio.warp.transform",
"numpy.where",
"os.path.splitext",
"numpy.vstack",
"os.path.join",
"rasterio.crs.CRS.from_epsg"
] | [((424, 450), 'os.path.splitext', 'os.path.splitext', (['las_path'], {}), '(las_path)\n', (440, 450), False, 'import glob, os, zipfile\n'), ((1193, 1220), 'rasterio.crs.CRS.from_epsg', 'rio.crs.CRS.from_epsg', (['(4326)'], {}), '(4326)\n', (1214, 1220), True, 'import rasterio as rio\n'), ((1248, 1278), 'rasterio.crs.CRS.from_epsg', 'rio.crs.CRS.from_epsg', (['las_crs'], {}), '(las_crs)\n', (1269, 1278), True, 'import rasterio as rio\n'), ((1355, 1404), 'rasterio.warp.transform', 'warp.transform', (['src_crs', 'dst_crs', 'xs', 'ys'], {'zs': 'None'}), '(src_crs, dst_crs, xs, ys, zs=None)\n', (1369, 1404), False, 'from rasterio import warp\n'), ((2831, 2855), 'numpy.zeros', 'np.zeros', (['(x_max, y_max)'], {}), '((x_max, y_max))\n', (2839, 2855), True, 'import numpy as np\n'), ((460, 490), 'zipfile.ZipFile', 'zipfile.ZipFile', (['las_path', '"""r"""'], {}), "(las_path, 'r')\n", (475, 490), False, 'import glob, os, zipfile\n'), ((872, 906), 'zipfile.ZipFile', 'zipfile.ZipFile', (['L8_NLCD_path', '"""r"""'], {}), "(L8_NLCD_path, 'r')\n", (887, 906), False, 'import glob, os, zipfile\n'), ((1637, 1672), 'laspy.file.File', 'laspy.file.File', (['las_file'], {'mode': '"""r"""'}), "(las_file, mode='r')\n", (1652, 1672), False, 'import laspy\n'), ((2903, 2924), 'rasterio.open', 'rio.open', (['L8_NLCD_tif'], {}), '(L8_NLCD_tif)\n', (2911, 2924), True, 'import rasterio as rio\n'), ((660, 690), 'zipfile.ZipFile', 'zipfile.ZipFile', (['zip_file', '"""r"""'], {}), "(zip_file, 'r')\n", (675, 690), False, 'import glob, os, zipfile\n'), ((1962, 2050), 'numpy.logical_and', 'np.logical_and', (['(x - square_size // 2 < coor[:, 0])', '(x + square_size // 2 > coor[:, 0])'], {}), '(x - square_size // 2 < coor[:, 0], x + square_size // 2 >\n coor[:, 0])\n', (1976, 2050), True, 'import numpy as np\n'), ((2106, 2194), 'numpy.logical_and', 'np.logical_and', (['(y - square_size // 2 < coor[:, 1])', '(y + square_size // 2 > coor[:, 1])'], {}), '(y - square_size // 2 < coor[:, 1], y + square_size // 2 >\n coor[:, 1])\n', (2120, 2194), True, 'import numpy as np\n'), ((579, 614), 'os.path.join', 'os.path.join', (['las_filename', '"""*.zip"""'], {}), "(las_filename, '*.zip')\n", (591, 614), False, 'import glob, os, zipfile\n'), ((734, 760), 'os.path.join', 'os.path.join', (['las_filename'], {}), '(las_filename)\n', (746, 760), False, 'import glob, os, zipfile\n'), ((805, 840), 'os.path.join', 'os.path.join', (['las_filename', '"""*.las"""'], {}), "(las_filename, '*.las')\n", (817, 840), False, 'import glob, os, zipfile\n'), ((2065, 2082), 'numpy.where', 'np.where', (['X_valid'], {}), '(X_valid)\n', (2073, 2082), True, 'import numpy as np\n'), ((2209, 2226), 'numpy.where', 'np.where', (['Y_valid'], {}), '(Y_valid)\n', (2217, 2226), True, 'import numpy as np\n'), ((1833, 1874), 'numpy.vstack', 'np.vstack', (['(inFile.x, inFile.y, inFile.z)'], {}), '((inFile.x, inFile.y, inFile.z))\n', (1842, 1874), True, 'import numpy as np\n')] |
# Created by <NAME>
import numpy as np
import torch
from agents.random_agent import RandomAgent
from game import Game
def evaluate_random(tasks, agent_type, models, num_trials=50, compare_agent=None):
"""
Evaluate an agent against 3 random agents on a list of tasks
:param tasks: list of task classes to evaluate on
:param agent_type: class of the agent to evaluate
:param models: dictionary accepted by Game of models for this agent
:param num_trials: int, number of trial games to run per task
:param compare_agent: optional other agent to compare agent_type to, default will use a random agent
:return: (win_rate, avg_score, percent_invalid, scores)
win_rate: percentage of time agent_type scores strictly better than compare_agent would on the same initial deal
match_rate: percentage of time agent_type scores at least as well
avg_score: average score that agent_type beats compare_agent by on the same initial deal
percent_invalid: percentage of time agent_type plays an invalid card
scores: list of score vectors
"""
with torch.no_grad():
scores = []
random_scores = []
num_invalid = 0
total_cards_played = 0
for task in tasks:
for trial_num in range(num_trials):
# print(trial_num)
# Evaluate agent
game = Game(task,
[agent_type] + [RandomAgent] * 3,
[models, {}, {}, {}],
# [{"model": model}, {}, {}, {}],
{"epsilon": 0, "verbose": False})
score, state = game.run()
infos = game.get_info()
scores.append(score)
# Evaluate current agent on same starting state
if compare_agent and not isinstance(compare_agent, RandomAgent):
game = Game(task,
[compare_agent] + [RandomAgent] * 3,
[models, {}, {}, {}],
# [{"model": model}, {}, {}, {}],
{"epsilon": 0, "verbose": False})
else:
game = Game(task, [RandomAgent] * 4, [{}] * 4, {"epsilon": 0, "verbose": False})
random_score, _ = game.run(state)
random_scores.append(random_score)
for info in infos:
if 0 in info and info[0] == "invalid":
num_invalid += 1
constant_game = task()
total_cards_played += constant_game.num_cards / constant_game.num_players * num_trials
wins = 0
matches = 0
for i, score in enumerate(scores):
if score[0] > random_scores[i][0]:
wins += 1
matches += 1
elif score[0] >= random_scores[i][0]:
matches += 1
# record.append(True if np.argmax(score) == 0 else False)
winrate = wins / len(scores)
matchrate = matches / len(scores)
avg_score_margin = (np.asarray(scores)[:, 0] - np.asarray(random_scores)[:, 0]).mean()
# calculate invalid
percent_invalid = num_invalid / total_cards_played
return winrate, matchrate, avg_score_margin, percent_invalid, scores
| [
"numpy.asarray",
"torch.no_grad",
"game.Game"
] | [((1112, 1127), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1125, 1127), False, 'import torch\n'), ((1397, 1502), 'game.Game', 'Game', (['task', '([agent_type] + [RandomAgent] * 3)', '[models, {}, {}, {}]', "{'epsilon': 0, 'verbose': False}"], {}), "(task, [agent_type] + [RandomAgent] * 3, [models, {}, {}, {}], {\n 'epsilon': 0, 'verbose': False})\n", (1401, 1502), False, 'from game import Game\n'), ((1936, 2044), 'game.Game', 'Game', (['task', '([compare_agent] + [RandomAgent] * 3)', '[models, {}, {}, {}]', "{'epsilon': 0, 'verbose': False}"], {}), "(task, [compare_agent] + [RandomAgent] * 3, [models, {}, {}, {}], {\n 'epsilon': 0, 'verbose': False})\n", (1940, 2044), False, 'from game import Game\n'), ((2251, 2324), 'game.Game', 'Game', (['task', '([RandomAgent] * 4)', '([{}] * 4)', "{'epsilon': 0, 'verbose': False}"], {}), "(task, [RandomAgent] * 4, [{}] * 4, {'epsilon': 0, 'verbose': False})\n", (2255, 2324), False, 'from game import Game\n'), ((3135, 3153), 'numpy.asarray', 'np.asarray', (['scores'], {}), '(scores)\n', (3145, 3153), True, 'import numpy as np\n'), ((3162, 3187), 'numpy.asarray', 'np.asarray', (['random_scores'], {}), '(random_scores)\n', (3172, 3187), True, 'import numpy as np\n')] |
from __future__ import print_function, division
caffe_root = '/TUB/robo/caffe-master/'
import sys
sys.path.insert(0, caffe_root+'python')
import caffe
import numpy as np
#load the data file
data_file = np.load('vgg_net_19_112.npy')
#get the weights and biases out of the array
#the weights have to be transposed because of differences between Caffe and Tensorflow
#format filter weights:
#Tensorflow: [height (0), width (1), depth (2), number of filters (3)]
#Caffe: [number of filters (3), depth (2), height (0), width (1)]
weights1 = data_file[0][0].transpose((3,2,0,1))
bias1 = data_file[0][1]
weights2 = data_file[1][0].transpose((3,2,0,1))
bias2 = data_file[1][1]
weights3 = data_file[2][0].transpose((3,2,0,1))
bias3 = data_file[2][1]
weights4 = data_file[3][0].transpose((3,2,0,1))
bias4 = data_file[3][1]
weights5 = data_file[4][0].transpose((3,2,0,1))
bias5 = data_file[4][1]
weights6 = data_file[5][0].transpose((3,2,0,1))
bias6 = data_file[5][1]
weights7 = data_file[6][0].transpose((3,2,0,1))
bias7 = data_file[6][1]
weights8 = data_file[7][0].transpose((3,2,0,1))
bias8 = data_file[7][1]
weights9 = data_file[8][0].transpose((3,2,0,1))
bias9 = data_file[8][1]
weights10 = data_file[9][0].transpose((3,2,0,1))
bias10 = data_file[9][1]
weights11 = data_file[10][0].transpose((3,2,0,1))
bias11 = data_file[10][1]
weights12 = data_file[11][0].transpose((3,2,0,1))
bias12 = data_file[11][1]
weights13 = data_file[12][0].transpose((3,2,0,1))
bias13 = data_file[12][1]
weights14 = data_file[13][0].transpose((3,2,0,1))
bias14 = data_file[13][1]
weights15 = data_file[14][0].transpose((3,2,0,1))
bias15 = data_file[14][1]
weights16 = data_file[15][0].transpose((3,2,0,1))
bias16 = data_file[15][1]
#connecting the tensor after last pooling layer with the first fully-connected layer
#here is the link to the video where this part is explained (https://youtu.be/kvXHOIn3-8s?t=3m38s)
fc1_w = data_file[16][0].reshape((4,4,512,4096))
fc1_w = fc1_w.transpose((3,2,0,1))
fc1_w = fc1_w.reshape((4096,8192))
fc1_b = data_file[16][1]
#fully connected layer format:
#Tensorflow: [number of inputs (0), number of outputs (1)]
#Caffe: [number of outputs (1), number of inputs (0)]
fc2_w = data_file[17][0].transpose((1,0))
fc2_b = data_file[17][1]
fc3_w = data_file[18][0].transpose((1,0))
fc3_b = data_file[18][1]
#define architecture
net = caffe.Net('vgg_net_19.prototxt', caffe.TEST)
#load parameters
net.params['conv1'][0].data[...] = weights1
net.params['conv1'][1].data[...] = bias1
net.params['conv2'][0].data[...] = weights2
net.params['conv2'][1].data[...] = bias2
net.params['conv3'][0].data[...] = weights3
net.params['conv3'][1].data[...] = bias3
net.params['conv4'][0].data[...] = weights4
net.params['conv4'][1].data[...] = bias4
net.params['conv5'][0].data[...] = weights5
net.params['conv5'][1].data[...] = bias5
net.params['conv6'][0].data[...] = weights6
net.params['conv6'][1].data[...] = bias6
net.params['conv7'][0].data[...] = weights7
net.params['conv7'][1].data[...] = bias7
net.params['conv8'][0].data[...] = weights8
net.params['conv8'][1].data[...] = bias8
net.params['conv9'][0].data[...] = weights9
net.params['conv9'][1].data[...] = bias9
net.params['conv10'][0].data[...] = weights10
net.params['conv10'][1].data[...] = bias10
net.params['conv11'][0].data[...] = weights11
net.params['conv11'][1].data[...] = bias11
net.params['conv12'][0].data[...] = weights12
net.params['conv12'][1].data[...] = bias12
net.params['conv13'][0].data[...] = weights13
net.params['conv13'][1].data[...] = bias13
net.params['conv14'][0].data[...] = weights14
net.params['conv14'][1].data[...] = bias14
net.params['conv15'][0].data[...] = weights15
net.params['conv15'][1].data[...] = bias15
net.params['conv16'][0].data[...] = weights16
net.params['conv16'][1].data[...] = bias16
net.params['fc1'][0].data[...] = fc1_w
net.params['fc1'][1].data[...] = fc1_b
net.params['fc2'][0].data[...] = fc2_w
net.params['fc2'][1].data[...] = fc2_b
net.params['fc3'][0].data[...] = fc3_w
net.params['fc3'][1].data[...] = fc3_b
#save caffemodel
net.save('vgg_net_19.caffemodel')
| [
"numpy.load",
"caffe.Net",
"sys.path.insert"
] | [((100, 141), 'sys.path.insert', 'sys.path.insert', (['(0)', "(caffe_root + 'python')"], {}), "(0, caffe_root + 'python')\n", (115, 141), False, 'import sys\n'), ((205, 234), 'numpy.load', 'np.load', (['"""vgg_net_19_112.npy"""'], {}), "('vgg_net_19_112.npy')\n", (212, 234), True, 'import numpy as np\n'), ((2369, 2413), 'caffe.Net', 'caffe.Net', (['"""vgg_net_19.prototxt"""', 'caffe.TEST'], {}), "('vgg_net_19.prototxt', caffe.TEST)\n", (2378, 2413), False, 'import caffe\n')] |
"""Description of Pd class."""
__author__ = 'ikibalin'
__version__ = "2020_08_19"
import numpy
from typing import NoReturn
from cryspy.A_functions_base.function_2_crystallography_base import \
calc_cos_ang
from cryspy.A_functions_base.matrix_operations import calc_m1_m2_m1t
from cryspy.A_functions_base.unit_cell import calc_matrix_t
from cryspy.B_parent_classes.cl_1_item import ItemN
from cryspy.B_parent_classes.cl_2_loop import LoopN
from cryspy.B_parent_classes.cl_3_data import DataN
from cryspy.B_parent_classes.preocedures import take_items_by_class
from cryspy.C_item_loop_classes.cl_1_diffrn_radiation import \
DiffrnRadiation
from cryspy.C_item_loop_classes.cl_1_extinction import Extinction
from cryspy.C_item_loop_classes.cl_1_phase import PhaseL
from cryspy.C_item_loop_classes.cl_1_refln import ReflnL
from cryspy.C_item_loop_classes.cl_1_refln_susceptibility import \
ReflnSusceptibilityL
from cryspy.C_item_loop_classes.cl_1_refine_ls import RefineLs
from cryspy.C_item_loop_classes.cl_1_chi2 import Chi2
from cryspy.C_item_loop_classes.cl_1_range import Range
from cryspy.C_item_loop_classes.cl_1_setup import Setup
from cryspy.C_item_loop_classes.cl_1_texture import Texture, TextureL
from cryspy.C_item_loop_classes.cl_1_exclude import ExcludeL
from cryspy.C_item_loop_classes.cl_1_tof_background import TOFBackground
from cryspy.C_item_loop_classes.cl_1_tof_intensity_incident import \
TOFIntensityIncident
from cryspy.C_item_loop_classes.cl_1_tof_meas import TOFMeasL
from cryspy.C_item_loop_classes.cl_1_tof_parameters import TOFParameters
from cryspy.C_item_loop_classes.cl_1_tof_peak import TOFPeakL
from cryspy.C_item_loop_classes.cl_1_tof_proc import TOFProcL
from cryspy.C_item_loop_classes.cl_1_tof_profile import TOFProfile
from cryspy.E_data_classes.cl_1_crystal import Crystal
from cryspy.E_data_classes.cl_1_mag_crystal import MagCrystal
class TOF(DataN):
"""
Time-of-flight powder diffraction (polarized or unpolarized neutrons, 1d).
Data items in the TOF category record details about
powder diffraction measurements by Time of FLight.
Methods
-------
- calc_profile
Attributes
----------
- setup, tof_profile, phase, tof_background, tof_meas (mandatory)
- diffrn_radiation, chi2, range, extinction,
texture, exclude, tof_proc, tof_peak, refine_ls, refln_#phase_name
refln_susceptibility_#phase_name (optional)
"""
CLASSES_MANDATORY = (TOFParameters, TOFProfile, PhaseL, TOFBackground,
TOFMeasL)
CLASSES_OPTIONAL = (DiffrnRadiation, Chi2, Range,
Texture, TOFIntensityIncident, ExcludeL, TOFProcL,
TOFPeakL, RefineLs, ReflnL, ReflnSusceptibilityL, Setup)
# CLASSES_INTERNAL = ()
CLASSES = CLASSES_MANDATORY + CLASSES_OPTIONAL
PREFIX = "tof"
# default values for the parameters
D_DEFAULT = {}
def __init__(self, data_name=None, **kwargs) -> NoReturn:
super(TOF, self).__init__()
self.__dict__["items"] = []
self.__dict__["data_name"] = data_name
for key, attr in self.D_DEFAULT.items():
setattr(self, key, attr)
for key, attr in kwargs.items():
setattr(self, key, attr)
def calc_profile(self, time, l_crystal, flag_internal: bool = True,
flag_polarized: bool = True):
"""Calculate intensity for the given diffraction angles.
Arguments
---------
- time: 1D numpy array of time in micro seconds (???)
- l_crystal: a list of Crystal objects of cryspy library
- l_peak_in: precalculated data about integrated intensities
(used to speed up the calculations)
- l_refln_in: precalculated data about nuclear structure factors
(used to speed up the calculations)
- l_refln_susceptibility_in: precalculated data about
(used to speed up the calculations)
- flag_internal: a flag to calculate or to use internal objects.
It should be True if user call the function.
It's True by default.
Output
------
- proc: output profile
- l_peak: data about peaks
- l_refln: data about nuclear structure factor
"""
if flag_internal:
d_internal_val = {}
self.d_internal_val = d_internal_val
else:
try:
d_internal_val = self.d_internal_val
except AttributeError:
d_internal_val = {}
self.d_internal_val = d_internal_val
tof_proc = TOFProcL()
tof_proc.numpy_time = time
try:
tof_background = self.tof_background
int_bkgd = tof_background.calc_background(time)
except AttributeError:
int_bkgd = 0.*time
tof_proc.numpy_intensity_bkg_calc = int_bkgd
tof_parameters = self.tof_parameters
# tof_profile = self.tof_profile
d = tof_parameters.calc_d_by_time(time)
d_min, d_max = tof_parameters.calc_d_min_max(time)
sthovl_min = 0.5/d_max
sthovl_max = 0.5/d_min
try:
texture = self.texture
h_ax, k_ax, l_ax = texture.h_ax, texture.k_ax, texture.l_ax
g_1, g_2 = texture.g_1, texture.g_2
except AttributeError:
texture = None
res_u_1d = numpy.zeros(time.shape[0], dtype=float)
res_d_1d = numpy.zeros(time.shape[0], dtype=float)
phase = self.phase
for phase_item in phase.items:
phase_label = phase_item.label
phase_scale = phase_item.scale
try:
phase_igsize = phase_item.igsize
if phase_igsize is None: phase_igsize = 0. # temporary solution
except AttributeError:
phase_igsize = 0.
for i_crystal, crystal in enumerate(l_crystal):
if crystal.data_name.lower() == phase_label.lower():
ind_cry = i_crystal
break
if ind_cry is None:
raise AttributeError(
f"Crystal with name '{crystal.data_name:}' is not found.")
return
crystal = l_crystal[ind_cry]
scale = phase_scale
try:
peak = d_internal_val[f"peak_{crystal.data_name:}"]
index_h = peak.numpy_index_h
index_k = peak.numpy_index_k
index_l = peak.numpy_index_l
mult = peak.numpy_index_mult
cond_2 = True
except KeyError:
if texture is None:
index_h, index_k, index_l, mult = crystal.calc_hkl(
sthovl_min, sthovl_max)
else:
index_h, index_k, index_l, mult = \
crystal.calc_hkl_in_range(sthovl_min, sthovl_max)
peak = TOFPeakL(loop_name=phase_label)
peak.numpy_index_h = numpy.array(index_h, dtype=int)
peak.numpy_index_k = numpy.array(index_k, dtype=int)
peak.numpy_index_l = numpy.array(index_l, dtype=int)
peak.numpy_index_mult = numpy.array(mult, dtype=int)
d_internal_val[f"peak_{crystal.data_name:}"] = peak
cond_2 = False
cond_1 = not(crystal.is_variables())
if cond_1 & cond_2:
np_iint_u = peak.numpy_intensity_plus
np_iint_d = peak.numpy_intensity_minus
else:
np_iint_u, np_iint_d = self.calc_iint(
index_h, index_k, index_l, crystal,
flag_internal=flag_internal)
peak.numpy_intensity_plus = np_iint_u
peak.numpy_intensity_minus = np_iint_d
cell = crystal.cell
sthovl_hkl = cell.calc_sthovl(index_h, index_k, index_l)
d_hkl = 0.5/sthovl_hkl
time_hkl = tof_parameters.calc_time_by_d(d_hkl)
profile_2d = self.calc_shape_profile(
d, d_hkl, phase_igsize=phase_igsize)
peak.numpy_time = time_hkl
tth_rad = tof_parameters.ttheta_bank * numpy.pi/180.
wavelength = 2.*d_hkl*numpy.sin(0.5*tth_rad)
wavelength_4 = wavelength**4
iint_u_0 = np_iint_u * mult * wavelength_4
iint_d_0 = np_iint_d * mult * wavelength_4
if tof_parameters.is_attribute("extinction"):
tof_extinction = tof_parameters.extinction
iint_u_0 = (1. - tof_extinction*iint_u_0)*mult*wavelength_4
iint_d_0 = (1. - tof_extinction*iint_d_0)*mult*wavelength_4
np_iint_u_2d = numpy.meshgrid(time, iint_u_0, indexing="ij")[1]
np_iint_d_2d = numpy.meshgrid(time, iint_d_0, indexing="ij")[1]
# texture
if texture is not None:
cond_2 = ((not(texture.is_variables())) &
(not(cell.is_variables())))
if cond_2:
try:
texture_2d = d_internal_val[
f"texture_2d_{crystal.data_name:}"]
cond_1 = False
except KeyError:
cond_1 = True
if cond_1:
cos_alpha_ax = calc_cos_ang(cell, h_ax, k_ax, l_ax,
index_h, index_k, index_l)
c_help = 1.-cos_alpha_ax**2
c_help[c_help < 0.] = 0.
sin_alpha_ax = numpy.sqrt(c_help)
cos_alpha_ax_2d = numpy.meshgrid(time, cos_alpha_ax,
indexing="ij")[1]
sin_alpha_ax_2d = numpy.meshgrid(time, sin_alpha_ax,
indexing="ij")[1]
# cos_alpha_2d = cos_alpha_ax_2d*cos_alpha_ang_2d + \
# sin_alpha_ax_2d*sin_alpha_ang_2d
# cos_alpha_ang_2d, sin_alpha_ang_2d
cos_alpha_2d = cos_alpha_ax_2d*1.+sin_alpha_ax_2d*0.
texture_2d = g_2 + (1. - g_2) * (1./g_1 + (g_1**2 - 1./g_1)
* cos_alpha_2d**2)**(-1.5)
d_internal_val[f"texture_2d_{crystal.data_name:}"] = \
texture_2d
profile_2d = profile_2d*texture_2d
res_u_2d = profile_2d*np_iint_u_2d
res_d_2d = profile_2d*np_iint_d_2d
# 0.5 to have the same meaning for scale factor as in FullProf
res_u_1d += 0.5*scale*res_u_2d.sum(axis=1)
res_d_1d += 0.5*scale*res_d_2d.sum(axis=1)
if flag_internal:
peak.numpy_to_items()
tof_proc.numpy_d_spacing = d
tof_proc.numpy_intensity_plus_net = res_u_1d
tof_proc.numpy_intensity_minus_net = res_d_1d
tof_proc.numpy_intensity_net = res_u_1d+res_d_1d
tof_proc.numpy_intensity_diff_total = res_u_1d-res_d_1d
if flag_polarized:
tof_proc.numpy_intensity_plus_total = res_u_1d+int_bkgd
tof_proc.numpy_intensity_minus_total = res_d_1d+int_bkgd
tof_proc.numpy_intensity_total = res_u_1d+res_d_1d+int_bkgd+int_bkgd
else:
tof_proc.numpy_intensity_plus_total = res_u_1d+0.5*int_bkgd
tof_proc.numpy_intensity_minus_total = res_d_1d+0.5*int_bkgd
tof_proc.numpy_intensity_total = res_u_1d+res_d_1d+int_bkgd
if flag_internal:
tof_proc.numpy_to_items()
l_calc_objs = []
for crystal in l_crystal:
try:
obj = d_internal_val[f"refln_{crystal.data_name}"]
l_calc_objs.append(obj)
except KeyError:
pass
try:
obj = d_internal_val[
f"refln_susceptibility_{crystal.data_name}"]
l_calc_objs.append(obj)
except KeyError:
pass
try:
obj = d_internal_val[f"peak_{crystal.data_name}"]
l_calc_objs.append(obj)
except KeyError:
pass
l_calc_objs.append(tof_proc)
self.add_items(l_calc_objs)
return tof_proc
def calc_chi_sq(self, l_crystal, flag_internal=True):
"""
Calculate chi square.
Arguments
---------
- l_crystal: a list of Crystal objects of cryspy library
- flag_internal: a flag to calculate or to use internal objects.
It should be True if user call the function.
It's True by default.
Output
------
- chi_sq_val: chi square of flip ratio
(Sum_i ((y_e_i - y_m_i) / sigma_i)**2)
- n: number of measured reflections
"""
tof_meas = self.tof_meas
flag_polarized = tof_meas.is_polarized()
np_time = tof_meas.numpy_time
if flag_polarized:
int_u_exp = tof_meas.numpy_intensity_plus
sint_u_exp = tof_meas.numpy_intensity_plus_sigma
int_d_exp = tof_meas.numpy_intensity_minus
sint_d_exp = tof_meas.numpy_intensity_minus_sigma
else:
int_exp = tof_meas.numpy_intensity
sint_exp = tof_meas.numpy_intensity_sigma
cond_in = numpy.ones(np_time.shape, dtype=bool)
try:
range_ = self.range
time_min = numpy.array(range_.time_min, dtype=float)
time_max = numpy.array(range_.time_max, dtype=float)
cond_in = numpy.logical_and(cond_in, np_time >= time_min)
cond_in = numpy.logical_and(cond_in, np_time <= time_max)
except AttributeError:
pass
np_time_in = np_time[cond_in]
if flag_polarized:
int_u_exp_in = int_u_exp[cond_in]
sint_u_exp_in = sint_u_exp[cond_in]
int_d_exp_in = int_d_exp[cond_in]
sint_d_exp_in = sint_d_exp[cond_in]
else:
int_exp_in = int_exp[cond_in]
sint_exp_in = sint_exp[cond_in]
tof_proc = self.calc_profile(
np_time_in, l_crystal, flag_internal=flag_internal,
flag_polarized=flag_polarized)
if flag_polarized:
tof_proc.numpy_intensity_plus = int_u_exp_in
tof_proc.numpy_intensity_plus_sigma = sint_u_exp_in
tof_proc.numpy_intensity_minus = int_d_exp_in
tof_proc.numpy_intensity_minus_sigma = sint_d_exp_in
tof_proc.numpy_intensity = int_u_exp_in+int_d_exp_in
tof_proc.numpy_intensity_sigma = numpy.sqrt(
numpy.square(sint_u_exp_in) + numpy.square(sint_d_exp_in))
else:
tof_proc.numpy_intensity = int_exp_in
tof_proc.numpy_intensity_sigma = sint_exp_in
int_u_mod = tof_proc.numpy_intensity_plus_total
int_d_mod = tof_proc.numpy_intensity_minus_total
if flag_polarized:
sint_sum_exp_in = (sint_u_exp_in**2 + sint_d_exp_in**2)**0.5
chi_sq_u = ((int_u_mod-int_u_exp_in)/sint_u_exp_in)**2
chi_sq_d = ((int_d_mod-int_d_exp_in)/sint_d_exp_in)**2
chi_sq_sum = ((int_u_mod+int_d_mod-int_u_exp_in-int_d_exp_in) /
sint_sum_exp_in)**2
chi_sq_dif = ((int_u_mod-int_d_mod-int_u_exp_in+int_d_exp_in) /
sint_sum_exp_in)**2
cond_u = numpy.logical_not(numpy.isnan(chi_sq_u))
cond_d = numpy.logical_not(numpy.isnan(chi_sq_d))
cond_sum = numpy.logical_not(numpy.isnan(chi_sq_sum))
cond_dif = numpy.logical_not(numpy.isnan(chi_sq_dif))
else:
chi_sq_sum = ((int_u_mod+int_d_mod-int_exp_in)/sint_exp_in)**2
cond_sum = numpy.logical_not(numpy.isnan(chi_sq_sum))
# exclude region
try:
exclude = self.exclude
l_excl_time_min = exclude.time_low
l_excl_time_max = exclude.time_high
if flag_polarized:
for excl_time_min, excl_time_max in zip(l_excl_time_min,
l_excl_time_max):
cond_1 = numpy.logical_or(np_time_in < 1.*excl_time_min,
np_time_in > 1.*excl_time_max)
cond_u = numpy.logical_and(cond_u, cond_1)
cond_d = numpy.logical_and(cond_d, cond_1)
cond_sum = numpy.logical_and(cond_sum, cond_1)
else:
for excl_time_min, excl_time_max in zip(l_excl_time_min,
l_excl_time_max):
cond_1 = numpy.logical_or(np_time_in < 1.*excl_time_min,
np_time_in > 1.*excl_time_max)
cond_sum = numpy.logical_and(cond_sum, cond_1)
except AttributeError:
pass
tof_proc.numpy_excluded = numpy.logical_not(cond_sum)
chi_sq_sum_val = (chi_sq_sum[cond_sum]).sum()
n_sum = cond_sum.sum()
if flag_polarized:
chi_sq_u_val = (chi_sq_u[cond_u]).sum()
n_u = cond_u.sum()
chi_sq_d_val = (chi_sq_d[cond_d]).sum()
n_d = cond_d.sum()
chi_sq_dif_val = (chi_sq_dif[cond_dif]).sum()
n_dif = cond_dif.sum()
chi2 = self.chi2
flag_u = chi2.up
flag_d = chi2.down
flag_sum = chi2.sum
flag_dif = chi2.diff
chi_sq_val = (int(flag_u)*chi_sq_u_val + int(flag_d)*chi_sq_d_val +
int(flag_sum)*chi_sq_sum_val +
int(flag_dif)*chi_sq_dif_val)
n = (int(flag_u)*n_u + int(flag_d)*n_d + int(flag_sum)*n_sum +
int(flag_dif)*n_dif)
else:
chi_sq_val = chi_sq_sum_val
n = n_sum
if flag_internal:
refine_ls = RefineLs(number_reflns=n,
goodness_of_fit_all=chi_sq_val/float(n),
weighting_scheme="sigma")
self.refine_ls = refine_ls
tof_proc.numpy_to_items()
return chi_sq_val, n
# def simulation(self, l_crystal, ttheta_start: float = 4.,
# ttheta_end: float = 120., ttheta_step: float = 0.1,
# flag_polarized: bool = True) -> NoReturn:
# """Simulate."""
# n_points = int(round((ttheta_end-ttheta_start)/ttheta_step))
# tth_in = numpy.linspace(ttheta_start, ttheta_end, n_points)
# if isinstance(l_crystal, Crystal):
# l_crystal = [l_crystal]
# self.calc_profile(tth_in, l_crystal, l_peak_in=None, l_refln_in=None,
# l_refln_susceptibility_in=None, l_dd_in=None,
# flag_internal=True, flag_polarized=flag_polarized)
# return
def calc_iint(self, index_h, index_k, index_l, crystal: Crystal,
flag_internal: bool = True):
"""Calculate the integrated intensity for h, k, l reflections.
Arguments
---------
- h, k, l: 1D numpy array of Miller indexes, dtype = int32
- l_crystal: a list of Crystal objects of cryspy library
- flag_internal: a flag to calculate or to use internal objects.
It should be True if user call the function.
It's True by default.
Output
------
- iint_u: 1D numpy array of integrated intensity up, dtype = float
- iint_d: 1D numpy array of integrated intensity up, dtype = float
- refln: ReflnL object of cryspy library (nuclear structure factor)
- refln_s: ReflnSusceptibilityL object of cryspy library
(nuclear structure factor)
"""
index_hkl = numpy.stack([index_h, index_k, index_l], axis=0)
if flag_internal:
try:
d_internal_val = self.d_internal_val
except AttributeError:
d_internal_val = {}
self.d_internal_val = d_internal_val
else:
d_internal_val = {}
self.d_internal_val = d_internal_val
tof_parameters = self.tof_parameters
try:
field = tof_parameters.field
except AttributeError:
field = 0.
try:
diffrn_radiation = self.diffrn_radiation
p_u = float(diffrn_radiation.polarization)
p_d = (2.*float(diffrn_radiation.efficiency)-1)*p_u
except AttributeError:
p_u = 0.0
p_d = 0.0
try:
if (not(flag_internal) | crystal.is_variables()):
raise KeyError
refln = d_internal_val[f"refln_{crystal.data_name:}"]
except KeyError:
refln = crystal.calc_refln(index_h, index_k, index_l,
flag_internal=flag_internal)
d_internal_val[f"refln_{crystal.data_name:}"] = refln
f_nucl = refln.numpy_f_calc
f_nucl_sq = abs(f_nucl*f_nucl.conjugate())
if isinstance(crystal, Crystal):
try:
if (not(flag_internal) | crystal.is_variables()):
raise KeyError
refln_s = d_internal_val[
f"refln_susceptibility_{crystal.data_name:}"]
except KeyError:
refln_s = crystal.calc_refln_susceptibility(
index_h, index_k, index_l, flag_internal=flag_internal)
d_internal_val[f"refln_susceptibility_{crystal.data_name:}"] \
= refln_s
sft_11 = refln_s.numpy_chi_11_calc
sft_12 = refln_s.numpy_chi_12_calc
sft_13 = refln_s.numpy_chi_13_calc
sft_21 = refln_s.numpy_chi_21_calc
sft_22 = refln_s.numpy_chi_22_calc
sft_23 = refln_s.numpy_chi_23_calc
sft_31 = refln_s.numpy_chi_31_calc
sft_32 = refln_s.numpy_chi_32_calc
sft_33 = refln_s.numpy_chi_33_calc
_11, _12 = field*sft_11, field*sft_12
_21, _13 = field*sft_21, field*sft_13
_22, _23 = field*sft_22, field*sft_23
_31, _32 = field*sft_31, field*sft_32
_33 = field*sft_33
_ij = numpy.stack([_11, _12, _13, _21, _22, _23, _31, _32, _33], axis=0)
cell = crystal.cell
unit_cell_parameters = numpy.array([
cell.length_a, cell.length_b, cell.length_c,
cell.angle_alpha*numpy.pi/180.,
cell.angle_beta*numpy.pi/180.,
cell.angle_gamma*numpy.pi/180.], dtype=float)
t_ij = calc_matrix_t(index_hkl, unit_cell_parameters, flag_unit_cell_parameters=False)[0]
#SIGMA = T CHI T^-1 = T chi T^T (because T is rotation matrix, therefore T^-1 = T^T)
th_ij = calc_m1_m2_m1t(t_ij, _ij)[0]
th_11, th_12, th_22 = th_ij[0], th_ij[1], th_ij[4]
# fm_p_sq = (field**2)*abs(0.5*(th_11*th_11.conjugate()+
# th_22*th_22.conjugate())+th_12*th_12.conjugate())
# fm_p_field = field*0.5*(th_11+th_22)
fm_p_sq = abs(0.5 * (th_11 * th_11.conjugate() +
th_22 * th_22.conjugate()) +
th_12 * th_12.conjugate())
fm_p_field = 0.5*(th_11 + th_22)
cross = 2.*(f_nucl.real*fm_p_field.real +
f_nucl.imag*fm_p_field.imag)
iint_u = f_nucl_sq + fm_p_sq + p_u*cross
iint_d = f_nucl_sq + fm_p_sq - p_d*cross
elif isinstance(crystal, MagCrystal):
try:
if (not(flag_internal) | crystal.is_variables()):
raise KeyError
f_mag_perp = d_internal_val[f"f_mag_perp_{crystal.data_name:}"]
except KeyError:
f_mag_perp = crystal.calc_f_mag_perp(index_h, index_k, index_l)
d_internal_val[f"f_mag_perp_{crystal.data_name:}"] = f_mag_perp
f_mag_perp_sq = abs(f_mag_perp*f_mag_perp.conjugate()).sum(axis=0)
iint_u = f_nucl_sq + f_mag_perp_sq
iint_d = f_nucl_sq + f_mag_perp_sq
return iint_u, iint_d
def _gauss_pd(self, time_2d):
"""One dimensional gauss powder diffraction."""
ag, bg = self.ag, self.bg
val_1 = bg*time_2d**2
val_2 = numpy.where(val_1 < 5., numpy.exp(-val_1), 0.)
self.gauss_pd = ag*val_2
def _lor_pd(self, time_2d):
"""One dimensional lorentz powder diffraction."""
al, bl = self.al, self.bl
self.lor_pd = al*1./(1.+bl*time_2d**2)
def calc_shape_profile(self, d, d_hkl, phase_igsize: float = 0.):
"""
Calculate shape profile.
Calculate profile in the range of time for reflections placed on
time_hkl with i_g parameter by default equal to zero
d, d_hkl in angstrems
"""
tof_parameters = self.tof_parameters
tof_profile = self.tof_profile
time = tof_parameters.calc_time_by_d(d)
time_hkl = tof_parameters.calc_time_by_d(d_hkl)
# FIXME: strain_g, size_g, size_l
np_shape_2d = tof_profile.calc_peak_shape_function(
d, time, time_hkl, size_g=phase_igsize, strain_g=0.,
size_l=0., strain_l=0.)
# Lorentz factor
tth_rad = tof_parameters.ttheta_bank*numpy.pi/180.
lorentz_factor = 1./(numpy.sin(tth_rad)*numpy.sin(0.5*tth_rad))
profile_2d = np_shape_2d*lorentz_factor
return profile_2d
def params_to_cif(self, separator="_", flag: bool = False,
flag_minimal: bool = True) -> str:
"""Save parameters to cif format."""
ls_out = []
l_cls = (DiffrnRadiation, Chi2, Range, Extinction, Texture,
TOFIntensityIncident, TOFParameters, TOFProfile, PhaseL,
ExcludeL, TOFBackground)
l_obj = [item for item in self.items if type(item) in l_cls]
l_itemn = [item for item in l_obj if isinstance(item, ItemN)]
l_loopn = [item for item in l_obj if isinstance(item, LoopN)]
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn])
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn])
return "\n".join(ls_out)
def data_to_cif(self, separator="_", flag: bool = False,
flag_minimal: bool = True) -> str:
"""Save data to cif format."""
ls_out = []
l_cls = (TOFMeasL, )
l_obj = [item for item in self.items if type(item) in l_cls]
l_itemn = [item for item in l_obj if isinstance(item, ItemN)]
l_loopn = [item for item in l_obj if isinstance(item, LoopN)]
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn])
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn])
return "\n".join(ls_out)
def calc_to_cif(self, separator="_", flag=False, flag_minimal=True) -> str:
"""Save calculations to cif format."""
ls_out = []
l_cls = (RefineLs, ReflnL, ReflnSusceptibilityL, TOFPeakL, TOFProcL)
l_obj = [item for item in self.items if type(item) in l_cls]
l_itemn = [item for item in l_obj if isinstance(item, ItemN)]
l_loopn = [item for item in l_obj if isinstance(item, LoopN)]
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn])
ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn])
return "\n".join(ls_out)
def apply_constraints(self):
"""Apply constraints."""
if self.pd_meas is not None:
self.pd_meas.apply_constraints()
def plots(self):
if self.is_attribute("tof_proc"):
tof_proc = self.tof_proc
res = tof_proc.plot_sum_diff()
return [res,]
elif self.is_attribute("tof_meas"):
return self.tof_meas.plots()
def get_dictionary(self):
self.form_object()
dict_tof = {}
phase, range_, tof_background = None, None, None
exclude = None
tof_meas, tof_parameters, tof_profile = None, None, None
diffrn_radiation, texture = None, None
setup = None
l_obj = take_items_by_class(self, (PhaseL, ))
if len(l_obj) > 0:
phase = l_obj[0]
l_obj = take_items_by_class(self, (Range, ))
if len(l_obj) > 0:
range_ = l_obj[0]
l_obj = take_items_by_class(self, (TOFBackground, ))
if len(l_obj) > 0:
tof_background = l_obj[0]
l_obj = take_items_by_class(self, (ExcludeL, ))
if len(l_obj) > 0:
exclude = l_obj[0]
l_obj = take_items_by_class(self, (TOFMeasL, ))
if len(l_obj) > 0:
tof_meas = l_obj[0]
l_obj = take_items_by_class(self, (TOFParameters, ))
if len(l_obj) > 0:
tof_parameters = l_obj[0]
l_obj = take_items_by_class(self, (TOFProfile, ))
if len(l_obj) > 0:
tof_profile = l_obj[0]
l_obj = take_items_by_class(self, (DiffrnRadiation, ))
if len(l_obj) > 0:
diffrn_radiation = l_obj[0]
l_obj = take_items_by_class(self, (TextureL, ))
if len(l_obj) > 0:
texture = l_obj[0]
l_obj = take_items_by_class(self, (Setup, ))
if len(l_obj) > 0:
setup = l_obj[0]
dict_tof["name"] = self.data_name
dict_tof["type_name"] = self.get_name()
if phase is not None:
dict_tof["phase_name"] = numpy.array(phase.label, dtype=str)
if phase.is_attribute("igsize"):
dict_tof["phase_ig"] = numpy.array(phase.igsize, dtype=float)
dict_tof["flags_phase_ig"] = numpy.array(phase.igsize_refinement, dtype=bool)
else:
dict_tof["phase_ig"] = numpy.zeros((len(phase.items),), dtype=float)
dict_tof["flags_phase_ig"] = numpy.zeros((len(phase.items),), dtype=bool)
if phase.is_attribute("scale"):
dict_tof["phase_scale"] = numpy.array(phase.scale, dtype=float)
dict_tof["flags_phase_scale"] = numpy.array(phase.scale_refinement, dtype=bool)
else:
dict_tof["phase_scale"] = numpy.zeros((len(phase.items),), dtype=float)
dict_tof["flags_phase_scale"] = numpy.zeros((len(phase.items),), dtype=bool)
if tof_background is not None:
dict_tof["background_time_max"] = tof_background.time_max
dict_tof["background_coefficients"] = tof_background.get_coefficients()
dict_tof["flags_background_coefficients"] = tof_background.get_flags_coefficients()
if tof_meas is not None:
time = numpy.array(tof_meas.time, dtype=float)
time_min = range_.time_min
time_max = range_.time_max
dict_tof["time_min"] = time_min
dict_tof["time_max"] = time_max
flag_in = numpy.logical_and(
time >= time_min,
time <= time_max)
dict_tof["time"] = time[flag_in]
if tof_meas.is_attribute("intensity_plus"):
int_plus = numpy.array(tof_meas.intensity_plus, dtype=float)[flag_in]
s_int_plus = numpy.array(tof_meas.intensity_plus_sigma, dtype=float)[flag_in]
int_minus = numpy.array(tof_meas.intensity_minus, dtype=float)[flag_in]
s_int_minus = numpy.array(tof_meas.intensity_minus_sigma, dtype=float)[flag_in]
dict_tof["signal_exp_plus"] = numpy.stack([int_plus, s_int_plus], axis=0)
dict_tof["signal_exp_minus"] = numpy.stack([int_minus, s_int_minus], axis=0)
else:
int_sum = numpy.array(tof_meas.intensity, dtype=float)[flag_in]
s_int_sum = numpy.array(tof_meas.intensity_sigma, dtype=float)[flag_in]
dict_tof["signal_exp"] = numpy.stack([int_sum, s_int_sum], axis=0)
time_in_range = time[flag_in]
flag_exclude = numpy.zeros(time_in_range.shape, dtype=bool)
if exclude is not None:
for item_e in exclude.items:
flag_in_1 = numpy.logical_and(
time_in_range >= item_e.time_min,
time_in_range <= item_e.time_max)
flag_exclude = numpy.logical_or(flag_exclude, flag_in_1)
dict_tof["excluded_points"] = flag_exclude
if tof_parameters is not None:
dict_tof["ttheta_bank"] = tof_parameters.ttheta_bank * numpy.pi/180
dict_tof["neutron_type"] = tof_parameters.neutrons
dict_tof["zero"] = tof_parameters.zero
dict_tof["dtt1"] = tof_parameters.dtt1
if tof_parameters.is_attribute("dtt2"):
dict_tof["dtt2"] = tof_parameters.dtt2
if tof_parameters.is_attribute("zerot"):
dict_tof["zerot"] = tof_parameters.zerot
if tof_parameters.is_attribute("dtt1t"):
dict_tof["dtt1t"] = tof_parameters.dtt1t
if tof_parameters.is_attribute("dtt2t"):
dict_tof["dtt2t"] = tof_parameters.dtt2t
if tof_profile is not None:
l_alpha = []
l_alpha_refinement = []
for numb in range(2):
if tof_profile.is_attribute(f"alpha{numb:}"):
l_alpha.append(getattr(tof_profile, f"alpha{numb:}"))
l_alpha_refinement.append(getattr(tof_profile, f"alpha{numb:}_refinement"))
else:
break
l_beta = []
l_beta_refinement = []
for numb in range(2):
if tof_profile.is_attribute(f"beta{numb:}"):
l_beta.append(getattr(tof_profile, f"beta{numb:}"))
l_beta_refinement.append(getattr(tof_profile, f"beta{numb:}_refinement"))
else:
break
l_gamma = []
l_gamma_refinement = []
for numb in range(2):
if tof_profile.is_attribute(f"gamma{numb:}"):
l_gamma.append(getattr(tof_profile, f"gamma{numb:}"))
l_gamma_refinement.append(getattr(tof_profile, f"gamma{numb:}_refinement"))
else:
break
l_sigma = []
l_sigma_refinement = []
for numb in range(3):
if tof_profile.is_attribute(f"sigma{numb:}"):
l_sigma.append(getattr(tof_profile, f"sigma{numb:}"))
l_sigma_refinement.append(getattr(tof_profile, f"sigma{numb:}_refinement"))
else:
break
if tof_profile.is_attribute("peak_shape"):
peak_shape = tof_profile.peak_shape
else:
peak_shape = "pseudo-Voigt"
dict_tof["profile_alphas"] = numpy.array(l_alpha, dtype=float)
dict_tof["flags_profile_alphas"] = numpy.array(l_alpha_refinement, dtype=float)
dict_tof["profile_betas"] = numpy.array(l_beta, dtype=float)
dict_tof["flags_profile_betas"] = numpy.array(l_beta_refinement, dtype=float)
dict_tof["profile_gammas"] = numpy.array(l_gamma, dtype=float)
dict_tof["flags_profile_gammas"] = numpy.array(l_gamma_refinement, dtype=float)
dict_tof["profile_sigmas"] = numpy.array(l_sigma, dtype=float)
dict_tof["flags_profile_sigmas"] = numpy.array(l_sigma_refinement, dtype=float)
dict_tof["profile_peak_shape"] = peak_shape
if diffrn_radiation is not None:
beam_polarization = diffrn_radiation.polarization
flipper_efficiency = diffrn_radiation.efficiency
dict_tof["beam_polarization"] = numpy.array([beam_polarization], dtype=float)
dict_tof["flipper_efficiency"] = numpy.array([flipper_efficiency], dtype=float)
dict_tof["flags_beam_polarization"] = numpy.array([diffrn_radiation.polarization_refinement], dtype=bool)
dict_tof["flags_flipper_efficiency"] = numpy.array([diffrn_radiation.efficiency_refinement], dtype=bool)
if texture is not None:
dict_tof["texture_name"] = numpy.array(texture.label, dtype=str)
dict_tof["texture_g1"] = numpy.array(texture.g_1, dtype=float)
dict_tof["texture_g2"] = numpy.array(texture.g_2, dtype=float)
dict_tof["texture_axis"] = numpy.array(
[texture.h_ax, texture.k_ax, texture.l_ax], dtype=float)
dict_tof["flags_texture_g1"] = numpy.array(texture.g_1_refinement, dtype=bool)
dict_tof["flags_texture_g2"] = numpy.array(texture.g_2_refinement, dtype=bool)
dict_tof["flags_texture_axis"] = numpy.array(
[texture.h_ax_refinement,
texture.k_ax_refinement,
texture.l_ax_refinement], dtype=bool)
if setup is not None:
dict_tof["magnetic_field"] = numpy.array([setup.field], dtype=float)
return dict_tof
def take_parameters_from_dictionary(self, ddict_diffrn, l_parameter_name: list=None, l_sigma: list=None):
keys = ddict_diffrn.keys()
if l_parameter_name is not None:
parameter_label = [hh[0] for hh in l_parameter_name]
else:
parameter_label = []
if "beam_polarization" in keys:
self.diffrn_radiation.polarization = ddict_diffrn["beam_polarization"]
if "flipper_efficiency" in keys:
self.diffrn_radiation.efficiency = ddict_diffrn["flipper_efficiency"]
if "phase_scale" in keys:
hh = ddict_diffrn["phase_scale"]
for i_item, item in enumerate(self.phase.items):
item.scale = float(hh[i_item])
if "phase_ig" in keys:
hh = ddict_diffrn["phase_ig"]
for i_item, item in enumerate(self.phase.items):
item.igsize = float(hh[i_item])
if len(parameter_label) > 0:
for name, sigma in zip(l_parameter_name, l_sigma):
if name[0] == "phase_scale":
self.phase.items[name[1][0]].scale_sigma = float(sigma)
if name[0] == "phase_ig":
self.phase.items[name[1][0]].igsize_sigma = float(sigma)
if name[0] == "beam_polarization":
self.diffrn_radiation.polarization_sigma = float(sigma)
if name[0] == "flipper_efficiency":
self.diffrn_radiation.efficiency_sigma = float(sigma)
if name[0] == "texture_g1":
self.texture.items[name[1][0]].g1_sigma = float(sigma)
if name[0] == "texture_g2":
self.texture.items[name[1][0]].g2_sigma = float(sigma)
if name[0] == "texture_axis":
ind_param, ind_a = name[1]
if ind_param == 0:
self.texture.items[ind_a].h_ax_sigma = float(sigma)
if ind_param == 1:
self.texture.items[ind_a].k_ax_sigma = float(sigma)
if ind_param == 2:
self.texture.items[ind_a].l_ax_sigma = float(sigma)
if (("signal_plus" in keys) and ("signal_minus" in keys)):
tof_proc = TOFProcL()
tof_proc.numpy_time = numpy.round(ddict_diffrn["time"], decimals=5)
tof_proc.numpy_intensity_plus_net = numpy.round(ddict_diffrn["signal_plus"], decimals=5)
tof_proc.numpy_intensity_minus_net = numpy.round(ddict_diffrn["signal_minus"], decimals=5)
if "signal_exp_plus" in keys:
tof_proc.numpy_intensity_plus = numpy.round(ddict_diffrn["signal_exp_plus"][0], decimals=5)
tof_proc.numpy_intensity_plus_sigma = numpy.round(ddict_diffrn["signal_exp_plus"][1], decimals=5)
tof_proc.numpy_intensity_minus = numpy.round(ddict_diffrn["signal_exp_minus"][0], decimals=5)
tof_proc.numpy_intensity_minus_sigma = numpy.round(ddict_diffrn["signal_exp_minus"][1], decimals=5)
else:
tof_proc.numpy_intensity = numpy.round(ddict_diffrn["signal_exp"][0], decimals=5)
tof_proc.numpy_intensity_sigma = numpy.round(ddict_diffrn["signal_exp"][1], decimals=5)
tof_proc.numpy_intensity_bkg_calc = numpy.round(ddict_diffrn["signal_background"], decimals=5)
tof_proc.numpy_excluded = ddict_diffrn["excluded_points"]
tof_proc.numpy_to_items()
self.tof_proc = tof_proc
l_tof_peak = []
l_refln = []
for item_phase in self.phase.items:
s_label = f"dict_in_out_{item_phase.label:}"
if s_label in keys:
dict_crystal = ddict_diffrn[s_label]
dict_crystal_keys = dict_crystal.keys()
if (("index_hkl" in dict_crystal_keys) and ("time_hkl" in dict_crystal_keys)):
index_hkl = dict_crystal["index_hkl"]
time_hkl = dict_crystal["time_hkl"]
tof_peak = TOFPeakL(loop_name = item_phase.label)
int_plus_max, int_minus_max = None, None
if "iint_plus_with_factors" in dict_crystal_keys:
int_plus_max = dict_crystal["iint_plus_with_factors"]
if "iint_minus_with_factors" in dict_crystal_keys:
int_minus_max = dict_crystal["iint_minus_with_factors"]
if "f_nucl":
refln = ReflnL(loop_name = item_phase.label)
refln.numpy_index_h = index_hkl[0]
refln.numpy_index_k = index_hkl[1]
refln.numpy_index_l = index_hkl[2]
refln.numpy_a_calc = dict_crystal["f_nucl"].real
refln.numpy_b_calc = dict_crystal["f_nucl"].imag
refln.numpy_to_items()
l_refln.append(refln)
if not((int_plus_max is None) and (int_minus_max is None)):
tof_peak.numpy_index_h = index_hkl[0]
tof_peak.numpy_index_k = index_hkl[1]
tof_peak.numpy_index_l = index_hkl[2]
tof_peak.numpy_time = numpy.round(time_hkl, decimals=3)
tof_peak.numpy_intensity_plus = int_plus_max
tof_peak.numpy_intensity_minus = int_minus_max
tof_peak.numpy_to_items()
l_tof_peak.append(tof_peak)
if len(l_tof_peak) > 0:
self.add_items(l_tof_peak)
if len(l_refln) > 0:
self.add_items(l_refln)
def estimate_background(self):
tof_background = self.tof_background
tof_proc = self.tof_proc
tof_proc.estimate_background(tof_background)
| [
"numpy.ones",
"numpy.isnan",
"numpy.sin",
"numpy.exp",
"cryspy.C_item_loop_classes.cl_1_refln.ReflnL",
"cryspy.B_parent_classes.preocedures.take_items_by_class",
"numpy.round",
"numpy.meshgrid",
"numpy.logical_not",
"cryspy.C_item_loop_classes.cl_1_tof_peak.TOFPeakL",
"cryspy.A_functions_base.un... | [((4709, 4719), 'cryspy.C_item_loop_classes.cl_1_tof_proc.TOFProcL', 'TOFProcL', ([], {}), '()\n', (4717, 4719), False, 'from cryspy.C_item_loop_classes.cl_1_tof_proc import TOFProcL\n'), ((5506, 5545), 'numpy.zeros', 'numpy.zeros', (['time.shape[0]'], {'dtype': 'float'}), '(time.shape[0], dtype=float)\n', (5517, 5545), False, 'import numpy\n'), ((5565, 5604), 'numpy.zeros', 'numpy.zeros', (['time.shape[0]'], {'dtype': 'float'}), '(time.shape[0], dtype=float)\n', (5576, 5604), False, 'import numpy\n'), ((13728, 13765), 'numpy.ones', 'numpy.ones', (['np_time.shape'], {'dtype': 'bool'}), '(np_time.shape, dtype=bool)\n', (13738, 13765), False, 'import numpy\n'), ((17388, 17415), 'numpy.logical_not', 'numpy.logical_not', (['cond_sum'], {}), '(cond_sum)\n', (17405, 17415), False, 'import numpy\n'), ((20305, 20353), 'numpy.stack', 'numpy.stack', (['[index_h, index_k, index_l]'], {'axis': '(0)'}), '([index_h, index_k, index_l], axis=0)\n', (20316, 20353), False, 'import numpy\n'), ((28803, 28839), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(PhaseL,)'], {}), '(self, (PhaseL,))\n', (28822, 28839), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((28914, 28949), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(Range,)'], {}), '(self, (Range,))\n', (28933, 28949), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29025, 29068), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(TOFBackground,)'], {}), '(self, (TOFBackground,))\n', (29044, 29068), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29152, 29190), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(ExcludeL,)'], {}), '(self, (ExcludeL,))\n', (29171, 29190), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29267, 29305), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(TOFMeasL,)'], {}), '(self, (TOFMeasL,))\n', (29286, 29305), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29383, 29426), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(TOFParameters,)'], {}), '(self, (TOFParameters,))\n', (29402, 29426), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29510, 29550), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(TOFProfile,)'], {}), '(self, (TOFProfile,))\n', (29529, 29550), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29631, 29676), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(DiffrnRadiation,)'], {}), '(self, (DiffrnRadiation,))\n', (29650, 29676), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29762, 29800), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(TextureL,)'], {}), '(self, (TextureL,))\n', (29781, 29800), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((29877, 29912), 'cryspy.B_parent_classes.preocedures.take_items_by_class', 'take_items_by_class', (['self', '(Setup,)'], {}), '(self, (Setup,))\n', (29896, 29912), False, 'from cryspy.B_parent_classes.preocedures import take_items_by_class\n'), ((13834, 13875), 'numpy.array', 'numpy.array', (['range_.time_min'], {'dtype': 'float'}), '(range_.time_min, dtype=float)\n', (13845, 13875), False, 'import numpy\n'), ((13899, 13940), 'numpy.array', 'numpy.array', (['range_.time_max'], {'dtype': 'float'}), '(range_.time_max, dtype=float)\n', (13910, 13940), False, 'import numpy\n'), ((13964, 14011), 'numpy.logical_and', 'numpy.logical_and', (['cond_in', '(np_time >= time_min)'], {}), '(cond_in, np_time >= time_min)\n', (13981, 14011), False, 'import numpy\n'), ((14034, 14081), 'numpy.logical_and', 'numpy.logical_and', (['cond_in', '(np_time <= time_max)'], {}), '(cond_in, np_time <= time_max)\n', (14051, 14081), False, 'import numpy\n'), ((22788, 22854), 'numpy.stack', 'numpy.stack', (['[_11, _12, _13, _21, _22, _23, _31, _32, _33]'], {'axis': '(0)'}), '([_11, _12, _13, _21, _22, _23, _31, _32, _33], axis=0)\n', (22799, 22854), False, 'import numpy\n'), ((22923, 23112), 'numpy.array', 'numpy.array', (['[cell.length_a, cell.length_b, cell.length_c, cell.angle_alpha * numpy.pi /\n 180.0, cell.angle_beta * numpy.pi / 180.0, cell.angle_gamma * numpy.pi /\n 180.0]'], {'dtype': 'float'}), '([cell.length_a, cell.length_b, cell.length_c, cell.angle_alpha *\n numpy.pi / 180.0, cell.angle_beta * numpy.pi / 180.0, cell.angle_gamma *\n numpy.pi / 180.0], dtype=float)\n', (22934, 23112), False, 'import numpy\n'), ((24944, 24961), 'numpy.exp', 'numpy.exp', (['(-val_1)'], {}), '(-val_1)\n', (24953, 24961), False, 'import numpy\n'), ((30129, 30164), 'numpy.array', 'numpy.array', (['phase.label'], {'dtype': 'str'}), '(phase.label, dtype=str)\n', (30140, 30164), False, 'import numpy\n'), ((31352, 31391), 'numpy.array', 'numpy.array', (['tof_meas.time'], {'dtype': 'float'}), '(tof_meas.time, dtype=float)\n', (31363, 31391), False, 'import numpy\n'), ((31583, 31636), 'numpy.logical_and', 'numpy.logical_and', (['(time >= time_min)', '(time <= time_max)'], {}), '(time >= time_min, time <= time_max)\n', (31600, 31636), False, 'import numpy\n'), ((32670, 32714), 'numpy.zeros', 'numpy.zeros', (['time_in_range.shape'], {'dtype': 'bool'}), '(time_in_range.shape, dtype=bool)\n', (32681, 32714), False, 'import numpy\n'), ((35564, 35597), 'numpy.array', 'numpy.array', (['l_alpha'], {'dtype': 'float'}), '(l_alpha, dtype=float)\n', (35575, 35597), False, 'import numpy\n'), ((35645, 35689), 'numpy.array', 'numpy.array', (['l_alpha_refinement'], {'dtype': 'float'}), '(l_alpha_refinement, dtype=float)\n', (35656, 35689), False, 'import numpy\n'), ((35730, 35762), 'numpy.array', 'numpy.array', (['l_beta'], {'dtype': 'float'}), '(l_beta, dtype=float)\n', (35741, 35762), False, 'import numpy\n'), ((35809, 35852), 'numpy.array', 'numpy.array', (['l_beta_refinement'], {'dtype': 'float'}), '(l_beta_refinement, dtype=float)\n', (35820, 35852), False, 'import numpy\n'), ((35894, 35927), 'numpy.array', 'numpy.array', (['l_gamma'], {'dtype': 'float'}), '(l_gamma, dtype=float)\n', (35905, 35927), False, 'import numpy\n'), ((35975, 36019), 'numpy.array', 'numpy.array', (['l_gamma_refinement'], {'dtype': 'float'}), '(l_gamma_refinement, dtype=float)\n', (35986, 36019), False, 'import numpy\n'), ((36061, 36094), 'numpy.array', 'numpy.array', (['l_sigma'], {'dtype': 'float'}), '(l_sigma, dtype=float)\n', (36072, 36094), False, 'import numpy\n'), ((36142, 36186), 'numpy.array', 'numpy.array', (['l_sigma_refinement'], {'dtype': 'float'}), '(l_sigma_refinement, dtype=float)\n', (36153, 36186), False, 'import numpy\n'), ((36452, 36497), 'numpy.array', 'numpy.array', (['[beam_polarization]'], {'dtype': 'float'}), '([beam_polarization], dtype=float)\n', (36463, 36497), False, 'import numpy\n'), ((36543, 36589), 'numpy.array', 'numpy.array', (['[flipper_efficiency]'], {'dtype': 'float'}), '([flipper_efficiency], dtype=float)\n', (36554, 36589), False, 'import numpy\n'), ((36640, 36707), 'numpy.array', 'numpy.array', (['[diffrn_radiation.polarization_refinement]'], {'dtype': 'bool'}), '([diffrn_radiation.polarization_refinement], dtype=bool)\n', (36651, 36707), False, 'import numpy\n'), ((36759, 36824), 'numpy.array', 'numpy.array', (['[diffrn_radiation.efficiency_refinement]'], {'dtype': 'bool'}), '([diffrn_radiation.efficiency_refinement], dtype=bool)\n', (36770, 36824), False, 'import numpy\n'), ((36898, 36935), 'numpy.array', 'numpy.array', (['texture.label'], {'dtype': 'str'}), '(texture.label, dtype=str)\n', (36909, 36935), False, 'import numpy\n'), ((36973, 37010), 'numpy.array', 'numpy.array', (['texture.g_1'], {'dtype': 'float'}), '(texture.g_1, dtype=float)\n', (36984, 37010), False, 'import numpy\n'), ((37048, 37085), 'numpy.array', 'numpy.array', (['texture.g_2'], {'dtype': 'float'}), '(texture.g_2, dtype=float)\n', (37059, 37085), False, 'import numpy\n'), ((37125, 37193), 'numpy.array', 'numpy.array', (['[texture.h_ax, texture.k_ax, texture.l_ax]'], {'dtype': 'float'}), '([texture.h_ax, texture.k_ax, texture.l_ax], dtype=float)\n', (37136, 37193), False, 'import numpy\n'), ((37254, 37301), 'numpy.array', 'numpy.array', (['texture.g_1_refinement'], {'dtype': 'bool'}), '(texture.g_1_refinement, dtype=bool)\n', (37265, 37301), False, 'import numpy\n'), ((37345, 37392), 'numpy.array', 'numpy.array', (['texture.g_2_refinement'], {'dtype': 'bool'}), '(texture.g_2_refinement, dtype=bool)\n', (37356, 37392), False, 'import numpy\n'), ((37438, 37543), 'numpy.array', 'numpy.array', (['[texture.h_ax_refinement, texture.k_ax_refinement, texture.l_ax_refinement]'], {'dtype': 'bool'}), '([texture.h_ax_refinement, texture.k_ax_refinement, texture.\n l_ax_refinement], dtype=bool)\n', (37449, 37543), False, 'import numpy\n'), ((37665, 37704), 'numpy.array', 'numpy.array', (['[setup.field]'], {'dtype': 'float'}), '([setup.field], dtype=float)\n', (37676, 37704), False, 'import numpy\n'), ((40010, 40020), 'cryspy.C_item_loop_classes.cl_1_tof_proc.TOFProcL', 'TOFProcL', ([], {}), '()\n', (40018, 40020), False, 'from cryspy.C_item_loop_classes.cl_1_tof_proc import TOFProcL\n'), ((40055, 40100), 'numpy.round', 'numpy.round', (["ddict_diffrn['time']"], {'decimals': '(5)'}), "(ddict_diffrn['time'], decimals=5)\n", (40066, 40100), False, 'import numpy\n'), ((40149, 40201), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_plus']"], {'decimals': '(5)'}), "(ddict_diffrn['signal_plus'], decimals=5)\n", (40160, 40201), False, 'import numpy\n'), ((40251, 40304), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_minus']"], {'decimals': '(5)'}), "(ddict_diffrn['signal_minus'], decimals=5)\n", (40262, 40304), False, 'import numpy\n'), ((41063, 41121), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_background']"], {'decimals': '(5)'}), "(ddict_diffrn['signal_background'], decimals=5)\n", (41074, 41121), False, 'import numpy\n'), ((8411, 8435), 'numpy.sin', 'numpy.sin', (['(0.5 * tth_rad)'], {}), '(0.5 * tth_rad)\n', (8420, 8435), False, 'import numpy\n'), ((8896, 8941), 'numpy.meshgrid', 'numpy.meshgrid', (['time', 'iint_u_0'], {'indexing': '"""ij"""'}), "(time, iint_u_0, indexing='ij')\n", (8910, 8941), False, 'import numpy\n'), ((8972, 9017), 'numpy.meshgrid', 'numpy.meshgrid', (['time', 'iint_d_0'], {'indexing': '"""ij"""'}), "(time, iint_d_0, indexing='ij')\n", (8986, 9017), False, 'import numpy\n'), ((15853, 15874), 'numpy.isnan', 'numpy.isnan', (['chi_sq_u'], {}), '(chi_sq_u)\n', (15864, 15874), False, 'import numpy\n'), ((15915, 15936), 'numpy.isnan', 'numpy.isnan', (['chi_sq_d'], {}), '(chi_sq_d)\n', (15926, 15936), False, 'import numpy\n'), ((15979, 16002), 'numpy.isnan', 'numpy.isnan', (['chi_sq_sum'], {}), '(chi_sq_sum)\n', (15990, 16002), False, 'import numpy\n'), ((16045, 16068), 'numpy.isnan', 'numpy.isnan', (['chi_sq_dif'], {}), '(chi_sq_dif)\n', (16056, 16068), False, 'import numpy\n'), ((16200, 16223), 'numpy.isnan', 'numpy.isnan', (['chi_sq_sum'], {}), '(chi_sq_sum)\n', (16211, 16223), False, 'import numpy\n'), ((23187, 23266), 'cryspy.A_functions_base.unit_cell.calc_matrix_t', 'calc_matrix_t', (['index_hkl', 'unit_cell_parameters'], {'flag_unit_cell_parameters': '(False)'}), '(index_hkl, unit_cell_parameters, flag_unit_cell_parameters=False)\n', (23200, 23266), False, 'from cryspy.A_functions_base.unit_cell import calc_matrix_t\n'), ((23387, 23412), 'cryspy.A_functions_base.matrix_operations.calc_m1_m2_m1t', 'calc_m1_m2_m1t', (['t_ij', '_ij'], {}), '(t_ij, _ij)\n', (23401, 23412), False, 'from cryspy.A_functions_base.matrix_operations import calc_m1_m2_m1t\n'), ((25981, 25999), 'numpy.sin', 'numpy.sin', (['tth_rad'], {}), '(tth_rad)\n', (25990, 25999), False, 'import numpy\n'), ((26000, 26024), 'numpy.sin', 'numpy.sin', (['(0.5 * tth_rad)'], {}), '(0.5 * tth_rad)\n', (26009, 26024), False, 'import numpy\n'), ((30250, 30288), 'numpy.array', 'numpy.array', (['phase.igsize'], {'dtype': 'float'}), '(phase.igsize, dtype=float)\n', (30261, 30288), False, 'import numpy\n'), ((30334, 30382), 'numpy.array', 'numpy.array', (['phase.igsize_refinement'], {'dtype': 'bool'}), '(phase.igsize_refinement, dtype=bool)\n', (30345, 30382), False, 'import numpy\n'), ((30663, 30700), 'numpy.array', 'numpy.array', (['phase.scale'], {'dtype': 'float'}), '(phase.scale, dtype=float)\n', (30674, 30700), False, 'import numpy\n'), ((30749, 30796), 'numpy.array', 'numpy.array', (['phase.scale_refinement'], {'dtype': 'bool'}), '(phase.scale_refinement, dtype=bool)\n', (30760, 30796), False, 'import numpy\n'), ((32194, 32237), 'numpy.stack', 'numpy.stack', (['[int_plus, s_int_plus]'], {'axis': '(0)'}), '([int_plus, s_int_plus], axis=0)\n', (32205, 32237), False, 'import numpy\n'), ((32285, 32330), 'numpy.stack', 'numpy.stack', (['[int_minus, s_int_minus]'], {'axis': '(0)'}), '([int_minus, s_int_minus], axis=0)\n', (32296, 32330), False, 'import numpy\n'), ((32558, 32599), 'numpy.stack', 'numpy.stack', (['[int_sum, s_int_sum]'], {'axis': '(0)'}), '([int_sum, s_int_sum], axis=0)\n', (32569, 32599), False, 'import numpy\n'), ((40395, 40454), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp_plus'][0]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp_plus'][0], decimals=5)\n", (40406, 40454), False, 'import numpy\n'), ((40509, 40568), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp_plus'][1]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp_plus'][1], decimals=5)\n", (40520, 40568), False, 'import numpy\n'), ((40618, 40678), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp_minus'][0]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp_minus'][0], decimals=5)\n", (40629, 40678), False, 'import numpy\n'), ((40734, 40794), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp_minus'][1]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp_minus'][1], decimals=5)\n", (40745, 40794), False, 'import numpy\n'), ((40856, 40910), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp'][0]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp'][0], decimals=5)\n", (40867, 40910), False, 'import numpy\n'), ((40960, 41014), 'numpy.round', 'numpy.round', (["ddict_diffrn['signal_exp'][1]"], {'decimals': '(5)'}), "(ddict_diffrn['signal_exp'][1], decimals=5)\n", (40971, 41014), False, 'import numpy\n'), ((7072, 7103), 'cryspy.C_item_loop_classes.cl_1_tof_peak.TOFPeakL', 'TOFPeakL', ([], {'loop_name': 'phase_label'}), '(loop_name=phase_label)\n', (7080, 7103), False, 'from cryspy.C_item_loop_classes.cl_1_tof_peak import TOFPeakL\n'), ((7141, 7172), 'numpy.array', 'numpy.array', (['index_h'], {'dtype': 'int'}), '(index_h, dtype=int)\n', (7152, 7172), False, 'import numpy\n'), ((7210, 7241), 'numpy.array', 'numpy.array', (['index_k'], {'dtype': 'int'}), '(index_k, dtype=int)\n', (7221, 7241), False, 'import numpy\n'), ((7279, 7310), 'numpy.array', 'numpy.array', (['index_l'], {'dtype': 'int'}), '(index_l, dtype=int)\n', (7290, 7310), False, 'import numpy\n'), ((7351, 7379), 'numpy.array', 'numpy.array', (['mult'], {'dtype': 'int'}), '(mult, dtype=int)\n', (7362, 7379), False, 'import numpy\n'), ((9537, 9600), 'cryspy.A_functions_base.function_2_crystallography_base.calc_cos_ang', 'calc_cos_ang', (['cell', 'h_ax', 'k_ax', 'l_ax', 'index_h', 'index_k', 'index_l'], {}), '(cell, h_ax, k_ax, l_ax, index_h, index_k, index_l)\n', (9549, 9600), False, 'from cryspy.A_functions_base.function_2_crystallography_base import calc_cos_ang\n'), ((9777, 9795), 'numpy.sqrt', 'numpy.sqrt', (['c_help'], {}), '(c_help)\n', (9787, 9795), False, 'import numpy\n'), ((15040, 15067), 'numpy.square', 'numpy.square', (['sint_u_exp_in'], {}), '(sint_u_exp_in)\n', (15052, 15067), False, 'import numpy\n'), ((15070, 15097), 'numpy.square', 'numpy.square', (['sint_d_exp_in'], {}), '(sint_d_exp_in)\n', (15082, 15097), False, 'import numpy\n'), ((16601, 16689), 'numpy.logical_or', 'numpy.logical_or', (['(np_time_in < 1.0 * excl_time_min)', '(np_time_in > 1.0 * excl_time_max)'], {}), '(np_time_in < 1.0 * excl_time_min, np_time_in > 1.0 *\n excl_time_max)\n', (16617, 16689), False, 'import numpy\n'), ((16755, 16788), 'numpy.logical_and', 'numpy.logical_and', (['cond_u', 'cond_1'], {}), '(cond_u, cond_1)\n', (16772, 16788), False, 'import numpy\n'), ((16818, 16851), 'numpy.logical_and', 'numpy.logical_and', (['cond_d', 'cond_1'], {}), '(cond_d, cond_1)\n', (16835, 16851), False, 'import numpy\n'), ((16883, 16918), 'numpy.logical_and', 'numpy.logical_and', (['cond_sum', 'cond_1'], {}), '(cond_sum, cond_1)\n', (16900, 16918), False, 'import numpy\n'), ((17113, 17201), 'numpy.logical_or', 'numpy.logical_or', (['(np_time_in < 1.0 * excl_time_min)', '(np_time_in > 1.0 * excl_time_max)'], {}), '(np_time_in < 1.0 * excl_time_min, np_time_in > 1.0 *\n excl_time_max)\n', (17129, 17201), False, 'import numpy\n'), ((17269, 17304), 'numpy.logical_and', 'numpy.logical_and', (['cond_sum', 'cond_1'], {}), '(cond_sum, cond_1)\n', (17286, 17304), False, 'import numpy\n'), ((31811, 31860), 'numpy.array', 'numpy.array', (['tof_meas.intensity_plus'], {'dtype': 'float'}), '(tof_meas.intensity_plus, dtype=float)\n', (31822, 31860), False, 'import numpy\n'), ((31899, 31954), 'numpy.array', 'numpy.array', (['tof_meas.intensity_plus_sigma'], {'dtype': 'float'}), '(tof_meas.intensity_plus_sigma, dtype=float)\n', (31910, 31954), False, 'import numpy\n'), ((31992, 32042), 'numpy.array', 'numpy.array', (['tof_meas.intensity_minus'], {'dtype': 'float'}), '(tof_meas.intensity_minus, dtype=float)\n', (32003, 32042), False, 'import numpy\n'), ((32082, 32138), 'numpy.array', 'numpy.array', (['tof_meas.intensity_minus_sigma'], {'dtype': 'float'}), '(tof_meas.intensity_minus_sigma, dtype=float)\n', (32093, 32138), False, 'import numpy\n'), ((32375, 32419), 'numpy.array', 'numpy.array', (['tof_meas.intensity'], {'dtype': 'float'}), '(tof_meas.intensity, dtype=float)\n', (32386, 32419), False, 'import numpy\n'), ((32457, 32507), 'numpy.array', 'numpy.array', (['tof_meas.intensity_sigma'], {'dtype': 'float'}), '(tof_meas.intensity_sigma, dtype=float)\n', (32468, 32507), False, 'import numpy\n'), ((32828, 32918), 'numpy.logical_and', 'numpy.logical_and', (['(time_in_range >= item_e.time_min)', '(time_in_range <= item_e.time_max)'], {}), '(time_in_range >= item_e.time_min, time_in_range <= item_e\n .time_max)\n', (32845, 32918), False, 'import numpy\n'), ((32998, 33039), 'numpy.logical_or', 'numpy.logical_or', (['flag_exclude', 'flag_in_1'], {}), '(flag_exclude, flag_in_1)\n', (33014, 33039), False, 'import numpy\n'), ((41797, 41833), 'cryspy.C_item_loop_classes.cl_1_tof_peak.TOFPeakL', 'TOFPeakL', ([], {'loop_name': 'item_phase.label'}), '(loop_name=item_phase.label)\n', (41805, 41833), False, 'from cryspy.C_item_loop_classes.cl_1_tof_peak import TOFPeakL\n'), ((9834, 9883), 'numpy.meshgrid', 'numpy.meshgrid', (['time', 'cos_alpha_ax'], {'indexing': '"""ij"""'}), "(time, cos_alpha_ax, indexing='ij')\n", (9848, 9883), False, 'import numpy\n'), ((9978, 10027), 'numpy.meshgrid', 'numpy.meshgrid', (['time', 'sin_alpha_ax'], {'indexing': '"""ij"""'}), "(time, sin_alpha_ax, indexing='ij')\n", (9992, 10027), False, 'import numpy\n'), ((42262, 42296), 'cryspy.C_item_loop_classes.cl_1_refln.ReflnL', 'ReflnL', ([], {'loop_name': 'item_phase.label'}), '(loop_name=item_phase.label)\n', (42268, 42296), False, 'from cryspy.C_item_loop_classes.cl_1_refln import ReflnL\n'), ((43028, 43061), 'numpy.round', 'numpy.round', (['time_hkl'], {'decimals': '(3)'}), '(time_hkl, decimals=3)\n', (43039, 43061), False, 'import numpy\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.