repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
robertjankowski/reproducing-dl-papers | [
"01ad85eac333b87358b3d2e2276292333cacf0e0"
] | [
"homophily_structural_balance/plotting/plot_positive_edge_density.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\n\n\ndef extract_name(word: str):\n return word.split('=')[-1]\n\n\ndef extract_info(filename: str):\n filename_splitted = filename.split('_')\n assert len(filename_splitted) == 7\n p = float(extract_name(filename_splitted[1]))\n iterations = int(extract_name(filename_splitted[2]))\n size = int(extract_name(filename_splitted[3]))\n G = int(extract_name(filename_splitted[4]))\n return p, iterations, size, G\n\n\ndef load_metrics(filename: str) -> list:\n with open(filename, 'r') as f:\n return [float(line.strip()) for line in f]\n\n\ndef plot_metrics(filename: str, metrics: list, output_path: str = None):\n p, iterations, size, G = extract_info(filename)\n x = np.linspace(0, iterations, len(metrics))\n\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n plt.figure(figsize=(8, 5))\n plt.grid(True, alpha=0.3)\n plt.plot(x, metrics, label=f'p = {p}, N = {size}, G = {G}')\n plt.ylabel(r'$\\rho$', fontsize=14)\n plt.xlabel('$t$', fontsize=14)\n plt.xticks(fontsize=14)\n plt.yticks(fontsize=14)\n plt.legend(fontsize=13)\n if output_path is not None:\n plt.savefig(output_path, bbox_inches='tight')\n else:\n plt.show()\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Plot positive edge density (rho)')\n parser.add_argument('--metrics-file', type=str, required=True, help='Path to calculated positive edge density')\n parser.add_argument('--output-figure', type=str, required=False, default=None, help='Where to save output figure')\n args = parser.parse_args()\n metrics = load_metrics(args.metrics_file)\n plot_metrics(args.metrics_file, metrics, args.output_figure)\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.xlabel"
]
] |
elephantscale/facies | [
"ea78a4917ebb5dbbe478b9fc27200c67b6e5576f"
] | [
"code/faciesplot.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n#Key:\n# 1=sandstone 2=c_siltstone 3=f_siltstone \n# 4=marine_silt_shale 5=mudstone 6=wackestone 7=dolomite\n# 8=packstone 9=bafflestone\n\n\nfacies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS',\n 'WS', 'D','PS', 'BS']\n\nfacies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D']\n\n#facies_color_map is a dictionary that maps facies labels\n#to their respective colors\n\n\nfacies_color_map = {}\nfor ind, label in enumerate(facies_labels):\n facies_color_map[label] = facies_colors[ind]\n\n \n \ndef label_facies(row, labels):\n return labels[ row['Facies'] -1]\n\ndef make_facies_log_plot(logs, facies_colors):\n #make sure logs are sorted by depth\n logs = logs.sort_values(by='Depth')\n cmap_facies = colors.ListedColormap(\n facies_colors[0:len(facies_colors)], 'indexed')\n \n ztop=logs.Depth.min(); zbot=logs.Depth.max()\n \n cluster=np.repeat(np.expand_dims(logs['Facies'].values,1), 100, 1)\n \n f, ax = plt.subplots(nrows=1, ncols=6, figsize=(8, 12))\n ax[0].plot(logs.GR, logs.Depth, '-g')\n ax[1].plot(logs.ILD_log10, logs.Depth, '-')\n ax[2].plot(logs.DeltaPHI, logs.Depth, '-', color='0.5')\n ax[3].plot(logs.PHIND, logs.Depth, '-', color='r')\n ax[4].plot(logs.PE, logs.Depth, '-', color='black')\n im=ax[5].imshow(cluster, interpolation='none', aspect='auto',\n cmap=cmap_facies,vmin=1,vmax=9)\n \n divider = make_axes_locatable(ax[5])\n cax = divider.append_axes(\"right\", size=\"20%\", pad=0.05)\n cbar=plt.colorbar(im, cax=cax)\n cbar.set_label((17*' ').join([' SS ', 'CSiS', 'FSiS', \n 'SiSh', ' MS ', ' WS ', ' D ', \n ' PS ', ' BS ']))\n cbar.set_ticks(range(0,1)); cbar.set_ticklabels('')\n \n for i in range(len(ax)-1):\n ax[i].set_ylim(ztop,zbot)\n ax[i].invert_yaxis()\n ax[i].grid()\n ax[i].locator_params(axis='x', nbins=3)\n \n ax[0].set_xlabel(\"GR\")\n ax[0].set_xlim(logs.GR.min(),logs.GR.max())\n ax[1].set_xlabel(\"ILD_log10\")\n ax[1].set_xlim(logs.ILD_log10.min(),logs.ILD_log10.max())\n ax[2].set_xlabel(\"DeltaPHI\")\n ax[2].set_xlim(logs.DeltaPHI.min(),logs.DeltaPHI.max())\n ax[3].set_xlabel(\"PHIND\")\n ax[3].set_xlim(logs.PHIND.min(),logs.PHIND.max())\n ax[4].set_xlabel(\"PE\")\n ax[4].set_xlim(logs.PE.min(),logs.PE.max())\n ax[5].set_xlabel('Facies')\n \n ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([])\n ax[4].set_yticklabels([]); ax[5].set_yticklabels([])\n ax[5].set_xticklabels([])\n f.suptitle('Well: %s'%logs.iloc[0]['WellName'], fontsize=14,y=0.94)\n\n\ndef compare_facies_plot(logs, compadre, facies_colors):\n \"\"\"plot the facies plot as a function of depth for both the prediction\n and the actual lithofacies labels.\n \"\"\"\n \n #make sure logs are sorted by depth\n logs = logs.sort_values(by='Depth')\n cmap_facies = colors.ListedColormap(\n facies_colors[0:len(facies_colors)], 'indexed')\n \n ztop=logs.Depth.min(); zbot=logs.Depth.max()\n \n cluster1 = np.repeat(np.expand_dims(logs['Facies'].values,1), 100, 1)\n cluster2 = np.repeat(np.expand_dims(logs[compadre].values,1), 100, 1)\n \n f, ax = plt.subplots(nrows=1, ncols=7, figsize=(9, 12))\n ax[0].plot(logs.GR, logs.Depth, '-g')\n ax[1].plot(logs.ILD_log10, logs.Depth, '-')\n ax[2].plot(logs.DeltaPHI, logs.Depth, '-', color='0.5')\n ax[3].plot(logs.PHIND, logs.Depth, '-', color='r')\n ax[4].plot(logs.PE, logs.Depth, '-', color='black')\n im1 = ax[5].imshow(cluster1, interpolation='none', aspect='auto',\n cmap=cmap_facies,vmin=1,vmax=9)\n im2 = ax[6].imshow(cluster2, interpolation='none', aspect='auto',\n cmap=cmap_facies,vmin=1,vmax=9)\n \n divider = make_axes_locatable(ax[6])\n cax = divider.append_axes(\"right\", size=\"20%\", pad=0.05)\n cbar=plt.colorbar(im2, cax=cax)\n cbar.set_label((17*' ').join([' SS ', 'CSiS', 'FSiS', \n 'SiSh', ' MS ', ' WS ', ' D ', \n ' PS ', ' BS ']))\n cbar.set_ticks(range(0,1)); cbar.set_ticklabels('')\n \n for i in range(len(ax)-2):\n ax[i].set_ylim(ztop,zbot)\n ax[i].invert_yaxis()\n ax[i].grid()\n ax[i].locator_params(axis='x', nbins=3)\n \n ax[0].set_xlabel(\"GR\")\n ax[0].set_xlim(logs.GR.min(),logs.GR.max())\n ax[1].set_xlabel(\"ILD_log10\")\n ax[1].set_xlim(logs.ILD_log10.min(),logs.ILD_log10.max())\n ax[2].set_xlabel(\"DeltaPHI\")\n ax[2].set_xlim(logs.DeltaPHI.min(),logs.DeltaPHI.max())\n ax[3].set_xlabel(\"PHIND\")\n ax[3].set_xlim(logs.PHIND.min(),logs.PHIND.max())\n ax[4].set_xlabel(\"PE\")\n ax[4].set_xlim(logs.PE.min(),logs.PE.max())\n ax[5].set_xlabel('Facies')\n ax[6].set_xlabel(compadre)\n \n ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([])\n ax[4].set_yticklabels([]); ax[5].set_yticklabels([])\n ax[5].set_xticklabels([])\n ax[6].set_xticklabels([])\n f.suptitle('Well: %s'%logs.iloc[0]['WellName'], fontsize=14,y=0.94)\n"
] | [
[
"matplotlib.pyplot.colorbar",
"numpy.expand_dims",
"matplotlib.pyplot.subplots"
]
] |
siyemuxu888/imagepy | [
"a933526483a15da282bacac54608d44d2173beb4",
"a933526483a15da282bacac54608d44d2173beb4"
] | [
"imagepy/tools/Transform/scale_tol.py",
"imagepy/menus/Plugins/Surf/surf_plg.py"
] | [
"import wx\nimport numpy as np\nfrom imagepy.core.engine import Tool, Filter\nimport scipy.ndimage as nimg\n\nclass ScaleTool(Tool):\n def __init__(self, plg):\n self.plg = plg\n self.para = plg.para\n self.moving = False\n \n def snap(self, x, y, lim):\n plg = self.plg\n if abs(x-plg.lt)<lim and abs(y-(plg.tp+plg.bm)/2)<lim:return 'l'\n if abs(x-plg.rt)<lim and abs(y-(plg.tp+plg.bm)/2)<lim:return 'r'\n if abs(x-(plg.lt+plg.rt)/2)<lim and abs(y-plg.tp)<lim:return 't'\n if abs(x-(plg.lt+plg.rt)/2)<lim and abs(y-plg.bm)<lim:return 'b'\n if abs(x-plg.lt)<lim and abs(y-plg.tp)<lim:return 'lt'\n if abs(x-plg.rt)<lim and abs(y-plg.bm)<lim:return 'rb'\n if abs(x-plg.rt)<lim and abs(y-plg.tp)<lim:return 'rt'\n if abs(x-plg.lt)<lim and abs(y-plg.bm)<lim:return 'lb'\n if (x-plg.lt)*(x-plg.rt)<0 and (y-plg.tp)*(y-plg.bm)<0:\n self.ox, self.oy = x, y\n return True\n return False\n \n def mouse_down(self, ips, x, y, btn, **key): \n lim = 5.0/key['canvas'].get_scale() \n self.moving = self.snap(x, y, lim)\n print(self.moving)\n \n def mouse_up(self, ips, x, y, btn, **key):\n if self.moving : self.plg.preview(ips, self.para)\n \n def mouse_move(self, ips, x, y, btn, **key):\n lim = 5.0/key['canvas'].get_scale()\n if btn==None:\n self.cursor = wx.CURSOR_CROSS\n if isinstance(self.snap(x, y, lim), str):\n self.cursor = wx.CURSOR_HAND\n elif self.moving==True:\n self.plg.lt+=x-self.ox\n self.plg.rt+=x-self.ox\n self.plg.bm+=y-self.oy\n self.plg.tp+=y-self.oy\n self.ox, self.oy = x, y\n self.plg.count()\n self.plg.dialog.reset()\n ips.update = True\n elif self.moving != False:\n print(\"scale_tol.ScaleTool.mouse_move\")\n if 'l' in self.moving:self.plg.lt = x\n if 'r' in self.moving:self.plg.rt = x\n if 't' in self.moving:self.plg.tp = y\n if 'b' in self.moving:self.plg.bm = y\n self.plg.count()\n self.plg.dialog.reset()\n ips.update = True\n\nclass Plugin(Filter):\n modal = False\n title = 'Scale'\n note = ['all', 'auto_msk', 'auto_snap', 'preview']\n para = {'kx': 1, 'ky':1, 'ox':0, 'oy':0, 'img':True, 'msk':False}\n view = [(float, (-100,100), 3, 'KX', 'kx', ''),\n (float, (-100,100), 3, 'KY', 'ky', ''),\n (int, (-10000,10000), 0, 'OffX', 'ox', 'pix'),\n (int, (-10000,10000), 0, 'OffY', 'oy', 'pix'),\n (bool, 'scale image', 'img'),\n (bool, 'scale mask', 'msk')]\n\n \n def draw(self, dc, f, **key):\n body = [(self.lt,self.bm),(self.rt,self.bm),\n (self.rt,self.tp),(self.lt,self.tp),(self.lt,self.bm)]\n dc.SetPen(wx.Pen((0,255,0), width=1, style=wx.SOLID))\n dc.DrawLines([f(*i) for i in body])\n for i in body:dc.DrawCircle(f(*i),2)\n dc.DrawCircle(f(self.lt, (self.tp+self.bm)/2),2)\n dc.DrawCircle(f(self.rt, (self.tp+self.bm)/2),2)\n dc.DrawCircle(f((self.lt+self.rt)/2, self.tp),2)\n dc.DrawCircle(f((self.lt+self.rt)/2, self.bm),2)\n \n def load(self, ips): \n self.bufroi = ips.roi\n self.lt, self.tp, self.rt, self.bm = 0, 0, ips.size[1], ips.size[0]\n \n if ips.roi!=None:\n box = ips.roi.get_box()\n if box[0]!=box[2] and box[1]!=box[3]:\n self.lt, self.tp, self.rt, self.bm = box\n\n self.orio = ((self.lt+self.rt)/2,(self.tp+self.bm)/2)\n self.oriw, self.orih = self.rt - self.lt, self.tp - self.bm\n\n self.para['ox'] = (self.lt+self.rt)/2\n self.para['oy'] = (self.tp+self.bm)/2\n self.para['kx'] = self.para['ky'] = 1\n \n ips.mark = self\n ips.update = True\n ips.tool = ScaleTool(self)\n return True\n \n def count(self, dir=True):\n if dir:\n self.para['ox'] = int((self.lt+self.rt)/2)\n self.para['oy'] = int((self.tp+self.bm)/2)\n self.para['kx'] = (self.rt-self.lt)*1.0/self.oriw\n self.para['ky'] = (self.tp-self.bm)*1.0/self.orih\n else:\n self.lt = self.para['ox']-self.oriw*self.para['kx']/2\n self.rt = self.para['ox']+self.oriw*self.para['kx']/2\n self.bm = self.para['oy']-self.orih*self.para['ky']/2\n self.tp = self.para['oy']+self.orih*self.para['ky']/2\n\n def ok(self, ips, para=None):\n Filter.ok(self, ips, para)\n ips.mark = None\n ips.tool = None\n \n def cancel(self, ips):\n Filter.cancel(self, ips)\n ips.roi = self.bufroi\n ips.mark = None\n ips.tool = None\n ips.update = 'pix'\n \n def run(self, ips, img, buf, para = None):\n if para == None: para = self.para\n self.count(False)\n trans = np.array([[1/self.para['ky'],0],[0,1/self.para['kx']]])\n o = np.array([self.para['oy'], self.para['ox']])\n offset = self.orio[::-1]-trans.dot(o)\n if self.para['img']:\n nimg.affine_transform(img, trans, output=buf, offset=offset)\n trans = np.array([[self.para['kx'],0],[0, self.para['ky']]])\n offset = o[::-1]-trans.dot(self.orio)\n if self.para['msk'] and self.bufroi!=None:ips.roi = self.bufroi.affine(trans, offset)\n if self.para['img'] and not ips.get_msk('out') is None: \n buf[ips.get_msk('out')] = img[ips.get_msk('out')]\n ips.update = True\n",
"import cv2, wx\nfrom imagepy.core.engine import Filter, Simple, Tool\nfrom imagepy.core.manager import WindowsManager\nfrom .matcher import Matcher\nimport numpy as np\nfrom imagepy import IPy\n\nCVSURF = cv2.xfeatures2d.SURF_create if cv2.__version__[0] ==\"3\" else cv2.SURF\n\nclass FeatMark:\n def __init__(self, feats):\n self.feats = feats\n\n def draw(self, dc, f, **key):\n for i in self.feats:\n dc.DrawCircle(f(i.pt), 3)\n\nclass Surf(Filter):\n title = 'Surf Detect'\n note = ['all', 'not-slice']\n\n para = {'upright':False, 'oct':3, 'int':4, 'thr':1000, 'ext':False}\n view = [(int, (0,5), 0, 'octaves', 'oct', ''),\n (int, (0,5), 0, 'intervals', 'int',''),\n (int, (500,2000), 0, 'threshold', 'thr','1-100'),\n (bool, 'extended', 'ext'),\n (bool, 'upright', 'upright')]\n\n def run(self, ips, snap, img, para):\n detector = CVSURF(hessianThreshold=para['thr'], nOctaves=para['oct'],\n nOctaveLayers=para['int'], upright=para['upright'],extended=para['ext'])\n kps = detector.detect(img)\n ips.surf_keypoint = kps\n ips.mark = FeatMark(kps)\n IPy.write(\"Detect completed, {} points found!\".format(len(kps)), 'Surf')\n\nclass Pick(Tool):\n title = 'Key Point Pick Tool'\n def __init__(self, pts1, pts2, pair, msk, ips1, ips2, host, style):\n self.pts1, self.pts2 = pts1, pts2\n self.ips1, self.ips2 = ips1, ips2\n self.pair, self.msk = pair, msk\n self.cur, self.host = -1, host\n self.pts = self.pts1 if host else self.pts2\n self.style = style\n\n def nearest(self, x, y):\n mind, mini = 1000, -1\n for i1, i2 in self.pair:\n i = i1 if self.host else i2\n d = np.sqrt((x-self.pts[i].pt[0])**2+(y-self.pts[i].pt[1])**2)\n if d<mind: mind, mini = d, (i1, i2)\n return mini if mind<5 else None\n\n def mouse_down(self, ips, x, y, btn, **key):\n cur = self.nearest(x, y)\n if cur==None:return\n self.ips1.tool.cur, self.ips2.tool.cur = cur\n self.ips1.update, self.ips2.update = True, True\n\n def mouse_up(self, ips, x, y, btn, **key):\n pass\n\n def mouse_move(self, ips, x, y, btn, **key):\n pass\n\n def mouse_wheel(self, ips, x, y, d, **key):\n pass\n\n def draw(self, dc, f, **key):\n #dc.SetPen(wx.TRANSPARENT_PEN)\n dc.SetBrush(wx.Brush((0,0,255)))\n if self.style:\n for i in self.pts:dc.DrawCircle(f(*i.pt), 3)\n tidx = self.pair[:,1-self.host][self.msk]\n dc.SetBrush(wx.Brush((255,255,0)))\n for i in tidx:\n dc.DrawCircle(f(*self.pts[i].pt), 3)\n if self.cur!=-1:\n dc.SetBrush(wx.Brush((255,0,0)))\n dc.DrawCircle(f(*self.pts[self.cur].pt), 3)\n\nclass Match(Simple):\n title = 'Surf Matcher'\n note = ['all']\n\n #parameter\n para = {'img1':'','img2':'','upright':False, 'log':False,\n 'oct':3, 'int':4, 'thr':1000, 'ext':False,\n 'trans':'None', 'std':1, 'style':'Blue/Yellow'}\n\n def load(self, ips):\n titles = WindowsManager.get_titles()\n self.para['img1'] = titles[0]\n self.para['img2'] = titles[0]\n Match.view = [('lab','========= two image in 8-bit ========='),\n (list, titles, str, 'image1', 'img1', ''),\n (list, titles, str, 'image2', 'img2', ''),\n ('lab',''),\n ('lab','====== parameter about the surf ======'),\n (int, (0,5), 0, 'octaves', 'oct', ''),\n (int, (0,5), 0, 'intervals', 'int',''),\n (int, (500,2000), 0, 'threshold', 'thr','1-100'),\n (bool, 'extended', 'ext'),\n (bool, 'upright', 'upright'),\n ('lab',''),\n ('lab','====== how to match and display ======'),\n (list, ['None', 'Affine', 'Homo'], str, 'transform', 'trans',''),\n (int, (1, 5), 0, 'Std', 'std', 'torlerance'),\n (list, ['Blue/Yellow', 'Hide'], str, 'Aspect', 'style', 'color'),\n (bool, 'Show log', 'log')]\n return True\n\n def filter_matches(self, kp1, kp2, matches, ratio = 0.75):\n mkp1, mkp2 = [], []\n for m in matches:\n if len(m) == 2 and m[0].distance < m[1].distance * ratio:\n m = m[0]\n mkp1.append( kp1[m.queryIdx] )\n mkp2.append( kp2[m.trainIdx] )\n p1 = np.float32([kp.pt for kp in mkp1])\n p2 = np.float32([kp.pt for kp in mkp2])\n kp_pairs = list(zip(mkp1, mkp2))\n return p1, p2, kp_pairs\n\n #process\n def run(self, ips, imgs, para = None):\n ips1 = WindowsManager.get(para['img1']).ips\n ips2 = WindowsManager.get(para['img2']).ips\n\n detector = CVSURF(hessianThreshold=para['thr'], nOctaves=para['oct'],\n nOctaveLayers=para['int'], upright=para['upright'],extended=para['ext'])\n kps1, feats1 = detector.detectAndCompute(ips1.img, None)\n kps2, feats2 = detector.detectAndCompute(ips2.img, None)\n dim, std = {'None':0, 'Affine':6, 'Homo':8}[para['trans']], para['std']/100.0\n style = para['style']=='Blue/Yellow'\n idx, msk, m = Matcher(dim, std).filter(kps1,feats1,kps2,feats2)\n picker1 = Pick(kps1, kps2, idx, msk, ips1, ips2, True, style)\n picker2 = Pick(kps1, kps2, idx, msk, ips1, ips2, False, style)\n ips1.tool, ips1.mark = picker1, picker1\n ips2.tool, ips2.mark = picker2, picker2\n if para['log']:self.log(kps1, kps2, msk, m, dim)\n ips1.update, ips2.update = True, True\n\n def log(self, pts1, pts2, msk, v, dim):\n sb = []\n sb.append('Image1:{} points detected!'.format(len(pts1)))\n sb.append('Image2:{} points detected!\\r\\n'.format(len(pts2)))\n sb.append('Matched Point:{0}/{1}\\r\\n'.format(msk.sum(),len(msk)))\n if dim == 0: return\n sb.append('Transformation:')\n sb.append('%15.4f%15.4f%15.4f'%tuple(v.A1[:3]))\n sb.append('%15.4f%15.4f%15.4f'%tuple(v.A1[3:6]))\n row = [0,0,1] if dim==6 else list(v[-2:])+[1]\n sb.append('%15.4f%15.4f%15.4f'%tuple(row))\n \n cont = '\\n'.join(sb)\n IPy.write(cont, 'Surf')\n\nplgs = [Surf, Match]\n\nif __name__ == '__main__':\n from .matcher import Matcher\n\n detector = CVSURF(1000, nOctaves=3, nOctaveLayers=4, upright=False,extended=False)\n #img1 = cv2.imread('/home/yxl/opencv-2.4/samples/c/box.png', 0)\n img1 = cv2.imread('/home/auss/Pictures/faces1.png',0)\n pts, des = detector.detectAndCompute(img1, None)\n\n matcher = cv2.BFMatcher(cv2.NORM_L2)\n raw_matches = matcher.knnMatch(des, trainDescriptors = des, k = 1)\n m = raw_matches[0][0]\n lt = [(i[0].distance, i[0].queryIdx, i[0].trainIdx) for i in raw_matches]\n lt = np.array(sorted(lt))\n\n matcher = Matcher(8, 3)\n idx, msk, m = matcher.filter(pts,des,pts,des)"
] | [
[
"numpy.array",
"scipy.ndimage.affine_transform"
],
[
"numpy.sqrt",
"numpy.float32"
]
] |
KedoKudo/jupyter-ht-hedm | [
"b447202fb9800e7b2916b38470db1b9a83357130"
] | [
"seisidd/tomo_plans.py"
] | [
"#!/usr/bin/env python\n\n\"\"\"\nPredefined bluesky scan plans\n\"\"\"\n\nimport numpy as np\nimport bluesky.plans as bp\nimport bluesky.preprocessors as bpp\nimport bluesky.plan_stubs as bps\n\nfrom .utility import load_config\n\n#@bpp.run_decorator()\ndef collect_white_field(experiment, cfg_tomo, atfront=True):\n \"\"\"\n Collect white/flat field images by moving the sample out of the FOV\n \"\"\"\n # unpack devices\n det = experiment.det\n tomostage = experiment.tomostage\n\n # move sample out of the way\n _x = cfg_tomo['fronte_white_ksamX'] if atfront else cfg_tomo['back_white_ksamX']\n _z = cfg_tomo['fronte_white_ksamZ'] if atfront else cfg_tomo['back_white_ksamZ']\n yield from bps.mv(tomostage.ksamX, _x)\n yield from bps.mv(tomostage.ksamZ, _z)\n\n # setup detector\n yield from bps.mv(det.hdf1.nd_array_port, 'PROC1')\n yield from bps.mv(det.tiff1.nd_array_port, 'PROC1') \n yield from bps.mv(det.proc1.enable, 1)\n yield from bps.mv(det.proc1.reset_filter, 1)\n yield from bps.mv(det.proc1.num_filter, cfg_tomo['n_frames'])\n yield from bps.mv(det.cam.trigger_mode, \"Internal\")\n yield from bps.mv(det.cam.image_mode, \"Multiple\")\n yield from bps.mv(det.cam.num_images, cfg_tomo['n_frames']*cfg_tomo['n_white'])\n yield from bps.trigger_and_read([det])\n\n # move sample back to FOV\n # NOTE:\n # not sure is this will work or not...\n yield from bps.mv(tomostage.ksamX, cfg_tomo['initial_ksamX'])\n yield from bps.mv(tomostage.ksamZ, cfg_tomo['initial_ksamZ'])\n\n\n#@bpp.run_decorator()\ndef collect_dark_field(experiment, cfg_tomo):\n \"\"\"\n Collect dark field images by close the shutter\n \"\"\"\n det = experiment.det\n\n yield from bps.mv(det.hdf1.nd_array_port, 'PROC1')\n yield from bps.mv(det.tiff1.nd_array_port, 'PROC1') \n yield from bps.mv(det.proc1.enable, 1)\n yield from bps.mv(det.proc1.reset_filter, 1)\n yield from bps.mv(det.proc1.num_filter, cfg_tomo['n_frames'])\n yield from bps.mv(det.cam.trigger_mode, \"Internal\")\n yield from bps.mv(det.cam.image_mode, \"Multiple\")\n yield from bps.mv(det.cam.num_images, cfg_tomo['n_frames']*cfg_tomo['n_dark'])\n yield from bps.trigger_and_read([det])\n\n\n#@bpp.run_decorator()\ndef step_scan(experiment, cfg_tomo):\n \"\"\"\n Collect projects with step motion\n \"\"\"\n # unpack devices\n det = experiment.det\n tomostage = experiment.tomostage\n\n yield from bps.mv(det.hdf1.nd_array_port, 'PROC1')\n yield from bps.mv(det.tiff1.nd_array_port, 'PROC1') \n yield from bps.mv(det.proc1.enable, 1)\n yield from bps.mv(det.proc1.reset_filter, 1)\n yield from bps.mv(det.proc1.num_filter, cfg_tomo['n_frames'])\n\n angs = np.arange(\n cfg_tomo['omega_start'], \n cfg_tomo['omega_end']+cfg_tomo['omega_step']/2,\n cfg_tomo['omega_step'],\n )\n for ang in angs:\n yield from bps.checkpoint()\n yield from bps.mv(tomostage.preci, ang)\n yield from bps.trigger_and_read([det])\n\n\n#@bpp.run_decorator()\ndef fly_scan(experiment, cfg_tomo):\n \"\"\"\n Collect projections with fly motion\n \"\"\"\n det = experiment.det\n psofly = experiment.psofly\n \n yield from bps.mv(det.hdf1.nd_array_port, 'PG1')\n yield from bps.mv(det.tiff1.nd_array_port, 'PG1')\n\n # we are assuming that the global psofly is available\n yield from bps.mv(\n psofly.start, cfg_tomo['omega_start'],\n psofly.end, cfg_tomo['omega_end'],\n psofly.scan_delta, abs(cfg_tomo['omega_step']),\n psofly.slew_speed, cfg_tomo['slew_speed'],\n )\n # taxi\n yield from bps.mv(psofly.taxi, \"Taxi\")\n yield from bps.mv(\n det.cam.num_images, cfg_tomo['n_projections'],\n det.cam.trigger_mode, \"Overlapped\",\n )\n # start the fly scan\n yield from bps.trigger(det, group='fly')\n yield from bps.abs_set(psofly.fly, \"Fly\", group='fly')\n yield from bps.wait(group='fly')\n\n\ndef tomo_scan(experiment, cfg):\n \"\"\"\n Tomography scan plan based on given configuration\n \"\"\"\n # unpack devices\n det = experiment.det\n tomostage = experiment.tomostage\n shutter = experiment.shutter\n shutter_suspender = experiment.suspend_shutter\n \n cfg = load_config(cfg) if type(cfg) != dict else cfg\n\n # update the cached motor position in the dict in case exp goes wrong\n _cahed_position = experiment.cache_motor_position()\n\n # step 0: preparation\n acquire_time = cfg['tomo']['acquire_time']\n n_white = cfg['tomo']['n_white']\n n_dark = cfg['tomo']['n_dark']\n angs = np.arange(\n cfg['tomo']['omega_start'], \n cfg['tomo']['omega_end']+cfg['tomo']['omega_step']/2,\n cfg['tomo']['omega_step'],\n )\n n_projections = len(angs)\n cfg['tomo']['n_projections'] = n_projections\n total_images = n_white + n_projections + n_white + n_dark\n fp = cfg['output']['filepath']\n fn = cfg['output']['fileprefix']\n \n # calculate slew speed for fly scan\n # https://github.com/decarlof/tomo2bm/blob/master/flir/libs/aps2bm_lib.py\n # TODO: considering blue pixels, use 2BM code as ref\n if cfg['tomo']['type'].lower() == 'fly':\n scan_time = (acquire_time+cfg['tomo']['readout_time'])*n_projections\n slew_speed = (angs.max() - angs.min())/scan_time\n cfg['tomo']['slew_speed'] = slew_speed\n \n # need to make sure that the sample out position is the same for both front and back\n x0, z0 = tomostage.ksamX.position, tomostage.ksamZ.position\n dfx, dfz = cfg['tomo']['sample_out_position']['samX'], cfg['tomo']['sample_out_position']['samZ']\n rotang = np.radians(cfg['tomo']['omega_end']-cfg['tomo']['omega_start'])\n rotm = np.array([[ np.cos(rotang), np.sin(rotang)],\n [-np.sin(rotang), np.cos(rotang)]])\n dbxz = np.dot(rotm, np.array([dfx, dfz]))\n dbx = dbxz[0] if abs(dbxz[0]) > 1e-8 else 0.0\n dbz = dbxz[1] if abs(dbxz[1]) > 1e-8 else 0.0\n # now put the value to dict\n cfg['tomo']['initial_ksamX'] = x0\n cfg['tomo']['initial_ksamZ'] = z0\n cfg['tomo']['fronte_white_ksamX'] = x0 + dfx\n cfg['tomo']['fronte_white_ksamZ'] = z0 + dfz\n cfg['tomo']['back_white_ksamX'] = x0 + dbx\n cfg['tomo']['back_white_ksamZ'] = z0 + dbz\n \n @bpp.run_decorator()\n @bpp.stage_decorator([det])\n def scan_closure():\n # open shutter for beam\n yield from bps.mv(shutter, 'open')\n yield from bps.install_suspender(shutter_suspender)\n \n # config output\n for me in [det.tiff1, det.hdf1]:\n yield from bps.mv(me.file_path, fp)\n yield from bps.mv(me.file_name, fn)\n yield from bps.mv(me.file_write_mode, 2)\n yield from bps.mv(me.num_capture, total_images)\n yield from bps.mv(me.file_template, \".\".join([r\"%s%s_%06d\",cfg['output']['type'].lower()])) \n\n if cfg['output']['type'] in ['tif', 'tiff']:\n yield from bps.mv(det.tiff1.enable, 1)\n yield from bps.mv(det.tiff1.capture, 1)\n yield from bps.mv(det.hdf1.enable, 0)\n elif cfg['output']['type'] in ['hdf', 'hdf1', 'hdf5']:\n yield from bps.mv(det.tiff1.enable, 0)\n yield from bps.mv(det.hdf1.enable, 1)\n yield from bps.mv(det.hdf1.capture, 1)\n else:\n raise ValueError(f\"Unsupported output type {cfg['output']['type']}\")\n\n # collect front white field\n yield from bps.mv(det.cam.frame_type, 0) # for HDF5 dxchange data structure\n yield from collect_white_field(experiment, cfg['tomo'], atfront=True)\n\n # collect projections\n yield from bps.mv(det.cam.frame_type, 1) # for HDF5 dxchange data structure\n if cfg['tomo']['type'].lower() == 'step':\n yield from step_scan(experiment, cfg['tomo'])\n elif cfg['tomo']['type'].lower() == 'fly':\n yield from fly_scan(experiment, cfg['tomo'])\n else:\n raise ValueError(f\"Unsupported scan type: {cfg['tomo']['type']}\")\n\n # collect back white field\n yield from bps.mv(det.cam.frame_type, 2) # for HDF5 dxchange data structure\n yield from collect_white_field(experiment, cfg['tomo'], atfront=False)\n\n # collect back dark field\n yield from bps.mv(det.cam.frame_type, 3) # for HDF5 dxchange data structure\n yield from bps.remove_suspender(shutter_suspender)\n yield from bps.mv(shutter, \"close\")\n yield from collect_dark_field(experiment, cfg['tomo'])\n\n return (yield from scan_closure())\n"
] | [
[
"numpy.cos",
"numpy.arange",
"numpy.array",
"numpy.sin",
"numpy.radians"
]
] |
petuum/tuun | [
"8eec472dbf0e5e695449b0fa2d98985469fd5b30"
] | [
"tuun/probo/models/gp_stan_transfer.py"
] | [
"\"\"\"\nClasses for GP models with Stan that perform transfer optimization.\n\"\"\"\n\nfrom argparse import Namespace\nimport numpy as np\nimport copy\n\nfrom .gp_stan import StanGp\nfrom .regression.transfer_regression import TransferRegression\nfrom ..util.misc_util import dict_to_namespace\n\n\nclass StanTransferGp(StanGp):\n \"\"\"\n GP model with transferred prior mean based on a regression model.\n \"\"\"\n def __init__(self, params=None, data=None, verbose=None):\n self.set_params(params)\n self.set_verbose(verbose)\n self.set_model(data)\n\n def set_params(self, params):\n \"\"\"Set self.params, the parameters for this model.\"\"\"\n super().set_params(params)\n params = dict_to_namespace(params)\n\n assert hasattr(params, 'transfer_config')\n self.params.transfer_config = params.transfer_config\n\n def set_model(self, data):\n \"\"\"Set GP Stan model and regression model.\"\"\"\n self.model = self.get_model()\n self.regressor = self.get_regressor(data)\n #self.regressor = self.get_proxy_regressor(data) # TODO\n\n def get_regressor(self, data):\n \"\"\"Return transfer (prior mean) regressor.\"\"\"\n\n # Define regressor\n regressor = TransferRegression(self.params.transfer_config)\n\n if len(data.x) < 1:\n regressor = None\n else:\n mean_errors = []\n\n # TODO: remove extra files such as .DS_STORE (or ignore files that break)\n for i, reg in enumerate(regressor.model_fnames):\n try:\n val_acc = regressor.evaluate_model(reg, data.x)\n error = np.mean((data.y - val_acc) ** 2)\n mean_errors.append((error, i))\n except:\n print(f'Transfer model file in tarball did not load: {reg}')\n mean_errors.sort()\n if mean_errors[0][0] > self.params.transfer_config.get('metric_threshold', 0.6):\n regressor.set_best_model(-1)\n else:\n regressor.set_best_model(mean_errors[0][1])\n\n return regressor\n\n def get_proxy_regressor(self, data):\n if not data:\n regressor = None\n else:\n def regressor(x): return np.linalg.norm(x)\n\n return regressor\n\n def transform_data_y(self):\n \"\"\"Transform data.y using PriorMeanDataTransformer.\"\"\"\n self.dt = PriorMeanDataTransformer(self.data, self.regressor, False)\n y_trans = self.dt.transform_y_data()\n self.data = Namespace(x=self.data.x, y=y_trans)\n\n def gen_list(self, x_list, z, s, nsamp):\n \"\"\"\n Draw nsamp samples from generative process, given list of inputs\n x_list, posterior sample z, and seed s.\n\n Parameters\n ----------\n x_list : list\n List of numpy ndarrays each with shape=(self.params.ndimx,)\n z : Namespace\n Namespace of GP hyperparameters.\n s : int\n The seed, a positive integer.\n nsamp : int\n The number of samples to draw from generative process.\n\n Returns\n -------\n list\n A list with len=len(x_list) of numpy ndarrays, each with\n shape=(nsamp,).\n \"\"\"\n x_list = self.transform_xin_list(x_list)\n pred_list = self.sample_gp_pred(nsamp, x_list)\n pred_list = [\n self.dt.inv_transform_y_data(pr, x) for pr, x in zip(pred_list, x_list)\n ]\n return pred_list\n\n def postgen_list(self, x_list, s, nsamp):\n \"\"\"\n Draw nsamp samples from posterior predictive distribution, given list\n of inputs x_list and seed s.\n\n Parameters\n ----------\n x_list : list\n List of numpy ndarrays each with shape=(self.params.ndimx,).\n s : int\n The seed, a positive integer.\n nsamp : int\n The number of samples to draw from the posterior predictive\n distribution.\n\n Returns\n -------\n list\n A list with len=len(x_list) of numpy ndarrays, each with\n shape=(nsamp,).\n \"\"\"\n x_list = self.transform_xin_list(x_list)\n pred_list = self.sample_gp_post_pred(\n nsamp, x_list, full_cov=True, nloop=np.min([50, nsamp])\n )\n pred_list = [\n self.dt.inv_transform_y_data(pr, x) for pr, x in zip(pred_list, x_list)\n ]\n return pred_list\n\n def __str__(self):\n return f'StanTransferGp with params={self.params}'\n\n\nclass PriorMeanDataTransformer:\n \"\"\"\n A class to transform (and inverse transform) data, based on a prior mean regression.\n \"\"\"\n\n def __init__(self, data, prior_mean_f, verbose=True):\n \"\"\"\n Parameters\n ----------\n data : Namespace\n Namespace containing data.\n prior_mean_f : function\n Prior mean function.\n verbose : bool\n If True, print description string.\n \"\"\"\n self._set_data(data)\n self._set_prior_mean_f(prior_mean_f)\n self._set_verbose(verbose)\n\n def _set_data(self, data):\n \"\"\"Set self.data\"\"\"\n self.data = data\n\n def _set_prior_mean_f(self, prior_mean_f):\n \"\"\"Set self.prior_mean_f.\"\"\"\n if prior_mean_f is None:\n # Default prior mean function is constant 0 function\n def prior_mean_f(x): return 0.\n\n self.prior_mean_f = prior_mean_f\n\n def _set_verbose(self, verbose):\n \"\"\"Set verbose options.\"\"\"\n self.verbose = verbose\n if self.verbose:\n self._print_str()\n\n def transform_y_data(self, y_data=None, x_data=None):\n \"\"\"Transform and return self.data.y\"\"\"\n\n # Transform self.data.y into new list\n y_trans = [y - self.prior_mean_f(x) for x, y in zip(self.data.x, self.data.y)]\n return y_trans\n\n def inv_transform_y_data(self, y_arr, x_single_arr):\n \"\"\"Return inverse transform of y_arr.\"\"\"\n\n # Compute prior mean val for the single input\n prior_mean_val = self.prior_mean_f(x_single_arr)\n\n # Inverse transform y_arr into list\n y_inv_trans_list = [y + prior_mean_val for y in list(y_arr)]\n\n # Transform back to array and return\n y_inv_trans = np.array(y_inv_trans_list).reshape(-1)\n return y_inv_trans\n\n def _print_str(self):\n \"\"\"Print a description string.\"\"\"\n print('*PriorMeanDataTransformer')\n"
] | [
[
"numpy.array",
"numpy.linalg.norm",
"numpy.min",
"numpy.mean"
]
] |
K4S4B4/learnable-triangulation-pytorch | [
"94f5121919785bf7c89dd973521a21c01104dbd5"
] | [
"mvn/utils/op.py"
] | [
"import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom mvn.utils.img import to_numpy, to_torch\nfrom mvn.utils import multiview\n\n\ndef integrate_tensor_2d(heatmaps, softmax=True):\n \"\"\"Applies softmax to heatmaps and integrates them to get their's \"center of masses\"\n\n Args:\n heatmaps torch tensor of shape (batch_size, n_heatmaps, h, w): input heatmaps\n\n Returns:\n coordinates torch tensor of shape (batch_size, n_heatmaps, 2): coordinates of center of masses of all heatmaps\n\n \"\"\"\n batch_size, n_heatmaps, h, w = heatmaps.shape\n\n heatmaps = heatmaps.reshape((batch_size, n_heatmaps, -1))\n if softmax:\n heatmaps = nn.functional.softmax(heatmaps, dim=2)\n else:\n heatmaps = nn.functional.relu(heatmaps)\n\n heatmaps = heatmaps.reshape((batch_size, n_heatmaps, h, w))\n\n mass_x = heatmaps.sum(dim=2)\n mass_y = heatmaps.sum(dim=3)\n\n mass_times_coord_x = mass_x * torch.arange(w).type(torch.float).to(mass_x.device)\n mass_times_coord_y = mass_y * torch.arange(h).type(torch.float).to(mass_y.device)\n\n x = mass_times_coord_x.sum(dim=2, keepdim=True)\n y = mass_times_coord_y.sum(dim=2, keepdim=True)\n\n if not softmax:\n x = x / mass_x.sum(dim=2, keepdim=True)\n y = y / mass_y.sum(dim=2, keepdim=True)\n\n coordinates = torch.cat((x, y), dim=2)\n coordinates = coordinates.reshape((batch_size, n_heatmaps, 2))\n\n return coordinates\n\n\ndef integrate_tensor_3d(volumes, softmax=True):\n batch_size, n_volumes, x_size, y_size, z_size = volumes.shape\n\n volumes = volumes.reshape((batch_size, n_volumes, -1))\n if softmax:\n volumes = nn.functional.softmax(volumes, dim=2)\n else:\n volumes = nn.functional.relu(volumes)\n\n volumes = volumes.reshape((batch_size, n_volumes, x_size, y_size, z_size))\n\n mass_x = volumes.sum(dim=3).sum(dim=3)\n mass_y = volumes.sum(dim=2).sum(dim=3)\n mass_z = volumes.sum(dim=2).sum(dim=2)\n\n mass_times_coord_x = mass_x * torch.arange(x_size).type(torch.float).to(mass_x.device)\n mass_times_coord_y = mass_y * torch.arange(y_size).type(torch.float).to(mass_y.device)\n mass_times_coord_z = mass_z * torch.arange(z_size).type(torch.float).to(mass_z.device)\n\n x = mass_times_coord_x.sum(dim=2, keepdim=True)\n y = mass_times_coord_y.sum(dim=2, keepdim=True)\n z = mass_times_coord_z.sum(dim=2, keepdim=True)\n\n if not softmax:\n x = x / mass_x.sum(dim=2, keepdim=True)\n y = y / mass_y.sum(dim=2, keepdim=True)\n z = z / mass_z.sum(dim=2, keepdim=True)\n\n coordinates = torch.cat((x, y, z), dim=2)\n coordinates = coordinates.reshape((batch_size, n_volumes, 3))\n\n return coordinates, volumes\n\n\ndef integrate_tensor_3d_with_coordinates(volumes, coord_volumes, softmax=True):\n batch_size, n_volumes, x_size, y_size, z_size = volumes.shape\n\n volumes = volumes.reshape((batch_size, n_volumes, -1))\n if softmax:\n volumes = nn.functional.softmax(volumes, dim=2)\n else:\n volumes = nn.functional.relu(volumes)\n\n volumes = volumes.reshape((batch_size, n_volumes, x_size, y_size, z_size))\n coordinates = torch.einsum(\"bnxyz, bxyzc -> bnc\", volumes, coord_volumes)\n\n return coordinates #, volumes\n\n\ndef unproject_heatmaps(heatmaps, proj_matricies, coord_volumes, volume_aggregation_method='sum', vol_confidences=None):\n device = heatmaps.device\n batch_size, n_views, n_joints, heatmap_shape = heatmaps.shape[0], heatmaps.shape[1], heatmaps.shape[2], tuple(heatmaps.shape[3:]) # 1,4,32,96x96\n volume_shape = coord_volumes.shape[1:4] #64x64x64\n\n volume_batch = torch.zeros(batch_size, n_joints, *volume_shape, device=device) # 1x32x64x64x64のTensor\n\n # TODO: speed up this this loop\n for batch_i in range(batch_size):\n coord_volume = coord_volumes[batch_i] # Bx64x64x64x3 -> 64x64x64x3\n grid_coord = coord_volume.reshape((-1, 3)) # 262144x3\n\n volume_batch_to_aggregate = torch.zeros(n_views, n_joints, *volume_shape, device=device) # 4x32x64x64x64\n\n for view_i in range(n_views):\n heatmap = heatmaps[batch_i, view_i] # 1x4x32x96x96 -> 32x96x96\n heatmap = heatmap.unsqueeze(0) # 1x32x96x96 (一番初めに次元を追加)\n\n grid_coord_proj = multiview.project_3d_points_to_image_plane_without_distortion( # 262144x3\n proj_matricies[batch_i, view_i], grid_coord, convert_back_to_euclidean=False\n )\n\n invalid_mask = grid_coord_proj[:, 2] <= 0.0 # depth must be larger than 0.0 #人がカメラに近づきすぎた場合に起こる??\n\n grid_coord_proj[grid_coord_proj[:, 2] == 0.0, 2] = 1.0 # not to divide by zero\n grid_coord_proj = multiview.homogeneous_to_euclidean(grid_coord_proj)\n\n # transform to [-1.0, 1.0] range\n grid_coord_proj_transformed = torch.zeros_like(grid_coord_proj) # 262144x2\n grid_coord_proj_transformed[:, 0] = 2 * (grid_coord_proj[:, 0] / heatmap_shape[0] - 0.5) # (0,0)->(96,96)の座標を、中心を(0,0)、左上を(-1,-1)、右下を(1,1)とする相対的な座標に変換\n grid_coord_proj_transformed[:, 1] = 2 * (grid_coord_proj[:, 1] / heatmap_shape[1] - 0.5)\n grid_coord_proj = grid_coord_proj_transformed\n\n # prepare to F.grid_sample\n grid_coord_proj = grid_coord_proj.unsqueeze(1).unsqueeze(0) # 引数で指定された場所に一つ次元を足すらしい 1x262144x1x2。heatmapが1x32x96x96\n try:\n current_volume = F.grid_sample(heatmap, grid_coord_proj, align_corners=True) # 1x32x262144x1 = Heatmap(1x32x96x96), grid_coord_proj(1x262144x1x2)\n except TypeError: # old PyTorch\n current_volume = F.grid_sample(heatmap, grid_coord_proj)\n\n # zero out non-valid points\n current_volume = current_volume.view(n_joints, -1) #32x262144\n current_volume[:, invalid_mask] = 0.0\n\n # reshape back to volume\n current_volume = current_volume.view(n_joints, *volume_shape) #32x64x64x64\n\n # collect\n volume_batch_to_aggregate[view_i] = current_volume\n\n # agregate resulting volume\n if volume_aggregation_method.startswith('conf'):\n volume_batch[batch_i] = (volume_batch_to_aggregate * vol_confidences[batch_i].view(n_views, n_joints, 1, 1, 1)).sum(0)\n elif volume_aggregation_method == 'sum':\n volume_batch[batch_i] = volume_batch_to_aggregate.sum(0)\n elif volume_aggregation_method == 'max':\n volume_batch[batch_i] = volume_batch_to_aggregate.max(0)[0]\n elif volume_aggregation_method == 'softmax':\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate.clone() # 2x32x64x64x64(n_views, n_joints, *volume_shape)\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate_softmin.view(n_views, -1) # reshape\n volume_batch_to_aggregate_softmin = nn.functional.softmax(volume_batch_to_aggregate_softmin, dim=0)\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate_softmin.view(n_views, n_joints, *volume_shape) #reshape back\n\n volume_batch[batch_i] = (volume_batch_to_aggregate * volume_batch_to_aggregate_softmin).sum(0)\n else:\n raise ValueError(\"Unknown volume_aggregation_method: {}\".format(volume_aggregation_method))\n\n return volume_batch\n\n\ndef gaussian_2d_pdf(coords, means, sigmas, normalize=True):\n normalization = 1.0\n if normalize:\n normalization = (2 * np.pi * sigmas[:, 0] * sigmas[:, 0])\n\n exp = torch.exp(-((coords[:, 0] - means[:, 0]) ** 2 / sigmas[:, 0] ** 2 + (coords[:, 1] - means[:, 1]) ** 2 / sigmas[:, 1] ** 2) / 2)\n return exp / normalization\n\n\ndef render_points_as_2d_gaussians(points, sigmas, image_shape, normalize=True):\n device = points.device\n n_points = points.shape[0]\n\n yy, xx = torch.meshgrid(torch.arange(image_shape[0]).to(device), torch.arange(image_shape[1]).to(device))\n grid = torch.stack([xx, yy], dim=-1).type(torch.float32)\n grid = grid.unsqueeze(0).repeat(n_points, 1, 1, 1) # (n_points, h, w, 2)\n grid = grid.reshape((-1, 2))\n\n points = points.unsqueeze(1).unsqueeze(1).repeat(1, image_shape[0], image_shape[1], 1)\n points = points.reshape(-1, 2)\n\n sigmas = sigmas.unsqueeze(1).unsqueeze(1).repeat(1, image_shape[0], image_shape[1], 1)\n sigmas = sigmas.reshape(-1, 2)\n\n images = gaussian_2d_pdf(grid, points, sigmas, normalize=normalize)\n images = images.reshape(n_points, *image_shape)\n\n return images\n"
] | [
[
"torch.stack",
"torch.nn.functional.softmax",
"torch.zeros_like",
"torch.exp",
"torch.nn.functional.relu",
"torch.arange",
"torch.nn.functional.grid_sample",
"torch.zeros",
"torch.einsum",
"torch.cat"
]
] |
ctiger34/BASIC-EMOTION-DETECTION | [
"1c2be519c70408159ea6e1093d5f139c99ea6e27"
] | [
"load_and_process.py"
] | [
"import pandas as pd\nimport cv2\nimport numpy as np\n\n\ndataset_path = 'fer2013/fer2013/fer2013.csv'\nimage_size=(48,48)\n\ndef load_fer2013():\n data = pd.read_csv(dataset_path)\n pixels = data['pixels'].tolist()\n width, height = 48, 48\n faces = []\n for pixel_sequence in pixels:\n face = [int(pixel) for pixel in pixel_sequence.split(' ')]\n face = np.asarray(face).reshape(width, height)\n face = cv2.resize(face.astype('uint8'),image_size)\n faces.append(face.astype('float32'))\n faces = np.asarray(faces)\n faces = np.expand_dims(faces, -1)\n emotions = pd.get_dummies(data['emotion']).as_matrix()\n return faces, emotions\n\ndef preprocess_input(x, v2=True):\n x = x.astype('float32')\n x = x / 255.0\n if v2:\n x = x - 0.5\n x = x * 2.0\n return x"
] | [
[
"pandas.read_csv",
"numpy.expand_dims",
"numpy.asarray",
"pandas.get_dummies"
]
] |
ray-ruisun/FedML | [
"24ff30d636bb70f64e94e9ca205375033597d3dd",
"24ff30d636bb70f64e94e9ca205375033597d3dd"
] | [
"app/fedcv/medical_chest_xray_image_clf/data/chexpert/data_loader.py",
"app/fedgraphnn/ego_networks_link_pred/data/utils.py"
] | [
"import logging\n\nimport os\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.transforms as transforms\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom .dataset import CheXpert\n\n\ndef _get_mean_and_std(dataset: Dataset):\n \"\"\"Compute the mean and std of dataset.\"\"\"\n data_loader = DataLoader(dataset, batch_size=1, shuffle=False)\n mean = torch.zeros(3)\n std = torch.zeros(3)\n for i, (img, _) in enumerate(data_loader):\n if i % 1000 == 0:\n print(i)\n mean += img.mean(dim=(0, 2, 3))\n std += img.std(dim=(0, 2, 3))\n mean /= len(data_loader)\n std /= len(data_loader)\n return mean, std\n\n\nclass Cutout(object):\n def __init__(self, length):\n self.length = length\n\n def __call__(self, img):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1:y2, x1:x2] = 0.0\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\n\ndef _data_transforms_chexpert():\n\n CHEXPERT_MEAN = [0.503, 0.503, 0.503]\n CHEXPERT_STD = [0.291, 0.291, 0.291]\n\n image_size = 256\n train_transform = transforms.Compose(\n [\n # transforms.ToPILImage(),\n transforms.RandomResizedCrop(image_size),\n # transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CHEXPERT_MEAN, CHEXPERT_STD),\n ]\n )\n\n # train_transform.transforms.append(Cutout(16))\n\n test_transform = transforms.Compose(\n [\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize(CHEXPERT_MEAN, CHEXPERT_STD),\n ]\n )\n\n return train_transform, test_transform\n\n\n# for centralized training\ndef get_dataloader(dataset, datadir, train_bs, test_bs, dataidxs=None, policy=\"zeros\"):\n return get_dataloader_chexpert(datadir, train_bs, test_bs, dataidxs, policy=policy)\n\n\n# for local devices\ndef get_dataloader_test(dataset, datadir, train_bs, test_bs, dataidxs_train, dataidxs_test, policy=\"zeros\"):\n return get_dataloader_test_chexpert(datadir, train_bs, test_bs, dataidxs_train, dataidxs_test, policy=policy)\n\n\ndef get_dataloader_chexpert(datadir, train_bs, test_bs, dataidxs=None, policy=\"zeros\"):\n dl_obj = CheXpert\n\n transform_train, transform_test = _data_transforms_chexpert()\n\n train_ds = dl_obj(\n datadir,\n dataidxs=dataidxs,\n train=True,\n transform=transform_train,\n download=False,\n policy=policy,\n )\n test_ds = dl_obj(\n datadir,\n dataidxs=None,\n train=False,\n transform=transform_test,\n download=False,\n policy=policy,\n )\n\n train_dl = DataLoader(\n dataset=train_ds,\n batch_size=train_bs,\n shuffle=True,\n drop_last=False,\n pin_memory=True,\n num_workers=4,\n )\n test_dl = DataLoader(\n dataset=test_ds,\n batch_size=test_bs,\n shuffle=False,\n drop_last=False,\n pin_memory=True,\n num_workers=4,\n )\n\n return train_dl, test_dl\n\n\ndef get_dataloader_test_chexpert(datadir, train_bs, test_bs, dataidxs_train=None, dataidxs_test=None, policy=\"zeros\"):\n dl_obj = CheXpert\n\n transform_train, transform_test = _data_transforms_chexpert()\n\n train_ds = dl_obj(\n datadir,\n dataidxs=dataidxs_train,\n train=True,\n transform=transform_train,\n download=True,\n policy=policy,\n )\n test_ds = dl_obj(\n datadir,\n dataidxs=dataidxs_test,\n train=False,\n transform=transform_test,\n download=True,\n policy=policy,\n )\n\n train_dl = DataLoader(\n dataset=train_ds,\n batch_size=train_bs,\n shuffle=True,\n drop_last=False,\n pin_memory=True,\n num_workers=4,\n )\n test_dl = DataLoader(\n dataset=test_ds,\n batch_size=test_bs,\n shuffle=False,\n drop_last=False,\n pin_memory=True,\n num_workers=4,\n )\n\n return train_dl, test_dl\n\n\ndef distributed_centralized_chexpert_loader(dataset, data_dir, world_size, rank, batch_size):\n \"\"\"\n Used for generating distributed dataloader for\n accelerating centralized training\n \"\"\"\n\n train_bs = batch_size\n test_bs = batch_size\n\n transform_train, transform_test = _data_transforms_chexpert()\n train_dataset = CheXpert(data_dir=data_dir, dataidxs=None, train=True, transform=transform_train)\n test_dataset = CheXpert(data_dir=data_dir, dataidxs=None, train=False, transform=transform_test)\n\n train_sam = DistributedSampler(train_dataset, num_replicas=world_size, rank=rank)\n test_sam = DistributedSampler(test_dataset, num_replicas=world_size, rank=rank)\n\n train_dl = data.DataLoader(\n train_dataset,\n batch_size=train_bs,\n sampler=train_sam,\n pin_memory=True,\n num_workers=4,\n )\n test_dl = data.DataLoader(\n test_dataset,\n batch_size=test_bs,\n sampler=test_sam,\n pin_memory=True,\n num_workers=4,\n )\n\n class_num = 1000\n\n train_data_num = len(train_dataset)\n test_data_num = len(test_dataset)\n\n return train_data_num, test_data_num, train_dl, test_dl, None, None, None, class_num\n\n\ndef load_partition_data_chexpert(\n data_dir,\n partition_method=\"random\",\n partition_alpha=None,\n client_number=100,\n batch_size=10,\n policy=\"zeros\",\n):\n transform_train, transform_test = _data_transforms_chexpert()\n\n train_dataset = CheXpert(\n data_dir=data_dir,\n dataidxs=None,\n train=True,\n transform=transform_train,\n policy=policy,\n )\n test_dataset = CheXpert(data_dir=data_dir, dataidxs=None, train=False, transform=transform_test, policy=policy)\n\n # get local dataset\n if partition_method == \"random\":\n num_train_items = int(len(train_dataset) / client_number)\n num_test_items = int(len(test_dataset) / client_number)\n dict_client = {}\n all_train_idxs = list(range(len(train_dataset)))\n all_test_idxs = list(range(len(test_dataset)))\n for client_idx in range(client_number):\n dict_client[client_idx] = {}\n dict_client[client_idx][\"train\"] = set(np.random.choice(all_train_idxs, num_train_items, replace=False))\n dict_client[client_idx][\"test\"] = set(np.random.choice(all_test_idxs, num_test_items, replace=False))\n all_train_idxs = list(set(all_train_idxs) - dict_client[client_idx][\"train\"])\n all_test_idxs = list(set(all_test_idxs) - dict_client[client_idx][\"test\"])\n if len(all_train_idxs) > 0:\n all_client_idxs = list(range(client_number))\n np.random.shuffle(all_client_idxs)\n choiced_client_idxs = all_client_idxs[: len(all_train_idxs)]\n for idx, client_idx in enumerate(choiced_client_idxs):\n dict_client[client_idx][\"train\"].add(all_train_idxs[idx])\n if len(all_test_idxs) > 0:\n all_client_idxs = list(range(client_number))\n np.random.shuffle(all_client_idxs)\n choiced_client_idxs = all_client_idxs[: len(all_test_idxs)]\n for idx, client_idx in enumerate(choiced_client_idxs):\n dict_client[client_idx][\"test\"].add(all_test_idxs[idx])\n else:\n raise NotImplementedError\n\n # build dataloader\n train_dl = []\n test_dl = []\n for client_idx in range(client_number):\n train_data_idxs = list(dict_client[client_idx][\"train\"])\n test_data_idxs = list(dict_client[client_idx][\"test\"])\n train_dl_, test_dl_ = get_dataloader_test_chexpert(\n datadir=data_dir,\n dataidxs_train=train_data_idxs,\n dataidxs_test=test_data_idxs,\n train_bs=batch_size,\n test_bs=batch_size,\n policy=policy,\n )\n train_dl.append(train_dl_)\n test_dl.append(test_dl_)\n\n logging.info(f\"Client {client_idx} train data num: {len(train_dl_)} test data num: {len(test_dl_)}\")\n\n logging.info(\"Partition data done\")\n # logging.info(\"Partition data for each client: {}\".format(dict_client))\n\n train_data_num = len(train_dataset)\n test_data_num = len(test_dataset)\n train_data_global = train_dataset\n test_data_global = test_dataset\n data_local_num_dict = {\n client_idx: len(dict_client[client_idx][\"train\"]) + len(dict_client[client_idx][\"test\"])\n for client_idx in range(client_number)\n }\n train_data_local_dict = {client_idx: train_dl_ for client_idx, train_dl_ in enumerate(train_dl)}\n test_data_local_dict = {client_idx: test_dl_ for client_idx, test_dl_ in enumerate(test_dl)}\n class_num = train_dataset.num_classes\n\n return (\n train_data_num,\n test_data_num,\n train_data_global,\n test_data_global,\n data_local_num_dict,\n train_data_local_dict,\n test_data_local_dict,\n class_num,\n )\n\n\nif __name__ == \"__main__\":\n data_path = os.path.join(\"D:\\\\\", \"dataset\", \"CheXpert\", \"CheXpert-v1.0-small\")\n data = CheXpert(data_dir=data_path, transform=transforms.ToTensor())\n print(len(data))\n print(data[0][0])\n print(data[0][1])\n\n # mean, std = _get_mean_and_std(data)\n # print(mean, std)\n\n # train_transform, valid_transform = _data_transforms_chexpert()\n # print(train_transform)\n # print(valid_transform)\n\n (\n train_data_num,\n test_data_num,\n train_data_global,\n test_data_global,\n data_local_num_dict,\n train_data_local_dict,\n test_data_local_dict,\n class_num,\n ) = load_partition_data_chexpert(data_dir=data_path, client_number=10, batch_size=10, policy=\"zeros\")\n\n print(train_data_num, test_data_num, class_num)\n",
"import numpy as np\nimport scipy.sparse as sp\nimport torch\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom torch_geometric.utils import to_networkx, degree\nimport torch.nn.functional as F\n\n\ndef convert_to_nodeDegreeFeatures(graphs):\n # print(graph.x)\n graph_infos = []\n maxdegree = 0\n for i, graph in enumerate(graphs):\n g = to_networkx(graph, to_undirected=True)\n gdegree = max(dict(g.degree).values())\n if gdegree > maxdegree:\n maxdegree = gdegree\n graph_infos.append(\n (graph, g.degree, graph.num_nodes)\n ) # (graph, node_degrees, num_nodes)\n\n new_graphs = []\n for i, tuple in enumerate(graph_infos):\n idx, x = tuple[0].edge_index[0], tuple[0].x\n deg = degree(idx, tuple[2], dtype=torch.long)\n deg = F.one_hot(deg, num_classes=maxdegree + 1).to(torch.float)\n\n new_graph = tuple[0].clone()\n new_graph.__setitem__(\"x\", deg)\n new_graphs.append(new_graph)\n\n return new_graphs\n\n\ndef split_data(graphs, train=None, test=None, shuffle=True, seed=None):\n y = torch.cat([graph.y for graph in graphs])\n graphs_tv, graphs_test = train_test_split(\n graphs,\n train_size=train,\n test_size=test,\n stratify=y,\n shuffle=shuffle,\n random_state=seed,\n )\n return graphs_tv, graphs_test\n\n\ndef np_uniform_sample_next(compact_adj, tree, fanout):\n last_level = tree[-1] # [batch, f^depth]\n batch_lengths = compact_adj.degrees[last_level]\n nodes = np.repeat(last_level, fanout, axis=1)\n batch_lengths = np.repeat(batch_lengths, fanout, axis=1)\n batch_next_neighbor_ids = np.random.uniform(\n size=batch_lengths.shape, low=0, high=1 - 1e-9\n )\n # Shape = (len(nodes), neighbors_per_node)\n batch_next_neighbor_ids = np.array(\n batch_next_neighbor_ids * batch_lengths, dtype=last_level.dtype\n )\n shape = batch_next_neighbor_ids.shape\n batch_next_neighbor_ids = np.array(\n compact_adj.compact_adj[nodes.reshape(-1), batch_next_neighbor_ids.reshape(-1)]\n ).reshape(shape)\n\n return batch_next_neighbor_ids\n\n\ndef np_traverse(\n compact_adj, seed_nodes, fanouts=(1,), sample_fn=np_uniform_sample_next\n):\n if not isinstance(seed_nodes, np.ndarray):\n raise ValueError(\"Seed must a numpy array\")\n\n if (\n len(seed_nodes.shape) > 2\n or len(seed_nodes.shape) < 1\n or not str(seed_nodes.dtype).startswith(\"int\")\n ):\n raise ValueError(\"seed_nodes must be 1D or 2D int array\")\n\n if len(seed_nodes.shape) == 1:\n seed_nodes = np.expand_dims(seed_nodes, 1)\n\n # Make walk-tree\n forest_array = [seed_nodes]\n for f in fanouts:\n next_level = sample_fn(compact_adj, forest_array, f)\n assert next_level.shape[1] == forest_array[-1].shape[1] * f\n\n forest_array.append(next_level)\n\n return forest_array\n\n\nclass WalkForestCollator(object):\n def __init__(self, normalize_features=False):\n self.normalize_features = normalize_features\n\n def __call__(self, molecule):\n comp_adj, feature_matrix, label, fanouts = molecule[0]\n node_ids = np.array(list(range(feature_matrix.shape[0])), dtype=np.int32)\n forest = np_traverse(comp_adj, node_ids, fanouts)\n torch_forest = [torch.from_numpy(forest[0]).flatten()]\n label = np.where(np.isnan(label), 0.0, label)\n\n for i in range(len(forest) - 1):\n torch_forest.append(torch.from_numpy(forest[i + 1]).reshape(-1, fanouts[i]))\n\n if self.normalize_features:\n mx = sp.csr_matrix(feature_matrix)\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.0\n r_mat_inv = sp.diags(r_inv)\n normalized_feature_matrix = r_mat_inv.dot(mx)\n normalized_feature_matrix = np.array(normalized_feature_matrix.todense())\n else:\n scaler = StandardScaler()\n scaler.fit(feature_matrix)\n normalized_feature_matrix = scaler.transform(feature_matrix)\n\n return (\n torch_forest,\n torch.as_tensor(normalized_feature_matrix, dtype=torch.float32),\n torch.as_tensor(label, dtype=torch.float32),\n )\n\n\nclass DefaultCollator(object):\n def __init__(self, normalize_features=True, normalize_adj=True):\n self.normalize_features = normalize_features\n self.normalize_adj = normalize_adj\n\n def __call__(self, molecule):\n adj_matrix, feature_matrix, label, _ = molecule[0]\n label = np.where(np.isnan(label), 0.0, label)\n\n if self.normalize_features:\n mx = sp.csr_matrix(feature_matrix)\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.0\n r_mat_inv = sp.diags(r_inv)\n normalized_feature_matrix = r_mat_inv.dot(mx)\n normalized_feature_matrix = np.array(normalized_feature_matrix.todense())\n else:\n scaler = StandardScaler()\n scaler.fit(feature_matrix)\n normalized_feature_matrix = scaler.transform(feature_matrix)\n\n if self.normalize_adj:\n rowsum = np.array(adj_matrix.sum(1))\n r_inv_sqrt = np.power(rowsum, -0.5).flatten()\n r_inv_sqrt[np.isinf(r_inv_sqrt)] = 0.0\n r_mat_inv_sqrt = sp.diags(r_inv_sqrt)\n normalized_adj_matrix = (\n adj_matrix.dot(r_mat_inv_sqrt).transpose().dot(r_mat_inv_sqrt)\n )\n else:\n normalized_adj_matrix = adj_matrix\n\n return (\n torch.as_tensor(\n np.array(normalized_adj_matrix.todense()), dtype=torch.float32\n ),\n torch.as_tensor(normalized_feature_matrix, dtype=torch.float32),\n torch.as_tensor(label, dtype=torch.float32),\n )"
] | [
[
"torch.utils.data.DataLoader",
"numpy.ones",
"numpy.random.shuffle",
"torch.utils.data.distributed.DistributedSampler",
"numpy.random.choice",
"numpy.clip",
"torch.from_numpy",
"torch.zeros",
"numpy.random.randint"
],
[
"numpy.random.uniform",
"torch.as_tensor",
"numpy.isinf",
"scipy.sparse.csr_matrix",
"numpy.repeat",
"scipy.sparse.diags",
"torch.nn.functional.one_hot",
"numpy.expand_dims",
"torch.from_numpy",
"numpy.power",
"numpy.isnan",
"numpy.array",
"torch.cat",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.StandardScaler"
]
] |
openmcworkshop/paramak | [
"c41dc4c2e68183869556544ee7a72deb1d16a8dc"
] | [
"paramak/reactor.py"
] | [
"\nimport json\nfrom collections import Iterable\nfrom pathlib import Path\n\nimport cadquery as cq\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nfrom cadquery import exporters\n\nimport paramak\nfrom paramak.neutronics_utils import (add_stl_to_moab_core,\n define_moab_core_and_tags)\nfrom paramak.utils import get_hash\n\n\nclass Reactor:\n \"\"\"The Reactor object allows shapes and components to be added and then\n collective operations to be performed on them. Combining all the shapes is\n required for creating images of the whole reactor and creating a Graveyard\n (bounding box) that is needed for neutronics simulations.\n\n Args:\n shapes_and_components (list): list of paramak.Shape\n \"\"\"\n\n def __init__(self, shapes_and_components):\n\n self.material_tags = []\n self.stp_filenames = []\n self.stl_filenames = []\n self.tet_meshes = []\n self.graveyard = None\n self.solid = None\n\n self.shapes_and_components = shapes_and_components\n self.reactor_hash_value = None\n\n self.graveyard_offset = None # set by the make_graveyard method\n\n @property\n def stp_filenames(self):\n values = []\n for shape_or_component in self.shapes_and_components:\n values.append(shape_or_component.stp_filename)\n return values\n\n @stp_filenames.setter\n def stp_filenames(self, value):\n self._stp_filenames = value\n\n @property\n def stl_filenames(self):\n values = []\n for shape_or_component in self.shapes_and_components:\n values.append(shape_or_component.stl_filename)\n return values\n\n @stl_filenames.setter\n def stl_filenames(self, value):\n self._stl_filenames = value\n\n @property\n def largest_dimension(self):\n \"\"\"Calculates a bounding box for the Reactor and returns the largest\n absolute value of the largest dimension of the bounding box\"\"\"\n largest_dimension = 0\n for component in self.shapes_and_components:\n largest_dimension = max(\n largest_dimension,\n component.largest_dimension)\n self._largest_dimension = largest_dimension\n return largest_dimension\n\n @largest_dimension.setter\n def largest_dimension(self, value):\n self._largest_dimension = value\n\n @property\n def material_tags(self):\n \"\"\"Returns a set of all the materials_tags used in the Reactor\n (excluding the plasma)\"\"\"\n values = []\n for shape_or_component in self.shapes_and_components:\n if isinstance(\n shape_or_component,\n (paramak.Plasma,\n paramak.PlasmaFromPoints,\n paramak.PlasmaBoundaries)) is False:\n values.append(shape_or_component.material_tag)\n return values\n\n @material_tags.setter\n def material_tags(self, value):\n self._material_tags = value\n\n @property\n def tet_meshes(self):\n values = []\n for shape_or_componet in self.shapes_and_components:\n values.append(shape_or_componet.tet_mesh)\n return values\n\n @tet_meshes.setter\n def tet_meshes(self, value):\n self._tet_meshes = value\n\n @property\n def shapes_and_components(self):\n \"\"\"Adds a list of parametric shape(s) and or parametric component(s)\n to the Reactor object. This allows collective operations to be\n performed on all the shapes in the reactor. When adding a shape or\n component the stp_filename of the shape or component should be unique\"\"\"\n if hasattr(self, \"create_solids\"):\n ignored_keys = [\"reactor_hash_value\"]\n if get_hash(self, ignored_keys) != self.reactor_hash_value:\n self.create_solids()\n self.reactor_hash_value = get_hash(self, ignored_keys)\n return self._shapes_and_components\n\n @shapes_and_components.setter\n def shapes_and_components(self, value):\n if not isinstance(value, Iterable):\n raise ValueError(\"shapes_and_components must be a list\")\n self._shapes_and_components = value\n\n @property\n def graveyard_offset(self):\n return self._graveyard_offset\n\n @graveyard_offset.setter\n def graveyard_offset(self, value):\n if value is None:\n self._graveyard_offset = None\n elif not isinstance(value, (float, int)):\n raise ValueError(\"graveyard_offset must be a number\")\n elif value < 0:\n raise ValueError(\"graveyard_offset must be positive\")\n self._graveyard_offset = value\n\n @property\n def solid(self):\n \"\"\"This combines all the parametric shapes and compents in the reactor\n object and rotates the viewing angle so that .solid operations in\n jupyter notebook.\n \"\"\"\n\n list_of_cq_vals = []\n\n for shape_or_compound in self.shapes_and_components:\n if isinstance(\n shape_or_compound.solid,\n cq.occ_impl.shapes.Compound):\n for solid in shape_or_compound.solid.Solids():\n list_of_cq_vals.append(solid)\n else:\n list_of_cq_vals.append(shape_or_compound.solid.val())\n\n compound = cq.Compound.makeCompound(list_of_cq_vals)\n\n compound = compound.rotate(\n startVector=(0, 1, 0), endVector=(0, 0, 1), angleDegrees=180\n )\n return compound\n\n @solid.setter\n def solid(self, value):\n self._solid = value\n\n def neutronics_description(self, include_plasma=False,\n include_graveyard=True\n ):\n \"\"\"A description of the reactor containing material tags, stp filenames,\n and tet mesh instructions. This is used for neutronics simulations which\n require linkage between volumes, materials and identification of which\n volumes to tet mesh. The plasma geometry is not included by default as\n it is typically not included in neutronics simulations. The reason for\n this is that the low number density results in minimal interaction with\n neutrons. However, it can be added if the include_plasma argument is set\n to True.\n\n Returns:\n dictionary: a dictionary of materials and filenames for the reactor\n \"\"\"\n\n neutronics_description = []\n\n for entry in self.shapes_and_components:\n\n if include_plasma is False and isinstance(\n entry,\n (paramak.Plasma,\n paramak.PlasmaFromPoints,\n paramak.PlasmaBoundaries)) is True:\n continue\n\n if entry.stp_filename is None:\n raise ValueError(\n \"Set Shape.stp_filename for all the \\\n Reactor entries before using this method\"\n )\n\n if entry.material_tag is None:\n raise ValueError(\n \"set Shape.material_tag for all the \\\n Reactor entries before using this method\"\n )\n\n neutronics_description.append(entry.neutronics_description())\n\n # This add the neutronics description for the graveyard which is unique\n # as it is automatically calculated instead of being added by the user.\n # Also the graveyard must have 'Graveyard' as the material name\n if include_graveyard is True:\n self.make_graveyard()\n neutronics_description.append(\n self.graveyard.neutronics_description())\n\n return neutronics_description\n\n def export_neutronics_description(\n self,\n filename=\"manifest.json\",\n include_plasma=False,\n include_graveyard=True):\n \"\"\"\n Saves Reactor.neutronics_description to a json file. The resulting json\n file contains a list of dictionaries. Each dictionary entry comprises\n of a material and a filename and optionally a tet_mesh instruction. The\n json file can then be used with the neutronics workflows to create a\n neutronics model. Creating of the neutronics model requires linkage\n between volumes, materials and identification of which volumes to\n tet_mesh. If the filename does not end with .json then .json will be\n added. The plasma geometry is not included by default as it is\n typically not included in neutronics simulations. The reason for this\n is that the low number density results in minimal interactions with\n neutrons. However, the plasma can be added if the include_plasma\n argument is set to True.\n\n Args:\n filename (str, optional): the filename used to save the neutronics\n description\n include_plasma (Boolean, optional): should the plasma be included.\n Defaults to False as the plasma volume and material has very\n little impact on the neutronics results due to the low density.\n Including the plasma does however slow down the simulation.\n include_graveyard (Boolean, optional): should the graveyard be\n included. Defaults to True as this is needed for DAGMC models.\n \"\"\"\n\n path_filename = Path(filename)\n\n if path_filename.suffix != \".json\":\n path_filename = path_filename.with_suffix(\".json\")\n\n path_filename.parents[0].mkdir(parents=True, exist_ok=True)\n\n with open(path_filename, \"w\") as outfile:\n json.dump(\n self.neutronics_description(\n include_plasma=include_plasma,\n include_graveyard=include_graveyard,\n ),\n outfile,\n indent=4,\n )\n\n print(\"saved geometry description to \", path_filename)\n\n return str(path_filename)\n\n def export_stp(self, output_folder=\"\", graveyard_offset=100,\n mode='solid'):\n \"\"\"Writes stp files (CAD geometry) for each Shape object in the reactor\n and the graveyard.\n\n Args:\n output_folder (str): the folder for saving the stp files to\n graveyard_offset (float, optional): the offset between the largest\n edge of the geometry and inner bounding shell created. Defaults\n to 100.\n mode (str, optional): the object to export can be either\n 'solid' which exports 3D solid shapes or the 'wire' which\n exports the wire edges of the shape. Defaults to 'solid'.\n Returns:\n list: a list of stp filenames created\n \"\"\"\n\n if len(self.stp_filenames) != len(set(self.stp_filenames)):\n raise ValueError(\n \"Set Reactor already contains a shape or component \\\n with this stp_filename\",\n self.stp_filenames,\n )\n\n filenames = []\n for entry in self.shapes_and_components:\n if entry.stp_filename is None:\n raise ValueError(\n \"set .stp_filename property for \\\n Shapes before using the export_stp method\"\n )\n filenames.append(\n str(Path(output_folder) / Path(entry.stp_filename)))\n entry.export_stp(\n filename=Path(output_folder) / Path(entry.stp_filename),\n mode=mode\n )\n\n # creates a graveyard (bounding shell volume) which is needed for\n # nuetronics simulations\n self.make_graveyard(graveyard_offset=graveyard_offset)\n filenames.append(\n str(Path(output_folder) / Path(self.graveyard.stp_filename)))\n self.graveyard.export_stp(\n Path(output_folder) / Path(self.graveyard.stp_filename)\n )\n\n return filenames\n\n def export_stl(self, output_folder=\"\", tolerance=0.001):\n \"\"\"Writes stl files (CAD geometry) for each Shape object in the reactor\n\n :param output_folder: the folder for saving the stp files to\n :type output_folder: str\n :param tolerance: the precision of the faceting\n :type tolerance: float\n\n :return: a list of stl filenames created\n :rtype: list\n \"\"\"\n\n if len(self.stl_filenames) != len(set(self.stl_filenames)):\n raise ValueError(\n \"Set Reactor already contains a shape or component \\\n with this stl_filename\",\n self.stl_filenames,\n )\n\n filenames = []\n for entry in self.shapes_and_components:\n print(\"entry.stl_filename\", entry.stl_filename)\n if entry.stl_filename is None:\n raise ValueError(\n \"set .stl_filename property for \\\n Shapes before using the export_stl method\"\n )\n\n filenames.append(\n str(Path(output_folder) / Path(entry.stl_filename)))\n entry.export_stl(\n Path(output_folder) /\n Path(\n entry.stl_filename),\n tolerance)\n\n # creates a graveyard (bounding shell volume) which is needed for\n # nuetronics simulations\n self.make_graveyard()\n filenames.append(\n str(Path(output_folder) / Path(self.graveyard.stl_filename)))\n self.graveyard.export_stl(\n Path(output_folder) / Path(self.graveyard.stl_filename)\n )\n\n print(\"exported stl files \", filenames)\n\n return filenames\n\n def export_h5m(\n self,\n filename='dagmc.h5m',\n skip_graveyard=False,\n tolerance=0.001,\n graveyard_offset=100):\n \"\"\"Converts stl files into DAGMC compatible h5m file using PyMOAB. The\n DAGMC file produced has not been imprinted and merged unlike the other\n supported method which uses Trelis to produce an imprinted and merged\n DAGMC geometry. If the provided filename doesn't end with .h5m it will\n be added\n\n Args:\n filename (str, optional): filename of h5m outputfile\n Defaults to \"dagmc.h5m\".\n skip_graveyard (boolean, optional): filename of h5m outputfile\n Defaults to False.\n tolerance (float, optional): the precision of the faceting\n Defaults to 0.001.\n graveyard_offset (float, optional): the offset between the largest\n edge of the geometry and inner bounding shell created. Defaults\n to 100.\n Returns:\n filename: output h5m filename\n \"\"\"\n\n path_filename = Path(filename)\n\n if path_filename.suffix != \".h5m\":\n path_filename = path_filename.with_suffix(\".h5m\")\n\n path_filename.parents[0].mkdir(parents=True, exist_ok=True)\n\n moab_core, moab_tags = define_moab_core_and_tags()\n\n surface_id = 1\n volume_id = 1\n\n for item in self.shapes_and_components:\n\n item.export_stl(item.stl_filename, tolerance=tolerance)\n moab_core = add_stl_to_moab_core(\n moab_core,\n surface_id,\n volume_id,\n item.material_tag,\n moab_tags,\n item.stl_filename)\n volume_id += 1\n surface_id += 1\n\n if skip_graveyard is False:\n self.make_graveyard(graveyard_offset=graveyard_offset)\n self.graveyard.export_stl(self.graveyard.stl_filename)\n volume_id = 2\n surface_id = 2\n moab_core = add_stl_to_moab_core(\n moab_core,\n surface_id,\n volume_id,\n self.graveyard.material_tag,\n moab_tags,\n self.graveyard.stl_filename\n )\n\n all_sets = moab_core.get_entities_by_handle(0)\n\n file_set = moab_core.create_meshset()\n\n moab_core.add_entities(file_set, all_sets)\n\n moab_core.write_file(str(path_filename))\n\n return filename\n\n def export_physical_groups(self, output_folder=\"\"):\n \"\"\"Exports several JSON files containing a look up table which is\n useful for identifying faces and volumes. The output file names are\n generated from .stp_filename properties.\n\n Args:\n output_folder (str, optional): directory of outputfiles.\n Defaults to \"\".\n\n Raises:\n ValueError: if one .stp_filename property is set to None\n\n Returns:\n list: list of output file names\n \"\"\"\n filenames = []\n for entry in self.shapes_and_components:\n if entry.stp_filename is None:\n raise ValueError(\n \"set .stp_filename property for \\\n Shapes before using the export_stp method\"\n )\n filenames.append(\n str(Path(output_folder) / Path(entry.stp_filename)))\n entry.export_physical_groups(\n Path(output_folder) / Path(entry.stp_filename))\n return filenames\n\n def export_svg(self, filename):\n \"\"\"Exports an svg file for the Reactor.solid. If the filename provided\n doesn't end with .svg it will be added.\n\n Args:\n filename (str): the filename of the svg file to be exported\n \"\"\"\n\n path_filename = Path(filename)\n\n if path_filename.suffix != \".svg\":\n path_filename = path_filename.with_suffix(\".svg\")\n\n path_filename.parents[0].mkdir(parents=True, exist_ok=True)\n\n with open(path_filename, \"w\") as out_file:\n exporters.exportShape(self.solid, \"SVG\", out_file)\n print(\"Saved file as \", path_filename)\n\n def export_graveyard(\n self,\n graveyard_offset=100,\n filename=\"Graveyard.stp\"):\n \"\"\"Writes an stp file (CAD geometry) for the reactor graveyard. This\n is needed for DAGMC simulations. This method also calls\n Reactor.make_graveyard with the offset.\n\n Args:\n filename (str): the filename for saving the stp file\n graveyard_offset (float): the offset between the largest edge of\n the geometry and inner bounding shell created. Defaults to\n Reactor.graveyard_offset\n\n Returns:\n str: the stp filename created\n \"\"\"\n\n self.make_graveyard(graveyard_offset=graveyard_offset)\n self.graveyard.export_stp(Path(filename))\n\n return filename\n\n def make_graveyard(self, graveyard_offset=100):\n \"\"\"Creates a graveyard volume (bounding box) that encapsulates all\n volumes. This is required by DAGMC when performing neutronics\n simulations.\n\n Args:\n graveyard_offset (float): the offset between the largest edge of\n the geometry and inner bounding shell created. Defaults to\n Reactor.graveyard_offset\n\n Returns:\n CadQuery solid: a shell volume that bounds the geometry, referred\n to as a graveyard in DAGMC\n \"\"\"\n\n self.graveyard_offset = graveyard_offset\n\n for component in self.shapes_and_components:\n if component.solid is None:\n component.create_solid()\n\n graveyard_shape = paramak.HollowCube(\n length=self.largest_dimension * 2 + graveyard_offset * 2,\n name=\"Graveyard\",\n material_tag=\"Graveyard\",\n stp_filename=\"Graveyard.stp\",\n stl_filename=\"Graveyard.stl\",\n )\n\n self.graveyard = graveyard_shape\n\n return graveyard_shape\n\n def export_2d_image(\n self,\n filename=\"2d_slice.png\",\n xmin=0.0,\n xmax=900.0,\n ymin=-600.0,\n ymax=600.0):\n \"\"\"Creates a 2D slice image (png) of the reactor.\n\n Args:\n filename (str): output filename of the image created\n\n Returns:\n str: png filename created\n \"\"\"\n\n path_filename = Path(filename)\n\n if path_filename.suffix != \".png\":\n path_filename = path_filename.with_suffix(\".png\")\n\n path_filename.parents[0].mkdir(parents=True, exist_ok=True)\n\n fig, ax = plt.subplots()\n\n # creates indvidual patches for each Shape which are combined together\n for entry in self.shapes_and_components:\n patch = entry._create_patch()\n ax.add_collection(patch)\n\n ax.axis(\"equal\")\n ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))\n ax.set_aspect(\"equal\", \"box\")\n\n Path(filename).parent.mkdir(parents=True, exist_ok=True)\n plt.savefig(filename, dpi=100)\n plt.close()\n\n print(\"\\n saved 2d image to \", str(path_filename))\n\n return str(path_filename)\n\n def export_html(self, filename=\"reactor.html\"):\n \"\"\"Creates a html graph representation of the points for the Shape\n objects that make up the reactor. Note, If filename provided doesn't end\n with .html then it will be appended.\n\n Args:\n filename (str): the filename to save the html graph\n\n Returns:\n plotly figure: figure object\n \"\"\"\n\n path_filename = Path(filename)\n\n if path_filename.suffix != \".html\":\n path_filename = path_filename.with_suffix(\".html\")\n\n path_filename.parents[0].mkdir(parents=True, exist_ok=True)\n\n fig = go.Figure()\n fig.update_layout(\n {\"title\": \"coordinates of components\", \"hovermode\": \"closest\"}\n )\n\n # accesses the Shape traces for each Shape and adds them to the figure\n for entry in self.shapes_and_components:\n fig.add_trace(entry._trace())\n\n fig.write_html(str(path_filename))\n print(\"Exported html graph to \", str(path_filename))\n\n return fig\n"
] | [
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots"
]
] |
jaycosaur/spynet | [
"535841bcea761463d27f7f3eb745ffe186d9f763"
] | [
"streaming_helpers.py"
] | [
"import queue\nimport time\nimport numpy as np\n\n\nclass CameraInformation:\n def __init__(self, cam_id: str):\n self._frame_queue: queue.Queue = queue.Queue(maxsize=1)\n self._frame_shape = None\n self._last_frame_time = None\n self.is_online = True\n self.node_id = cam_id\n\n def write_frame(self, frame):\n try:\n self._frame_queue.get_nowait()\n except queue.Empty:\n pass\n self._frame_shape = frame.shape\n self._last_frame_time = time.time()\n self._frame_queue.put_nowait(frame)\n\n def read_frame(self,):\n try:\n frame = self._frame_queue.get(timeout=2)\n if not self.is_online:\n self.is_online = True\n return frame\n except queue.Empty:\n if self.is_online:\n self.is_online = False\n return np.zeros(self._frame_shape)\n"
] | [
[
"numpy.zeros"
]
] |
liiliiliil/ride-hailing-platform-with-simulator | [
"c9eae7f718c9e10c7ba4955e5093d4fb21d16d25"
] | [
"data_processing/draw_value_map.py"
] | [
"import os\nimport time\nimport pickle\n\nimport math\nimport numpy as np\nimport linecache\nimport matplotlib.pyplot as plt\n# from matplotlib.pyplot import MultipleLocator\nimport grid\n\ndata_path = 'E:/dataset/didi/processed'\nsave_path = 'E:/dataset/didi/processed/order_20161101_sampled_value_map_fig'\ndata_file_name = 'processed_data' # '.pkl' will be added for binary file\nvalue_map_file_name = 'value_map' # '.pkl' will be added for binary file\n\nn_time_unit = 144\nsize_hexagon_to_edge = 0.0048\nhexagon_size_factor_for_plot = 1\nrange_map_longitude = [103.96, 104.18]\nrange_map_latitude = [30.59, 30.77]\n\nsize_hexagon = size_hexagon_to_edge * 2 / math.sqrt(3) # length to the point\n\nif not os.path.exists(save_path):\n os.mkdir(save_path)\n\nwith open(os.path.join(data_path, data_file_name+'.pkl'), 'rb') as f:\n data = pickle.load(f)\nwith open(os.path.join(data_path, value_map_file_name+'.pkl'), 'rb') as f:\n value_map = pickle.load(f)\n\n\n\n# make hexagon\ngrid = grid.Hexagon(size_to_edge=size_hexagon_to_edge*hexagon_size_factor_for_plot)\ngrid_interval_lo = size_hexagon * 1.5\ngrid_interval_la = size_hexagon_to_edge * 2\n\ngrid_centers = []\nfor la in np.arange(range_map_latitude[1]-size_hexagon, range_map_latitude[0]-0.00001, -grid_interval_la):\n row = []\n count = 0\n for lo in np.arange(range_map_longitude[0], range_map_longitude[1]+0.00001, grid_interval_lo):\n if count % 2 == 0:\n row.append([lo, la])\n else:\n row.append([lo, la+size_hexagon_to_edge])\n count += 1\n grid_centers.append(row)\n\ngrid_centers_mat = np.array(grid_centers)\nshape_grid_centers_mat = grid_centers_mat.shape\nn_grids = shape_grid_centers_mat[0]*shape_grid_centers_mat[1]\n\ngrid_index_mat = np.arange(n_grids).reshape(shape_grid_centers_mat[:2])\n\nprint('shape of grids is', shape_grid_centers_mat)\nprint('number of grids is', n_grids)\n\ngrid_centers_flat_T = grid_centers_mat.reshape(n_grids, 2).T\n\n\nmax_value = np.max(value_map)\nmin_value = np.min(value_map)\nprint('maximum value in value_map is', max_value)\nprint('minimum value in value_map is', min_value)\n# value_map = (value_map - min_value) / max_value\n# max_value = np.max(value_map)\n# min_value = np.min(value_map)\n# print('maximum value in value_map after normalization is', max_value)\n# print('minimum value in value_map after normalization is', min_value)\n \n\n\nfor t in range(n_time_unit):\n fig = plt.figure()\n plt.title('value map of time unit %d' % t)\n plt.scatter(grid_centers_flat_T[0], grid_centers_flat_T[1], c=value_map[t], marker='H', s=100, alpha=0.5)\n plt.colorbar()\n fig.savefig(os.path.join(save_path, '%d.jpg'%t))\n \n\n"
] | [
[
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.title",
"numpy.max",
"numpy.min",
"numpy.array",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.scatter"
]
] |
Amir-Mehrpanah/hgraph2graph | [
"6d37153afe09f7684381ce56e8366675e22833e9"
] | [
"hgraph/decoder.py"
] | [
"import torch\nimport torch.nn as nn\nimport rdkit.Chem as Chem\nimport torch.nn.functional as F\nfrom hgraph.nnutils import *\nfrom hgraph.encoder import IncHierMPNEncoder\nfrom hgraph.mol_graph import MolGraph\nfrom hgraph.inc_graph import IncTree, IncGraph\n\nclass HTuple():\n def __init__(self, node=None, mess=None, vmask=None, emask=None):\n self.node, self.mess = node, mess\n self.vmask, self.emask = vmask, emask\n\nclass HierMPNDecoder(nn.Module):\n\n def __init__(self, vocab, avocab, rnn_type, embed_size, hidden_size, latent_size, depthT, depthG, dropout, attention=False):\n super(HierMPNDecoder, self).__init__()\n self.vocab = vocab\n self.avocab = avocab\n self.hidden_size = hidden_size\n self.embed_size = embed_size\n self.latent_size = latent_size\n self.use_attention = attention\n self.itensor = torch.LongTensor([]).cuda()\n\n self.hmpn = IncHierMPNEncoder(vocab, avocab, rnn_type, embed_size, hidden_size, depthT, depthG, dropout)\n self.rnn_cell = self.hmpn.tree_encoder.rnn\n self.E_assm = self.hmpn.E_i \n self.E_order = torch.eye(MolGraph.MAX_POS).cuda()\n\n self.topoNN = nn.Sequential(\n nn.Linear(hidden_size + latent_size, hidden_size),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_size, 1)\n )\n self.clsNN = nn.Sequential(\n nn.Linear(hidden_size + latent_size, hidden_size),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_size, vocab.size()[0])\n )\n self.iclsNN = nn.Sequential(\n nn.Linear(hidden_size + latent_size, hidden_size),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_size, vocab.size()[1])\n )\n self.matchNN = nn.Sequential(\n nn.Linear(hidden_size + embed_size + MolGraph.MAX_POS, hidden_size),\n nn.ReLU(),\n )\n self.W_assm = nn.Linear(hidden_size, latent_size)\n\n if latent_size != hidden_size:\n self.W_root = nn.Linear(latent_size, hidden_size)\n\n if self.use_attention:\n self.A_topo = nn.Linear(hidden_size, latent_size)\n self.A_cls = nn.Linear(hidden_size, latent_size)\n self.A_assm = nn.Linear(hidden_size, latent_size)\n\n self.topo_loss = nn.BCEWithLogitsLoss(size_average=False)\n self.cls_loss = nn.CrossEntropyLoss(size_average=False)\n self.icls_loss = nn.CrossEntropyLoss(size_average=False)\n self.assm_loss = nn.CrossEntropyLoss(size_average=False)\n \n def apply_tree_mask(self, tensors, cur, prev):\n fnode, fmess, agraph, bgraph, cgraph, scope = tensors\n agraph = agraph * index_select_ND(cur.emask, 0, agraph)\n bgraph = bgraph * index_select_ND(cur.emask, 0, bgraph)\n cgraph = cgraph * index_select_ND(prev.vmask, 0, cgraph)\n return fnode, fmess, agraph, bgraph, cgraph, scope\n\n def apply_graph_mask(self, tensors, hgraph):\n fnode, fmess, agraph, bgraph, scope = tensors\n agraph = agraph * index_select_ND(hgraph.emask, 0, agraph)\n bgraph = bgraph * index_select_ND(hgraph.emask, 0, bgraph)\n return fnode, fmess, agraph, bgraph, scope\n\n def update_graph_mask(self, graph_batch, new_atoms, hgraph):\n new_atom_index = hgraph.vmask.new_tensor(new_atoms)\n hgraph.vmask.scatter_(0, new_atom_index, 1)\n\n new_atom_set = set(new_atoms)\n new_bonds = [] #new bonds are the subgraph induced by new_atoms\n for zid in new_atoms:\n for nid in graph_batch[zid]:\n if nid not in new_atom_set: continue\n new_bonds.append( graph_batch[zid][nid]['mess_idx'] )\n\n new_bond_index = hgraph.emask.new_tensor(new_bonds)\n if len(new_bonds) > 0:\n hgraph.emask.scatter_(0, new_bond_index, 1)\n return new_atom_index, new_bond_index\n\n def init_decoder_state(self, tree_batch, tree_tensors, src_root_vecs):\n batch_size = len(src_root_vecs)\n num_mess = len(tree_tensors[1])\n agraph = tree_tensors[2].clone()\n bgraph = tree_tensors[3].clone()\n\n for i,tup in enumerate(tree_tensors[-1]):\n root = tup[0]\n assert agraph[root,-1].item() == 0\n agraph[root,-1] = num_mess + i\n for v in tree_batch.successors(root):\n mess_idx = tree_batch[root][v]['mess_idx'] \n assert bgraph[mess_idx,-1].item() == 0\n bgraph[mess_idx,-1] = num_mess + i\n\n new_tree_tensors = tree_tensors[:2] + [agraph, bgraph] + tree_tensors[4:]\n htree = HTuple()\n htree.mess = self.rnn_cell.get_init_state(tree_tensors[1], src_root_vecs)\n htree.emask = torch.cat( [bgraph.new_zeros(num_mess), bgraph.new_ones(batch_size)], dim=0 )\n\n return htree, new_tree_tensors\n\n def attention(self, src_vecs, batch_idx, queries, W_att):\n size = batch_idx.size()\n if batch_idx.dim() > 1:\n batch_idx = batch_idx.view(-1)\n queries = queries.view(-1, queries.size(-1))\n\n src_vecs = src_vecs.index_select(0, batch_idx)\n att_score = torch.bmm( src_vecs, W_att(queries).unsqueeze(-1) )\n att_vecs = F.softmax(att_score, dim=1) * src_vecs\n att_vecs = att_vecs.sum(dim=1)\n return att_vecs if len(size) == 1 else att_vecs.view(size[0], size[1], -1)\n\n def get_topo_score(self, src_tree_vecs, batch_idx, topo_vecs):\n if self.use_attention:\n topo_cxt = self.attention(src_tree_vecs, batch_idx, topo_vecs, self.A_topo)\n else:\n topo_cxt = src_tree_vecs.index_select(index=batch_idx, dim=0)\n return self.topoNN( torch.cat([topo_vecs, topo_cxt], dim=-1) ).squeeze(-1)\n\n def get_cls_score(self, src_tree_vecs, batch_idx, cls_vecs, cls_labs):\n if self.use_attention:\n cls_cxt = self.attention(src_tree_vecs, batch_idx, cls_vecs, self.A_cls)\n else:\n cls_cxt = src_tree_vecs.index_select(index=batch_idx, dim=0)\n\n cls_vecs = torch.cat([cls_vecs, cls_cxt], dim=-1)\n cls_scores = self.clsNN(cls_vecs)\n\n if cls_labs is None: #inference mode\n icls_scores = self.iclsNN(cls_vecs) #no masking\n else:\n vocab_masks = self.vocab.get_mask(cls_labs)\n icls_scores = self.iclsNN(cls_vecs) + vocab_masks #apply mask by log(x + mask): mask=0 or -INF\n return cls_scores, icls_scores\n\n def get_assm_score(self, src_graph_vecs, batch_idx, assm_vecs):\n if self.use_attention:\n assm_cxt = self.attention(src_graph_vecs, batch_idx, assm_vecs, self.A_assm)\n else:\n assm_cxt = index_select_ND(src_graph_vecs, 0, batch_idx)\n return (self.W_assm(assm_vecs) * assm_cxt).sum(dim=-1)\n\n def forward(self, src_mol_vecs, graphs, tensors, orders):\n batch_size = len(orders)\n tree_batch, graph_batch = graphs\n tree_tensors, graph_tensors = tensors\n inter_tensors = tree_tensors\n\n src_root_vecs, src_tree_vecs, src_graph_vecs = src_mol_vecs\n init_vecs = src_root_vecs if self.latent_size == self.hidden_size else self.W_root(src_root_vecs)\n\n htree, tree_tensors = self.init_decoder_state(tree_batch, tree_tensors, init_vecs)\n hinter = HTuple(\n mess = self.rnn_cell.get_init_state(inter_tensors[1]),\n emask = self.itensor.new_zeros(inter_tensors[1].size(0))\n )\n hgraph = HTuple(\n mess = self.rnn_cell.get_init_state(graph_tensors[1]),\n vmask = self.itensor.new_zeros(graph_tensors[0].size(0)),\n emask = self.itensor.new_zeros(graph_tensors[1].size(0))\n )\n \n all_topo_preds, all_cls_preds, all_assm_preds = [], [], []\n new_atoms = []\n tree_scope = tree_tensors[-1]\n for i in range(batch_size):\n root = tree_batch.nodes[ tree_scope[i][0] ]\n clab, ilab = self.vocab[ root['label'] ]\n all_cls_preds.append( (init_vecs[i], i, clab, ilab) ) #cluster prediction\n new_atoms.extend(root['cluster'])\n\n subgraph = self.update_graph_mask(graph_batch, new_atoms, hgraph)\n graph_tensors = self.hmpn.embed_graph(graph_tensors) + (graph_tensors[-1],) #preprocess graph tensors\n\n maxt = max([len(x) for x in orders])\n max_cls_size = max( [len(attr) * 2 for node,attr in tree_batch.nodes(data='cluster')] )\n\n for t in range(maxt):\n batch_list = [i for i in range(batch_size) if t < len(orders[i])]\n assert htree.emask[0].item() == 0 and hinter.emask[0].item() == 0 and hgraph.vmask[0].item() == 0 and hgraph.emask[0].item() == 0\n\n subtree = [], []\n for i in batch_list:\n xid, yid, tlab = orders[i][t]\n subtree[0].append(xid)\n if yid is not None:\n mess_idx = tree_batch[xid][yid]['mess_idx']\n subtree[1].append(mess_idx)\n\n subtree = htree.emask.new_tensor(subtree[0]), htree.emask.new_tensor(subtree[1]) \n htree.emask.scatter_(0, subtree[1], 1)\n hinter.emask.scatter_(0, subtree[1], 1)\n\n cur_tree_tensors = self.apply_tree_mask(tree_tensors, htree, hgraph)\n cur_inter_tensors = self.apply_tree_mask(inter_tensors, hinter, hgraph)\n cur_graph_tensors = self.apply_graph_mask(graph_tensors, hgraph)\n htree, hinter, hgraph = self.hmpn(cur_tree_tensors, cur_inter_tensors, cur_graph_tensors, htree, hinter, hgraph, subtree, subgraph)\n\n new_atoms = []\n for i in batch_list:\n xid, yid, tlab = orders[i][t]\n all_topo_preds.append( (htree.node[xid], i, tlab) ) #topology prediction\n if yid is not None:\n mess_idx = tree_batch[xid][yid]['mess_idx']\n new_atoms.extend( tree_batch.nodes[yid]['cluster'] ) #NOTE: regardless of tlab = 0 or 1\n\n if tlab == 0: continue\n\n cls = tree_batch.nodes[yid]['smiles']\n clab, ilab = self.vocab[ tree_batch.nodes[yid]['label'] ]\n mess_idx = tree_batch[xid][yid]['mess_idx']\n hmess = self.rnn_cell.get_hidden_state(htree.mess)\n all_cls_preds.append( (hmess[mess_idx], i, clab, ilab) ) #cluster prediction using message\n \n inter_label = tree_batch.nodes[yid]['inter_label']\n inter_label = [ (pos, self.vocab[(cls, icls)][1]) for pos,icls in inter_label ]\n inter_size = self.vocab.get_inter_size(ilab)\n\n if len(tree_batch.nodes[xid]['cluster']) > 2: #uncertainty occurs only when previous cluster is a ring\n nth_child = tree_batch[yid][xid]['label'] #must be yid -> xid (graph order labeling is different from tree)\n cands = tree_batch.nodes[yid]['assm_cands']\n icls = list(zip(*inter_label))[1]\n cand_vecs = self.enum_attach(hgraph, cands, icls, nth_child)\n\n if len(cand_vecs) < max_cls_size:\n pad_len = max_cls_size - len(cand_vecs)\n cand_vecs = F.pad(cand_vecs, (0,0,0,pad_len))\n\n batch_idx = hgraph.emask.new_tensor( [i] * max_cls_size )\n all_assm_preds.append( (cand_vecs, batch_idx, 0) ) #the label is always the first of assm_cands\n\n subgraph = self.update_graph_mask(graph_batch, new_atoms, hgraph)\n\n topo_vecs, batch_idx, topo_labels = zip_tensors(all_topo_preds)\n topo_scores = self.get_topo_score(src_tree_vecs, batch_idx, topo_vecs)\n topo_loss = self.topo_loss(topo_scores, topo_labels.float())\n topo_acc = get_accuracy_bin(topo_scores, topo_labels)\n\n cls_vecs, batch_idx, cls_labs, icls_labs = zip_tensors(all_cls_preds)\n cls_scores, icls_scores = self.get_cls_score(src_tree_vecs, batch_idx, cls_vecs, cls_labs)\n cls_loss = self.cls_loss(cls_scores, cls_labs) + self.icls_loss(icls_scores, icls_labs)\n cls_acc = get_accuracy(cls_scores, cls_labs)\n icls_acc = get_accuracy(icls_scores, icls_labs)\n\n if len(all_assm_preds) > 0:\n assm_vecs, batch_idx, assm_labels = zip_tensors(all_assm_preds)\n assm_scores = self.get_assm_score(src_graph_vecs, batch_idx, assm_vecs)\n assm_loss = self.assm_loss(assm_scores, assm_labels)\n assm_acc = get_accuracy_sym(assm_scores, assm_labels)\n else:\n assm_loss, assm_acc = 0, 1\n \n loss = (topo_loss + cls_loss + assm_loss) / batch_size\n return loss, cls_acc, icls_acc, topo_acc, assm_acc\n\n def enum_attach(self, hgraph, cands, icls, nth_child):\n cands = self.itensor.new_tensor(cands)\n icls_vecs = self.itensor.new_tensor(icls * len(cands))\n icls_vecs = self.E_assm( icls_vecs )\n\n nth_child = self.itensor.new_tensor([nth_child] * len(cands.view(-1)))\n order_vecs = self.E_order.index_select(0, nth_child)\n\n cand_vecs = hgraph.node.index_select(0, cands.view(-1))\n cand_vecs = torch.cat( [cand_vecs, icls_vecs, order_vecs], dim=-1 )\n cand_vecs = self.matchNN(cand_vecs)\n\n if len(icls) == 2:\n cand_vecs = cand_vecs.view(-1, 2, self.hidden_size).sum(dim=1)\n return cand_vecs\n\n def decode(self, src_mol_vecs, greedy=True, max_decode_step=100, beam=5):\n src_root_vecs, src_tree_vecs, src_graph_vecs = src_mol_vecs\n batch_size = len(src_root_vecs)\n\n tree_batch = IncTree(batch_size, node_fdim=2, edge_fdim=3)\n graph_batch = IncGraph(self.avocab, batch_size, node_fdim=self.hmpn.atom_size, edge_fdim=self.hmpn.atom_size + self.hmpn.bond_size)\n stack = [[] for i in range(batch_size)]\n\n init_vecs = src_root_vecs if self.latent_size == self.hidden_size else self.W_root(src_root_vecs)\n batch_idx = self.itensor.new_tensor(range(batch_size))\n cls_scores, icls_scores = self.get_cls_score(src_tree_vecs, batch_idx, init_vecs, None)\n root_cls = cls_scores.max(dim=-1)[1]\n icls_scores = icls_scores + self.vocab.get_mask(root_cls)\n root_cls, root_icls = root_cls.tolist(), icls_scores.max(dim=-1)[1].tolist()\n\n super_root = tree_batch.add_node() \n for bid in range(batch_size):\n clab, ilab = root_cls[bid], root_icls[bid]\n root_idx = tree_batch.add_node( batch_idx.new_tensor([clab, ilab]) )\n tree_batch.add_edge(super_root, root_idx) \n stack[bid].append(root_idx)\n\n root_smiles = self.vocab.get_ismiles(ilab)\n new_atoms, new_bonds, attached = graph_batch.add_mol(bid, root_smiles, [], 0)\n tree_batch.register_cgraph(root_idx, new_atoms, new_bonds, attached)\n \n #invariance: tree_tensors is equal to inter_tensors (but inter_tensor's init_vec is 0)\n tree_tensors = tree_batch.get_tensors()\n graph_tensors = graph_batch.get_tensors()\n\n htree = HTuple( mess = self.rnn_cell.get_init_state(tree_tensors[1]) )\n hinter = HTuple( mess = self.rnn_cell.get_init_state(tree_tensors[1]) )\n hgraph = HTuple( mess = self.rnn_cell.get_init_state(graph_tensors[1]) )\n h = self.rnn_cell.get_hidden_state(htree.mess)\n h[1 : batch_size + 1] = init_vecs #wiring root (only for tree, not inter)\n \n for t in range(max_decode_step):\n batch_list = [ bid for bid in range(batch_size) if len(stack[bid]) > 0 ]\n if len(batch_list) == 0: break\n\n batch_idx = batch_idx.new_tensor(batch_list)\n cur_tree_nodes = [stack[bid][-1] for bid in batch_list]\n subtree = batch_idx.new_tensor(cur_tree_nodes), batch_idx.new_tensor([])\n subgraph = batch_idx.new_tensor( tree_batch.get_cluster_nodes(cur_tree_nodes) ), batch_idx.new_tensor( tree_batch.get_cluster_edges(cur_tree_nodes) )\n\n htree, hinter, hgraph = self.hmpn(tree_tensors, tree_tensors, graph_tensors, htree, hinter, hgraph, subtree, subgraph)\n topo_scores = self.get_topo_score(src_tree_vecs, batch_idx, htree.node.index_select(0, subtree[0]))\n topo_scores = torch.sigmoid(topo_scores)\n if greedy:\n topo_preds = topo_scores.tolist()\n else:\n topo_preds = torch.bernoulli(topo_scores).tolist()\n\n new_mess = []\n expand_list = []\n for i,bid in enumerate(batch_list):\n if topo_preds[i] > 0.5 and tree_batch.can_expand(stack[bid][-1]):\n expand_list.append( (len(new_mess), bid) )\n new_node = tree_batch.add_node() #new node label is yet to be predicted\n edge_feature = batch_idx.new_tensor( [stack[bid][-1], new_node, 0] ) #parent to child is 0\n new_edge = tree_batch.add_edge(stack[bid][-1], new_node, edge_feature) \n stack[bid].append(new_node)\n new_mess.append(new_edge)\n else:\n child = stack[bid].pop()\n if len(stack[bid]) > 0:\n nth_child = tree_batch.graph.in_degree(stack[bid][-1]) #edge child -> father has not established\n edge_feature = batch_idx.new_tensor( [child, stack[bid][-1], nth_child] )\n new_edge = tree_batch.add_edge(child, stack[bid][-1], edge_feature)\n new_mess.append(new_edge)\n\n subtree = subtree[0], batch_idx.new_tensor(new_mess)\n subgraph = [], []\n htree, hinter, hgraph = self.hmpn(tree_tensors, tree_tensors, graph_tensors, htree, hinter, hgraph, subtree, subgraph)\n cur_mess = self.rnn_cell.get_hidden_state(htree.mess).index_select(0, subtree[1])\n\n if len(expand_list) > 0:\n idx_in_mess, expand_list = zip(*expand_list)\n idx_in_mess = batch_idx.new_tensor( idx_in_mess )\n expand_idx = batch_idx.new_tensor( expand_list )\n forward_mess = cur_mess.index_select(0, idx_in_mess)\n cls_scores, icls_scores = self.get_cls_score(src_tree_vecs, expand_idx, forward_mess, None)\n scores, cls_topk, icls_topk = hier_topk(cls_scores, icls_scores, self.vocab, beam)\n if not greedy:\n scores = torch.exp(scores) #score is output of log_softmax\n shuf_idx = torch.multinomial(scores, beam, replacement=True).tolist()\n\n for i,bid in enumerate(expand_list):\n new_node, fa_node = stack[bid][-1], stack[bid][-2]\n success = False\n cls_beam = range(beam) if greedy else shuf_idx[i]\n for kk in cls_beam: #try until one is chemically valid\n if success: break\n clab, ilab = cls_topk[i][kk], icls_topk[i][kk]\n node_feature = batch_idx.new_tensor( [clab, ilab] )\n tree_batch.set_node_feature(new_node, node_feature)\n smiles, ismiles = self.vocab.get_smiles(clab), self.vocab.get_ismiles(ilab)\n fa_cluster, _, fa_used = tree_batch.get_cluster(fa_node)\n inter_cands, anchor_smiles, attach_points = graph_batch.get_assm_cands(fa_cluster, fa_used, ismiles)\n\n if len(inter_cands) == 0:\n continue\n elif len(inter_cands) == 1:\n sorted_cands = [(inter_cands[0], 0)]\n nth_child = 0\n else:\n nth_child = tree_batch.graph.in_degree(fa_node)\n icls = [self.vocab[ (smiles,x) ][1] for x in anchor_smiles]\n cands = inter_cands if len(attach_points) <= 2 else [ (x[0],x[-1]) for x in inter_cands ]\n cand_vecs = self.enum_attach(hgraph, cands, icls, nth_child)\n\n batch_idx = batch_idx.new_tensor( [bid] * len(inter_cands) )\n assm_scores = self.get_assm_score(src_graph_vecs, batch_idx, cand_vecs).tolist()\n sorted_cands = sorted( list(zip(inter_cands, assm_scores)), key = lambda x:x[1], reverse=True )\n\n for inter_label,_ in sorted_cands:\n inter_label = list(zip(inter_label, attach_points))\n if graph_batch.try_add_mol(bid, ismiles, inter_label):\n new_atoms, new_bonds, attached = graph_batch.add_mol(bid, ismiles, inter_label, nth_child)\n tree_batch.register_cgraph(new_node, new_atoms, new_bonds, attached)\n tree_batch.update_attached(fa_node, inter_label)\n success = True\n break\n\n if not success: #force backtrack\n child = stack[bid].pop() #pop the dummy new_node which can't be added\n nth_child = tree_batch.graph.in_degree(stack[bid][-1]) \n edge_feature = batch_idx.new_tensor( [child, stack[bid][-1], nth_child] )\n new_edge = tree_batch.add_edge(child, stack[bid][-1], edge_feature)\n\n child = stack[bid].pop() \n if len(stack[bid]) > 0:\n nth_child = tree_batch.graph.in_degree(stack[bid][-1]) \n edge_feature = batch_idx.new_tensor( [child, stack[bid][-1], nth_child] )\n new_edge = tree_batch.add_edge(child, stack[bid][-1], edge_feature)\n\n return graph_batch.get_mol()\n\n"
] | [
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.functional.softmax",
"torch.nn.functional.pad",
"torch.multinomial",
"torch.nn.CrossEntropyLoss",
"torch.exp",
"torch.eye",
"torch.nn.BCEWithLogitsLoss",
"torch.sigmoid",
"torch.LongTensor",
"torch.nn.ReLU",
"torch.cat",
"torch.bernoulli"
]
] |
johncliu/Horizon | [
"cfa7a873ada5de3bb01e78e2f237d9849b8270b2"
] | [
"ml/rl/test/test_normalization.py"
] | [
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nimport unittest\n\nimport numpy as np\nimport numpy.testing as npt\nimport six\nfrom caffe2.python import core, workspace\nfrom ml.rl.caffe_utils import C2\nfrom ml.rl.preprocessing import identify_types, normalization\nfrom ml.rl.preprocessing.identify_types import BOXCOX, CONTINUOUS, ENUM\nfrom ml.rl.preprocessing.normalization import (\n NormalizationParameters,\n sort_features_by_normalization,\n)\nfrom ml.rl.preprocessing.preprocessor_net import PreprocessorNet\nfrom ml.rl.test.preprocessing_util import (\n BOXCOX_FEATURE_ID,\n ENUM_FEATURE_ID,\n PROBABILITY_FEATURE_ID,\n id_to_type,\n read_data,\n)\nfrom ml.rl.test.utils import NumpyFeatureProcessor\nfrom scipy import special\n\n\nclass TestNormalization(unittest.TestCase):\n def _feature_type_override(self, feature_id):\n \"\"\"\n This should only be used to test CONTINUOUS_ACTION\n \"\"\"\n if id_to_type(feature_id) == identify_types.CONTINUOUS_ACTION:\n return identify_types.CONTINUOUS_ACTION\n return None\n\n def test_prepare_normalization_and_normalize(self):\n feature_value_map = read_data()\n\n normalization_parameters = {}\n for name, values in feature_value_map.items():\n normalization_parameters[name] = normalization.identify_parameter(\n values, 10, feature_type=self._feature_type_override(name)\n )\n for k, v in normalization_parameters.items():\n if id_to_type(k) == CONTINUOUS:\n self.assertEqual(v.feature_type, CONTINUOUS)\n self.assertIs(v.boxcox_lambda, None)\n self.assertIs(v.boxcox_shift, None)\n elif id_to_type(k) == BOXCOX:\n self.assertEqual(v.feature_type, BOXCOX)\n self.assertIsNot(v.boxcox_lambda, None)\n self.assertIsNot(v.boxcox_shift, None)\n else:\n assert v.feature_type == id_to_type(k)\n sorted_features, _ = sort_features_by_normalization(normalization_parameters)\n\n norm_net = core.Net(\"net\")\n C2.set_net(norm_net)\n preprocessor = PreprocessorNet()\n input_matrix = np.zeros([10000, len(sorted_features)], dtype=np.float32)\n for i, feature in enumerate(sorted_features):\n input_matrix[:, i] = feature_value_map[feature]\n input_matrix_blob = \"input_matrix_blob\"\n workspace.FeedBlob(input_matrix_blob, np.array([], dtype=np.float32))\n output_blob, _ = preprocessor.normalize_dense_matrix(\n input_matrix_blob, sorted_features, normalization_parameters, \"\", False\n )\n workspace.FeedBlob(input_matrix_blob, input_matrix)\n workspace.RunNetOnce(norm_net)\n normalized_feature_matrix = workspace.FetchBlob(output_blob)\n\n normalized_features = {}\n on_column = 0\n for feature in sorted_features:\n norm = normalization_parameters[feature]\n if norm.feature_type == ENUM:\n column_size = len(norm.possible_values)\n else:\n column_size = 1\n normalized_features[feature] = normalized_feature_matrix[\n :, on_column : (on_column + column_size)\n ]\n on_column += column_size\n\n self.assertTrue(\n all(\n [\n np.isfinite(parameter.stddev) and np.isfinite(parameter.mean)\n for parameter in normalization_parameters.values()\n ]\n )\n )\n for k, v in six.iteritems(normalized_features):\n self.assertTrue(np.all(np.isfinite(v)))\n feature_type = normalization_parameters[k].feature_type\n if feature_type == identify_types.PROBABILITY:\n sigmoidv = special.expit(v)\n self.assertTrue(\n np.all(\n np.logical_and(np.greater(sigmoidv, 0), np.less(sigmoidv, 1))\n )\n )\n elif feature_type == identify_types.ENUM:\n possible_values = normalization_parameters[k].possible_values\n self.assertEqual(v.shape[0], len(feature_value_map[k]))\n self.assertEqual(v.shape[1], len(possible_values))\n\n possible_value_map = {}\n for i, possible_value in enumerate(possible_values):\n possible_value_map[possible_value] = i\n\n for i, row in enumerate(v):\n original_feature = feature_value_map[k][i]\n self.assertEqual(\n possible_value_map[original_feature], np.where(row == 1)[0][0]\n )\n elif feature_type == identify_types.QUANTILE:\n for i, feature in enumerate(v[0]):\n original_feature = feature_value_map[k][i]\n expected = NumpyFeatureProcessor.value_to_quantile(\n original_feature, normalization_parameters[k].quantiles\n )\n self.assertAlmostEqual(feature, expected, 2)\n elif feature_type == identify_types.BINARY:\n pass\n elif (\n feature_type == identify_types.CONTINUOUS\n or feature_type == identify_types.BOXCOX\n ):\n one_stddev = np.isclose(np.std(v, ddof=1), 1, atol=0.01)\n zero_stddev = np.isclose(np.std(v, ddof=1), 0, atol=0.01)\n zero_mean = np.isclose(np.mean(v), 0, atol=0.01)\n self.assertTrue(\n np.all(zero_mean),\n \"mean of feature {} is {}, not 0\".format(k, np.mean(v)),\n )\n self.assertTrue(np.all(np.logical_or(one_stddev, zero_stddev)))\n elif feature_type == identify_types.CONTINUOUS_ACTION:\n less_than_max = v < 1\n more_than_min = v > -1\n self.assertTrue(\n np.all(less_than_max),\n \"values are not less than 1: {}\".format(v[less_than_max == False]),\n )\n self.assertTrue(\n np.all(more_than_min),\n \"values are not more than -1: {}\".format(v[more_than_min == False]),\n )\n else:\n raise NotImplementedError()\n\n def test_normalize_dense_matrix_enum(self):\n normalization_parameters = {\n 1: NormalizationParameters(\n identify_types.ENUM,\n None,\n None,\n None,\n None,\n [12, 4, 2],\n None,\n None,\n None,\n ),\n 2: NormalizationParameters(\n identify_types.CONTINUOUS, None, 0, 0, 1, None, None, None, None\n ),\n 3: NormalizationParameters(\n identify_types.ENUM, None, None, None, None, [15, 3], None, None, None\n ),\n }\n norm_net = core.Net(\"net\")\n C2.set_net(norm_net)\n preprocessor = PreprocessorNet()\n\n inputs = np.zeros([4, 3], dtype=np.float32)\n feature_ids = [2, 1, 3] # Sorted according to feature type\n inputs[:, feature_ids.index(1)] = [12, 4, 2, 2]\n inputs[:, feature_ids.index(2)] = [1.0, 2.0, 3.0, 3.0]\n inputs[:, feature_ids.index(3)] = [15, 3, 15, normalization.MISSING_VALUE]\n input_blob = C2.NextBlob(\"input_blob\")\n workspace.FeedBlob(input_blob, np.array([0], dtype=np.float32))\n normalized_output_blob, _ = preprocessor.normalize_dense_matrix(\n input_blob, feature_ids, normalization_parameters, \"\", False\n )\n workspace.FeedBlob(input_blob, inputs)\n workspace.RunNetOnce(norm_net)\n normalized_feature_matrix = workspace.FetchBlob(normalized_output_blob)\n\n np.testing.assert_allclose(\n np.array(\n [\n [1.0, 1, 0, 0, 1, 0],\n [2.0, 0, 1, 0, 0, 1],\n [3.0, 0, 0, 1, 1, 0],\n [3.0, 0, 0, 1, 0, 0], # Missing values should go to all 0\n ]\n ),\n normalized_feature_matrix,\n )\n\n def test_persistency(self):\n feature_value_map = read_data()\n normalization_parameters = {}\n for name, values in feature_value_map.items():\n normalization_parameters[name] = normalization.identify_parameter(\n values, feature_type=self._feature_type_override(name)\n )\n\n s = normalization.serialize(normalization_parameters)\n read_parameters = normalization.deserialize(s)\n # Unfortunately, Thrift serializatin seems to lose a bit of precision.\n # Using `==` will be false.\n self.assertEqual(read_parameters.keys(), normalization_parameters.keys())\n for k in normalization_parameters:\n self.assertEqual(\n read_parameters[k].feature_type,\n normalization_parameters[k].feature_type,\n )\n self.assertEqual(\n read_parameters[k].possible_values,\n normalization_parameters[k].possible_values,\n )\n for field in [\n \"boxcox_lambda\",\n \"boxcox_shift\",\n \"mean\",\n \"stddev\",\n \"quantiles\",\n \"min_value\",\n \"max_value\",\n ]:\n if getattr(normalization_parameters[k], field) is None:\n self.assertEqual(\n getattr(read_parameters[k], field),\n getattr(normalization_parameters[k], field),\n )\n else:\n npt.assert_allclose(\n getattr(read_parameters[k], field),\n getattr(normalization_parameters[k], field),\n )\n\n def test_preprocessing_network(self):\n feature_value_map = read_data()\n\n normalization_parameters = {}\n for name, values in feature_value_map.items():\n normalization_parameters[name] = normalization.identify_parameter(\n values, feature_type=self._feature_type_override(name)\n )\n test_features = NumpyFeatureProcessor.preprocess(\n feature_value_map, normalization_parameters\n )\n\n net = core.Net(\"PreprocessingTestNet\")\n C2.set_net(net)\n preprocessor = PreprocessorNet()\n name_preprocessed_blob_map = {}\n for feature_name in feature_value_map:\n workspace.FeedBlob(str(feature_name), np.array([0], dtype=np.int32))\n preprocessed_blob, _ = preprocessor.preprocess_blob(\n str(feature_name), [normalization_parameters[feature_name]]\n )\n name_preprocessed_blob_map[feature_name] = preprocessed_blob\n\n workspace.CreateNet(net)\n\n for feature_name, feature_value in six.iteritems(feature_value_map):\n feature_value = np.expand_dims(feature_value, -1)\n workspace.FeedBlob(str(feature_name), feature_value)\n workspace.RunNetOnce(net)\n\n for feature_name in feature_value_map:\n normalized_features = workspace.FetchBlob(\n name_preprocessed_blob_map[feature_name]\n )\n if feature_name != ENUM_FEATURE_ID:\n normalized_features = np.squeeze(normalized_features, -1)\n\n tolerance = 0.01\n if feature_name == BOXCOX_FEATURE_ID:\n # At the limit, boxcox has some numerical instability\n tolerance = 0.5\n non_matching = np.where(\n np.logical_not(\n np.isclose(\n normalized_features,\n test_features[feature_name],\n rtol=tolerance,\n atol=tolerance,\n )\n )\n )\n self.assertTrue(\n np.all(\n np.isclose(\n normalized_features,\n test_features[feature_name],\n rtol=tolerance,\n atol=tolerance,\n )\n ),\n \"{} does not match: {} {}\".format(\n feature_name,\n normalized_features[non_matching].tolist(),\n test_features[feature_name][non_matching].tolist(),\n ),\n )\n\n def test_type_override(self):\n # Take a feature that should be identified as probability\n feature_value_map = read_data()\n probability_values = feature_value_map[PROBABILITY_FEATURE_ID]\n\n # And ask for a binary anyways\n parameter = normalization.identify_parameter(\n probability_values, feature_type=identify_types.BINARY\n )\n self.assertEqual(parameter.feature_type, \"BINARY\")\n"
] | [
[
"numpy.logical_or",
"numpy.squeeze",
"numpy.zeros",
"numpy.less",
"numpy.mean",
"numpy.isclose",
"numpy.greater",
"numpy.expand_dims",
"scipy.special.expit",
"numpy.all",
"numpy.array",
"numpy.std",
"numpy.where",
"numpy.isfinite"
]
] |
boycehbz/DMMR | [
"18fcee7ce584fdccfa08bcda883d9b4fcb962c04"
] | [
"core/smplx/lbs_.py"
] | [
"# -*- coding: utf-8 -*-\n\n# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is\n# holder of all proprietary rights on this computer program.\n# You can only use this computer program if you have closed\n# a license agreement with MPG or you get the right to use the computer\n# program from someone who is authorized to grant you that right.\n# Any use of the computer program without a valid license is prohibited and\n# liable to prosecution.\n#\n# Copyright©2019 Max-Planck-Gesellschaft zur Förderung\n# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute\n# for Intelligent Systems. All rights reserved.\n#\n# Contact: ps-license@tuebingen.mpg.de\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\n\nfrom .utils import rot_mat_to_euler\n\n\ndef find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx,\n dynamic_lmk_b_coords,\n neck_kin_chain, dtype=torch.float32):\n ''' Compute the faces, barycentric coordinates for the dynamic landmarks\n\n\n To do so, we first compute the rotation of the neck around the y-axis\n and then use a pre-computed look-up table to find the faces and the\n barycentric coordinates that will be used.\n\n Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de)\n for providing the original TensorFlow implementation and for the LUT.\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n pose: torch.tensor Bx(Jx3), dtype = torch.float32\n The current pose of the body model\n dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long\n The look-up table from neck rotation to faces\n dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32\n The look-up table from neck rotation to barycentric coordinates\n neck_kin_chain: list\n A python list that contains the indices of the joints that form the\n kinematic chain of the neck.\n dtype: torch.dtype, optional\n\n Returns\n -------\n dyn_lmk_faces_idx: torch.tensor, dtype = torch.long\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n dyn_lmk_b_coords: torch.tensor, dtype = torch.float32\n A tensor of size BxL that contains the indices of the faces that\n will be used to compute the current dynamic landmarks.\n '''\n\n batch_size = vertices.shape[0]\n\n aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,\n neck_kin_chain)\n rot_mats = batch_rodrigues(\n aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)\n\n rel_rot_mat = torch.eye(3, device=vertices.device,\n dtype=dtype).unsqueeze_(dim=0)\n for idx in range(len(neck_kin_chain)):\n rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)\n\n y_rot_angle = torch.round(\n torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,\n max=39)).to(dtype=torch.long)\n neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)\n mask = y_rot_angle.lt(-39).to(dtype=torch.long)\n neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)\n y_rot_angle = (neg_mask * neg_vals +\n (1 - neg_mask) * y_rot_angle)\n\n dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,\n 0, y_rot_angle)\n dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,\n 0, y_rot_angle)\n\n return dyn_lmk_faces_idx, dyn_lmk_b_coords\n\n\ndef vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):\n ''' Calculates landmarks by barycentric interpolation\n\n Parameters\n ----------\n vertices: torch.tensor BxVx3, dtype = torch.float32\n The tensor of input vertices\n faces: torch.tensor Fx3, dtype = torch.long\n The faces of the mesh\n lmk_faces_idx: torch.tensor L, dtype = torch.long\n The tensor with the indices of the faces used to calculate the\n landmarks.\n lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32\n The tensor of barycentric coordinates that are used to interpolate\n the landmarks\n\n Returns\n -------\n landmarks: torch.tensor BxLx3, dtype = torch.float32\n The coordinates of the landmarks for each mesh in the batch\n '''\n # Extract the indices of the vertices for each face\n # BxLx3\n batch_size, num_verts = vertices.shape[:2]\n device = vertices.device\n\n lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(\n batch_size, -1, 3)\n\n lmk_faces += torch.arange(\n batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts\n\n lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(\n batch_size, -1, 3, 3)\n\n landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])\n return landmarks\n\n\ndef lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents,\n lbs_weights, pose2rot=True, dtype=torch.float32):\n ''' Performs Linear Blend Skinning with the given shape and pose parameters\n\n Parameters\n ----------\n betas : torch.tensor BxNB\n The tensor of shape parameters\n pose : torch.tensor Bx(J + 1) * 3\n The pose parameters in axis-angle format\n v_template torch.tensor BxVx3\n The template mesh that will be deformed\n shapedirs : torch.tensor 1xNB\n The tensor of PCA shape displacements\n posedirs : torch.tensor Px(V * 3)\n The pose PCA coefficients\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from\n the position of the vertices\n parents: torch.tensor J\n The array that describes the kinematic tree for the model\n lbs_weights: torch.tensor N x V x (J + 1)\n The linear blend skinning weights that represent how much the\n rotation matrix of each part affects each vertex\n pose2rot: bool, optional\n Flag on whether to convert the input pose tensor to rotation\n matrices. The default value is True. If False, then the pose tensor\n should already contain rotation matrices and have a size of\n Bx(J + 1)x9\n dtype: torch.dtype, optional\n\n Returns\n -------\n verts: torch.tensor BxVx3\n The vertices of the mesh after applying the shape and pose\n displacements.\n joints: torch.tensor BxJx3\n The joints of the model\n '''\n\n batch_size = max(betas.shape[0], pose.shape[0])\n device = betas.device\n\n # Add shape contribution\n v_shaped = v_template + blend_shapes(betas, shapedirs)\n # v_shaped *= scale\n # Get the joints\n # NxJx3 array\n J = vertices2joints(J_regressor, v_shaped)\n\n # 3. Add pose blend shapes\n # N x J x 3 x 3\n ident = torch.eye(3, dtype=dtype, device=device)\n if pose2rot:\n rot_mats = batch_rodrigues(\n pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3])\n\n pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])\n # (N x P) x (P, V * 3) -> N x V x 3\n pose_offsets = torch.matmul(pose_feature, posedirs) \\\n .view(batch_size, -1, 3)\n else:\n pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident\n rot_mats = pose.view(batch_size, -1, 3, 3)\n\n pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),\n posedirs).view(batch_size, -1, 3)\n\n v_posed = pose_offsets + v_shaped\n # 4. Get the global joint location\n J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)\n\n # 5. Do skinning:\n # W is N x V x (J + 1)\n W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])\n # (N x V x (J + 1)) x (N x (J + 1) x 16)\n num_joints = J_regressor.shape[0]\n T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \\\n .view(batch_size, -1, 4, 4)\n\n homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],\n dtype=dtype, device=device)\n v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)\n v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))\n\n verts = v_homo[:, :, :3, 0]\n\n return verts, J_transformed\n\n\ndef vertices2joints(J_regressor, vertices):\n ''' Calculates the 3D joint locations from the vertices\n\n Parameters\n ----------\n J_regressor : torch.tensor JxV\n The regressor array that is used to calculate the joints from the\n position of the vertices\n vertices : torch.tensor BxVx3\n The tensor of mesh vertices\n\n Returns\n -------\n torch.tensor BxJx3\n The location of the joints\n '''\n\n return torch.einsum('bik,ji->bjk', [vertices, J_regressor])\n\n\ndef blend_shapes(betas, shape_disps):\n ''' Calculates the per vertex displacement due to the blend shapes\n\n\n Parameters\n ----------\n betas : torch.tensor Bx(num_betas)\n Blend shape coefficients\n shape_disps: torch.tensor Vx3x(num_betas)\n Blend shapes\n\n Returns\n -------\n torch.tensor BxVx3\n The per-vertex displacement due to shape deformation\n '''\n\n # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]\n # i.e. Multiply each shape displacement by its corresponding beta and\n # then sum them.\n blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])\n return blend_shape\n\n\ndef batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):\n ''' Calculates the rotation matrices for a batch of rotation vectors\n Parameters\n ----------\n rot_vecs: torch.tensor Nx3\n array of N axis-angle vectors\n Returns\n -------\n R: torch.tensor Nx3x3\n The rotation matrices for the given axis-angle parameters\n '''\n\n batch_size = rot_vecs.shape[0]\n device = rot_vecs.device\n\n angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)\n rot_dir = rot_vecs / angle\n\n cos = torch.unsqueeze(torch.cos(angle), dim=1)\n sin = torch.unsqueeze(torch.sin(angle), dim=1)\n\n # Bx1 arrays\n rx, ry, rz = torch.split(rot_dir, 1, dim=1)\n K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)\n\n zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)\n K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \\\n .view((batch_size, 3, 3))\n\n ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)\n rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)\n return rot_mat\n\n\ndef transform_mat(R, t):\n ''' Creates a batch of transformation matrices\n Args:\n - R: Bx3x3 array of a batch of rotation matrices\n - t: Bx3x1 array of a batch of translation vectors\n Returns:\n - T: Bx4x4 Transformation matrix\n '''\n # No padding left or right, only add an extra row\n return torch.cat([F.pad(R, [0, 0, 0, 1]),\n F.pad(t, [0, 0, 0, 1], value=1)], dim=2)\n\n\ndef batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32):\n \"\"\"\n Applies a batch of rigid transformations to the joints\n\n Parameters\n ----------\n rot_mats : torch.tensor BxNx3x3\n Tensor of rotation matrices\n joints : torch.tensor BxNx3\n Locations of joints\n parents : torch.tensor BxN\n The kinematic tree of each object\n dtype : torch.dtype, optional:\n The data type of the created tensors, the default is torch.float32\n\n Returns\n -------\n posed_joints : torch.tensor BxNx3\n The locations of the joints after applying the pose rotations\n rel_transforms : torch.tensor BxNx4x4\n The relative (with respect to the root joint) rigid transformations\n for all the joints\n \"\"\"\n joints = torch.unsqueeze(joints, dim=-1)\n\n rel_joints = joints.clone()\n rel_joints[:, 1:] -= joints[:, parents[1:]]\n\n transforms_mat = transform_mat(\n rot_mats.reshape(-1, 3, 3),\n rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)\n\n # transforms_mat[:, 0][:,:3,:3] *= scale\n transform_chain = [transforms_mat[:, 0]]\n for i in range(1, parents.shape[0]):\n # Subtract the joint location at the rest pose\n # No need for rotation, since it's identity when at rest\n curr_res = torch.matmul(transform_chain[parents[i]],\n transforms_mat[:, i])\n transform_chain.append(curr_res)\n\n transforms = torch.stack(transform_chain, dim=1)\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n # The last column of the transformations contains the posed joints\n posed_joints = transforms[:, :, :3, 3]\n\n joints_homogen = F.pad(joints, [0, 0, 0, 1])\n\n rel_transforms = transforms - F.pad(\n torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])\n\n return posed_joints, rel_transforms\n"
] | [
[
"torch.unsqueeze",
"torch.ones",
"torch.stack",
"torch.split",
"torch.cos",
"torch.bmm",
"torch.nn.functional.pad",
"torch.norm",
"torch.sin",
"torch.arange",
"torch.index_select",
"torch.zeros",
"torch.einsum",
"torch.eye",
"torch.cat",
"torch.matmul"
]
] |
ardhanii/covid19-sir | [
"59d95156b375c41259c46ce4e656b86903f92ec2"
] | [
"covsirphy/loading/db_owid.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport country_converter as coco\nimport pandas as pd\nfrom covsirphy.util.term import Term\nfrom covsirphy.loading.db_base import _RemoteDatabase\n\n\nclass _OWID(_RemoteDatabase):\n \"\"\"\n Access \"Our World In Data\".\n https://github.com/owid/covid-19-data/tree/master/public/data\n https://ourworldindata.org/coronavirus\n\n Args:\n filename (str): CSV filename to save records\n \"\"\"\n # URL for vaccine data\n URL_V = \"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/\"\n URL_V_REC = f\"{URL_V}vaccinations.csv\"\n URL_V_LOC = f\"{URL_V}locations.csv\"\n # URL for PCR data\n URL_P = \"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/testing/\"\n URL_P_REC = f\"{URL_P}covid-testing-all-observations.csv\"\n # Citation\n CITATION = \"Hasell, J., Mathieu, E., Beltekian, D. et al.\" \\\n \" A cross-country database of COVID-19 testing. Sci Data 7, 345 (2020).\" \\\n \" https://doi.org/10.1038/s41597-020-00688-8\"\n # Column names and data types\n # {\"name in database\": \"name defined in Term class\"}\n COL_DICT = {\n \"date\": Term.DATE,\n \"location\": Term.COUNTRY,\n Term.PROVINCE: Term.PROVINCE,\n \"iso_code\": Term.ISO3,\n \"vaccines\": Term.PRODUCT,\n \"total_vaccinations\": Term.VAC,\n \"people_vaccinated\": Term.V_ONCE,\n \"people_fully_vaccinated\": Term.V_FULL,\n \"tests\": Term.TESTS,\n }\n\n def download(self, verbose):\n \"\"\"\n Download the dataset from the server and set the list of primary sources.\n\n Args:\n verbose (int): level of verbosity\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n defined by the first values of self.COL_DICT.values()\n\n Note:\n If @verbose is equal to or over 1, how to show the list will be explained.\n \"\"\"\n # Download datasets\n if verbose:\n print(\"Retrieving datasets from Our World In Data https://github.com/owid/covid-19-data/\")\n # Vaccinations\n v_rec_cols = [\n \"date\", \"location\", \"iso_code\", \"total_vaccinations\", \"people_vaccinated\", \"people_fully_vaccinated\"]\n v_rec_df = pd.read_csv(self.URL_V_REC, usecols=v_rec_cols)\n v_loc_df = pd.read_csv(self.URL_V_LOC, usecols=[\"location\", \"vaccines\"])\n v_df = v_rec_df.merge(v_loc_df, how=\"left\", on=\"location\")\n # Tests\n pcr_rec_cols = [\"ISO code\", \"Date\", \"Daily change in cumulative total\", \"Cumulative total\"]\n pcr_df = pd.read_csv(self.URL_P_REC, usecols=pcr_rec_cols)\n pcr_df = pcr_df.rename(columns={\"ISO code\": \"iso_code\", \"Date\": \"date\"})\n pcr_df[\"cumsum\"] = pcr_df.groupby(\"iso_code\")[\"Daily change in cumulative total\"].cumsum()\n pcr_df = pcr_df.assign(tests=lambda x: x[\"Cumulative total\"].fillna(x[\"cumsum\"]))\n # Combine data (vaccinations/tests)\n df = v_df.set_index([\"iso_code\", \"date\"])\n df = df.combine_first(pcr_df.set_index([\"iso_code\", \"date\"]).loc[:, [\"tests\"]])\n df = df.reset_index()\n # Location (country/province)\n df[\"location\"] = df[\"location\"].replace(\n {\n # COG\n \"Congo\": \"Republic of the Congo\",\n }\n )\n df = df.loc[~df[\"iso_code\"].str.contains(\"OWID_\")]\n df[\"location\"] = df.groupby(\"iso_code\")[\"location\"].bfill()\n df.loc[df[\"location\"] == df[\"iso_code\"], \"location\"] = None\n df.loc[df[\"location\"].isna(), \"location\"] = df.loc[df[\"location\"].isna(), \"iso_code\"].apply(\n lambda x: coco.convert(x, to=\"name_short\", not_found=None))\n df[self.PROVINCE] = self.UNKNOWN\n return df\n"
] | [
[
"pandas.read_csv"
]
] |
egonrian/google-research | [
"9049acf9246c1b75170f0c6757e62a8f619a9db6",
"2c0043ecd507e75e2df9973a3015daf9253e1467",
"2c0043ecd507e75e2df9973a3015daf9253e1467"
] | [
"task_set/tasks/fixed/fixed_text_rnn_classification_test.py",
"depth_and_motion_learning/consistency_losses.py",
"protein_lm/embed_test.py"
] | [
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for task_set.tasks.fixed_text_rnn_classification.\"\"\"\nfrom absl.testing import parameterized\n\nfrom task_set import registry\nfrom task_set.tasks import family_test_utils\nfrom task_set.tasks.fixed import fixed_text_rnn_classification # pylint: disable=unused-import\nimport tensorflow.compat.v1 as tf\n\n\nclass FixedTextRNNClassificationTest(family_test_utils.SingleTaskTestCase):\n\n def test_right_number_of_tasks(self):\n task_names = registry.task_registry.get_all_fixed_config_names()\n self.assertLen(task_names, 12)\n\n @parameterized.parameters(registry.task_registry.get_all_fixed_config_names())\n def test_tasks(self, task_name):\n self.task_test(registry.task_registry.get_instance(task_name))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Loss functions that impose RGB and depth motion-consistency across frames.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\n\nfrom depth_and_motion_learning import resampler\nfrom depth_and_motion_learning import transform_utils\n\n\ndef rgbd_consistency_loss(frame1transformed_depth,\n frame1rgb,\n frame2depth,\n frame2rgb,\n validity_mask=None):\n \"\"\"Computes a loss that penalizes RGBD inconsistencies between frames.\n\n This function computes 3 losses that penalize inconsistencies between two\n frames: depth, RGB, and structural similarity. It IS NOT SYMMETRIC with\n respect to both frames. In particular, to address occlusions, it only\n penalizes depth and RGB inconsistencies at pixels where frame1 is closer to\n the camera than frame2 (Why? see https://arxiv.org/abs/1904.04998). Therefore\n the intended usage pattern is running it twice - second time with the two\n frames swapped.\n\n Args:\n frame1transformed_depth: A transform_depth_map.TransformedDepthMap object\n representing the depth map of frame 1 after it was motion-transformed to\n frame 2, a motion transform that accounts for all camera and object motion\n that occurred between frame1 and frame2. The tensors inside\n frame1transformed_depth are of shape [B, H, W].\n frame1rgb: A tf.Tensor of shape [B, H, W, C] containing the RGB image at\n frame1.\n frame2depth: A tf.Tensor of shape [B, H, W] containing the depth map at\n frame2.\n frame2rgb: A tf.Tensor of shape [B, H, W, C] containing the RGB image at\n frame2.\n validity_mask: a tf.Tensor of a floating point type and a shape of\n [B, H, W, 1] containing a validity mask.\n\n Returns:\n A dicionary from string to tf.Tensor, with the following entries:\n depth_error: A tf scalar, the depth mismatch error between the two frames.\n rgb_error: A tf scalar, the rgb mismatch error between the two frames.\n ssim_error: A tf scalar, the strictural similarity mismatch error between\n the two frames.\n depth_proximity_weight: A tf.Tensor of shape [B, H, W], representing a\n function that peaks (at 1.0) for pixels where there is depth consistency\n between the two frames, and is small otherwise.\n frame1_closer_to_camera: A tf.Tensor of shape [B, H, W, 1], a mask that is\n 1.0 when the depth map of frame 1 has smaller depth than frame 2.\n \"\"\"\n frame2rgbd = tf.concat(\n [frame2rgb, tf.expand_dims((frame2depth), -1)], axis=-1)\n frame2rgbd_resampled = resampler.resampler_with_unstacked_warp(\n frame2rgbd,\n frame1transformed_depth.pixel_x,\n frame1transformed_depth.pixel_y,\n safe=False)\n frame2rgb_resampled, frame2depth_resampled = tf.split(\n frame2rgbd_resampled, [3, 1], axis=-1)\n frame2depth_resampled = tf.squeeze(frame2depth_resampled, axis=-1)\n\n # f1td.depth is the predicted depth at [pixel_y, pixel_x] for frame2. Now we\n # generate (by interpolation) the actual depth values for frame2's depth, at\n # the same locations, so that we can compare the two depths.\n\n # We penalize inconsistencies between the two frames' depth maps only if the\n # transformed depth map (of frame 1) falls closer to the camera than the\n # actual depth map (of frame 2). This is intended for avoiding penalizing\n # points that become occluded because of the transform.\n # So what about depth inconsistencies where frame1's depth map is FARTHER from\n # the camera than frame2's? These will be handled when we swap the roles of\n # frame 1 and 2 (more in https://arxiv.org/abs/1904.04998).\n frame1_closer_to_camera = tf.to_float(\n tf.logical_and(\n frame1transformed_depth.mask,\n tf.less(frame1transformed_depth.depth, frame2depth_resampled)))\n frames_l1_diff = tf.abs(frame2depth_resampled - frame1transformed_depth.depth)\n if validity_mask is not None:\n frames_l1_diff = frames_l1_diff * tf.squeeze(validity_mask, axis=[3])\n depth_error = tf.reduce_mean(\n tf.math.multiply_no_nan(frames_l1_diff, frame1_closer_to_camera))\n\n frames_rgb_l1_diff = tf.abs(frame2rgb_resampled - frame1rgb)\n if validity_mask is not None:\n frames_rgb_l1_diff = frames_rgb_l1_diff * validity_mask\n rgb_error = tf.math.multiply_no_nan(\n frames_rgb_l1_diff, tf.expand_dims(frame1_closer_to_camera, -1))\n rgb_error = tf.reduce_mean(rgb_error)\n\n # We generate a weight function that peaks (at 1.0) for pixels where when the\n # depth difference is less than its standard deviation across the frame, and\n # fall off to zero otherwise. This function is used later for weighing the\n # structural similarity loss term. We only want to demand structural\n # similarity for surfaces that are close to one another in the two frames.\n depth_error_second_moment = _weighted_average(\n tf.square(frame2depth_resampled - frame1transformed_depth.depth),\n frame1_closer_to_camera) + 1e-4\n depth_proximity_weight = tf.math.multiply_no_nan(\n depth_error_second_moment /\n (tf.square(frame2depth_resampled - frame1transformed_depth.depth) +\n depth_error_second_moment), tf.to_float(frame1transformed_depth.mask))\n\n if validity_mask is not None:\n depth_proximity_weight = depth_proximity_weight * tf.squeeze(\n validity_mask, axis=[3])\n\n # If we don't stop the gradient training won't start. The reason is presumably\n # that then the network can push the depths apart instead of seeking RGB\n # consistency.\n depth_proximity_weight = tf.stop_gradient(depth_proximity_weight)\n\n ssim_error, avg_weight = weighted_ssim(\n frame2rgb_resampled,\n frame1rgb,\n depth_proximity_weight,\n c1=float('inf'), # These values of c1 and c2 seemed to work better than\n c2=9e-6) # defaults. TODO(gariel): Make them parameters rather\n # than hard coded.\n ssim_error_mean = tf.reduce_mean(\n tf.math.multiply_no_nan(ssim_error, avg_weight))\n\n endpoints = {\n 'depth_error': depth_error,\n 'rgb_error': rgb_error,\n 'ssim_error': ssim_error_mean,\n 'depth_proximity_weight': depth_proximity_weight,\n 'frame1_closer_to_camera': frame1_closer_to_camera\n }\n return endpoints\n\n\ndef motion_field_consistency_loss(frame1transformed_pixelx,\n frame1transformed_pixely, mask, rotation1,\n translation1, rotation2, translation2):\n \"\"\"Computes a cycle consistency loss between two motion maps.\n\n Given two rotation and translation maps (of two frames), and a mapping from\n one frame to the other, this function assists in imposing that the fields at\n frame 1 represent the opposite motion of the ones in frame 2.\n\n In other words: At any given pixel on frame 1, if we apply the translation and\n rotation designated at that pixel, we land on some pixel in frame 2, and if we\n apply the translation and rotation designated there, we land back at the\n original pixel at frame 1.\n\n Args:\n frame1transformed_pixelx: A tf.Tensor of shape [B, H, W] representing the\n motion-transformed x-location of each pixel in frame 1.\n frame1transformed_pixely: A tf.Tensor of shape [B, H, W] representing the\n motion-transformed y-location of each pixel in frame 1.\n mask: A tf.Tensor of shape [B, H, W, 2] expressing the weight of each pixel\n in the calculation of the consistency loss.\n rotation1: A tf.Tensor of shape [B, 3] representing rotation angles.\n translation1: A tf.Tensor of shape [B, H, W, 3] representing translation\n vectors.\n rotation2: A tf.Tensor of shape [B, 3] representing rotation angles.\n translation2: A tf.Tensor of shape [B, H, W, 3] representing translation\n vectors.\n\n Returns:\n A dicionary from string to tf.Tensor, with the following entries:\n rotation_error: A tf scalar, the rotation consistency error.\n translation_error: A tf scalar, the translation consistency error.\n\n \"\"\"\n\n translation2resampled = resampler.resampler_with_unstacked_warp(\n translation2,\n tf.stop_gradient(frame1transformed_pixelx),\n tf.stop_gradient(frame1transformed_pixely),\n safe=False)\n rotation1field = tf.broadcast_to(\n _expand_dims_twice(rotation1, -2), tf.shape(translation1))\n rotation2field = tf.broadcast_to(\n _expand_dims_twice(rotation2, -2), tf.shape(translation2))\n rotation1matrix = transform_utils.matrix_from_angles(rotation1field)\n rotation2matrix = transform_utils.matrix_from_angles(rotation2field)\n\n rot_unit, trans_zero = transform_utils.combine(rotation2matrix,\n translation2resampled,\n rotation1matrix, translation1)\n eye = tf.eye(3, batch_shape=tf.shape(rot_unit)[:-2])\n\n # We normalize the product of rotations by the product of their norms, to make\n # the loss agnostic of their magnitudes, only wanting them to be opposite in\n # directions. Otherwise the loss has a tendency to drive the rotations to\n # zero.\n rot_error = tf.reduce_mean(tf.square(rot_unit - eye), axis=(3, 4))\n rot1_scale = tf.reduce_mean(tf.square(rotation1matrix - eye), axis=(3, 4))\n rot2_scale = tf.reduce_mean(tf.square(rotation2matrix - eye), axis=(3, 4))\n rot_error /= (1e-24 + rot1_scale + rot2_scale)\n rotation_error = tf.reduce_mean(rot_error)\n\n def norm(x):\n return tf.reduce_sum(tf.square(x), axis=-1)\n\n # Here again, we normalize by the magnitudes, for the same reason.\n translation_error = tf.reduce_mean(tf.math.multiply_no_nan(\n mask, norm(trans_zero) /\n (1e-24 + norm(translation1) + norm(translation2resampled))))\n\n return {\n 'rotation_error': rotation_error,\n 'translation_error': translation_error\n }\n\n\ndef rgbd_and_motion_consistency_loss(frame1transformed_depth,\n frame1rgb,\n frame2depth,\n frame2rgb,\n rotation1,\n translation1,\n rotation2,\n translation2,\n validity_mask=None):\n \"\"\"A helper that bundles rgbd and motion consistency losses together.\"\"\"\n endpoints = rgbd_consistency_loss(\n frame1transformed_depth,\n frame1rgb,\n frame2depth,\n frame2rgb,\n validity_mask=validity_mask)\n # We calculate the loss only for when frame1transformed_depth is closer to the\n # camera than frame2 (occlusion-awareness). See explanation in\n # rgbd_consistency_loss above.\n mask = endpoints['frame1_closer_to_camera']\n if validity_mask is not None:\n mask *= tf.squeeze(validity_mask, axis=3)\n endpoints.update(\n motion_field_consistency_loss(frame1transformed_depth.pixel_x,\n frame1transformed_depth.pixel_y, mask,\n rotation1, translation1, rotation2,\n translation2))\n return endpoints\n\n\ndef weighted_ssim(x, y, weight, c1=0.01**2, c2=0.03**2, weight_epsilon=0.01):\n \"\"\"Computes a weighted structured image similarity measure.\n\n See https://en.wikipedia.org/wiki/Structural_similarity#Algorithm. The only\n difference here is that not all pixels are weighted equally when calculating\n the moments - they are weighted by a weight function.\n\n Args:\n x: A tf.Tensor representing a batch of images, of shape [B, H, W, C].\n y: A tf.Tensor representing a batch of images, of shape [B, H, W, C].\n weight: A tf.Tensor of shape [B, H, W], representing the weight of each\n pixel in both images when we come to calculate moments (means and\n correlations).\n c1: A floating point number, regularizes division by zero of the means.\n c2: A floating point number, regularizes division by zero of the second\n moments.\n weight_epsilon: A floating point number, used to regularize division by the\n weight.\n\n Returns:\n A tuple of two tf.Tensors. First, of shape [B, H-2, W-2, C], is scalar\n similarity loss oer pixel per channel, and the second, of shape\n [B, H-2. W-2, 1], is the average pooled `weight`. It is needed so that we\n know how much to weigh each pixel in the first tensor. For example, if\n `'weight` was very small in some area of the images, the first tensor will\n still assign a loss to these pixels, but we shouldn't take the result too\n seriously.\n \"\"\"\n if c1 == float('inf') and c2 == float('inf'):\n raise ValueError('Both c1 and c2 are infinite, SSIM loss is zero. This is '\n 'likely unintended.')\n weight = tf.expand_dims(weight, -1)\n average_pooled_weight = _avg_pool3x3(weight)\n weight_plus_epsilon = weight + weight_epsilon\n inverse_average_pooled_weight = 1.0 / (average_pooled_weight + weight_epsilon)\n\n def weighted_avg_pool3x3(z):\n wighted_avg = _avg_pool3x3(z * weight_plus_epsilon)\n return wighted_avg * inverse_average_pooled_weight\n\n mu_x = weighted_avg_pool3x3(x)\n mu_y = weighted_avg_pool3x3(y)\n sigma_x = weighted_avg_pool3x3(x**2) - mu_x**2\n sigma_y = weighted_avg_pool3x3(y**2) - mu_y**2\n sigma_xy = weighted_avg_pool3x3(x * y) - mu_x * mu_y\n if c1 == float('inf'):\n ssim_n = (2 * sigma_xy + c2)\n ssim_d = (sigma_x + sigma_y + c2)\n elif c2 == float('inf'):\n ssim_n = 2 * mu_x * mu_y + c1\n ssim_d = mu_x**2 + mu_y**2 + c1\n else:\n ssim_n = (2 * mu_x * mu_y + c1) * (2 * sigma_xy + c2)\n ssim_d = (mu_x**2 + mu_y**2 + c1) * (sigma_x + sigma_y + c2)\n result = ssim_n / ssim_d\n return tf.clip_by_value((1 - result) / 2, 0, 1), average_pooled_weight\n\n\ndef _avg_pool3x3(x):\n return tf.nn.avg_pool(x, [1, 3, 3, 1], [1, 1, 1, 1], 'VALID')\n\n\ndef _weighted_average(x, w, epsilon=1.0):\n weighted_sum = tf.reduce_sum(x * w, axis=(1, 2), keepdims=True)\n sum_of_weights = tf.reduce_sum(w, axis=(1, 2), keepdims=True)\n return weighted_sum / (sum_of_weights + epsilon)\n\n\ndef _expand_dims_twice(x, dim):\n return tf.expand_dims(tf.expand_dims(x, dim), dim)\n",
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Tests for embedding functions.\"\"\"\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport mock\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom protein_lm import data\nfrom protein_lm import embed\nfrom protein_lm import models\n\n\nclass EncodingTest(parameterized.TestCase, tf.test.TestCase):\n\n @parameterized.parameters(\n (10, None, 4),\n (None, 10, 4),\n (None, 3, 3),\n (3, None, 3))\n def test_encode_string_sequences(self, domain_length, length,\n expected_output_length):\n seqs = ['ABCD', 'EFG']\n domain = data.make_protein_domain(\n length=domain_length) if domain_length else None\n\n output_batch = embed._encode_string_sequences(\n seqs, domain=domain, length=length)\n self.assertEqual(output_batch.shape, (2, expected_output_length))\n\n\ndef _get_model(domain):\n return models.FlaxLM(\n domain=domain,\n num_layers=1,\n num_heads=1,\n qkv_dim=32,\n emb_dim=32,\n mlp_dim=32)\n\n\nclass EmbedTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n self._domain = data.make_protein_domain(length=12)\n self._model = _get_model(self._domain)\n self._embed_fn = embed.get_embed_fn(\n model=self._model,\n domain=self._domain,\n reduce_fn=embed.masked_reduce_fn)\n super().setUp()\n\n def test_get_embed_fn_int_sequences(self):\n p1 = 'ACDEFHIKLNQP'\n p2 = 'ALNQP'\n encoded = self._domain.encode([p1, p2])\n int_embs = self._embed_fn(encoded)\n self.assertEqual((2, 32), int_embs.shape)\n\n def test_embed_strings(self):\n p1 = 'ACDEFHIKLNQP'\n p2 = 'ALNQP'\n str_embs = self._embed_fn([p1, p2])\n self.assertEqual((2, 32), str_embs.shape)\n\n @parameterized.parameters(\n (embed.sum_reducer, [[5, 7, 9]]),\n (embed.mean_reducer, [[2.5, 3.5, 4.5]]),\n (embed.max_reducer, [[4, 5, 6]]),\n )\n def test_reducer(self, reduce_fn, expected):\n embedding = np.array([[[1, 2, 6], [4, 5, 3], [7, 10, 9]]])\n mask = np.array([[1, 1, 0]])\n reduced = reduce_fn(embedding, mask)\n self.assertAllClose(reduced, expected)\n\n @parameterized.parameters(\n (True, True, True, True, [[1, 2]]),\n (False, True, True, True, [[3, 4]]),\n (True, False, True, True, [[7, 8]]),\n (True, True, False, True, [[9, 10]]),\n (True, True, True, False, [[46, 11]]),\n )\n def test_masked_reduce_fn(self, ignore_eos, ignore_bos, ignore_pad,\n ignore_mask, expected):\n embedding = np.array([[[1, 2], [13, 14], [5, 6], [17, 18], [91, 20]]])\n domain = self._domain\n inputs = np.array([[0, domain.vocab.bos, domain.vocab.eos, domain.vocab.pad,\n domain.vocab.mask]])\n reduced = embed.masked_reduce_fn(embedding=embedding,\n inputs=inputs,\n ignore_eos=ignore_eos,\n ignore_bos=ignore_bos,\n ignore_pad=ignore_pad,\n ignore_mask=ignore_mask)\n self.assertAllClose(reduced, expected)\n\n def test_validate_input_int_sequences(self):\n with self.assertRaisesRegex(ValueError, 'Input int-encoded sequences'):\n self._embed_fn([np.ones(14)])\n\n\nclass ProteinLMEmbedderTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n self._domain = data.make_protein_domain(length=12)\n self._model = _get_model(self._domain)\n super().setUp()\n\n # TODO(gandreea): get this test to by fixing domain.encode padding issues\n # def test_embedder_encoding(self):\n # seqs = ['ACDEFHIKLNQP', 'ALNQP']\n # str_embs = self._embed_fn(seqs)\n # int_embs = self._embed_fn(self._domain.encode(seqs))\n # self.assertAllClose(int_embs, str_embs)\n\n def test_embedder_batching(self):\n \"\"\"Asserts that the model is always called with fixed-size batches.\"\"\"\n batch_size = 4\n embedder = embed.ProteinLMEmbedder(\n model=self._model, output_head='output_emb', batch_size=batch_size)\n embedder._embed_fn = mock.Mock(wraps=embedder._embed_fn)\n # Call on various differently-sized batches.\n expected_call_shapes = []\n expected_batch_shape = (batch_size, self._domain.length)\n for num_seqs in [1, 3, 5, 10]:\n embedder(self._domain.sample_uniformly(num_seqs))\n expected_num_batches = int(np.ceil(num_seqs / batch_size))\n expected_call_shapes.extend([expected_batch_shape] * expected_num_batches)\n\n actual_call_shapes = [\n call[0][0].shape for call in embedder._embed_fn.call_args_list\n ]\n self.assertAllEqual(actual_call_shapes, expected_call_shapes)\n\n\nif __name__ == '__main__':\n absltest.main()\n"
] | [
[
"tensorflow.compat.v1.test.main"
],
[
"tensorflow.compat.v1.stop_gradient",
"tensorflow.compat.v1.math.multiply_no_nan",
"tensorflow.compat.v1.less",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.nn.avg_pool",
"tensorflow.compat.v1.to_float",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.split",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.abs",
"tensorflow.compat.v1.square",
"tensorflow.compat.v1.clip_by_value"
],
[
"numpy.array",
"numpy.ones",
"numpy.ceil"
]
] |
shanky1947/Air-Draw | [
"ab370f96384414ba5c4e369f5465cd8e28b4f3f0"
] | [
"Air Canvas (only)/Different Canvas Codes/detect1.py"
] | [
"# get hsv values using trackbar\nimport cv2\nimport numpy as np\nimport time\n\n# A required callback method that goes into the trackbar function.\ndef nothing(x):\n pass\n\n# Initializing the webcam feed.\ncap = cv2.VideoCapture(0)\ncap.set(3,1280)\ncap.set(4,720)\n\n# Create a window named trackbars.\ncv2.namedWindow(\"Trackbars\")\n\n# Now create 6 trackbars that will control the lower and upper range of \n# H,S and V channels. The Arguments are like this: Name of trackbar, \n# window name, range,callback function. For Hue the range is 0-179 and\n# for S,V its 0-255.\ncv2.createTrackbar(\"L - H\", \"Trackbars\", 0, 179, nothing)\ncv2.createTrackbar(\"L - S\", \"Trackbars\", 0, 255, nothing)\ncv2.createTrackbar(\"L - V\", \"Trackbars\", 0, 255, nothing)\ncv2.createTrackbar(\"U - H\", \"Trackbars\", 179, 179, nothing)\ncv2.createTrackbar(\"U - S\", \"Trackbars\", 255, 255, nothing)\ncv2.createTrackbar(\"U - V\", \"Trackbars\", 255, 255, nothing)\n \n \nwhile True:\n \n # Start reading the webcam feed frame by frame.\n ret, frame = cap.read()\n if not ret:\n break\n # Flip the frame horizontally (Not required)\n frame = cv2.flip( frame, 1 ) \n \n # Convert the BGR image to HSV image.\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n \n # Get the new values of the trackbar in real time as the user changes \n # them\n l_h = cv2.getTrackbarPos(\"L - H\", \"Trackbars\")\n l_s = cv2.getTrackbarPos(\"L - S\", \"Trackbars\")\n l_v = cv2.getTrackbarPos(\"L - V\", \"Trackbars\")\n u_h = cv2.getTrackbarPos(\"U - H\", \"Trackbars\")\n u_s = cv2.getTrackbarPos(\"U - S\", \"Trackbars\")\n u_v = cv2.getTrackbarPos(\"U - V\", \"Trackbars\")\n \n # Set the lower and upper HSV range according to the value selected\n # by the trackbar\n lower_range = np.array([l_h, l_s, l_v])\n upper_range = np.array([u_h, u_s, u_v])\n \n # Filter the image and get the binary mask, where white represents \n # your target color\n mask = cv2.inRange(hsv, lower_range, upper_range)\n \n # You can also visualize the real part of the target color (Optional)\n res = cv2.bitwise_and(frame, frame, mask=mask)\n \n # Converting the binary mask to 3 channel image, this is just so \n # we can stack it with the others\n mask_3 = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n \n # stack the mask, orginal frame and the filtered result\n stacked = np.hstack((mask_3,frame,res))\n \n # Show this stacked frame at 40% of the size.\n cv2.imshow('Trackbars',cv2.resize(stacked,None,fx=0.4,fy=0.4))\n \n # If the user presses ESC then exit the program\n key = cv2.waitKey(1)\n if key == 27:\n break\n \n # If the user presses `s` then print this array.\n if key == ord('s'):\n \n thearray = [[l_h,l_s,l_v],[u_h, u_s, u_v]]\n print(thearray)\n \n # Also save this array as penval.npy\n np.save('penval',thearray)\n break\n \n# Release the camera & destroy the windows. \ncap.release()\ncv2.destroyAllWindows()"
] | [
[
"numpy.array",
"numpy.save",
"numpy.hstack"
]
] |
123972/PCA-nutricion | [
"aff3c51a71c887c3fa367dbf9d599be5915c80cc",
"aff3c51a71c887c3fa367dbf9d599be5915c80cc"
] | [
"src/pca/todoJunto.py",
"environment/lib/python3.8/site-packages/sklearn/decomposition/tests/test_dict_learning.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n\nimport codecs\nimport sys\n\nimport sklearn as sk\nimport pandas as pd\nimport numpy as np \nimport math\n\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\n\nfrom src.pca.algoritmo_QR import eigenvectores_eigenvalores_QR_vf\nfrom src.pca.metodo_potencia_deflation import power_iteration\nfrom src.pca.metodo_potencia_deflation import power_deflation\n\n\ndef PCA_from_sklearn(X):\n \"\"\"\n componentes_principales(X): Función que devuelve las componentes principales.\n \n Parámetros\n ----------\n n_components: número de componentes. \n svd_solver: str {‘auto’, ‘full’, ‘arpack’, ‘randomized’}\n Se elige 'full', lo que significa que se ejecuta completamente SVD llamando al \n solucionador estándar LAPACK a través de scipy.linalg.svd y se seleccionan los componentes mediante postprocessing.\n \n Atributos\n ---------\n varianza_explicada: porcentaje de varianza explicada por cada componente.\n valores_singulares: valores singulares correspondientes a cada componente.\n pca.components_: ejes principales que representan las direcciones de máxima varianza en los datos.\n eigenvalues: son los valores propios utilizando la matriz de covarianza.\n \n Método\n ---------\n fit_transform: ajusta el modelo a los datos y aplica la reducción de dimensionalidad en los datos.\n \"\"\"\n X = pd.DataFrame(X)\n n_components = len(X.columns)\n pca_1 = PCA(n_components, svd_solver='full')\n componentesprincipales_1 = pca_1.fit_transform(X)\n pca_1.components_\n var_exp = pca_1.explained_variance_ratio_\n \n ##Se obtiene el número de componentes a través de la varianza explicada acumulada de los componentes, la cual debe sumar 60%.\n var_acumulada = var_exp.cumsum()\n conteo = (var_acumulada) < 0.8\n n_componentes = conteo.sum() + 1\n pca = PCA(n_componentes, svd_solver='full')\n componentesprincipales = pca.fit_transform(X)\n pca.components_\n varianza_explicada = pca.explained_variance_ratio_\n eigenvalues = pca.explained_variance_\n val_sing = pca.singular_values_\n \n return pca, varianza_explicada, componentesprincipales, val_sing, pca.components_, eigenvalues\n\n\ndef PCA_from_SVD(A):\n \"\"\"\n Función para PCA a partir de la SVD de numpy \n params: A\t\t\tmatriz de datos\n num_componentes \tnúmero de componentes deseados\n\n return: valores_singulares\tLos valores singulares de la descomposición SVD\n\t componentes\t\tLos coeficientes para calcular los componentes principales\n\t Z\t\t\tLos datos transformados (componentes principales)\n\t varianza_explicada\tLa varianza explicada por cada componente principal\n \"\"\"\n \n # Centrar los datos\n A = np.array(A) # convertir los datos a un numpy array por si vienen de un DataFrame\n A_centered = A - A.mean(axis=0)\n \n # Calcular SVD\n U, S, Vt = np.linalg.svd(A_centered, full_matrices=False)\n \n # Los valores singulares\n valores_singulares = S\n \n # Los componentes (coeficientes)\n componentes = ((Vt))\n \n # Los datos transformados (componentes principales)\n Z = A_centered@np.transpose(Vt)\n \n # La varianza explicada\n varianza_explicada = S**2/np.sum(S**2)\n \n # Calcula número de componentes de manera automatica de acuerdo a la variana explicada\n # Threshold de 60%\n n = A.shape[1] #numero de columnas\n varianza_acumulada = varianza_explicada.cumsum()\n conteo = (varianza_acumulada) < 0.8\n num_componentes = conteo.sum() + 1\n \n # regresar 4 objetos\n return valores_singulares[:num_componentes], componentes[:num_componentes], Z[:,:num_componentes], varianza_explicada[:num_componentes]\n\n\ndef PCA_from_SVD_jacobi(A):\n \"\"\"\n Función para PCA a partir de la SVD \n params: A\t\t\tmatriz de datos\n num_componentes \tnúmero de componentes deseados\n return: valores_singulares\tLos valores singulares de la descomposición SVD\n\t componentes\t\tLos coeficientes para calcular los componentes principales\n\t Z\t\t\tLos datos transformados (componentes principales)\n\t varianza_explicada\tLa varianza explicada por cada componente principal\n \"\"\"\n \n # Centrar los datos\n A = np.array(A) # convertir los datos a un numpy array por si vienen de un DataFrame\n A_centered = A - A.mean(axis=0)\n \n # Modificar esta línea de código, mandar a llamar la función creada por el equipo \n # Calcular SVD\n U, S, Vt = svd_jacobi_aprox(A_centered,1e-12,500)\n \n # Los valores singulares\n valores_singulares = S\n \n # Los componentes (coeficientes)\n componentes = ((Vt))\n \n # Los datos transformados (componentes principales)\n Z = A_centered@np.transpose(Vt)\n \n # La varianza explicada\n varianza_explicada = S**2/np.sum(S**2)\n \n # Calcula número de componentes de manera automatica de acuerdo a la variana explicada\n # Threshold de 60%\n n = A.shape[1] #numero de columnas\n varianza_acumulada = varianza_explicada.cumsum()\n conteo = (varianza_acumulada) < 0.8\n num_componentes = conteo.sum() + 1 \n \n # regresar 4 objetos\n return valores_singulares[:(num_componentes)], componentes[:(num_componentes)], Z[:,:(num_componentes)], varianza_explicada[:(num_componentes)]\n\n\ndef PCA_from_QR_vf(data,niter = 450):\n \"\"\"\n Función para PCA a partir de los eigenvectores \n params: data:\t\t\tmatriz de datos\n niter: número de iteraciones máximas \n \n \n return: componentes\t\tLos coeficientes para calcular los componentes principales (eigenvectores de la matriz de covarianzas)\n Z\t\t\tLos datos transformados (componentes principales)\n varianza_explicada\tLa varianza explicada por cada componente principal\n \n Depende de la función: eigenvectores_QR\n \"\"\"\n \n # convertir a array\n A = np.array(data)\n \n # Centrar los datos\n mean_vec = np.mean(A, axis=0)\n datos_centrados = (A - mean_vec)\n\n # Matriz de Covarianzas\n #C = (datos_centrados.T@datos_centrados)/(datos_centrados.shape[0]-1)\n C = (A - mean_vec).T.dot((A - mean_vec)) / (A.shape[0]-1)\n \n # Calcular algoritmo QR\n E, Q = eigenvectores_eigenvalores_QR_vf(C,niter)\n \n \n # Los componentes (coeficientes)\n componentes = Q.T\n \n # Los datos transformados (componentes principales)\n # Aquí marcaba error al filtrar porque no se reconocia a Z como numpy array\n Z = datos_centrados@Q\n \n # La varianza explicada\n varianza_explicada = E/np.sum(E)\n \n # Calcula número de componentes de manera automatica de acuerdo a la variana explicada\n # Threshold de 60%\n n = data.shape[1] #numero de columnas\n varianza_acumulada = varianza_explicada.cumsum()\n conteo = (varianza_acumulada) < 0.8\n num_componentes = conteo.sum() + 1\n \n # regresar 4 objetos\n return E[:num_componentes], componentes[:num_componentes], Z[:,:num_componentes], varianza_explicada[:num_componentes] #, varianza_acumulada, num_componentes\n\ndef PCA_from_potencia(X):\n \"\"\"\n Función que calcula PCA a partir del método de la potencia y deflation de Hotteling \n params: A:\t\t\tmatriz de datos\n \n \n return: eigenvalues\t\tNumpy array con los eigenvectores de A\n eigenvectors\tNumpy array con los correspondientes eigenvectores de A \n \n \"\"\"\n \n prop = 0 # Proporción de varianza explicada\n comp = 1 \n cur_var = 0\n comp_vecs = np.zeros([X.shape[1], X.shape[1]])\n \n # convertir a array\n A = np.array(X)\n \n # Centrar los datos\n mean_vec = np.mean(A, axis=0)\n datos_centrados = (A - mean_vec)\n \n #Calculamos la matriz de covarianzas\n cov = np.dot(X.T, X)/X.shape[0]\n \n #Aplicamos el método de la potencia\n evalues_pow, evectors_pow = power_deflation(cov,2000)\n \n # La varianza explicada\n varianza_explicada = evalues_pow/np.sum(evalues_pow)\n \n # Los datos transformados (componentes principales)\n Z = datos_centrados@evectors_pow\n \n \n # Calcula número de componentes de manera automatica de acuerdo a la variana explicada\n # Threshold de 80%\n n = X.shape[1] #numero de columnas\n varianza_acumulada = varianza_explicada.cumsum()\n conteo = (varianza_acumulada) < 0.8\n num_componentes = conteo.sum() + 1\n \n return evalues_pow[:num_componentes], evectors_pow.T[:num_componentes], Z[:,:num_componentes], varianza_explicada[:num_componentes]",
"import pytest\n\nimport numpy as np\nimport itertools\n\nfrom sklearn.exceptions import ConvergenceWarning\n\nfrom sklearn.utils import check_array\n\nfrom sklearn.utils._testing import assert_array_almost_equal\nfrom sklearn.utils._testing import assert_array_equal\nfrom sklearn.utils._testing import ignore_warnings\nfrom sklearn.utils._testing import TempMemmap\n\nfrom sklearn.decomposition import DictionaryLearning\nfrom sklearn.decomposition import MiniBatchDictionaryLearning\nfrom sklearn.decomposition import SparseCoder\nfrom sklearn.decomposition import dict_learning\nfrom sklearn.decomposition import dict_learning_online\nfrom sklearn.decomposition import sparse_encode\n\n\nrng_global = np.random.RandomState(0)\nn_samples, n_features = 10, 8\nX = rng_global.randn(n_samples, n_features)\n\n\ndef test_sparse_encode_shapes_omp():\n rng = np.random.RandomState(0)\n algorithms = ['omp', 'lasso_lars', 'lasso_cd', 'lars', 'threshold']\n for n_components, n_samples in itertools.product([1, 5], [1, 9]):\n X_ = rng.randn(n_samples, n_features)\n dictionary = rng.randn(n_components, n_features)\n for algorithm, n_jobs in itertools.product(algorithms, [1, 3]):\n code = sparse_encode(X_, dictionary, algorithm=algorithm,\n n_jobs=n_jobs)\n assert code.shape == (n_samples, n_components)\n\n\ndef test_dict_learning_shapes():\n n_components = 5\n dico = DictionaryLearning(n_components, random_state=0).fit(X)\n assert dico.components_.shape == (n_components, n_features)\n\n n_components = 1\n dico = DictionaryLearning(n_components, random_state=0).fit(X)\n assert dico.components_.shape == (n_components, n_features)\n assert dico.transform(X).shape == (X.shape[0], n_components)\n\n\ndef test_dict_learning_overcomplete():\n n_components = 12\n dico = DictionaryLearning(n_components, random_state=0).fit(X)\n assert dico.components_.shape == (n_components, n_features)\n\n\ndef test_max_iter():\n def ricker_function(resolution, center, width):\n \"\"\"Discrete sub-sampled Ricker (Mexican hat) wavelet\"\"\"\n x = np.linspace(0, resolution - 1, resolution)\n x = ((2 / (np.sqrt(3 * width) * np.pi ** .25))\n * (1 - (x - center) ** 2 / width ** 2)\n * np.exp(-(x - center) ** 2 / (2 * width ** 2)))\n return x\n\n def ricker_matrix(width, resolution, n_components):\n \"\"\"Dictionary of Ricker (Mexican hat) wavelets\"\"\"\n centers = np.linspace(0, resolution - 1, n_components)\n D = np.empty((n_components, resolution))\n for i, center in enumerate(centers):\n D[i] = ricker_function(resolution, center, width)\n D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis]\n return D\n\n transform_algorithm = 'lasso_cd'\n resolution = 1024\n subsampling = 3 # subsampling factor\n n_components = resolution // subsampling\n\n # Compute a wavelet dictionary\n D_multi = np.r_[tuple(ricker_matrix(width=w, resolution=resolution,\n n_components=n_components // 5)\n for w in (10, 50, 100, 500, 1000))]\n\n X = np.linspace(0, resolution - 1, resolution)\n first_quarter = X < resolution / 4\n X[first_quarter] = 3.\n X[np.logical_not(first_quarter)] = -1.\n X = X.reshape(1, -1)\n\n # check that the underlying model fails to converge\n with pytest.warns(ConvergenceWarning):\n model = SparseCoder(D_multi, transform_algorithm=transform_algorithm,\n transform_max_iter=1)\n model.fit_transform(X)\n\n # check that the underlying model converges w/o warnings\n with pytest.warns(None) as record:\n model = SparseCoder(D_multi, transform_algorithm=transform_algorithm,\n transform_max_iter=2000)\n model.fit_transform(X)\n assert not record.list\n\n\ndef test_dict_learning_lars_positive_parameter():\n n_components = 5\n alpha = 1\n err_msg = \"Positive constraint not supported for 'lars' coding method.\"\n with pytest.raises(ValueError, match=err_msg):\n dict_learning(X, n_components, alpha=alpha, positive_code=True)\n\n\n@pytest.mark.parametrize(\"transform_algorithm\", [\n \"lasso_lars\",\n \"lasso_cd\",\n \"threshold\",\n])\n@pytest.mark.parametrize(\"positive_code\", [False, True])\n@pytest.mark.parametrize(\"positive_dict\", [False, True])\ndef test_dict_learning_positivity(transform_algorithm,\n positive_code,\n positive_dict):\n n_components = 5\n dico = DictionaryLearning(\n n_components, transform_algorithm=transform_algorithm, random_state=0,\n positive_code=positive_code, positive_dict=positive_dict,\n fit_algorithm=\"cd\").fit(X)\n\n code = dico.transform(X)\n if positive_dict:\n assert (dico.components_ >= 0).all()\n else:\n assert (dico.components_ < 0).any()\n if positive_code:\n assert (code >= 0).all()\n else:\n assert (code < 0).any()\n\n\n@pytest.mark.parametrize(\"positive_dict\", [False, True])\ndef test_dict_learning_lars_dict_positivity(positive_dict):\n n_components = 5\n dico = DictionaryLearning(\n n_components, transform_algorithm=\"lars\", random_state=0,\n positive_dict=positive_dict, fit_algorithm=\"cd\").fit(X)\n\n if positive_dict:\n assert (dico.components_ >= 0).all()\n else:\n assert (dico.components_ < 0).any()\n\n\ndef test_dict_learning_lars_code_positivity():\n n_components = 5\n dico = DictionaryLearning(\n n_components, transform_algorithm=\"lars\", random_state=0,\n positive_code=True, fit_algorithm=\"cd\").fit(X)\n\n err_msg = \"Positive constraint not supported for '{}' coding method.\"\n err_msg = err_msg.format(\"lars\")\n with pytest.raises(ValueError, match=err_msg):\n dico.transform(X)\n\n\ndef test_dict_learning_reconstruction():\n n_components = 12\n dico = DictionaryLearning(n_components, transform_algorithm='omp',\n transform_alpha=0.001, random_state=0)\n code = dico.fit(X).transform(X)\n assert_array_almost_equal(np.dot(code, dico.components_), X)\n\n dico.set_params(transform_algorithm='lasso_lars')\n code = dico.transform(X)\n assert_array_almost_equal(np.dot(code, dico.components_), X, decimal=2)\n\n # used to test lars here too, but there's no guarantee the number of\n # nonzero atoms is right.\n\n\ndef test_dict_learning_reconstruction_parallel():\n # regression test that parallel reconstruction works with n_jobs>1\n n_components = 12\n dico = DictionaryLearning(n_components, transform_algorithm='omp',\n transform_alpha=0.001, random_state=0, n_jobs=4)\n code = dico.fit(X).transform(X)\n assert_array_almost_equal(np.dot(code, dico.components_), X)\n\n dico.set_params(transform_algorithm='lasso_lars')\n code = dico.transform(X)\n assert_array_almost_equal(np.dot(code, dico.components_), X, decimal=2)\n\n\ndef test_dict_learning_lassocd_readonly_data():\n n_components = 12\n with TempMemmap(X) as X_read_only:\n dico = DictionaryLearning(n_components, transform_algorithm='lasso_cd',\n transform_alpha=0.001, random_state=0,\n n_jobs=4)\n with ignore_warnings(category=ConvergenceWarning):\n code = dico.fit(X_read_only).transform(X_read_only)\n assert_array_almost_equal(np.dot(code, dico.components_), X_read_only,\n decimal=2)\n\n\ndef test_dict_learning_nonzero_coefs():\n n_components = 4\n dico = DictionaryLearning(n_components, transform_algorithm='lars',\n transform_n_nonzero_coefs=3, random_state=0)\n code = dico.fit(X).transform(X[np.newaxis, 1])\n assert len(np.flatnonzero(code)) == 3\n\n dico.set_params(transform_algorithm='omp')\n code = dico.transform(X[np.newaxis, 1])\n assert len(np.flatnonzero(code)) == 3\n\n\ndef test_dict_learning_unknown_fit_algorithm():\n n_components = 5\n dico = DictionaryLearning(n_components, fit_algorithm='<unknown>')\n with pytest.raises(ValueError):\n dico.fit(X)\n\n\ndef test_dict_learning_split():\n n_components = 5\n dico = DictionaryLearning(n_components, transform_algorithm='threshold',\n random_state=0)\n code = dico.fit(X).transform(X)\n dico.split_sign = True\n split_code = dico.transform(X)\n\n assert_array_almost_equal(split_code[:, :n_components] -\n split_code[:, n_components:], code)\n\n\ndef test_dict_learning_online_shapes():\n rng = np.random.RandomState(0)\n n_components = 8\n code, dictionary = dict_learning_online(X, n_components=n_components,\n alpha=1, random_state=rng)\n assert code.shape == (n_samples, n_components)\n assert dictionary.shape == (n_components, n_features)\n assert np.dot(code, dictionary).shape == X.shape\n\n\ndef test_dict_learning_online_lars_positive_parameter():\n alpha = 1\n err_msg = \"Positive constraint not supported for 'lars' coding method.\"\n with pytest.raises(ValueError, match=err_msg):\n dict_learning_online(X, alpha=alpha, positive_code=True)\n\n\n@pytest.mark.parametrize(\"transform_algorithm\", [\n \"lasso_lars\",\n \"lasso_cd\",\n \"threshold\",\n])\n@pytest.mark.parametrize(\"positive_code\", [False, True])\n@pytest.mark.parametrize(\"positive_dict\", [False, True])\ndef test_minibatch_dictionary_learning_positivity(transform_algorithm,\n positive_code,\n positive_dict):\n n_components = 8\n dico = MiniBatchDictionaryLearning(\n n_components, transform_algorithm=transform_algorithm, random_state=0,\n positive_code=positive_code, positive_dict=positive_dict,\n fit_algorithm='cd').fit(X)\n\n code = dico.transform(X)\n if positive_dict:\n assert (dico.components_ >= 0).all()\n else:\n assert (dico.components_ < 0).any()\n if positive_code:\n assert (code >= 0).all()\n else:\n assert (code < 0).any()\n\n\n@pytest.mark.parametrize(\"positive_dict\", [False, True])\ndef test_minibatch_dictionary_learning_lars(positive_dict):\n n_components = 8\n\n dico = MiniBatchDictionaryLearning(\n n_components, transform_algorithm=\"lars\", random_state=0,\n positive_dict=positive_dict, fit_algorithm='cd').fit(X)\n\n if positive_dict:\n assert (dico.components_ >= 0).all()\n else:\n assert (dico.components_ < 0).any()\n\n\n@pytest.mark.parametrize(\"positive_code\", [False, True])\n@pytest.mark.parametrize(\"positive_dict\", [False, True])\ndef test_dict_learning_online_positivity(positive_code,\n positive_dict):\n rng = np.random.RandomState(0)\n n_components = 8\n\n code, dictionary = dict_learning_online(X, n_components=n_components,\n method=\"cd\",\n alpha=1, random_state=rng,\n positive_dict=positive_dict,\n positive_code=positive_code)\n if positive_dict:\n assert (dictionary >= 0).all()\n else:\n assert (dictionary < 0).any()\n if positive_code:\n assert (code >= 0).all()\n else:\n assert (code < 0).any()\n\n\ndef test_dict_learning_online_verbosity():\n n_components = 5\n # test verbosity\n from io import StringIO\n import sys\n\n old_stdout = sys.stdout\n try:\n sys.stdout = StringIO()\n dico = MiniBatchDictionaryLearning(n_components, n_iter=20, verbose=1,\n random_state=0)\n dico.fit(X)\n dico = MiniBatchDictionaryLearning(n_components, n_iter=20, verbose=2,\n random_state=0)\n dico.fit(X)\n dict_learning_online(X, n_components=n_components, alpha=1, verbose=1,\n random_state=0)\n dict_learning_online(X, n_components=n_components, alpha=1, verbose=2,\n random_state=0)\n finally:\n sys.stdout = old_stdout\n\n assert dico.components_.shape == (n_components, n_features)\n\n\ndef test_dict_learning_online_estimator_shapes():\n n_components = 5\n dico = MiniBatchDictionaryLearning(n_components, n_iter=20, random_state=0)\n dico.fit(X)\n assert dico.components_.shape == (n_components, n_features)\n\n\ndef test_dict_learning_online_overcomplete():\n n_components = 12\n dico = MiniBatchDictionaryLearning(n_components, n_iter=20,\n random_state=0).fit(X)\n assert dico.components_.shape == (n_components, n_features)\n\n\ndef test_dict_learning_online_initialization():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features)\n dico = MiniBatchDictionaryLearning(n_components, n_iter=0,\n dict_init=V, random_state=0).fit(X)\n assert_array_equal(dico.components_, V)\n\n\ndef test_dict_learning_online_readonly_initialization():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features)\n V.setflags(write=False)\n MiniBatchDictionaryLearning(n_components, n_iter=1, dict_init=V,\n random_state=0, shuffle=False).fit(X)\n\n\ndef test_dict_learning_online_partial_fit():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n dict1 = MiniBatchDictionaryLearning(n_components, n_iter=10 * len(X),\n batch_size=1,\n alpha=1, shuffle=False, dict_init=V,\n random_state=0).fit(X)\n dict2 = MiniBatchDictionaryLearning(n_components, alpha=1,\n n_iter=1, dict_init=V,\n random_state=0)\n for i in range(10):\n for sample in X:\n dict2.partial_fit(sample[np.newaxis, :])\n\n assert not np.all(sparse_encode(X, dict1.components_, alpha=1) == 0)\n assert_array_almost_equal(dict1.components_, dict2.components_,\n decimal=2)\n\n\ndef test_sparse_encode_shapes():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n for algo in ('lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'):\n code = sparse_encode(X, V, algorithm=algo)\n assert code.shape == (n_samples, n_components)\n\n\n@pytest.mark.parametrize(\"algo\", [\n 'lasso_lars',\n 'lasso_cd',\n 'threshold'\n])\n@pytest.mark.parametrize(\"positive\", [False, True])\ndef test_sparse_encode_positivity(algo, positive):\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n code = sparse_encode(X, V, algorithm=algo, positive=positive)\n if positive:\n assert (code >= 0).all()\n else:\n assert (code < 0).any()\n\n\n@pytest.mark.parametrize(\"algo\", ['lars', 'omp'])\ndef test_sparse_encode_unavailable_positivity(algo):\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n err_msg = \"Positive constraint not supported for '{}' coding method.\"\n err_msg = err_msg.format(algo)\n with pytest.raises(ValueError, match=err_msg):\n sparse_encode(X, V, algorithm=algo, positive=True)\n\n\ndef test_sparse_encode_input():\n n_components = 100\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n Xf = check_array(X, order='F')\n for algo in ('lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'):\n a = sparse_encode(X, V, algorithm=algo)\n b = sparse_encode(Xf, V, algorithm=algo)\n assert_array_almost_equal(a, b)\n\n\ndef test_sparse_encode_error():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n code = sparse_encode(X, V, alpha=0.001)\n assert not np.all(code == 0)\n assert np.sqrt(np.sum((np.dot(code, V) - X) ** 2)) < 0.1\n\n\ndef test_sparse_encode_error_default_sparsity():\n rng = np.random.RandomState(0)\n X = rng.randn(100, 64)\n D = rng.randn(2, 64)\n code = ignore_warnings(sparse_encode)(X, D, algorithm='omp',\n n_nonzero_coefs=None)\n assert code.shape == (100, 2)\n\n\ndef test_unknown_method():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n with pytest.raises(ValueError):\n sparse_encode(X, V, algorithm=\"<unknown>\")\n\n\ndef test_sparse_coder_estimator():\n n_components = 12\n rng = np.random.RandomState(0)\n V = rng.randn(n_components, n_features) # random init\n V /= np.sum(V ** 2, axis=1)[:, np.newaxis]\n code = SparseCoder(dictionary=V, transform_algorithm='lasso_lars',\n transform_alpha=0.001).transform(X)\n assert not np.all(code == 0)\n assert np.sqrt(np.sum((np.dot(code, V) - X) ** 2)) < 0.1\n\n\ndef test_sparse_coder_parallel_mmap():\n # Non-regression test for:\n # https://github.com/scikit-learn/scikit-learn/issues/5956\n # Test that SparseCoder does not error by passing reading only\n # arrays to child processes\n\n rng = np.random.RandomState(777)\n n_components, n_features = 40, 64\n init_dict = rng.rand(n_components, n_features)\n # Ensure that `data` is >2M. Joblib memory maps arrays\n # if they are larger than 1MB. The 4 accounts for float32\n # data type\n n_samples = int(2e6) // (4 * n_features)\n data = np.random.rand(n_samples, n_features).astype(np.float32)\n\n sc = SparseCoder(init_dict, transform_algorithm='omp', n_jobs=2)\n sc.fit_transform(data)\n\n\ndef test_sparse_coder_n_features_in():\n d = np.array([[1, 2, 3], [1, 2, 3]])\n sc = SparseCoder(d)\n assert sc.n_features_in_ == d.shape[1]\n"
] | [
[
"numpy.sum",
"numpy.transpose",
"numpy.zeros",
"sklearn.decomposition.PCA",
"pandas.DataFrame",
"numpy.linalg.svd",
"numpy.array",
"numpy.dot",
"numpy.mean"
],
[
"numpy.sum",
"sklearn.utils._testing.TempMemmap",
"numpy.random.RandomState",
"sklearn.utils._testing.assert_array_equal",
"sklearn.decomposition.dict_learning_online",
"numpy.logical_not",
"numpy.random.rand",
"sklearn.decomposition.sparse_encode",
"numpy.linspace",
"numpy.flatnonzero",
"sklearn.utils._testing.assert_array_almost_equal",
"numpy.sqrt",
"sklearn.decomposition.SparseCoder",
"numpy.all",
"sklearn.utils._testing.ignore_warnings",
"sklearn.decomposition.MiniBatchDictionaryLearning",
"sklearn.decomposition.DictionaryLearning",
"numpy.empty",
"sklearn.utils.check_array",
"numpy.exp",
"sklearn.decomposition.dict_learning",
"numpy.array",
"numpy.dot"
]
] |
mnabavi84/dcamp-intro-python | [
"218b67106061d45cfa18a1b1d46487900f9aa539"
] | [
"11-Numpy Basic Statistics.py"
] | [
"# np_baseball is available\r\n\r\n# Import numpy\r\nimport numpy as np\r\n\r\n# Create np_height_in from np_baseball\r\nnp_height_in = np_baseball[:,0]\r\n\r\n# Print out the mean of np_height_in\r\nprint(np.mean(np_height_in))\r\n\r\n# Print out the median of np_height_in\r\nprint(np.median(np_height_in))\r\n\r\n\r\n# np_baseball is available\r\n\r\n# Import numpy\r\nimport numpy as np\r\n\r\n# Print mean height (first column)\r\navg = np.mean(np_baseball[:,0])\r\nprint(\"Average: \" + str(avg))\r\n\r\n# Print median height. Replace 'None'\r\nmed = np.median(np_baseball[:,0])\r\nprint(\"Median: \" + str(med))\r\n\r\n# Print out the standard deviation on height. Replace 'None'\r\nstddev = np.std(np_baseball[:,0])\r\nprint(\"Standard Deviation: \" + str(stddev))\r\n\r\n# Print out correlation between first and second column. Replace 'None'\r\ncorr = np.corrcoef(np_baseball[:,0], np_baseball[:,1])\r\nprint(\"Correlation: \" + str(corr))\r\n\r\n\r\n# heights and positions are available as lists\r\n\r\n# Import numpy\r\nimport numpy as np\r\n\r\n# Convert positions and heights to numpy arrays: np_positions, np_heights\r\nnp_positions = np.array(positions)\r\nnp_heights = np.array(heights)\r\n\r\n# Heights of the goalkeepers: gk_heights\r\ngk_heights = np_heights[np_positions == 'GK']\r\n\r\n# Heights of the other players: other_heights\r\nother_heights = np_heights[np_positions != 'GK']\r\n\r\n# Print out the median height of goalkeepers. Replace 'None'\r\nprint(\"Median height of goalkeepers: \" + str(np.median(gk_heights)))\r\n\r\n# Print out the median height of other players. Replace 'None'\r\nprint(\"Median height of other players: \" + str(np.median(other_heights)))\r\n"
] | [
[
"numpy.median",
"numpy.array",
"numpy.std",
"numpy.mean",
"numpy.corrcoef"
]
] |
kili-technology/active-learning | [
"72dce7d91b988264dd7fa1a972d9af45e9648c4c"
] | [
"experiments/mnist_simple/class_imbalance.py"
] | [
"import os\nimport logging\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport al\nfrom al.dataset import mnist\nfrom al.model.model_zoo.simple_cnn import ConvModel\nfrom al.model.mnist import MnistLearner\nfrom al.dataset.mnist import MnistDataset\nfrom al.train.active_train import ActiveTrain\nfrom al.helpers.experiment import set_up_experiment, load_config\nfrom al.experiments import set_up_learner\n\n\nDATASET = 'mnist'\n\nFOLDER_PATH = os.path.dirname(__file__)\nOUTPUT_DIR, FIGURE_DIR, logger, logger_name = set_up_experiment(\n __file__, FOLDER_PATH, logging_lvl=20)\n\nlogger.info('-------------------------')\nlogger.info('--LAUNCHING EXPERIMENTS--')\nlogger.info('-------------------------')\n\nconfig = load_config(FOLDER_PATH, DATASET)\nsetupper = set_up_learner(DATASET)\n\nconfig['active_learning']['output_dir'] = OUTPUT_DIR\nconfig['experiment']['logger_name'] = logger_name\nmodel_name = 'simple_cnn'\n\nstrategies = ['random_sampling', 'margin_sampling']\nrepeats = 1\nscore_data = {}\nconfig['active_learning']['assets_per_query'] = 20\nconfig['active_learning']['n_iter'] = 5\nconfig['active_learning']['init_size'] = 100\n\nconfig['train_parameters']['batch_size'] = 16\nconfig['train_parameters']['iterations'] = 100\n\nconfig['experiment']['n_classes'] = 2\n\nraw_dataset, _ = setupper(config, OUTPUT_DIR, logger,\n index_train=np.arange(60000))\nfull_train_dataset = raw_dataset.dataset\n\nfirst_class = 1\nsecond_class = 2\nfirst_classes = []\nsecond_classes = []\np = 0.1\n\nfor i in range(len(full_train_dataset)):\n if full_train_dataset[i][1].numpy() == first_class:\n first_classes.append(i)\n elif full_train_dataset[i][1].numpy() == second_class and np.random.rand() < p:\n second_classes.append(i)\n\ntrain_indices = np.array(first_classes + second_classes)\nnp.random.permutation(train_indices)\n\nfor i in range(repeats):\n logger.info('---------------------------')\n logger.info(f'--------ROUND OF TRAININGS NUMBER #{i+1}--------')\n logger.info('---------------------------')\n for strategy in strategies:\n dataset, learner = setupper(\n config, OUTPUT_DIR, logger, index_train=train_indices)\n logger.info('---------------------------')\n logger.info(f'----STRATEGY : {strategy}----')\n logger.info('---------------------------')\n trainer = ActiveTrain(learner, dataset, strategy, logger_name)\n scores = trainer.train(\n config['train_parameters'], **config['active_learning'])\n score_data[(strategy, i)] = scores\n logger.info(f'----DONE----\\n')\n logger.info('---------------------------')\n logger.info(f'--------DONE--------')\n logger.info('---------------------------\\n\\n\\n')\n\n\n# data = []\n# for (strategy, experiment_number), scores_experiment in score_data.items():\n# for step_result in scores_experiment:\n# val_step_result = step_result['val']\n# step = step_result['step']\n# data.append(\n# {'strategy': strategy,\n# 'experiment': experiment_number,\n# 'step': step,\n# **val_step_result})\n# df = pd.DataFrame(data)\n\n# plot_dir = os.path.join(os.path.dirname(__file__), 'figures')\n\n# plt.figure(num=0, figsize=(12, 5))\n# sns.lineplot(x='step', y='accuracy', hue='strategy', data=df)\n# plt.ylabel('Accuracy')\n# plt.show()\n# plt.savefig(os.path.join(plot_dir, 'accuracy_imbalance.png'))\n"
] | [
[
"numpy.array",
"numpy.arange",
"numpy.random.permutation",
"numpy.random.rand"
]
] |
yuancaimaiyi/gtsfm | [
"cc5781c35af23498d45cd96a1818e4786c5cca80"
] | [
"gtsfm/common/gtsfm_data.py"
] | [
"\"\"\"Class to hold the tracks and cameras of a 3D scene.\nThis can be the output of either data association or of bundle adjustment.\n\nAuthors: Ayush Baid, John Lambert, Xiaolong Wu\n\"\"\"\nimport itertools\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport numpy as np\nfrom gtsam import PinholeCameraCal3Bundler, Pose3, SfmTrack\n\nimport gtsfm.utils.graph as graph_utils\nimport gtsfm.utils.logger as logger_utils\nimport gtsfm.utils.reprojection as reproj_utils\n\nlogger = logger_utils.get_logger()\n\nEQUALITY_TOLERANCE = 1e-5\nPRINT_NUM_SIG_FIGS = 2\n\n\nclass GtsfmData:\n \"\"\"Class containing cameras and tracks, essentially describing the complete 3D scene.\n\n This class is needed over GTSAM's SfmData type because GTSAM's type does not allow for non-contiguous cameras.\n The situation of non-contiguous cameras can exists because of failures in front-end.\n \"\"\"\n\n def __init__(self, number_images: int) -> None:\n \"\"\"Initializes the class.\n\n Args:\n number_images: number of images/cameras in the scene.\n \"\"\"\n self._cameras: Dict[int, PinholeCameraCal3Bundler] = {}\n self._tracks: List[SfmTrack] = []\n self._number_images = number_images\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Checks equality with the other object.\"\"\"\n\n if not isinstance(other, GtsfmData):\n return False\n\n if self._number_images != other.number_images():\n return False\n\n for i, cam in self._cameras.items():\n other_cam = other.get_camera(i)\n if not cam.equals(other_cam, EQUALITY_TOLERANCE):\n return False\n\n for j in range(self.number_tracks()):\n track = self.get_track(j)\n other_track = other.get_track(j)\n\n if track.number_measurements() != other_track.number_measurements():\n return False\n\n for k in range(track.number_measurements()):\n i, uv = track.measurement(k)\n other_i, other_uv = other_track.measurement(k)\n\n if i != other_i:\n return False\n if not np.allclose(uv, other_uv):\n return False\n\n return True\n\n def number_images(self) -> int:\n \"\"\"Getter for the number of images.\n\n Returns:\n Number of images.\n \"\"\"\n return self._number_images\n\n def number_tracks(self) -> int:\n \"\"\"Getter for the number of tracks.\n\n Returns:\n Number of tracks.\n \"\"\"\n return len(self._tracks)\n\n def get_valid_camera_indices(self) -> List[int]:\n \"\"\"Getter for image indices where there is a valid (not None) camera.\n\n Returns:\n List of indices with a valid camera.\n \"\"\"\n return list(self._cameras.keys())\n\n def get_camera(self, index: int) -> Optional[PinholeCameraCal3Bundler]:\n \"\"\"Getter for camera.\n\n Args:\n index: the image index to fetch the camera for.\n\n Returns:\n The camera if it is a valid one, None otherwise.\n \"\"\"\n return self._cameras.get(index)\n\n def get_camera_poses(self) -> List[Optional[Pose3]]:\n \"\"\"Getter for camera poses wTi.\n\n This function returns the pose for all cameras (equal to number_images in GtsfmData), even if they were not\n computed by the pipeline.\n\n Returns:\n camera poses as a list, each representing wTi\n \"\"\"\n cameras = [self.get_camera(i) for i in range(self.number_images())]\n poses = [camera.pose() if camera is not None else None for camera in cameras]\n\n return poses\n\n def get_track(self, index: int) -> SfmTrack:\n \"\"\"Getter for the track.\n\n Args:\n index: track index to fetch.\n\n Returns:\n Requested track.\n \"\"\"\n return self._tracks[index]\n\n def add_track(self, track: SfmTrack) -> bool:\n \"\"\"Add a track, after checking if all the cameras in the track are already added.\n\n Args:\n track: track to add.\n\n Returns:\n Flag indicating the success of adding operation.\n \"\"\"\n # check if all cameras are already added\n for j in range(track.number_measurements()):\n i, _ = track.measurement(j)\n\n if i not in self._cameras:\n return False\n\n self._tracks.append(track)\n return True\n\n def add_camera(self, index: int, camera: PinholeCameraCal3Bundler) -> None:\n \"\"\"Adds a camera.\n\n Args:\n index: the index associated with this camera.\n camera: camera object to it.\n\n Raises:\n ValueError: if the camera to be added is not a valid camera object.\n \"\"\"\n if camera is None:\n raise ValueError(\"Camera cannot be None, should be a valid camera\")\n self._cameras[index] = camera\n\n def get_track_length_statistics(self) -> Tuple[float, float]:\n \"\"\"Compute mean and median lengths of all the tracks.\n\n Returns:\n Mean track length.\n Median track length.\n \"\"\"\n if self.number_tracks() == 0:\n return 0, 0\n\n track_lengths = self.get_track_lengths()\n return np.mean(track_lengths), np.median(track_lengths)\n\n def get_track_lengths(self) -> np.ndarray:\n \"\"\"Get an array containing the lengths of all tracks.\n\n Returns:\n Array containing all track lengths.\n \"\"\"\n if self.number_tracks() == 0:\n return np.array([], dtype=np.uint32)\n\n track_lengths = [self.get_track(j).number_measurements() for j in range(self.number_tracks())]\n return np.array(track_lengths, dtype=np.uint32)\n\n def select_largest_connected_component(self) -> \"GtsfmData\":\n \"\"\"Selects the subset of data belonging to the largest connected component of the graph where the edges are\n between cameras which feature in the same track.\n\n Returns:\n New GtSfmData object with the subset of tracks and cameras.\n \"\"\"\n camera_edges = []\n for sfm_track in self._tracks:\n cameras_in_use = []\n for m_idx in range(sfm_track.number_measurements()):\n i, _ = sfm_track.measurement(m_idx)\n cameras_in_use.append(i)\n\n # Recreate track connectivity from track information\n # For example: a track has cameras [0, 2, 5]. In that case we will add pairs (0, 2), (0, 5), (2, 5)\n camera_edges += list(itertools.combinations(cameras_in_use, 2))\n\n if len(camera_edges) == 0:\n return GtsfmData(self._number_images)\n\n cameras_in_largest_cc = graph_utils.get_nodes_in_largest_connected_component(camera_edges)\n logger.info(\n \"Largest connected component contains {} of {} cameras returned by front-end (of {} total imgs)\".format(\n len(cameras_in_largest_cc), len(self.get_valid_camera_indices()), self._number_images\n )\n )\n return GtsfmData.from_selected_cameras(self, cameras_in_largest_cc)\n\n @classmethod\n def from_selected_cameras(cls, gtsfm_data: \"GtsfmData\", camera_indices: List[int]) -> \"GtsfmData\":\n \"\"\"Selects the cameras in the input list and the tracks associated with those cameras.\n\n Args:\n gtsfm_data: data to pick the cameras from.\n camera_indices: camera indices to select and keep in the new data.\n\n Returns:\n New object with the selected cameras and associated tracks.\n \"\"\"\n new_data = cls(gtsfm_data.number_images())\n\n for i in gtsfm_data.get_valid_camera_indices():\n if i in camera_indices:\n new_data.add_camera(i, gtsfm_data.get_camera(i))\n\n new_camera_indices = new_data.get_valid_camera_indices()\n\n # add tracks which have all the camera present in new data\n for j in range(gtsfm_data.number_tracks()):\n track = gtsfm_data.get_track(j)\n is_valid = True\n for k in range(track.number_measurements()):\n i, _ = track.measurement(k)\n if i not in new_camera_indices:\n is_valid = False\n break\n if is_valid:\n new_data.add_track(track)\n\n return new_data\n\n def get_scene_reprojection_errors(self) -> np.ndarray:\n \"\"\"Get the scene reprojection errors for all 3D points and all associated measurements.\n\n Returns:\n Reprojection errors as a 1D numpy array.\n \"\"\"\n scene_reproj_errors: List[float] = []\n for track in self._tracks:\n track_errors, _ = reproj_utils.compute_track_reprojection_errors(self._cameras, track)\n scene_reproj_errors.extend(track_errors)\n\n return np.array(scene_reproj_errors)\n\n\n def aggregate_metrics(self) -> Dict[str, Any]:\n \"\"\"Aggregate metrics about the reprojection errors and 3d track lengths (summary stats).\n\n Args:\n ba_data: bundle adjustment result\n\n Returns:\n dictionary containing metrics of bundle adjustment result\n \"\"\"\n track_lengths_3d = self.get_track_lengths()\n scene_reproj_errors = self.get_scene_reprojection_errors()\n\n convert_to_rounded_float = lambda x: float(np.round(x, 3))\n\n stats_dict = {}\n stats_dict[\"number_tracks\"] = self.number_tracks()\n stats_dict[\"3d_track_lengths\"] = {\n \"min\": convert_to_rounded_float(track_lengths_3d.min()),\n \"mean\": convert_to_rounded_float(np.mean(track_lengths_3d)),\n \"median\": convert_to_rounded_float(np.median(track_lengths_3d)),\n \"max\": convert_to_rounded_float(track_lengths_3d.max()),\n }\n stats_dict[\"reprojection_errors\"] = {\n \"min\": convert_to_rounded_float(np.min(scene_reproj_errors)),\n \"mean\": convert_to_rounded_float(np.mean(scene_reproj_errors)),\n \"median\": convert_to_rounded_float(np.median(scene_reproj_errors)),\n \"max\": convert_to_rounded_float(np.max(scene_reproj_errors)),\n }\n return stats_dict\n\n def get_avg_scene_reprojection_error(self) -> float:\n \"\"\"Get average reprojection error for all 3d points in the entire scene\n\n Returns:\n Average of reprojection errors for every 3d point to its 2d measurements\n \"\"\"\n scene_reproj_errors = self.get_scene_reprojection_errors()\n scene_avg_reproj_error = np.mean(scene_reproj_errors)\n return scene_avg_reproj_error\n\n def log_scene_reprojection_error_stats(self) -> None:\n \"\"\"Logs reprojection error stats for all 3d points in the entire scene.\"\"\"\n scene_reproj_errors = self.get_scene_reprojection_errors()\n logger.info(\"Min scene reproj error: %.3f\", np.min(scene_reproj_errors))\n logger.info(\"Avg scene reproj error: %.3f\", np.mean(scene_reproj_errors))\n logger.info(\"Median scene reproj error: %.3f\", np.median(scene_reproj_errors))\n logger.info(\"Max scene reproj error: %.3f\", np.max(scene_reproj_errors))\n\n def __validate_track(self, track: SfmTrack, reproj_err_thresh: float) -> bool:\n \"\"\"Validates a track based on reprojection errors and cheirality checks.\n\n Args:\n track: track with 3D landmark and measurements.\n reproj_err_thresh: reprojection err threshold for each measurement.\n\n Returns:\n validity of the track.\n \"\"\"\n errors, avg_reproj_error = reproj_utils.compute_track_reprojection_errors(self._cameras, track)\n # track is valid as all measurements have error below the threshold\n cheirality_success = np.all(~np.isnan(errors))\n return np.all(errors < reproj_err_thresh) and cheirality_success\n\n def filter_landmarks(self, reproj_err_thresh: float = 5) -> \"GtsfmData\":\n \"\"\"Filters out landmarks with high reprojection error\n\n Args:\n reproj_err_thresh: reprojection err threshold for each measurement.\n \"\"\"\n # TODO: move this function to utils or GTSAM\n filtered_data = GtsfmData(self.number_images())\n\n # add all the cameras\n for i in self.get_valid_camera_indices():\n filtered_data.add_camera(i, self.get_camera(i))\n\n for j in range(self.number_tracks()):\n track = self.get_track(j)\n\n if self.__validate_track(track, reproj_err_thresh):\n filtered_data.add_track(track)\n\n return filtered_data\n"
] | [
[
"numpy.allclose",
"numpy.median",
"numpy.max",
"numpy.all",
"numpy.min",
"numpy.isnan",
"numpy.array",
"numpy.round",
"numpy.mean"
]
] |
EmergentSystemLabStudent/Prosodic-DAA | [
"068af5db337ed977c059e788353414d3aa9a8ac8"
] | [
"prosodic_daa/sample/pyhlm_sample_murakami.py"
] | [
"import os\nimport numpy as np\nfrom pyhlm.model import WeakLimitHDPHLM, WeakLimitHDPHLMPython\nfrom pyhlm.internals.hlm_states import WeakLimitHDPHLMStates\nfrom pyhlm.word_model import LetterHSMM, LetterHSMMPython\nimport pyhsmm\nimport warnings\nfrom tqdm import trange\nwarnings.filterwarnings('ignore')\nimport time\n\n#%%\ndef load_datas(dataset_dir):\n data = []\n names = np.loadtxt(dataset_dir + \"files.txt\", dtype=str)\n files = names\n for name in names:\n mfcc = np.loadtxt(dataset_dir + \"DATA/\" + name + \".txt\")\n delta = np.loadtxt(dataset_dir + \"DATA/\" + name + \"_d.txt\")\n delta_delta = np.loadtxt(dataset_dir + \"DATA/\" + name + \"_dd.txt\")\n data.append(np.hstack((mfcc, np.hstack((delta,delta_delta)))))\n return data\n\ndef unpack_durations(dur):\n unpacked = np.zeros(dur.sum())\n d = np.cumsum(dur[:-1])\n unpacked[d-1] = 1.0\n return unpacked\n\ndef save_stateseq(model, dataset_dir):\n # Save sampled states sequences.\n names = np.loadtxt(dataset_dir + \"files.txt\", dtype=str)\n for i, s in enumerate(model.states_list):\n with open(\"results/\" + names[i] + \"_s.txt\", \"a\") as f:\n np.savetxt(f, s.stateseq)\n with open(\"results/\" + names[i] + \"_l.txt\", \"a\") as f:\n np.savetxt(f, s.letter_stateseq)\n with open(\"results/\" + names[i] + \"_d.txt\", \"a\") as f:\n np.savetxt(f, unpack_durations(s.durations_censored))\n\ndef save_params(itr_idx, model):\n with open(\"parameters/ITR_{0:04d}.txt\".format(itr_idx), \"w\") as f:\n f.write(str(model.params))\n\ndef save_loglikelihood(model):\n with open(\"summary_files/log_likelihood.txt\", \"a\") as f:\n f.write(str(model.log_likelihood()) + \"\\n\")\n\ndef save_resample_times(resample_time):\n with open(\"summary_files/resample_times.txt\", \"a\") as f:\n f.write(str(resample_time) + \"\\n\")\n\n\n#%%\nif not os.path.exists('results'):\n os.mkdir('results')\n\nif not os.path.exists('parameters'):\n os.mkdir('parameters')\n\nif not os.path.exists('summary_files'):\n os.mkdir('summary_files')\n\n#%%\ndataset_dir = \"murakami_dataset/\"\n\n#%%\nthread_num = 64\npre_train_iter = 1\ntrain_iter = 100\ntrunc = 120\nobs_dim = 9\nletter_upper = 50\nword_upper = 50\nmodel_hypparams = {'num_states': word_upper, 'alpha': 10, 'gamma': 10, 'init_state_concentration': 10}\nobs_hypparams = {\n 'mu_0':np.zeros(obs_dim),\n 'sigma_0':np.identity(obs_dim),\n 'kappa_0':0.01,\n 'nu_0':obs_dim+2\n}\ndur_hypparams = {\n 'alpha_0':200,\n 'beta_0':10\n}\n\n#%%\nletter_obs_distns = [pyhsmm.distributions.Gaussian(**obs_hypparams) for state in range(letter_upper)]\nletter_dur_distns = [pyhsmm.distributions.PoissonDuration(**dur_hypparams) for state in range(letter_upper)]\ndur_distns = [pyhsmm.distributions.PoissonDuration(lmbda=20) for state in range(word_upper)]\nlength_distn = pyhsmm.distributions.PoissonDuration(alpha_0=30, beta_0=10, lmbda=3)\n\n#%%\nletter_hsmm = LetterHSMM(alpha=10, gamma=10, init_state_concentration=10, obs_distns=letter_obs_distns, dur_distns=letter_dur_distns)\nmodel = WeakLimitHDPHLM(model_hypparams, letter_hsmm, dur_distns, length_distn)\n\n#%%\nfiles = np.loadtxt(dataset_dir + \"files.txt\", dtype=str)\ndatas = load_datas(dataset_dir)\n\n#%% Pre training.\nfor d in datas:\n letter_hsmm.add_data(d, trunc=trunc)\nfor t in trange(pre_train_iter):\n letter_hsmm.resample_model(num_procs=1)\nletter_hsmm.states_list = []\n\n#%%\nprint(\"Add datas...\")\nfor d in datas:\n model.add_data(d, trunc=trunc, generate=False)\nmodel.resample_states(num_procs=thread_num)\n# # or\n# for d in datas:\n# model.add_data(d, trunc=trunc, initialize_from_prior=False)\nprint(\"Done!\")\n\n#%% Save init params and pyper params\nwith open(\"parameters/hypparams.txt\", \"w\") as f:\n f.write(str(model.hypparams))\nsave_params(0, model)\nsave_loglikelihood(model)\n\n#%%\nfor t in trange(train_iter):\n st = time.time()\n model.resample_model(num_procs=thread_num)\n resample_model_time = time.time() - st\n save_stateseq(model, dataset_dir)\n save_loglikelihood(model)\n save_params(t+1, model)\n save_resample_times(resample_model_time)\n print(model.word_list)\n print(model.word_counts())\n print(\"log_likelihood:{}\".format(model.log_likelihood()))\n print(\"resample_model:{}\".format(resample_model_time))\n"
] | [
[
"numpy.cumsum",
"numpy.zeros",
"numpy.savetxt",
"numpy.hstack",
"numpy.identity",
"numpy.loadtxt"
]
] |
trojanjay/sfa-numpy | [
"bff5737ef429f31228d20a9e1d0ce7d46d3080d3"
] | [
"examples/modal_beamforming_open_circular_array.py"
] | [
"\"\"\"\n Compute the plane wave decomposition for an incident broadband plane wave\n on an open circular array using a modal beamformer of finite order.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport micarray\nfrom micarray.util import db\n\nNsf = 50 # order of the incident sound field\nN = 30 # order of modal beamformer/microphone array\npw_angle = 1.23 * np.pi # incidence angle of plane wave\npol_pwd = np.linspace(0, 2*np.pi, 180, endpoint=False) # angles for plane wave decomposition\nk = np.linspace(0, 20, 100) # wavenumber vector\nr = 1 # radius of array\n\n# get uniform grid (microphone positions) of order N\npol, weights = micarray.modal.angular.grid_equal_polar_angle(N)\n\n# pressure on the surface of an open cylinder for an incident plane wave\nBn = micarray.modal.radial.circular_pw(Nsf, k, r, setup='open')\nD = micarray.modal.radial.circ_diagonal_mode_mat(Bn)\nPsi_p = micarray.modal.angular.cht_matrix(Nsf, pol)\nPsi_pw = micarray.modal.angular.cht_matrix(Nsf, pw_angle)\np = np.matmul(np.matmul(Psi_p, D), np.conj(Psi_pw.T))\np = np.squeeze(p)\n\n# incident plane wave exhibiting infinite spatial bandwidth\n# p = np.exp(1j * k[:, np.newaxis]*r * np.cos(pol - pw_angle))\n\n# plane wave decomposition using modal beamforming\nBn = micarray.modal.radial.circular_pw(N, k, r, setup='open')\nDn, _ = micarray.modal.radial.regularize(1/Bn, 3000, 'softclip')\nD = micarray.modal.radial.circ_diagonal_mode_mat(Dn)\nPsi_p = micarray.modal.angular.cht_matrix(N, pol, weights)\nPsi_q = micarray.modal.angular.cht_matrix(N, pol_pwd)\nA_pwd = np.matmul(np.matmul(Psi_q, D), np.conj(Psi_p.T))\nq_pwd = np.squeeze(np.matmul(A_pwd, np.expand_dims(p, 2)))\nq_pwd_t = np.fft.fftshift(np.fft.irfft(q_pwd, axis=0), axes=0)\n\n# visualize plane wave decomposition (aka beampattern)\nplt.figure()\nplt.pcolormesh(k, pol_pwd/np.pi, db(q_pwd.T), vmin=-40)\nplt.colorbar()\nplt.xlabel(r'$kr$')\nplt.ylabel(r'$\\phi / \\pi$')\nplt.title('Plane wave docomposition by modal beamformer (frequency domain)')\nplt.savefig('modal_beamforming_open_circular_array_fd.png')\n\nplt.figure()\nplt.pcolormesh(range(2*len(k)-2), pol_pwd/np.pi, db(q_pwd_t.T), vmin=-40)\nplt.colorbar()\nplt.ylabel(r'$\\phi / \\pi$')\nplt.title('Plane wave docomposition by modal beamformer (time domain)')\nplt.savefig('modal_beamforming_open_circular_array_td.png')\n"
] | [
[
"numpy.matmul",
"numpy.squeeze",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"numpy.conj",
"numpy.fft.irfft",
"matplotlib.pyplot.title",
"numpy.expand_dims",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.colorbar",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
uclyyu/over9000 | [
"9e2e0aa4be9da941372a21ea627c38a3eb7be617"
] | [
"ralamb.py"
] | [
"import torch, math\nfrom torch.optim.optimizer import Optimizer\n\n# RAdam + LARS\nclass Ralamb(Optimizer):\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):\n defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)\n self.buffer = [[None, None, None] for ind in range(10)]\n super(Ralamb, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Ralamb, self).__setstate__(state)\n\n def step(self, closure=None):\n\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data.float()\n if grad.is_sparse:\n raise RuntimeError('Ralamb does not support sparse gradients')\n\n p_data_fp32 = p.data.float()\n\n state = self.state[p]\n\n if len(state) == 0:\n state['step'] = 0\n state['exp_avg'] = torch.zeros_like(p_data_fp32)\n state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)\n else:\n state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)\n state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['betas']\n\n # Decay the first and second moment running average coefficient\n # m_t\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n # v_t\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n\n state['step'] += 1\n buffered = self.buffer[int(state['step'] % 10)]\n\n if state['step'] == buffered[0]:\n N_sma, radam_step_size = buffered[1], buffered[2]\n else:\n buffered[0] = state['step']\n beta2_t = beta2 ** state['step']\n N_sma_max = 2 / (1 - beta2) - 1\n N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)\n buffered[1] = N_sma\n\n # more conservative since it's an approximated value\n if N_sma >= 5:\n radam_step_size = math.sqrt((1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (N_sma_max - 2)) / (1 - beta1 ** state['step'])\n else:\n radam_step_size = 1.0 / (1 - beta1 ** state['step'])\n buffered[2] = radam_step_size\n\n if group['weight_decay'] != 0:\n p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)\n\n # more conservative since it's an approximated value\n radam_step = p_data_fp32.clone()\n if N_sma >= 5:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n radam_step.addcdiv_(-radam_step_size * group['lr'], exp_avg, denom)\n else:\n radam_step.add_(-radam_step_size * group['lr'], exp_avg)\n\n radam_norm = radam_step.pow(2).sum().sqrt()\n weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)\n if weight_norm == 0 or radam_norm == 0:\n trust_ratio = 1\n else:\n trust_ratio = weight_norm / radam_norm\n\n state['weight_norm'] = weight_norm\n state['adam_norm'] = radam_norm\n state['trust_ratio'] = trust_ratio\n\n if N_sma >= 5:\n p_data_fp32.addcdiv_(-radam_step_size * group['lr'] * trust_ratio, exp_avg, denom)\n else:\n p_data_fp32.add_(-radam_step_size * group['lr'] * trust_ratio, exp_avg)\n\n p.data.copy_(p_data_fp32)\n\n return loss\n"
] | [
[
"torch.zeros_like"
]
] |
micbia/tools21cm | [
"72081e94e4d83511380baacce427d79d13da2fa5"
] | [
"t2c/segmentation.py"
] | [
"\"\"\"\nCreated by Michele Bianco, 9 July 2021\n\"\"\"\n\nimport numpy as np, pkg_resources\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras import backend as K\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.framework import ops \nfrom tensorflow.python.ops import array_ops \nfrom tensorflow.python.ops import math_ops \n\ndef sigmoid_balanced_cross_entropy_with_logits(_sentinel=None, labels=None, logits=None, beta=None, name=None):\n nn_ops._ensure_xent_args(\"sigmoid_cross_entropy_with_logits\", _sentinel,labels, logits)\n with ops.name_scope(name, \"logistic_loss\", [logits, labels]) as name: \n logits = ops.convert_to_tensor(logits, name=\"logits\") \n labels = ops.convert_to_tensor(labels, name=\"labels\") \n try:\n labels.get_shape().merge_with(logits.get_shape())\n except ValueError:\n raise ValueError(\"logits and labels must have the same shape (%s vs %s)\" %(logits.get_shape(), labels.get_shape())) \n zeros = array_ops.zeros_like(logits, dtype=logits.dtype) \n cond = (logits >= zeros) \n relu_logits = array_ops.where(cond, logits, zeros) \n neg_abs_logits = array_ops.where(cond, -logits, logits) \n balanced_cross_entropy = relu_logits*(1.-beta)-logits*labels*(1.-beta)+math_ops.log1p(math_ops.exp(neg_abs_logits))*((1.-beta)*(1.-labels)+beta*labels)\n return tf.reduce_mean(balanced_cross_entropy)\n\ndef balanced_cross_entropy(y_true, y_pred):\n \"\"\"\n To decrease the number of false negatives, set beta>1. To decrease the number of false positives, set beta<1.\n \"\"\"\n beta = tf.maximum(tf.reduce_mean(1 - y_true), tf.keras.backend.epsilon())\n y_pred = tf.clip_by_value(y_pred, tf.keras.backend.epsilon(), 1 - tf.keras.backend.epsilon())\n y_pred = K.log(y_pred / (1 - y_pred))\n return sigmoid_balanced_cross_entropy_with_logits(logits=y_pred, labels=y_true, beta=beta)\n\n\ndef iou(y_true, y_pred):\n \"\"\"\n Return the Intersection over Union (IoU) for a given label.\n Args:\n y_true: the expected y values as a one-hot\n y_pred: the predicted y values as a one-hot or softmax output\n label: the label to return the IoU for\n Returns:\n the IoU for the given label\n \"\"\"\n\n intersection = K.sum(K.abs(y_true * y_pred))\n #intersection = K.sum(y_true * y_pred)\n union = K.sum(y_true) + K.sum(y_pred) - intersection\n # avoid divide by zero - if the union is zero, return 1, otherwise, return the intersection over union\n return K.switch(K.equal(union, 0), 1.0, intersection / union)\n\n\ndef dice_coef(y_true, y_pred, smooth=1):\n \"\"\"\n Dice = (2*|X & Y|)/ (|X|+ |Y|)\n = 2*sum(|A*B|)/(sum(A^2)+sum(B^2))\n ref: https://arxiv.org/pdf/1606.04797v1.pdf\n \"\"\"\n intersection = K.sum(K.abs(y_true * y_pred), axis=-1)\n return (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + K.sum(K.square(y_pred),-1) + smooth)\n\n\n\n################################################################\n\nclass segunet21cm:\n def __init__(self, tta=1, verbose=False):\n \"\"\" SegU-Net: segmentation of 21cm images with U-shape network (Bianco et al. 2021, https://arxiv.org/abs/2102.06713)\n - tta (int): default 0 (super-fast, no pixel-error map) implement the error map\n with time-test aumentated techique in the prediction process\n - verbose (bool): default False, activate verbosity\n \n Description:\n tta = 0 : fast (~7 sec), it tends to be a few percent less accurate (<2%) then the other two cases, no pixel-error map (no TTA manipulation)\n tta = 1 : medium (~17 sec), accurate and preferable than tta=0, with pixel-error map (3 samples)\n tta = 2 : slow (~10 min), accurate, with pixel-error map (~100 samples)\n \n Returns:\n - X_seg (ndarray) : recovered binary field (1 = neutral and 0 = ionized regions)\n - X_err (ndarray) : pixel-error map of the recovered binary field\n \n Example:\n $ from tools21cm import segmentation\n $ seg = segmentation.segunet21cm(tta=1, verbose=True) # load model (need to be done once)\n $ Xseg, Xseg_err = seg.prediction(x=dT3)\n\n Print of the Network's Configuration file:\n [TRAINING]\n BATCH_SIZE = 64\n AUGMENT = NOISESMT\n IMG_SHAPE = 128, 128\n CHAN_SIZE = 256\n DROPOUT = 0.05\n KERNEL_SIZE = 3\n EPOCHS = 100\n LOSS = balanced_cross_entropy\n METRICS = iou, dice_coef, binary_accuracy, binary_crossentropy\n LR = 1e-3\n RECOMP = False\n GPUS = 2\n PATH = /home/michele/Documents/PhD_Sussex/output/ML/dataset/inputs/data2D_128_030920/\n \n [RESUME]\n RESUME_PATH = /home/michele/Documents/PhD_Sussex/output/ML/dataset/outputs/new/02-10T23-52-36_128slice/\n BEST_EPOCH = 56\n RESUME_EPOCH = 66\n\n \"\"\"\n self.TTA = tta\n self.VERBOSE = verbose\n\n if(self.TTA == 2):\n # slow\n self.MANIP = self.IndependentOperations(verbose=self.VERBOSE)\n elif(self.TTA == 1):\n # fast\n self.MANIP = {'opt0': [lambda a: a, 0, 0]}\n elif(self.TTA == 0):\n # super-fast\n self.MANIP = {'opt0': [lambda a: a, 0, 0]}\n \n self.NR_MANIP = len(self.MANIP)\n\n # load model\n MODEL_NAME = pkg_resources.resource_filename('t2c', 'input_data/segunet_02-10T23-52-36_128slice_ep56.h5')\n if (os.path.exists(MODEL_NAME)):\n pass\n else:\n if(self.VERBOSE): print(' Download network weights: %s' %MODEL_NAME)\n\n MODEL_EPOCH = 56\n METRICS = {'balanced_cross_entropy':balanced_cross_entropy, 'iou':iou, 'dice_coef':dice_coef} \n self.MODEL_LOADED = load_model(MODEL_NAME, custom_objects=METRICS)\n \n if(self.VERBOSE): print(' Loaded model: %s' %MODEL_NAME)\n\n def UniqueRows(self, arr):\n \"\"\" Remove duplicate row array in 2D data \n - arr (narray): array with duplicate row\n \n Example:\n >> d = np.array([[0,1,2],[0,1,2],[0,0,0],[0,0,2],[0,1,2]])\n >> UniqueRows(d) \n \n array([[0, 0, 0],\n [0, 0, 2],\n [0, 1, 2]])\n \"\"\"\n arr = np.array(arr)\n\n if(arr.ndim == 2):\n arr = np.ascontiguousarray(arr)\n unique_arr = np.unique(arr.view([('', arr.dtype)]*arr.shape[1]))\n new_arr = unique_arr.view(arr.dtype).reshape((unique_arr.shape[0], arr.shape[1]))\n elif(arr.ndim == 1):\n new_arr = np.array(list(dict.fromkeys(arr)))\n\n return new_arr\n\n\n def IndependentOperations(self, verbose=False):\n ''' How many unique manipulations (horzontal and vertical flip, rotation, etc...) \n can we operate on a cube? \n Each indipendent operation is considered as an additional rappresentation\n of the same coeval data, so that it can be considered for errorbar with SegU-Net '''\n\n data = np.array(range(3**3)).reshape((3,3,3)) \n\n func = [lambda a: a,\n np.fliplr, \n np.flipud, \n lambda a: np.flipud(np.fliplr(a)),\n lambda a: np.fliplr(np.flipud(a))]\n axis = [0,1,2] \n angl_rot = [0,1,2,3] \n\n\n tot_manipl_data_flat = np.zeros((len(func)*len(axis)*len(angl_rot), data.size)) \n tot_operations = {'opt%d' %k:[] for k in range(0,len(func)*len(axis)*len(angl_rot))} \n\n i = 0 \n for f in func: \n cube = f(data)\n for rotax in axis: \n ax_tup = [0,1,2] \n ax_tup.remove(rotax)\n for rot in angl_rot:\n tot_manipl_data_flat[i] = np.rot90(cube, k=rot, axes=ax_tup).flatten() \n # function, axis of rotation, angle of rotation, slice index\n tot_operations['opt%d' %i] = [f, rotax, rot] \n i += 1 \n\n uniq_manipl_data_flat = self.UniqueRows(tot_manipl_data_flat).astype(int)\n uniq_operations = {}\n\n for iumdf, uniq_mdf in enumerate(uniq_manipl_data_flat):\n for itmdf, tot_mdf in enumerate(tot_manipl_data_flat):\n if(all(uniq_mdf == tot_mdf)):\n uniq_operations['opt%d' %iumdf] = tot_operations['opt%d' %itmdf]\n break\n \n assert uniq_manipl_data_flat.shape[0] == len(uniq_operations)\n if(verbose): print('tot number of (unique) manipulation we can do on a cube: %d' %(len(uniq_operations)))\n\n return uniq_operations\n\n\n def prediction(self, x):\n img_shape = x.shape\n if(self.TTA == 2):\n X_tta = np.zeros((np.append(3*len(self.MANIP), img_shape)))\n elif(self.TTA == 1):\n X_tta = np.zeros((np.append(3*len(self.MANIP), img_shape)))\n elif(self.TTA == 0):\n X_tta = np.zeros((np.append(len(self.MANIP), img_shape)))\n \n if(self.VERBOSE):\n loop = tqdm(range(len(self.MANIP)))\n else:\n loop = range(len(self.MANIP))\n\n for iopt in loop:\n opt, rotax, rot = self.MANIP['opt%d' %iopt]\n ax_tup = [0,1,2] \n ax_tup.remove(rotax)\n\n cube = np.rot90(opt(x), k=rot, axes=ax_tup) \n X = cube[np.newaxis, ..., np.newaxis]\n\n for j in range(img_shape[0]):\n if(self.TTA == 0):\n X_tta[iopt,j,:,:] = self.MODEL_LOADED.predict(X[:,j,:,:,:], verbose=0).squeeze()\n else:\n X_tta[iopt,j,:,:] = self.MODEL_LOADED.predict(X[:,j,:,:,:], verbose=0).squeeze()\n X_tta[iopt+len(self.MANIP),:,j,:] = self.MODEL_LOADED.predict(X[:,:,j,:,:], verbose=0).squeeze()\n X_tta[iopt+len(self.MANIP)*2,:,:,j] = self.MODEL_LOADED.predict(X[:,:,:,j,:], verbose=0).squeeze()\n\n for itta in range(X_tta.shape[0]):\n opt, rotax, rot = self.MANIP['opt%d' %(itta%len(self.MANIP))]\n ax_tup = [0,1,2] \n ax_tup.remove(rotax)\n X_tta[itta] = opt(np.rot90(X_tta[itta], k=-rot, axes=ax_tup))\n\n X_seg = np.round(np.mean(X_tta, axis=0))\n X_err = np.std(X_tta, axis=0)\n\n return X_seg, X_err\n"
] | [
[
"tensorflow.keras.backend.sum",
"tensorflow.keras.backend.log",
"tensorflow.keras.backend.epsilon",
"tensorflow.python.ops.nn_ops._ensure_xent_args",
"numpy.ascontiguousarray",
"numpy.fliplr",
"numpy.mean",
"tensorflow.keras.backend.abs",
"numpy.std",
"tensorflow.python.framework.ops.convert_to_tensor",
"numpy.flipud",
"tensorflow.keras.models.load_model",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.reduce_mean",
"tensorflow.keras.backend.square",
"tensorflow.python.framework.ops.name_scope",
"numpy.rot90",
"tensorflow.python.ops.array_ops.where",
"tensorflow.keras.backend.equal",
"numpy.array",
"tensorflow.python.ops.math_ops.exp"
]
] |
jrobertojunior/face-parsing.PyTorch | [
"d34f39c9ae9726ac8eaf39ecff824a14ec4e15b9"
] | [
"preprocessing/main.py"
] | [
"import cv2 as cv\nimport numpy as np\nimport os\n\ndef preprocess(labels_path, sep_labels_path):\n # list all files on labels_path\n labels_filenames = os.listdir(labels_path)\n\n count = 0\n for label_filename in labels_filenames:\n label_path = os.path.join(labels_path, label_filename)\n\n print(f'segmenting {label_filename}')\n masks = segment_labels(label_path)\n\n for att in masks:\n mask = masks[att]\n path = f\"{sep_labels_path}/{label_filename[:-4]}_{att}.png\"\n print(f'{count} - writing {path}')\n cv.imwrite(path, mask)\n\n count += 1\n # cv.imwrite(f'{label_filename[:-4]}_{mask}', mask)\n\n\ndef segment_labels(label_path):\n atts = {\n \"background\": (0, 0, 0),\n \"mouth\": (255, 0, 0),\n \"eyes\": (0, 255, 0),\n \"nose\": (0, 0, 255),\n \"face\": (128, 128, 128),\n \"hair\": (255, 255, 0),\n \"eyebrows\": (255, 0, 255),\n \"ears\": (0, 255, 255),\n \"teeth\": (255, 255, 255),\n \"beard\": (255, 192, 192),\n \"sunglasses\": (0, 128, 128),\n }\n\n label = cv.imread(label_path)\n mask = np.zeros(label.shape, dtype=np.uint8)\n\n masks = {}\n\n for att in atts:\n color = atts[att]\n\n mask = cv.inRange(label, color, color)\n masks[att] = mask\n # cv.imshow(att, mask)\n # cv.waitKey(0)\n\n # cv.imwrite(f\"{sep_labels_path}/{label_path[:-4]}_{att}.png\", mask)\n\n return masks\n\n\n# separate_masks(\"./labels.png\")\npreprocess(\"./organized_dataset/labels\", \"./organized_dataset/segmented_labels\")\n"
] | [
[
"numpy.zeros"
]
] |
Principe92/contextualbandits | [
"43cf5be10b3d39d74f9da5c5fe1cfae5bc2dd6f5"
] | [
"example/loc3/rewards.py"
] | [
"import pandas\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as st\nfrom pylab import rcParams\n\n\ndf = pandas.read_csv('rewards_loc3.csv')\n\nucb,ts,ovr,egr,egr2,agr,agr2,efr,ac,aac,sft = df['ucb'],df['ts'],df['ovr'],\\\ndf['egr'],df['egr2'],df['agr'],df['agr2'],df['efr'],df['ac'],df['aac'],df['sft']\n\n#y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11 = np.mean(ucb), np.mean(ts) \\\n#,np.mean(ovr), np.mean(egr), np.mean(egr2) \\\n#,np.mean(agr), np.mean(agr2), np.mean(efr) \\\n#,np.mean(ac), np.mean(aac), np.mean(sft)\n\ndef get_mean_reward(reward_lst):\n mean_rew=list()\n for r in range(len(reward_lst)):\n mean_rew.append(sum(reward_lst[:r+1]) / ((r+1)))\n return mean_rew\n\ny1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11 = get_mean_reward(ucb), get_mean_reward(ts) \\\n,get_mean_reward(ovr), get_mean_reward(egr), get_mean_reward(egr2) \\\n,get_mean_reward(agr), get_mean_reward(agr2), get_mean_reward(efr) \\\n,get_mean_reward(ac), get_mean_reward(aac), get_mean_reward(sft)\n\nx1, x2 = [index for index in range(len(ucb))], [index for index in range(len(ts))]\nx3, x4 = [index for index in range(len(df['ovr']))], [index for index in range(len(df['egr']))]\nx5, x6 = [index for index in range(len(df['egr2']))], [index for index in range(len(df['agr']))]\nx7, x8 = [index for index in range(len(df['agr2']))], [index for index in range(len(df['efr']))]\nx9, x10 = [index for index in range(len(df['ac']))], [index for index in range(len(df['aac']))]\nx11 = [index for index in range(len(df['sft']))]\n\n\ndef CI_model(y, confidence = 0.95):\n std_err_y = st.sem(y)\n n_y = len(y)\n h_y = std_err_y * st.t.ppf((1 + confidence) / 2, n_y - 1)\n return h_y\n\nh_y1, h_y2, h_y3, h_y4, h_y5, h_y6, h_y7, h_y8, h_y9, h_y10, h_y11 = CI_model(ucb), CI_model(ts), CI_model(ovr),\\\nCI_model(egr), CI_model(egr2), CI_model(agr), CI_model(agr2), CI_model(efr), CI_model(ac), CI_model(aac), CI_model(sft)\nplt.errorbar(x1, y1, yerr= h_y1, label='Bootstrapped Upper-Confidence Bound (C.I.=80%)')\nplt.errorbar(x2, y2, yerr= h_y2, label='Bootstrapped Thompson Sampling')\nplt.errorbar(x3, y3, yerr= h_y3, label='Separate Classifiers + Beta Prior')\nplt.errorbar(x4, y4, yerr= h_y4, label='Epsilon-Greedy (p0=20%, decay=0.9999')\nplt.errorbar(x5, y5, yerr= h_y5, label='Epsilon-Greedy (p0=20%, no decay')\nplt.errorbar(x6, y6, yerr= h_y6, label='Adaptive Greedy (decaying threshold)')\nplt.errorbar(x7, y7, yerr= h_y7, label='Adaptive Greedy (p0=30%, decaying percentile)')\nplt.errorbar(x8, y8, yerr= h_y8, label='Explore First (n=1,500)')\nplt.errorbar(x9, y9, yerr= h_y9, label='Active Explorer')\nplt.errorbar(x10, y10, yerr= h_y10, label='Adaptive Active Greedy')\nplt.errorbar(x11, y11, yerr= h_y11, label='Softmax Explorer')\n#plt.plot(np.repeat(y.mean(axis=0).max(),len(rewards_sft)),linewidth=4,ls='dashed', label='Overall Best Arm (no context)')\n\nax = plt.subplot(111)\n\n\nplt.xlabel('Rounds (models were updated every 50 rounds)', size=10)\nplt.ylabel('Cummulative Mean Reward', size=10)\nplt.title('Comparison of Online Contextual Bandit Policies in location 3')\n# Shrink current axis by 20%\nbox = ax.get_position()\nax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n# Put a legend to the right of the current axis\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nplt.savefig(\"location_3.png\", bbox_inches='tight', dpi = 600)\n"
] | [
[
"scipy.stats.t.ppf",
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"scipy.stats.sem",
"matplotlib.pyplot.title",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
]
] |
Jesmine0902/TSP_CPLEX_2 | [
"8853d6837bd5408b8925eb5f45e21c79945a5904"
] | [
"Add/add_heuristic_engine.py"
] | [
"import pandas as pd\n\n__author__ = 'slei'\n\n\nclass AddHeuristicTSP:\n \"\"\" Finds the shortest path using a heuristic method \"\"\"\n\n def __init__(self, cities_df):\n self.df = cities_df\n self.edges = list((t.origin, t.destination) for t in df.itertuples())\n self.distance = dict([((t.origin, t.destination), t.distance) for t in df.itertuples()])\n self.cities = list(set(df['destination']))\n self.cities_lst = []\n self.tour_lst = []\n self.distance_lst = []\n self.tour_leg_distances_lst = []\n self._final_df = None\n self._shortest_distance = None\n self._shortest_tour = None\n\n def find_subtour(self, starting_city):\n \"\"\" Given a starting city, finds a tour by selecting next shortest distance from list of unvisited cities \"\"\"\n tour = []\n tour_distance_lst = [0]\n cities_unvisited = list(set(self.df['destination']))\n initial_city = starting_city\n current_city = initial_city\n tour.append(current_city)\n cities_unvisited.pop(0)\n total_distance = 0\n count = 0\n\n while len(cities_unvisited) > 0:\n # remove any city that has already been visited from consideration\n df_unvisited = self.df[self.df['destination'].isin(cities_unvisited)]\n\n # filter for rows based on first criterion\n is_current = df_unvisited['origin'] == current_city\n df2 = df_unvisited[is_current]\n\n # find the nearest city\n index_min = df2['distance'].idxmin()\n min_row = df2.loc[index_min]\n d = min_row.distance\n destination = min_row.destination\n\n # update next city and tour and total distance\n current_city = destination\n total_distance = total_distance + d\n tour_distance_lst.append(d)\n\n # update city tracker lists\n tour.append(current_city)\n index_i = cities_unvisited.index(current_city)\n cities_unvisited.pop(index_i)\n count = count + 1\n\n # check\n print(\"next destination: \", destination)\n print(\"distance: \", d)\n print(\"total_distance: \", total_distance)\n print(\"tour: \", tour)\n print(\"tour_distance_lst: \", tour_distance_lst)\n print(\"cities_unvisited: \", cities_unvisited)\n print()\n\n # adding the distance from last city back to initial city\n last_city = tour[-1]\n last_mile = (initial_city, last_city)\n last_mile_distance = self.distance[last_mile]\n tour.append(initial_city)\n total_distance = total_distance + last_mile_distance\n tour_distance_lst.append(last_mile_distance)\n\n # check\n print(\"last_mile: \", last_mile)\n print(\"last_mile_distance: \", last_mile_distance)\n print(\"tour: \", tour)\n print(\"total_distance: \", total_distance)\n print(\"tour_leg_distances_lst: \", tour_distance_lst)\n\n # update lists\n self.tour_lst.append(tour)\n self.distance_lst.append(total_distance)\n self.tour_leg_distances_lst.append(tour_distance_lst)\n\n @property\n def final_df(self):\n \"\"\" Add description here\"\"\"\n if self._final_df is None:\n self._final_df = self._generate_final_df()\n return self._final_df\n\n def _generate_final_df(self):\n for c in self.cities: # for every city in the dataset\n print(\"city: \", c) # generate a tour for each\n print(\"--------------------------------------------------------------------------------\")\n self.find_subtour(c)\n print('********************************************************************************')\n print()\n\n soln_dict = {'city': self.cities, 'tour': self.tour_lst, 'tour_leg_distances': self.tour_leg_distances_lst,\n 'distance': self.distance_lst}\n return pd.DataFrame(soln_dict)\n\n @property\n def shortest_distance(self):\n \"\"\" Add description here\"\"\"\n if self._shortest_distance is None:\n return self._calculate_shortest_distance()\n\n def _calculate_shortest_distance(self): # find the tour with the lowest distance\n index_min_final = self.final_df['distance'].idxmin() # returns the index location of min value\n min_row_final = self.final_df.loc[index_min_final]\n return min_row_final.distance\n\n @property\n def shortest_tour(self):\n \"\"\" Add description here\"\"\"\n if self._shortest_tour is None:\n return self._generate_shortest_tour()\n\n def _generate_shortest_tour(self):\n index_min_final = self.final_df['distance'].idxmin() # returns the index location of min value\n min_row_final = self.final_df.loc[index_min_final]\n return min_row_final.tour\n\n\n# ********************************************************************************\n# ********************************************************************************\n\nif __name__ == '__main__':\n df = pd.read_csv('city_data_add.csv')\n tsp = AddHeuristicTSP(df)\n\n tsp.final_df\n print(\"final_df\")\n print(tsp.final_df)\n print()\n\n print(\"shortest_distance_final\", tsp.shortest_distance)\n print(\"shortest_tour_final\", tsp.shortest_tour)\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
YellowOfTheEgg/ots-eval | [
"8ec08e60330d41f8f7ffd571dd6301cdedaefd99"
] | [
"ots_eval/stability_evaluation/close.py"
] | [
"import numpy as np\nfrom scipy.spatial.distance import euclidean\nfrom typing import Union\nimport pandas\n\n\nclass CLOSE(object):\n\n def __init__(self, data: pandas.DataFrame, measure: Union[str, callable] = 'mse', minPts: int = None, output: bool = False,\n jaccard: bool = False, weighting: bool = False, exploitation_term: bool = False):\n \"\"\"\n Params:\n data (pandas.DataFrame) - pandas dataframe with columns order 'object_id', 'time', 'cluster_id' containing cluster belongings,\n features ..\n Note: outliers should have negative labels/cluster_ids, these should be different for different times\n Optional:\n measure (str or callable) - for used quality measure, possible measures:\n 'sse', 'mse', 'mae', 'max', 'dbi', 'exploit'\n minPts (int) - used minPts for density-based quality measure\n output (boolean) - whether intermediate results should be printed\n jaccard (boolean) - whether the jaccard index should be used for proportion\n weighting (boolean) - whether the weighting function should be used for subsequence_score\n exploitation_term (boolean) - whether the exploitation term should be included in CLOSE calculation\n \"\"\"\n self._data = data\n self._column_names = data.columns.values\n self._object_column_name = self._column_names[0]\n self._time_column_name = self._column_names[1]\n self._cluster_column_name = self._column_names[2]\n\n self._jaccard = jaccard\n self._weighting = weighting\n self._exp_term = exploitation_term\n\n self._minPts = minPts\n self._output = output\n self.pos_measures = {### Measures for Clusters\n 'sse': self.calc_sse, # NOTE: sse is not between 0 and 1\n 'mse': self.calc_mse, # NOTE: mse is only between 0 and 1, if data is normalized\n 'mae': self.calc_mae, # NOTE: mae is only between 0 and 1, if data is normalized\n 'max': self.calc_max_dist,\n 'dbi': self.calc_min_pts,\n 'None': self.return_zero,\n ### Measures for Time Clusterings\n 'exploit': self.calc_exploit_at_t}\n\n if measure in self.pos_measures:\n self.measure = self.pos_measures[measure]\n elif callable(measure):\n self.measure = measure\n else:\n self.measure = self.pos_measures['mse']\n\n def rate_clustering(self, start_time: int = None, end_time: int = None, return_measures: bool = False) -> Union[float, dict]:\n \"\"\"\n Optional:\n start_time (int) - time that should be considered as beginning\n end_time (int) - time which should be rated up to\n return_measures (boolean) - whether additional information such as average stability\n and quality should be returned\n Returns:\n CLOSE score (float): rating of clustering regarding all clusters\n (dict): with key 'stability_evaluation', 'stability', 'quality', 'pre-factor' with additional information\n if 'return_measures' is True\n \"\"\"\n cluster_ratings = self.rate_clusters(start_time, end_time)\n gr_clusters = self._data.groupby(self._cluster_column_name)\n\n score = 0\n avg_quality = 0\n avg_stab = 0\n\n for cluster in cluster_ratings:\n cluster_objects = gr_clusters.get_group(cluster)[self._object_column_name].unique()\n cluster_time = gr_clusters.get_group(cluster)[self._time_column_name].iloc[0]\n feature_list = self.get_feature_list(cluster_objects, cluster_time)\n\n measure = self.measure(feature_list)\n avg_quality += measure\n avg_stab += cluster_ratings[cluster]\n score += (cluster_ratings[cluster] * (1 - measure))\n\n num_clusters = len(cluster_ratings)\n num_timestamps = self.get_num_timestamps(start_time, end_time)\n\n if num_clusters <= 0:\n if self._output:\n print('Clustering has no Clusters!!')\n return 0\n\n avg_quality /= num_clusters\n if self._output:\n print('Average Quality: ', str(avg_quality))\n avg_stab /= num_clusters\n if self._output:\n print('Average Stability: ', str(avg_stab))\n\n if self._exp_term:\n exp_term = self.calc_exploit()\n factor = (1 / num_clusters) * (1 - (num_timestamps / num_clusters) ** 2) * exp_term\n else:\n factor = (1 / num_clusters) * (1 - (num_timestamps / num_clusters)**2)\n\n if not return_measures:\n return score * factor\n\n else:\n return {'stability_evaluation': score * factor,\n 'stability': avg_stab,\n 'quality': avg_quality,\n 'pre-factor': (1 - (num_timestamps / num_clusters) ** 2)}\n\n def rate_time_clustering(self, start_time: int = None, end_time: int = None, return_measures: bool = False) -> Union[float, dict]:\n \"\"\"\n Optional:\n start_time (optional) - int: time that should be considered as beginning\n end_time (optional) - int: time which should be rated up to\n return_measures (boolean) - whether additional information such as average stability and quality should be returned\n Returns:\n CLOSE score (float) - rating of clustering regarding all time clusterings\n (dict): with key 'stability_evaluation', 'stability', 'quality', 'pre-factor' with additional information\n if 'return_measures' is True\n \"\"\"\n cluster_ratings = self.rate_clusters(start_time, end_time)\n num_timestamps, timestamps = self.get_num_timestamps(start_time, end_time, return_timestamps=True)\n\n score = 0\n if return_measures:\n quality = 0\n stability = 0\n\n for time in timestamps:\n if not return_measures:\n score += self.calc_t_clustering_rating(cluster_ratings, time)\n else:\n cur_scores = self.calc_t_clustering_rating(cluster_ratings, time, return_measures=True)\n score += cur_scores['score']\n quality += cur_scores['quality']\n stability += cur_scores['stability']\n\n if return_measures:\n quality /= num_timestamps\n stability /= num_timestamps\n\n num_clusters = len(cluster_ratings)\n if num_clusters <= 0:\n if self._output:\n print('Over-Time Clustering has no Clusters!!')\n return 0\n\n if self._exp_term:\n exp_term = self.calc_exploit()\n factor = (1 / num_timestamps) * (1 - (num_timestamps / num_clusters) ** 2) * exp_term\n else:\n factor = (1 / num_timestamps) * (1 - (num_timestamps / num_clusters) ** 2)\n\n if not return_measures:\n return score * factor\n else:\n return {'stability_evaluation': score * factor,\n 'stability': stability,\n 'quality': quality,\n 'pre-factor': factor}\n\n def calc_t_clustering_rating(self, cluster_ratings: dict, time: int, return_measures: bool = False) -> Union[float, dict]:\n \"\"\"\n Params:\n cluster_ratings (dict) - {<object_id>: <rating>} with ratings of objects\n time (int) - time that should be considered\n Optional:\n return_measures (boolean) - whether additional information such as average stability and quality should be returned\n Output:\n CLOSE score (float) - rating of clustering at considered time\n (dict): with key 'score', 'stability', 'quality' with additional information if 'return_measures' is True\n \"\"\"\n avg_stab = 0\n\n clusters_at_time = self._data[self._data[self._time_column_name] == time][self._cluster_column_name].unique()\n clusters_at_time = np.delete(clusters_at_time, np.where(clusters_at_time < 0))\n \n for cluster in clusters_at_time:\n try:\n avg_stab += cluster_ratings[cluster]\n except:\n continue\n\n num_clusters = len(clusters_at_time)\n if num_clusters <= 0:\n if self._output:\n print('Time Clustering at Time ', str(time), ' has no Clusters!!')\n return 0\n\n avg_stab /= num_clusters\n if self._output:\n print('Average Stability at Time ', str(time), ' : ', str(avg_stab))\n\n quality = self.measure(time)\n if self._output:\n print('Quality of Clustering at Time ' , str(time), ' : ', str(quality))\n\n t_clustering_score = avg_stab * quality\n if not return_measures:\n return t_clustering_score\n else:\n return {\n 'score': t_clustering_score,\n 'stability': avg_stab,\n 'quality': quality\n }\n\n def rate_clusters(self, start_time: int = None, end_time: int = None, id: Union[int, str, list] = None) -> dict:\n \"\"\"\n Optional:\n start_time (int) - time that should be considered as beginning\n end_time (int) - time which should be rated up to\n id (int, str, list or None) - representing the cluster_ids that should be rated. If id is None,\n all objects are rated\n Returns:\n ratings (dict) - {<cluster_id>: <rating>} with ratings of clusters\n \"\"\"\n ids_to_rate = self.get_ids_to_rate(id, self._cluster_column_name, start_time, end_time)\n ids = ids_to_rate[:]\n\n # don't rate outliers\n for i in ids_to_rate:\n if int(i) < 0:\n ids.remove(i)\n\n ratings = self.calc_cluster_rating(ids, start_time)\n return ratings\n\n def calc_cluster_rating(self, ids_to_rate: Union[list, np.ndarray], start_time: int = None) -> dict:\n \"\"\"\n Params:\n ids_to_rate (array-like) - list of clusters that should be rated\n Optional:\n start_time (int) - time that should be considered as beginning\n Returns:\n ratings - dict {<cluster_id>: <rating>} with ratings of clusters\n \"\"\"\n if start_time is None:\n start_time = np.min(self._data[self._time_column_name].unique())\n\n ratings = {}\n cluster_compositions = self.obtain_cluster_compositions()\n gr_clusters = self._data.groupby(self._cluster_column_name)\n\n # iterate over all cluster ids\n for id in ids_to_rate:\n time = gr_clusters.get_group(id)[self._time_column_name].iloc[0]\n\n # rate the clusters of all timestamps except of the first one\n if time != start_time:\n num_merged_clusters = len(cluster_compositions[id])\n obj_list = gr_clusters.get_group(id)[self._object_column_name].unique().tolist()\n obj_ratings = self.calc_object_rating(cluster_compositions, obj_list, time)\n score = 0\n for obj in obj_ratings:\n score += obj_ratings[obj]\n try:\n score /= len(obj_ratings)\n except ZeroDivisionError:\n if self._output:\n print('Cluster ', str(id), ' has no non-outlier members.')\n else:\n continue\n\n clusters = list(cluster_compositions[id].keys())\n num_timestamps = len(self._data.loc[self._data[self._cluster_column_name].isin(clusters)]\n [self._time_column_name].unique())\n try:\n div = num_merged_clusters / num_timestamps\n score /= div\n except ZeroDivisionError:\n if self._output:\n print(\"<<ZeroDivisionError - Cluster Score>> Cluster ID: \", str(id), \" Merged Clusters: \", str(num_merged_clusters),\n \" Num Timestamps: \", str(num_timestamps))\n else:\n continue\n ratings[id] = score\n\n # clusters of the first timestamp have a stability of 1.0\n else:\n ratings[id] = 1.0\n return ratings\n\n def rate_object(self, id: Union[int, str, list] = None, start_time: int = None, end_time: int = None) -> dict:\n \"\"\"\n Optional:\n id (int, str, list or None) - representing the data points that should be rated. If id is None,\n all objects are rated\n start_time (int) - time that should be considered as beginning\n end_time (int) - representing the timestamp which should be rated up to\n Returns:\n ratings (dict) - {<object_id>: <rating>} with ratings of objects\n \"\"\"\n ids_to_rate = self.get_ids_to_rate(id, self._object_column_name)\n if end_time is None:\n end_time = np.max(self._data[self._time_column_name].unique())\n cluster_compositions = self.obtain_cluster_compositions()\n ratings = self.calc_object_rating(cluster_compositions, ids_to_rate, end_time, start_time)\n return ratings\n\n def calc_object_rating(self, cluster_composition: dict, ids_to_rate: Union[list, np.ndarray], end_time: int, start_time: int = None) -> dict:\n \"\"\"\n Params:\n cluster_composition (dict) - {<cluster_id>: {<contained_cluster_id>: <proportion>}} containing the proportions of\n clusters (contained_cluster_id) that belong to cluster (cluster_id)\n ids_to_rate (array-like) - list of data points that should be rated\n end_time (int) - representing the timestamp which should be rated up to\n Optional:\n start_time (int) - time that should be considered as beginning\n Returns:\n ratings - dict {<object_id>: <rating>} with ratings of objects\n \"\"\"\n ratings = {}\n gr_clusters = self._data.groupby(self._object_column_name)\n\n # iterate over object ids\n for id in ids_to_rate:\n cur_group = gr_clusters.get_group(id)\n cur_group = cur_group[cur_group[self._time_column_name] <= end_time]\n\n if start_time is not None:\n cur_group = cur_group[cur_group[self._time_column_name] >= start_time]\n\n try:\n # id of the cluster of the last considered timestamp\n last_cluster = cur_group[cur_group[self._time_column_name] == end_time][self._cluster_column_name].iloc[\n 0]\n except IndexError:\n print(\">>INDEXERROR - LAST CLUSTER<< ID: \", str(id), \", Start Time: \", str(start_time), \", End Time: \",\n str(end_time))\n continue\n\n # if object is an outlier for the considered timestamp, it is skipped\n if int(last_cluster) < 0:\n continue\n\n cluster_ids = cur_group[self._cluster_column_name].unique()\n\n object_ratings = []\n num_clusters = 0\n has_outlier = False\n for cluster in cluster_ids:\n if cluster == last_cluster:\n continue\n # Add the proportion of clusters before last timestamp, that merged in last cluster\n else:\n # outliers get worst rating of 0.0\n if int(cluster) < 0:\n object_ratings.append(0.0)\n has_outlier = True\n else:\n object_ratings.append(cluster_composition[last_cluster][cluster])\n num_clusters += 1\n if not has_outlier and len(object_ratings) == 0:\n # print(str(id) + \" has no data before t=\" + str(end_time))\n continue\n\n if self._weighting:\n try:\n weighting_denominator = 0\n for i in range(1, num_clusters + 1):\n weighting_denominator += i\n\n if num_clusters > 0:\n object_rating = 0\n for i in range(num_clusters):\n object_rating += object_ratings[i] * ((i + 1) / weighting_denominator)\n\n else:\n continue\n except (TypeError, ZeroDivisionError):\n # print(str(id) + \" is not assigned to any cluster before t=\" + str(end_time))\n continue\n else:\n try:\n object_rating = np.sum(object_ratings)\n object_rating /= num_clusters\n except (TypeError, ZeroDivisionError):\n # print(str(id) + \" is not assigned to any cluster before t=\" + str(end_time))\n continue\n\n ratings[id] = round(object_rating, 3)\n return ratings\n\n def calc_exploit(self) -> float:\n \"\"\"\n Returns:\n exploitation_term (float) - exploitation term for whole clustering\n \"\"\"\n num_objects = len(self._data[self._object_column_name].unique())\n num_no_outliers = len(self._data[self._data[self._cluster_column_name] >= 0][self._object_column_name].unique())\n return num_no_outliers / num_objects\n\n\n ######## HELPER FUNCTIONS ########\n\n def get_feature_list(self, objects: Union[list, np.ndarray], time: int) -> np.ndarray:\n \"\"\"\n Params:\n objects (array-like) - list of objects_ids that belong to considered cluster\n time (int) - time of cluster that is considered\n\n Output:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n \"\"\"\n feature_list = []\n for obj in objects:\n features = self._data[\n (self._data[self._object_column_name] == obj) & (self._data[self._time_column_name] == time)]\n try:\n features = \\\n features.drop([self._object_column_name, self._cluster_column_name, self._time_column_name],\n axis=1).iloc[0].tolist()\n except IndexError:\n print(\">>INDEXERROR - FEATURE LIST<< ID: \", str(obj), \", Time: \", str(time))\n continue\n\n if len(features) <= 0:\n print(\"No features found for object \", str(obj))\n continue\n feature_list.append(features)\n return np.array(feature_list)\n\n def get_num_timestamps(self, start_time: int, end_time: int, return_timestamps: bool = False) -> int:\n \"\"\"\n Params:\n start_time (int) - first timestamp to be considered\n end_time (int) - last timestamp to be considered\n Optional:\n return_timestamps (boolean) - list of all timestamps\n Returns:\n num_timestamps (int) - number of timestamps between start_time and end_time\n \"\"\"\n timestamp_list = self._data[self._time_column_name].unique()\n if start_time is not None:\n timestamp_list = [i for i in timestamp_list if i >= start_time]\n if end_time is not None:\n timestamp_list = [i for i in timestamp_list if i <= end_time]\n num_timestamps = len(timestamp_list)\n if not return_timestamps:\n return num_timestamps\n else:\n return num_timestamps, timestamp_list\n\n def get_ids_to_rate(self, id: Union[int, str, list], id_name: str, start_time: int = None, end_time: int = None) -> list:\n \"\"\"\n Params:\n id (int, str, list or None) - representing the data points that should be rated. If id is None, all objects are rated\n id_name (str) - either self._cluster_column_name or self._object_column_name, which ids to extract\n Optional:\n start_time (int) - first timestamp to be considered\n end_time (int) - last timestamp to be considered\n Returns:\n ids_to_rate (list) - list of ids that should be rated\n \"\"\"\n if id is None:\n data = self._data.copy()\n if start_time is not None:\n data = data[data[self._time_column_name] >= start_time]\n if end_time is not None:\n data = data[data[self._time_column_name] <= end_time]\n ids_to_rate = data[id_name].unique().tolist()\n elif isinstance(id, int) or isinstance(id, str):\n ids_to_rate = [id]\n elif isinstance(id, list):\n ids_to_rate = id[:]\n else:\n raise Exception('id has to be int, str, list or None')\n return ids_to_rate\n\n def obtain_cluster_compositions(self) -> dict:\n \"\"\"\n Returns:\n cluster_compositions (dict) - dict of dicts {<cluster_id>: {<cluster_id>: <proportion>}} with cluster compositions\n\n Example:\n {5: {1: 1.0, 2: 0.1, 4: 0.5}} describes that\n 100% of cluster 1, 10% of cluster 2 and 50% of cluster 4 belong to cluster 5\n \"\"\"\n cluster_compositions = {}\n g_clusters = self._data.groupby([self._time_column_name, self._cluster_column_name])\n\n if not self._jaccard:\n cluster_members = self._data.groupby(self._cluster_column_name).count()\n\n # iterate over all clusters - 'group' contains the time and cluster_id\n # and 'objects' is the corresponding dataframe\n for group, objects in g_clusters:\n # Ignore outliers\n if int(group[1]) < 0:\n continue\n\n objects = objects[self._object_column_name].values.tolist()\n\n # temporal intersection\n # select considered clusters with later timestamps than the current one to check which clusters the\n # current one merged into and count, how many objects of the current cluster are in the considered clusters\n # example of a series from the dataframe: [cluster_id, count] with [2, 10]\n # meaning: 10 objects of the current cluster merged into the cluster with the id 2\n temp_intersection = (self._data.loc[(self._data[self._object_column_name].isin(objects)) &\n (self._data[self._time_column_name] > group[0])]).groupby(self._cluster_column_name).count()\n\n # iterate over all clusters which the current cluster has merged into\n # 'cluster' contains the cluster_id\n # and 'con_objects' is the corresponding number of objects of the temporal intersection\n for cluster, num_objects in temp_intersection.iterrows():\n # Ignore outliers\n if int(cluster) < 0:\n continue\n\n # for all considered clusters save the proportion of the current cluster that merged into the considered\n # one\n # example: {3: {2: 0.3}, 4: {2: 0.1}}\n # meaning: 30% of (current) cluster 2 merged into (considered) cluster 3 and 10% into (considered) cluster 4\n if cluster not in cluster_compositions:\n cluster_compositions[cluster] = {}\n\n if self._jaccard:\n # cardinality of the union of both considered clusters\n card_union = len(self._data.loc[(self._data[self._cluster_column_name] == cluster) |\n (self._data[self._cluster_column_name] == group[1])]\n [self._object_column_name].unique())\n # jaccard distance\n cluster_compositions[cluster][group[1]] = round(float(num_objects.values[1]) /\n float(card_union), 3)\n else:\n cluster_compositions[cluster][group[1]] = round(float(num_objects.values[1]) /\n float(cluster_members.loc[group[1]].values[1]), 3)\n if group[1] not in cluster_compositions:\n cluster_compositions[group[1]] = {}\n return cluster_compositions\n\n\n ######## QUALITY MEASURES ########\n\n @staticmethod\n def calc_sse(feature_list: list) -> float:\n \"\"\"\n Params:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n Returns:\n sse (float) - sum of squared errors to centroid of cluster\n \"\"\"\n centroid = np.average(feature_list, axis=0)\n sse = np.sum(np.power(feature_list - centroid[None, :], 2))\n return sse\n\n def calc_mse(self, feature_list: list) -> float:\n \"\"\"\n Params:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n Returns:\n mse (float) - mean squared error of cluster\n \"\"\"\n sse = self.calc_sse(feature_list)\n return sse / len(feature_list)\n\n @staticmethod\n def calc_mae(feature_list: list) -> float:\n \"\"\"\n Params:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n Returns:\n mae (float) - mean average errors to centroid of cluster\n \"\"\"\n centroid = np.average(feature_list, axis=0)\n mae = np.average(np.abs(feature_list - centroid[None, :]))\n return mae\n\n @staticmethod\n def calc_max_dist(feature_list: list) -> float:\n \"\"\"\n Params:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n Returns:\n max_dist (float) - maximal distance of cluster member to centroid of cluster\n \"\"\"\n max_dist = 0\n for i in range(len(feature_list) - 1):\n for j in range(i + 1, len(feature_list)):\n cur_dist = euclidean(np.array(feature_list[i]), np.array(feature_list[j]))\n if cur_dist > max_dist:\n max_dist = cur_dist\n max_dist /= 2 ** (1 / 2)\n return max_dist\n\n def calc_min_pts(self, feature_list: list) -> float:\n \"\"\"\n Params:\n feature_list (list) - list of lists containing the features of objects in the considered cluster\n Returns:\n avg_dist (float) - average distance of cluster members to their minPts neighbor\n \"\"\"\n avg_dist = 0\n for i in range(len(feature_list)):\n dist_list = [10] * self._minPts\n for j in range(len(feature_list)):\n if i == j:\n continue\n cur_dist = euclidean(np.array(feature_list[i]), np.array(feature_list[j]))\n for k in range(len(dist_list)):\n if cur_dist < dist_list[k]:\n dist_list.insert(k, cur_dist)\n dist_list.pop(self._minPts)\n avg_dist += dist_list[self._minPts - 1]\n avg_dist /= len(feature_list)\n return avg_dist\n\n @staticmethod\n def return_zero():\n \"\"\"\n Function is used if no quality measure should be used in CLOSE\n This is the case when only the exploitation term is considered\n\n Returns:\n 0\n \"\"\"\n return 0\n\n def calc_exploit_at_t(self, time: int) -> float:\n \"\"\"\n Params:\n time (int) - time to be considered\n Returns:\n rating (float) - exploitation rating of time clustering\n \"\"\"\n num_objects_at_t = len(self._data[self._data[self._time_column_name] == time][self._object_column_name].unique())\n num_no_outliers = len(self._data[(self._data[self._time_column_name] == time) &\n (self._data[self._cluster_column_name] >= 0)][self._object_column_name].unique())\n return num_no_outliers / num_objects_at_t\n\n\n"
] | [
[
"numpy.sum",
"numpy.abs",
"numpy.power",
"numpy.array",
"numpy.where",
"numpy.average"
]
] |
dajes/labelfficient | [
"5dd0566224fb04285e690bf8576eacc04a7c87cd"
] | [
"commons/siam_mask/experiments/siammask_sharp/resnet.py"
] | [
"import torch.nn as nn\nimport torch\nfrom torch.autograd import Variable\nimport math\nimport torch.utils.model_zoo as model_zoo\nfrom commons.siam_mask.models.features import Features\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(Features):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n # padding = (2 - stride) + (dilation // 2 - 1)\n padding = 2 - stride\n assert stride==1 or dilation==1, \"stride and dilation must have one equals to zero at least\"\n if dilation > 1:\n padding = dilation\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=padding, bias=False, dilation=dilation)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n if out.size() != residual.size():\n print(out.size(), residual.size())\n out += residual\n\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, layer4=False, layer3=False):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=0, # 3\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2) # 31x31, 15x15\n\n self.feature_size = 128 * block.expansion\n\n if layer3:\n self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2) # 15x15, 7x7\n self.feature_size = (256 + 128) * block.expansion\n else:\n self.layer3 = lambda x:x # identity\n\n if layer4:\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4) # 7x7, 3x3\n self.feature_size = 512 * block.expansion\n else:\n self.layer4 = lambda x:x # identity\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, dilation=1):\n downsample = None\n dd = dilation\n if stride != 1 or self.inplanes != planes * block.expansion:\n if stride == 1 and dilation == 1:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n else:\n if dilation > 1:\n dd = dilation // 2\n padding = dd\n else:\n dd = 1\n padding = 0\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=3, stride=stride, bias=False,\n padding=padding, dilation=dd),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n # layers.append(block(self.inplanes, planes, stride, downsample, dilation=dilation))\n layers.append(block(self.inplanes, planes, stride, downsample, dilation=dd))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, dilation=dilation))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n p0 = self.relu(x)\n x = self.maxpool(p0)\n\n p1 = self.layer1(x)\n p2 = self.layer2(p1)\n p3 = self.layer3(p2)\n\n return p0, p1, p2, p3\n\n\ndef resnet18(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\n\ndef resnet34(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n\ndef resnet50(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef resnet101(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\n\ndef resnet152(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model\n\n\nif __name__ == '__main__':\n net = resnet50()\n print(net)\n net = net.cuda()\n\n var = torch.FloatTensor(1,3,127,127).cuda()\n var = Variable(var)\n\n net(var)\n print('*************')\n var = torch.FloatTensor(1,3,255,255).cuda()\n var = Variable(var)\n\n net(var)\n\n"
] | [
[
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.FloatTensor",
"torch.autograd.Variable",
"torch.nn.Conv2d",
"torch.nn.Sequential",
"torch.utils.model_zoo.load_url",
"torch.nn.ReLU"
]
] |
AlexBlack2202/EigenGAN-Tensorflow | [
"86b21a47a824a2bb04a088c3e78b03d03a53735c"
] | [
"tflib/distribute/distribute.py"
] | [
"import tensorflow as tf\n\nfrom tensorflow.python.client import device_lib\n\n\ndef get_available_gpus():\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == 'GPU']\n\ngpus = get_available_gpus\n\n\ndef split_nest(nest, num_or_size_splits, axis=0):\n \"\"\"Split nested structure.\n\n Examples\n --------\n >>> split_nest({'a': shape(10, 20), 'b': shape(4, 15)}, 2, axis=0)\n >>> [{'a': shape(5, 20), 'b': shape(2, 15)}, {'a': shape(5, 20), 'b': shape(2, 15)}]\n\n \"\"\"\n flatten = tf.nest.flatten(nest)\n split_flatten = [tf.split(x, num_or_size_splits, axis=axis) for x in flatten]\n return [tf.nest.pack_sequence_as(nest, x) for x in zip(*split_flatten)]\n\n\ndef parameter_server_strategy_run(devices, fn, split_args, split_kwargs=None):\n split_kwargs = [{}] * len(devices) if split_kwargs is None else split_kwargs\n\n assert len(devices) == len(split_args) == len(split_kwargs)\n\n split_returns = []\n for device, args, kwargs in zip(devices, split_args, split_kwargs):\n with tf.device(device):\n args = args if isinstance(args, (list, tuple)) else (args,)\n split_returns.append(fn(*args, **kwargs))\n\n return split_returns\n\nparellel_run = parameter_server_strategy_run\n\n\ndef average_gradients(tower_grads):\n \"\"\"Calculate the average gradient for each shared variable across all towers.\n\n Note that this function provides a synchronization point across all towers.\n\n Parameters\n ----------\n tower_grads:\n List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n\n Returns\n -------\n List of pairs of (gradient, variable) where the gradient has been averaged\n across all towers.\n\n \"\"\"\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n for g, _ in grad_and_vars:\n # Add 0 dimension to the gradients to represent the tower.\n expanded_g = tf.expand_dims(g, 0)\n\n # Append on a 'tower' dimension which we will average over below.\n grads.append(expanded_g)\n\n # Average over the 'tower' dimension.\n grad = tf.concat(axis=0, values=grads)\n grad = tf.reduce_mean(grad, 0)\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n"
] | [
[
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.nest.pack_sequence_as",
"tensorflow.device",
"tensorflow.reduce_mean",
"tensorflow.expand_dims",
"tensorflow.concat",
"tensorflow.nest.flatten",
"tensorflow.split"
]
] |
vdutor/VFF | [
"459be5b480bba49e8c15dc7daeca5fd1ddd762df"
] | [
"experiments/increasing_dim/Exp_1/kron.py"
] | [
"import numpy as np\nimport sys\nimport gpflow\nimport VFF\n\nfrom time import time\n\nfrom config import *\n\ndim = sys.argv[1]\nrep = sys.argv[2]\n\nprint('vff: dimension {}, replicate {}'.format(dim, r))\n\n# data\ndata = np.load('data/data_dim{}_rep{}.npz'.format(dim, 0))\n\n# full_gp\ndef prodkern(dim):\n return gpflow.kernels.Prod([gpflow.kernels.Matern32(1, active_dims=[i], lengthscales=lengthscale)\n for i in range(dim)])\nk = prodkern(dim)\nm = gpflow.gpr.GPR(data['Xtrain'], data['Ytrain'], kern=k)\nm.likelihood.variance = noise_var\ndata = np.load('data/data_dim{}_rep{}.npz'.format(dim, r))\nmarg_lik = m.compute_log_likelihood().squeeze()\nmean_log_pred = np.mean(m.predict_density(data['Xtest'], data['Ytest']))\n\nfile = open(\"results/full.csv\",\"a\") \nfile.write(\"{}, {}, {}, {}\".format(dim, rep, marg_lik, mean_log_pred)) \nfile.close() \n\n\n##########################\n# kron\nresults = pd.DataFrame()\n\nfor dim in dimensions:\n a, b = -1.5 * np.ones(dim), 1.5 * np.ones(dim)\n k = prodkern(dim)\n for r in range(repeats):\n print('kron replicate ',r,'/',repeats)\n data = np.load('data/data_dim{}_rep{}.npz'.format(dim, r))\n for M in num_freqs:\n if (2*M-1)**dim: \n a, b = -0.5 * np.ones(dim), 1.5 * np.ones(dim)\n m = VFF.vgp.VGP_kron(data['Xtrain'], data['Ytrain'], np.arange(M), a, b,\n kerns=prodkern(dim).kern_list,\n likelihood=gpflow.likelihoods.Gaussian(),\n use_two_krons=True)\n m.likelihood.variance = noise_var\n\n # only optimize q(u)\n m.kerns.fixed = True\n m.likelihood.fixed = True\n\n start = time()\n m.optimize()\n marg_lik = m.compute_log_likelihood().squeeze()\n mean_log_pred = np.mean(m.predict_density(data['Xtest'], data['Ytest']))\n t = time() - start\n\n results = results.append(dict(dim=dim, rep=r, marg_lik=marg_lik,\n mean_log_pred=mean_log_pred, time=t,\n num_inducing=M),\n ignore_index=True)\n\n # do this inside the loop so we can get partial results if something crashes\n results.to_csv('results/kron.csv')\n\n##########################\n# kron_opt\nresults = pd.DataFrame()\n\nfor dim in dimensions:\n a, b = -1.5 * np.ones(dim), 1.5 * np.ones(dim)\n k = prodkern(dim)\n for r in range(repeats):\n print('kron_opt replicate ',r,'/',repeats)\n data = np.load('data/data_dim{}_rep{}.npz'.format(dim, r))\n for M in num_freqs:\n if (2*M-1)**dim:\n m = VFF.vgp.VGP_kron(data['Xtrain'], data['Ytrain'], np.arange(M), a, b,\n kerns=k.kern_list,\n likelihood=gpflow.likelihoods.Gaussian(),\n use_two_krons=True)\n m.likelihood.variance = noise_var\n # build kronecker GP model\n start = time()\n m.optimize()\n marg_lik = m.compute_log_likelihood().squeeze()\n mean_log_pred = np.mean(m.predict_density(data['Xtest'], data['Ytest']))\n t = time() - start\n\n results = results.append(dict(dim=dim, rep=r, marg_lik=marg_lik,\n mean_log_pred=mean_log_pred, time=t,\n num_inducing=M),\n ignore_index=True)\n\n results.to_csv('results/kron_opt.csv')\n\n\n\n##########################\n# Sparse\nresults = pd.DataFrame()\n\nfor dim in dimensions:\n for r in range(repeats):\n print('Sparse replicate ',r,'/',repeats)\n data = np.load('data/data_dim{}_rep{}.npz'.format(dim, r))\n num_inducing = (2*num_freqs-1)**dim\n for M in num_inducing:\n if M < 500: \n # build sparse GP model\n Z = KMeans(n_clusters=M).fit(data['Xtrain']).cluster_centers_\n m = gpflow.sgpr.SGPR(data['Xtrain'], data['Ytrain'], Z=Z, kern=prodkern(dim))\n m.likelihood.variance = noise_var\n\n start = time()\n marg_lik = m.compute_log_likelihood().squeeze()\n mean_log_pred = np.mean(m.predict_density(data['Xtest'], data['Ytest']))\n t = time() - start\n\n results = results.append(dict(dim=dim, rep=r, marg_lik=marg_lik,\n mean_log_pred=mean_log_pred, time=t,\n num_inducing=M),\n ignore_index=True)\n\n # do this inside the loop so we can get partial results if something crashes\n results.to_csv('results/sparse_kmeans.csv')\n\n\n\n##########################\n# Sparse GP opt \nresults = pd.DataFrame()\n\nfor dim in dimensions:\n for r in range(repeats):\n print('sparse opt replicate ',r,'/',repeats)\n data = np.load('data/data_dim{}_rep{}.npz'.format(dim, r))\n num_inducing = (2*num_freqs-1)**dim\n for M in num_inducing:\n if M < 500: \n # build sparse GP model\n Z = KMeans(n_clusters=M).fit(data['Xtrain']).cluster_centers_\n m = gpflow.sgpr.SGPR(data['Xtrain'], data['Ytrain'], Z=Z, kern=prodkern(dim))\n m.likelihood.variance = noise_var\n\n # only optimize Z\n m.kern.fixed = True\n m.likelihood.fixed = True\n\n start = time()\n m.optimize()\n marg_lik = m.compute_log_likelihood().squeeze()\n mean_log_pred = np.mean(m.predict_density(data['Xtest'], data['Ytest']))\n t = time() - start\n\n results = results.append(dict(dim=dim, rep=r, marg_lik=marg_lik,\n mean_log_pred=mean_log_pred, time=t,\n num_inducing=M),\n ignore_index=True)\n\n # do this inside the loop so we can get partial results if something crashes\n results.to_csv('results/sparse_opt.csv')\n\n\n##########################\n# \n"
] | [
[
"numpy.arange",
"numpy.ones"
]
] |
Akshat-unt/jina | [
"b0b058f99f3ee4dcbcbbf2acbf04c5d7e7e9c717"
] | [
"tests/integration/issues/hanging_termination/test_hanging_termination.py"
] | [
"import os\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom jina import Flow, Document\nfrom jina.clients import Client\nfrom jina.logging.profile import TimeContext\nfrom jina.parsers import set_client_cli_parser\nfrom typing import Dict\nfrom jina import DocumentArray, Executor, requests\n\n\nclass DumpExecutor(Executor):\n @requests\n def dump(self, docs: DocumentArray, parameters: Dict, **kwargs):\n shards = int(parameters['shards'])\n dump_path = parameters['dump_path']\n shard_size = len(docs) / shards\n os.makedirs(dump_path, exist_ok=True)\n for i in range(shards):\n dump_file = f'{dump_path}/{i}.ndjson'\n docs_to_be_dumped = docs[int(i * shard_size) : int((i + 1) * shard_size)]\n docs_to_be_dumped.save(dump_file)\n\n\nclass ErrorExecutor(Executor):\n @requests\n def dump(self, docs: DocumentArray, **kwargs):\n if len(docs) > 0:\n assert False\n\n\nclass ReloadExecutor(Executor):\n def __init__(self, dump_path=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # backwards compatibility\n assert 'dump_path' in kwargs['runtime_args'].keys()\n if dump_path is not None:\n shard_id = getattr(self.runtime_args, 'pea_id', None)\n shard_dump_path = os.path.join(dump_path, f'{shard_id}.ndjson')\n self._docs = DocumentArray.load(shard_dump_path)\n else:\n self._docs = DocumentArray()\n\n @requests\n def search(self, docs: DocumentArray, **kwargs):\n docs.clear()\n docs.extend(self._docs)\n\n\nclass MergeExecutor(Executor):\n @requests\n def merge(self, docs_matrix: DocumentArray, **kwargs):\n merged_docs = DocumentArray()\n for docs in docs_matrix:\n merged_docs.extend(docs)\n return merged_docs\n\n\ndef get_client(port):\n args = set_client_cli_parser().parse_args(\n ['--host', 'localhost', '--port', str(port)]\n )\n\n return Client(args)\n\n\ndef get_documents(count=10, emb_size=7):\n for i in range(count):\n yield Document(\n id=i,\n text=f'hello world {i}',\n embedding=np.random.random(emb_size),\n tags={'tag_field': f'tag data {i}'},\n )\n\n\ndef path_size(dump_path):\n return (\n sum(\n f.stat().st_size\n for f in Path(dump_path).glob('**/*')\n if f.is_file()\n )\n / 1e6\n )\n\n\n@pytest.mark.repeat(20)\n@pytest.mark.parametrize('shards', [5, 3, 1])\n@pytest.mark.parametrize('nr_docs', [7])\n@pytest.mark.parametrize('emb_size', [10])\ndef test_dump_reload(tmpdir, shards, nr_docs, emb_size, times_to_index=2):\n \"\"\"showcases using replicas + dump + rolling update with independent clients\"\"\"\n\n with Flow().add(uses=DumpExecutor, name='dump_exec').add(\n uses=ErrorExecutor, name='error_exec'\n ) as flow_dump:\n merge_executor = MergeExecutor if shards > 1 else None\n with Flow().add(\n uses=ReloadExecutor,\n name='reload_exec',\n replicas=2,\n shards=shards,\n uses_after=merge_executor,\n ) as flow_reload:\n for run_number in range(times_to_index):\n dump_path = os.path.join(tmpdir, f'dump-{run_number}')\n client_dbms = get_client(flow_dump.port_expose)\n client_query = get_client(flow_reload.port_expose)\n docs = list(\n get_documents(\n count=nr_docs * (run_number + 1),\n emb_size=emb_size,\n )\n )\n\n with TimeContext(f'### dumping {len(docs)} docs'):\n client_dbms.post(\n on='/dump',\n inputs=docs,\n target_peapod='dump_exec',\n parameters={'dump_path': dump_path, 'shards': shards},\n )\n\n print(f'### dump path size: {path_size(dump_path)} MBs')\n\n with TimeContext(f'### rolling update on {len(docs)}'):\n # flow object is used for ctrl requests\n flow_reload.rolling_update('reload_exec', dump_path)\n\n for _ in range(5):\n result = client_query.post(\n on='/search', inputs=[Document()], return_results=True\n )\n\n assert len(docs) == len(result[0].docs)\n"
] | [
[
"numpy.random.random"
]
] |
claireguichon/pynet | [
"92706375e61fb5cb523548303b7d04769c9de134"
] | [
"pynet/cam.py"
] | [
"# -*- coding: utf-8 -*-\n##########################################################################\n# NSAp - Copyright (C) CEA, 2019\n# Distributed under the terms of the CeCILL-B license, as published by\n# the CEA-CNRS-INRIA. Refer to the LICENSE file or to\n# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html\n# for details.\n##########################################################################\n\n\n\"\"\"\nModule that provides tools to compute class activation map.\n\"\"\"\n\n\n# Imports\nimport logging\nimport skimage\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as func\n\n\n# Global parameters\nlogger = logging.getLogger(\"pynet\")\n\n\nclass FeatureExtractor(object):\n \"\"\" Class for extracting activations and registering gradients from\n targetted intermediate layers.\n \"\"\"\n def __init__(self, model, target_layers):\n self.model = model\n self.target_layers = target_layers\n self.gradients = []\n\n def save_gradient(self, grad):\n self.gradients.append(grad)\n\n def __call__(self, x):\n outputs = []\n self.gradients = []\n for name, module in self.model._modules.items():\n x = module(x)\n if name in self.target_layers:\n x.register_hook(self.save_gradient)\n outputs += [x]\n return outputs, x\n\n\nclass ModelOutputs(object):\n \"\"\" Class for making a forward pass, and getting:\n 1- the network output.\n 2- activations from intermeddiate targetted layers.\n 3- gradients from intermeddiate targetted layers.\n \"\"\"\n def __init__(self, model, target_layers):\n self.model = model\n self.feature_extractor = FeatureExtractor(\n self.model.features, target_layers)\n\n def get_activations_gradient(self):\n return self.feature_extractor.gradients\n\n def get_activations(self, x):\n return self.feature_extractor(x)\n\n def __call__(self, x):\n if hasattr(self.model, \"pre\"):\n x = self.model.pre(x)\n target_activations, output = self.feature_extractor(x)\n if hasattr(self.model, \"pool\"):\n output = self.model.pool(output)\n output = output.view(output.size(0), -1)\n output = self.model.classifier(output)\n return target_activations, output\n\n\nclass GradCam(object):\n \"\"\" Class for computing class activation map.\n \"\"\"\n def __init__(self, model, target_layers, labels, top=1):\n self.model = model\n self.labels = labels\n self.top = top\n self.model.eval()\n self.extractor = ModelOutputs(self.model, target_layers)\n\n def forward(self, input):\n return self.model(input)\n\n def __call__(self, input):\n features, output = self.extractor(input)\n pred_prob = func.softmax(output, dim=1).data.squeeze()\n probs, indices = pred_prob.sort(0, True)\n probs = probs.data.numpy()\n indices = indices.data.numpy()\n heatmaps = {}\n for cnt, (prob, index) in enumerate(zip(probs, indices)):\n if cnt == self.top:\n break\n label = self.labels[str(index)][1]\n line = \"{0:.3f} -> {1}\".format(prob, label)\n logger.info(line)\n one_hot = np.zeros((1, output.size()[-1]), dtype=np.float32)\n one_hot[0][index] = 1\n one_hot = Variable(torch.from_numpy(one_hot), requires_grad=True)\n one_hot = torch.sum(one_hot * output)\n self.model.features.zero_grad()\n self.model.classifier.zero_grad()\n one_hot.backward(retain_graph=True)\n gradients = self.extractor.get_activations_gradient()[-1]\n gradients = gradients.cpu().data.numpy()\n pooled_gradients = np.mean(gradients, axis=(0, 2, 3))\n activations = features[-1]\n activations = activations.cpu().data.numpy()\n for cnt, weight in enumerate(pooled_gradients):\n activations[:, cnt] *= weight\n heatmap = np.mean(activations, axis=1).squeeze()\n heatmap = np.maximum(heatmap, 0)\n heatmap -= np.min(heatmap)\n heatmap /= np.max(heatmap)\n heatmap_highres = skimage.transform.resize(\n heatmap, input.shape[2:])\n heatmaps[label] = (input, heatmap, heatmap_highres)\n return heatmaps\n"
] | [
[
"torch.sum",
"torch.nn.functional.softmax",
"numpy.max",
"torch.from_numpy",
"numpy.min",
"numpy.maximum",
"numpy.mean"
]
] |
GatherLab/OLED-evaluation | [
"419dfd5d2c3773f5f90d76aef634f8b1cc0b6378"
] | [
"src/UI_assign_group_window.py"
] | [
"# -*- coding: utf-8 -*-\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nimport json\nimport core_functions as cf\nimport numpy as np\n\nfrom UI_labeled_slider import LabeledSlider\n\n\nclass Ui_AssignGroup(object):\n def setupUi(self, AssignGroups):\n # Note: this is not how it should be done but currently I don't know\n # how to do it differently. This is only needed to be able to emit\n # signals to the main window\n\n AssignGroups.setObjectName(\"AssignGroups\")\n AssignGroups.setWindowTitle(\"Group Assignement Dialog\")\n AssignGroups.resize(509, 317)\n AssignGroups.setStyleSheet(\n \"QWidget {\\n\"\n \" background-color: rgb(44, 49, 60);\\n\"\n \" color: rgb(255, 255, 255);\\n\"\n ' font: 63 10pt \"Segoe UI\";\\n'\n \"}\\n\"\n \"QPushButton {\\n\"\n \" border: 2px solid rgb(52, 59, 72);\\n\"\n \" border-radius: 5px;\\n\"\n \" background-color: rgb(52, 59, 72);\\n\"\n \"}\\n\"\n \"QPushButton:hover {\\n\"\n \" background-color: rgb(57, 65, 80);\\n\"\n \" border: 2px solid rgb(61, 70, 86);\\n\"\n \"}\\n\"\n \"QPushButton:pressed {\\n\"\n \" background-color: rgb(35, 40, 49);\\n\"\n \" border: 2px solid rgb(43, 50, 61);\\n\"\n \"}\\n\"\n \"QPushButton:checked {\\n\"\n \" background-color: rgb(35, 40, 49);\\n\"\n \" border: 2px solid rgb(85, 170, 255);\\n\"\n \"}\"\n \"QLineEdit {\\n\"\n \" border: 2px solid rgb(61, 70, 86);\\n\"\n \" border-radius: 5px;\\n\"\n \" background-color: rgb(52, 59, 72);\\n\"\n \"}\\n\"\n \"QSpinBox {\\n\"\n \" border: 2px solid rgb(61, 70, 86);\\n\"\n \" border-radius: 5px;\\n\"\n \" background-color: rgb(52, 59, 72);\\n\"\n \"}\\n\"\n \"QDoubleSpinBox {\\n\"\n \" border: 2px solid rgb(61, 70, 86);\\n\"\n \" border-radius: 5px;\\n\"\n \" background-color: rgb(52, 59, 72);\\n\"\n \"}\\n\"\n )\n self.verticalLayout = QtWidgets.QVBoxLayout(AssignGroups)\n self.verticalLayout.setContentsMargins(25, 10, 25, 10)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n # # Device settings\n # self.device_settings_header_label = QtWidgets.QLabel(AssignGroups)\n # self.device_settings_header_label.setMinimumSize(QtCore.QSize(0, 20))\n # self.device_settings_header_label.setStyleSheet(\n # 'font: 75 bold 10pt \"Segoe UI\";'\n # )\n # self.device_settings_header_label.setObjectName(\"device_settings_header_label\")\n # self.verticalLayout.addWidget(self.device_settings_header_label)\n\n # self.header_line_1 = QtWidgets.QFrame()\n # self.header_line_1.setFrameShape(QtWidgets.QFrame.HLine)\n # self.header_line_1.setFrameShadow(QtWidgets.QFrame.Sunken)\n # self.verticalLayout.addWidget(self.header_line_1)\n # self.header_line_1.setStyleSheet(\n # \"QFrame {\\n\" \" border: 2px solid rgb(52, 59, 72);\\n\" \"}\\n\"\n # )\n\n # self.manualRowCountGridLayout = 1\n\n # Define dialog in which parameters should be entered\n # dialog = QtWidgets.QDialog()\n # dialog.setWindowTitle(\"Group Assignement Dialog\")\n\n # Select the scan that shall be evaluated\n if not self.include_all_scans:\n self.select_scan_number_label = QtWidgets.QLabel()\n self.select_scan_number_label.setObjectName(\"select_scan_number_label\")\n self.verticalLayout.addWidget(self.select_scan_number_label)\n\n self.select_scan_number_ComboBox = QtWidgets.QComboBox()\n self.select_scan_number_ComboBox.setObjectName(\n \"select_scan_number_ComboBox\"\n )\n\n for i in range(self.parameters[\"no_of_scans\"]):\n self.select_scan_number_ComboBox.addItem(str(int(i + 1)))\n\n self.select_scan_number_ComboBox.setCurrentIndex(0)\n self.verticalLayout.addWidget(self.select_scan_number_ComboBox)\n\n # Select the number of groups to define\n self.no_groups_label = QtWidgets.QLabel()\n self.verticalLayout.addWidget(self.no_groups_label)\n\n self.no_groups_LabeledSlider = LabeledSlider(\n 1,\n int(np.size(np.unique(self.parameters[\"device_number\"]))),\n interval=1,\n orientation=QtCore.Qt.Horizontal,\n )\n\n self.verticalLayout.addWidget(self.no_groups_LabeledSlider)\n\n self.available_devices_label = QtWidgets.QLabel()\n self.verticalLayout.addWidget(self.available_devices_label)\n\n # if np.size(self.paths) == 1:\n # verticalLayout.addWidget(self.no_groups_LabeledSlider)\n\n # Define the group assignement fields\n self.group_definition_gridLayout = QtWidgets.QGridLayout()\n self.group_definition_gridLayout.setSpacing(10)\n\n # Group names and its container\n self.group_name_label = QtWidgets.QLabel()\n self.group_definition_gridLayout.addWidget(self.group_name_label, 1, 0, 1, 1)\n\n self.group_name_LineEdit_container = np.empty(0, dtype=\"object\")\n self.group_name_LineEdit_container = np.append(\n self.group_name_LineEdit_container, QtWidgets.QLineEdit()\n )\n self.group_definition_gridLayout.addWidget(\n self.group_name_LineEdit_container[0], 2, 0\n )\n\n # Enter device numbers and its container\n self.device_assignment_label = QtWidgets.QLabel()\n self.group_definition_gridLayout.addWidget(\n self.device_assignment_label, 1, 1, 1, 1\n )\n\n self.device_assignment_LineEdit_container = np.empty(0, dtype=\"object\")\n self.device_assignment_LineEdit_container = np.append(\n self.device_assignment_LineEdit_container, QtWidgets.QLineEdit()\n )\n self.group_definition_gridLayout.addWidget(\n self.device_assignment_LineEdit_container[0], 2, 1\n )\n\n # Assign a spectrum file to the group\n if not self.autodetect_spectrum:\n self.spectrum_file_label = QtWidgets.QLabel()\n self.group_definition_gridLayout.addWidget(\n self.spectrum_file_label, 1, 2, 1, 1\n )\n\n self.group_spectrum_PushButton_container = np.empty(0, dtype=\"object\")\n self.group_spectrum_PushButton_container = np.append(\n self.group_spectrum_PushButton_container, QtWidgets.QPushButton(\"\")\n )\n self.group_spectrum_PushButton_container[0].setStyleSheet(\n \"background-color: red\"\n )\n self.group_definition_gridLayout.addWidget(\n self.group_spectrum_PushButton_container[0], 2, 2\n )\n\n # Definition of a plotting color for the group\n self.group_color_label = QtWidgets.QLabel()\n self.group_definition_gridLayout.addWidget(self.group_color_label, 1, 3, 1, 1)\n self.group_colors_PushButton_container = np.empty(0, dtype=\"object\")\n self.group_colors_PushButton_container = np.append(\n self.group_colors_PushButton_container, QtWidgets.QPushButton(\"\")\n )\n self.group_colors_PushButton_container[0].setStyleSheet(\n \"background-color: \" + str(self.group_color[0])\n )\n self.group_definition_gridLayout.addWidget(\n self.group_colors_PushButton_container[0], 2, 3\n )\n\n # Define the bottom pushbuttons that allows to close and save the dialog\n self.leave_horizontalLayout = QtWidgets.QHBoxLayout()\n self.close_pushButton = QtWidgets.QPushButton(\"Close\")\n\n self.save_pushButton = QtWidgets.QPushButton(\"Save\")\n\n self.leave_horizontalLayout.addWidget(self.close_pushButton)\n self.leave_horizontalLayout.addWidget(self.save_pushButton)\n\n self.verticalLayout.addLayout(self.group_definition_gridLayout)\n self.verticalLayout.addLayout(self.leave_horizontalLayout)\n\n self.setLayout(self.verticalLayout)\n\n self.retranslateUi(AssignGroups)\n QtCore.QMetaObject.connectSlotsByName(AssignGroups)\n\n def retranslateUi(self, AssignGroups):\n _translate = QtCore.QCoreApplication.translate\n AssignGroups.setWindowTitle(_translate(\"AssignGroups\", \"Assign Groups\"))\n\n if not self.include_all_scans:\n self.select_scan_number_label.setText(\n _translate(\"AssignGroups\", \"Select Scan\")\n )\n self.no_groups_label.setText(\n _translate(\"AssignGroups\", \"Select Number of Groups\")\n )\n self.available_devices_label.setText(\n _translate(\n \"AssignGroups\",\n \"Available Devices for Assignment \"\n + str(self.parameters[\"device_number\"]),\n )\n )\n self.group_name_label.setText(_translate(\"AssignGroups\", \"Group Name\"))\n self.device_assignment_label.setText(\n _translate(\"AssignGroups\", \"Assign Devices (seperated by ,)\")\n )\n self.group_color_label.setText(_translate(\"AssignGroups\", \"Color\"))\n if not self.autodetect_spectrum:\n self.spectrum_file_label.setText(_translate(\"AssignGroups\", \"Spectrum\"))\n"
] | [
[
"numpy.unique",
"numpy.empty"
]
] |
czw1296924847/ResGraphNet | [
"1638236e4138719c324afc3137f31cfec8a9de64"
] | [
"run/run_ResGraphNet.py"
] | [
"\"\"\"\nTesting ResGraphNet\n\"\"\"\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport torch\nimport os\nimport os.path as osp\nimport matplotlib.pyplot as plt\n\nimport sys\nsys.path.append(\"..\")\nimport func.cal as cal\n\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n# device = \"cpu\"\nl_x = 60 # Data sequence length\nl_y = 1 # Label sequence length\nlr = 0.0001 # Learning rate\nweight_decay = 5e-4\nepochs = 4000\nhidden_dim = 64\ngnn_style = \"ResGraphNet\"\nsave_fig = True # Whether to save picture\nsave_txt = False # Whether to save txt\nsave_np = True # Whether to save np file\nsave_model = True # Whether to save network model\nratio_train = 0.5 # Proportion of training datasets\nfig_size = (16, 12)\nts_name_all = [\"cli_dash\", \"HadCRUT5\", \"temp_month\", \"temp_year\", \"elect\", \"traffic\", \"sales\"]\nts_name_folder = \"HadCRUT5\" # Name of the folder where the data resides\nts_name = \"HadCRUT5_global\" # Name of the selected time series\niv = 1 # sampling interval, used for plotting curves\nway = \"mean\" # The style of plot curves of real data and predict results\n\nx_address = osp.join(\"../datasets\", ts_name_folder, ts_name + \".npy\")\nx = np.load(x_address)\nnum = x.shape[0] # The length of time series\n\nresult_address = osp.join(\"../result\", ts_name, \"ResGraphNet\")\nif not(osp.exists(result_address)):\n os.makedirs(result_address)\n\nnum_train = int(ratio_train * num)\ndata_train, data_test = x[:num_train], x[num_train:num] # get training dataset and test dataset\n\nlen_interp = l_y + 6\ndata_test_ = np.array(data_test[:-l_y].tolist() + data_test[-len_interp-l_y:-l_y].tolist() + data_test[-l_y:].tolist())\n\n# Using Graph Neural network, prepare data information\nx_train, y_train = cal.create_inout_sequences(data_train, l_x, l_y, style=\"arr\")\nx_test, y_test = cal.create_inout_sequences(data_test_, l_x, l_y, style=\"arr\")\n\nx_train = torch.from_numpy(x_train).float().to(device)\nx_test = torch.from_numpy(x_test).float().to(device)\ny_train = torch.from_numpy(y_train).float().to(device)\ny_test = torch.from_numpy(y_test).float().to(device)\nnum_nodes = x_train.shape[0] + x_test.shape[0]\nnum_train = x_train.shape[0]\n\nx = torch.cat((x_train, x_test), dim=0)\ny = torch.cat((y_train, y_test), dim=0)\n\nadm = cal.path_graph(num_nodes)\n# adm = cal.ts_un(num_nodes, 6)\nedge_index, edge_weight = cal.tran_adm_to_edge_index(adm)\n\ntrain_index = torch.arange(num_train, dtype=torch.long)\ntest_index = torch.arange(num_train, num_nodes, dtype=torch.long)\ntrain_mask = cal.index_to_mask(train_index, num_nodes).to(device)\ntest_mask = cal.index_to_mask(test_index, num_nodes).to(device)\n\n# Using ResGraphNet, predicting time series (The Proposed Network Model)\nmodel = cal.GNNTime(l_x, hidden_dim, l_y, edge_weight, gnn_style, num_nodes).to(device)\ncriterion = torch.nn.MSELoss().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\nedge_index = edge_index.to(device)\n\nstart_time = datetime.datetime.now()\nprint(\"Running, {}\".format(gnn_style))\nfor epoch in range(epochs):\n model.train()\n optimizer.zero_grad()\n output = model(x, edge_index)\n output_train, y_train = output[train_mask], y[train_mask]\n train_loss = criterion(output_train[:, -1], y_train[:, -1])\n train_loss.backward()\n optimizer.step()\n\n model.eval()\n y_test_1 = y[test_mask][:-len_interp-l_y, :]\n y_test_2 = y[test_mask][-l_y:, :]\n y_test = torch.cat((y_test_1, y_test_2), dim=0)\n output_test = output[test_mask][:-len_interp, :]\n test_loss = criterion(output_test[:, -1], y_test[:, -1])\n\n train_true = y_train.detach().cpu().numpy()[:, -1]\n train_predict = output_train.detach().cpu().numpy()[:, -1]\n test_true = y_test.detach().cpu().numpy()[:, -1]\n test_predict = output_test.detach().cpu().numpy()[:, -1]\n\n r2_train = cal.get_r2_score(train_predict, train_true, axis=1)\n r2_test = cal.get_r2_score(test_predict, test_true, axis=1)\n\n if (epoch + 1) % 100 == 0:\n print(\"Epoch: {:05d} Loss_Train: {:.5f} Loss_Test: {:.5f} R2_Train: {:.7f} R2_Test: {:.7f}\".\n format(epoch + 1, train_loss.item(), test_loss.item(), r2_train, r2_test))\n\n# predict and plot future time series\nplot_predict = test_predict[-l_y:]\nplot_true = test_true[-l_y:]\nmse_plot = np.mean(np.square(plot_predict - plot_true))\nprint(\"mse_plot: {}\".format(mse_plot))\ncal.plot_spiral(plot_predict) # predict results in the coming year\nif save_fig:\n plt.savefig(osp.join(result_address, \"future_predict.png\"))\ncal.plot_spiral(plot_true) # true data in the coming year\nif save_fig:\n plt.savefig(osp.join(result_address, \"future_true.png\"))\n\n# calculate running time\nend_time = datetime.datetime.now()\nrun_time = end_time - start_time # The running time of program\n\n# save model and numpy.file\nif save_model:\n torch.save(model, osp.join(result_address, \"{}.pkl\".format(gnn_style)))\nif save_np:\n np.save(osp.join(result_address, \"train_true.npy\"), train_true)\n np.save(osp.join(result_address, \"test_true.npy\"), test_true)\n np.save(osp.join(result_address, \"train_predict_{}.npy\".format(gnn_style)), train_predict)\n np.save(osp.join(result_address, \"test_predict_{}.npy\".format(gnn_style)), test_predict)\n\n# plot the error and results\ne_gnn = test_true - test_predict\ncal.plot_distribute(e_gnn, 40, 4, x_name=\"e\")\nif save_fig:\n plt.savefig(osp.join(result_address, ts_name + \"_\" + gnn_style + \"_error_distribution.png\"))\n\ncal.plot_result(train_true, test_true, train_predict, test_predict, iv, way, fig_size)\nif save_fig:\n plt.savefig(osp.join(result_address, ts_name + \"_\" + gnn_style + \".png\"))\n\n# print indicators\nrmse_train = cal.get_rmse(train_predict, train_true)\nrmse_test = cal.get_rmse(test_predict, test_true)\nr2_train = cal.get_r2_score(train_predict, train_true, axis=1)\nr2_test = cal.get_r2_score(test_predict, test_true, axis=1)\nprint(\"{}: RMSE_Train={:.5f} RMSE_Test={:.5f} R2_Train={:.7f} R2_Test={:.7f}\".\n format(gnn_style, rmse_train, rmse_test, r2_train, r2_test))\n\n# The output results of each model are appended to the file\nif save_txt:\n info_txt_address = osp.join(result_address, \"ResGraphNet_result.txt\") # txt file address for saving parameter information\n info_df_address = osp.join(result_address, \"ResGraphNet_result.csv\") # csv file address for saving parameter information\n f = open(info_txt_address, 'a')\n if osp.getsize(info_txt_address) == 0: # add the name of each feature in the first line of the text\n f.write(\"gnn_style r2_test r2_train run_time l_x l_y hidden_dim lr epochs\\n\")\n f.write(str(gnn_style) + \" \")\n f.write(str(r2_test) + \" \")\n f.write(str(r2_train) + \" \")\n f.write(str(run_time) + \" \")\n f.write(str(l_x) + \" \")\n f.write(str(l_y) + \" \")\n f.write(str(hidden_dim) + \" \")\n f.write(str(lr) + \" \")\n f.write(str(epochs) + \" \")\n\n f.write(\"\\n\") # Prepare for next running\n f.close() # close file\n\n info = np.loadtxt(info_txt_address, dtype=str)\n columns = info[0, :].tolist()\n values = info[1:, :]\n info_df = pd.DataFrame(values, columns=columns)\n info_df.to_csv(info_df_address)\n\n\nprint()\nplt.show()\nprint()\n"
] | [
[
"numpy.load",
"torch.nn.MSELoss",
"pandas.DataFrame",
"matplotlib.pyplot.show",
"torch.arange",
"torch.cuda.is_available",
"torch.from_numpy",
"numpy.square",
"torch.cat",
"numpy.loadtxt"
]
] |
JaworWr/Dynamic-inverse-kinematics | [
"b9da50b88152682060075a44da940e6f98690a9a"
] | [
"idea.py"
] | [
"import numpy as np\n\n\ndef FNS(scores):\n domination = np.all(scores[:, None, :] <= scores[None, :, :], axis=2) # domination[i, j] = \"i dominuje j\"\n domination &= np.any(scores[:, None, :] < scores[None, :, :], axis=2)\n Nx = domination.sum(0)\n\n Pf = []\n ranks = np.zeros(scores.shape[0])\n r = 0\n Q = np.nonzero(Nx == 0)[0]\n while Q.size > 0:\n Nx[Q] = -1\n Pf.append(Q)\n ranks[Q] = r\n r += 1\n for i in Q:\n Nx[domination[i, :]] -= 1\n Q = np.nonzero(Nx == 0)[0]\n\n return Pf, ranks\n\n\ndef crowding_distance(scores):\n indices = np.argsort(scores, 0)\n sorted_scores = np.take_along_axis(scores, indices, 0)\n cd = np.zeros(scores.shape[0])\n for k in range(scores.shape[1]):\n if sorted_scores[-1, k] != sorted_scores[0, k]:\n cd[indices[[0, -1], k]] = np.inf\n cd[indices[1:-1, k]] += (sorted_scores[2:, k] - sorted_scores[:-2, k]) / (\n sorted_scores[-1, k] - sorted_scores[0, k])\n return cd\n\n\ndef random_population(d, n, x_min, x_max):\n return np.hstack([np.random.uniform(x_min, x_max, (n, d))])\n\n\ndef tournament_selection(ranks, dists, n):\n candidates = np.random.choice(n, (n, 2), replace=True)\n mask = np.where(\n ranks[candidates[:, 0]] == ranks[candidates[:, 1]],\n dists[candidates[:, 0]] > dists[candidates[:, 1]],\n ranks[candidates[:, 0]] < ranks[candidates[:, 1]]\n )\n result = candidates[:, 1]\n result[mask] = candidates[mask, 0]\n return result\n\n\ndef crossover(x, p, eta): # simulated binary crossover\n n, d = x.shape\n l = n // 2\n mask = np.random.random((l, d)) <= p\n m = np.sum(mask)\n mi = np.random.random(m)\n beta = np.where(\n mi < 0.5,\n np.power(2 * mi, 1. / (eta + 1.)),\n np.power(1. / (2. * (1 - mi)), 1. / (eta + 1.))\n )\n c1 = x[:l, :].copy()\n c2 = x[l:, :].copy()\n c1[mask] = 0.5 * (1 + beta) * x[:l, :][mask] + 0.5 * (1 - beta) * x[l:, :][mask]\n c2[mask] = 0.5 * (1 + beta) * x[:l, :][mask] + 0.5 * (1 - beta) * x[l:, :][mask]\n return np.vstack([c1, c2])\n\n\ndef mutation(x, x_min, x_max, p, eta): # polynomial mutation\n n, d = x.shape\n mask = np.random.random((n, d)) <= p\n if isinstance(x_min, np.ndarray):\n x_min = np.repeat(x_min[None, :], n, axis=0)\n x_min = x_min[mask]\n if isinstance(x_max, np.ndarray):\n x_max = np.repeat(x_max[None, :], n, axis=0)\n x_max = x_max[mask]\n m = np.sum(mask)\n mi = np.random.random(m)\n beta = np.where(\n mi < 0.5,\n np.power(2 * mi, 1. / (eta + 1.)) - 1.,\n 1. - np.power(2. * (1 - mi), 1. / (eta + 1.))\n )\n y = x.copy()\n y[mask] = np.where(\n mi < 0.5,\n x[mask] + beta * (x[mask] - x_min),\n x[mask] + beta * (x_max - x[mask])\n )\n return y\n\n\ndef elitist_selection(fronts, dists, to_take):\n taken = []\n for front in fronts:\n if len(front) <= to_take:\n taken += list(front)\n if len(front) == to_take:\n break\n to_take -= len(front)\n else:\n indices = np.argsort(-dists[front])[:to_take]\n taken += list(front[indices])\n break\n return taken\n\n\ndef constraint_violation(constraints):\n n, d = constraints.shape\n sort_indices = np.argsort(constraints, 0)\n violations = np.zeros(n)\n for i in range(d):\n values, counts = np.unique(constraints[:, i], return_counts=True) # unikalne wartości są zwracane posortowane\n counts = np.cumsum(counts)\n counts = list(counts)\n if values[0] != 0:\n counts = [0] + counts\n for rank, (j, k) in enumerate(zip([0] + counts, counts + [len(counts)])):\n violations[sort_indices[j:k, i]] += rank\n return violations\n\n\ndef evaluation(objective, n_constraints, population):\n obj_results = objective(population)\n constraint_values = obj_results[:, -n_constraints:]\n violation_measure = constraint_violation(constraint_values)\n scores = np.concatenate([obj_results[:, :-n_constraints], violation_measure[:, None]], 1)\n return scores\n\n\ndef split_and_select(population, scores, n_f, n_inf):\n dists = crowding_distance(scores)\n mask_f = scores[:, -1] == 0\n population_f = population[mask_f, :]\n scores_f = scores[mask_f, :]\n dists_f = dists[mask_f]\n population_inf = population[~mask_f, :]\n scores_inf = scores[~mask_f, :]\n dists_inf = dists[~mask_f]\n\n s_f = population_f.shape[0]\n s_inf = population_inf.shape[0]\n n = n_f + n_inf\n if s_f < n_f:\n to_take_f = s_f\n to_take_inf = n - s_f\n elif s_inf < n_inf:\n to_take_inf = s_inf\n to_take_f = n - s_inf\n else:\n to_take_f = n_f\n to_take_inf = n_inf\n\n fronts_f, ranks_f = FNS(scores_f)\n taken_f = elitist_selection(fronts_f, dists_f, to_take_f)\n\n fronts_inf, ranks_inf = FNS(scores_inf)\n taken_inf = elitist_selection(fronts_inf, dists_inf, to_take_inf)\n\n return population_f[taken_f, :], population_inf[taken_inf, :], scores_f[taken_f, :], scores_inf[taken_inf, :]\n\n\ndef IDEA(objective, n_constraints, x_min, x_max, d, n, *args, **kwargs):\n population = random_population(d, n, x_min, x_max)\n return sub_IDEA(population, objective, n_constraints, x_min, x_max, n, *args, **kwargs)\n\n\ndef dynamic_IDEA(objective, n_constraints, T, x_min, x_max, d, n, alpha_inf,\n *args, num_iterations_init, num_iterations, n_immigrants=0, **kwargs):\n population = random_population(d, n, x_min, x_max)\n\n print(\"=\" * 80)\n print(\"t=0\")\n print(\"=\" * 80)\n\n t = 0\n\n def round_objective(round_population):\n return objective(t, round_population)\n\n p, s = sub_IDEA(population, round_objective, n_constraints, x_min, x_max, n, alpha_inf, *args,\n num_iterations=num_iterations_init, **kwargs)\n population_history = [p]\n score_history = [s]\n\n n_to_keep = n - n_immigrants\n n_inf = int(n_to_keep * alpha_inf)\n n_f = n_to_keep - n_inf\n\n for t in range(1, T):\n print(\"=\" * 80)\n print(f\"t={t}\")\n print(\"=\" * 80)\n\n population = p[-1, :, :]\n scores = s[-1, :, :]\n if n_immigrants > 0:\n population_f, population_inf, scores_f, scores_inf = split_and_select(population, scores, n_f, n_inf)\n\n immigrants = random_population(d, n_immigrants, x_min, x_max)\n population = np.vstack([population_f, population_inf, immigrants])\n assert population.shape[0] == n\n\n p, s = sub_IDEA(population, round_objective, n_constraints, x_min, x_max, n, alpha_inf, *args,\n num_iterations=num_iterations, **kwargs)\n population_history.append(p)\n score_history.append(s)\n\n return population_history, score_history\n\n\ndef sub_IDEA(population, objective, n_constraints, x_min, x_max, n, alpha_inf,\n eta_c, eta_m, p_c, p_m, num_iterations, log_interval=10):\n n_inf = int(n * alpha_inf)\n n_f = n - n_inf\n populations = []\n scores = evaluation(objective, n_constraints, population)\n scores_hist = []\n\n fronts, ranks = FNS(scores)\n dists = crowding_distance(scores)\n\n def log_message():\n count_f = population_f.shape[0]\n count_inf = population_inf.shape[0]\n print(\n f\"Iteration {iter_}, \" +\n\n f\"#feasible: {count_f}, best: {scores_f[:, :-1].min(0) if count_f > 0 else '-'}, \" +\n f\"#infeasible: {count_inf}, best: {scores_inf.min(0) if count_inf > 0 else '-'}\"\n )\n\n for iter_ in range(num_iterations):\n parent_indices = tournament_selection(ranks, dists, n)\n offspring = crossover(population[parent_indices, :], p_c, eta_c)\n offspring = np.clip(offspring, x_min, x_max)\n offspring = mutation(offspring, x_min, x_max, p_m, eta_m)\n offspring_scores = evaluation(objective, n_constraints, offspring)\n\n population = np.vstack([population, offspring])\n scores = np.vstack([scores, offspring_scores])\n\n population_f, population_inf, scores_f, scores_inf = split_and_select(population, scores, n_f, n_inf)\n\n population = np.vstack([population_f, population_inf])\n scores = np.vstack([scores_f, scores_inf])\n fronts, ranks = FNS(scores)\n dists = crowding_distance(scores)\n\n populations.append(population.copy())\n scores_hist.append(scores.copy())\n\n if iter_ % log_interval == 0:\n log_message()\n log_message()\n return np.stack(populations, 0), np.stack(scores_hist, 0)\n"
] | [
[
"numpy.sum",
"numpy.any",
"numpy.argsort",
"numpy.stack",
"numpy.vstack",
"numpy.random.choice",
"numpy.take_along_axis",
"numpy.where",
"numpy.nonzero",
"numpy.unique",
"numpy.random.uniform",
"numpy.zeros",
"numpy.repeat",
"numpy.all",
"numpy.power",
"numpy.cumsum",
"numpy.random.random",
"numpy.clip",
"numpy.concatenate"
]
] |
Keck-FOBOS/producer | [
"6f2b0d3f29f62187bf593567081061e53ddb5a4e"
] | [
"producer/util.py"
] | [
"\"\"\"\nMiscellaneous package utilities.\n\n.. include:: ../include/links.rst\n\"\"\"\n\nfrom itertools import chain, combinations\n\nfrom IPython import embed \n\nimport numpy\n\n\ndef all_subclasses(cls):\n \"\"\"\n Collect all the subclasses of the provided class.\n\n The search follows the inheritance to the highest-level class. Intermediate\n base classes are included in the returned set, but not the base class itself.\n\n Thanks to:\n https://stackoverflow.com/questions/3862310/how-to-find-all-the-subclasses-of-a-class-given-its-name\n\n Args:\n cls (object):\n The base class\n\n Returns:\n :obj:`set`: The unique set of derived classes, including any\n intermediate base classes in the inheritance thread.\n \"\"\"\n return set(cls.__subclasses__()).union(\n [s for c in cls.__subclasses__() for s in all_subclasses(c)])\n\n\ndef string_table(tbl, delimeter='print', has_header=True):\n \"\"\"\n Provided the array of data, format it with equally spaced columns\n and add a header (first row) and contents delimeter.\n\n Args:\n tbl (`numpy.ndarray`_):\n Array of string representations of the data to print.\n delimeter (:obj:`str`, optional):\n If the first row in the table containts the column headers (see\n ``has_header``), this sets the delimeter between first table row and\n the column data. Use ``'print'`` for a simple line of hyphens,\n anything else results in an ``rst`` style table formatting.\n has_header (:obj:`bool`, optional):\n The first row in ``tbl`` contains the column headers.\n\n Returns:\n :obj:`str`: Single long string with the data table.\n \"\"\"\n nrows, ncols = tbl.shape\n col_width = [numpy.amax([len(dij) for dij in dj]) for dj in tbl.T]\n\n _nrows = nrows\n start = 1\n if delimeter != 'print':\n _nrows += 2\n start += 1\n if has_header:\n _nrows += 1\n start += 1\n\n row_string = ['']*_nrows\n\n for i in range(start,nrows+start-1):\n row_string[i] = ' '.join([tbl[1+i-start,j].ljust(col_width[j]) for j in range(ncols)])\n if delimeter == 'print':\n # Heading row\n row_string[0] = ' '.join([tbl[0,j].ljust(col_width[j]) for j in range(ncols)])\n # Delimiter\n if has_header:\n row_string[1] = '-'*len(row_string[0])\n return '\\n'.join(row_string)+'\\n'\n\n # For an rst table\n row_string[0] = ' '.join([ '='*col_width[j] for j in range(ncols)])\n row_string[1] = ' '.join([tbl[0,j].ljust(col_width[j]) for j in range(ncols)])\n if has_header:\n row_string[2] = row_string[0]\n row_string[-1] = row_string[0]\n return '\\n'.join(row_string)+'\\n'\n\n\ndef powerset(iterable, reverse=False):\n \"\"\"\"\n Construct an iterable that steps through all combinations of the\n provided iterable.\n\n This is pulled from the recipes provided by the itertools\n documentation.\n\n Examples:\n \n Get all unique combinations of the list [1,2,3]:\n >>> list(powerset([1,2,3]))\n [() (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)]\n\n Args:\n iterable (iterable):\n An iterable object\n reverse (:obj:`bool`, optional):\n Reverse the order (only roughly) of the iterable by placing\n the longer sequences first.\n \n Returns:\n `itertools.chain`: Iterable object that returns the sequence of\n combinations.\n \"\"\"\n rng = range(len(iterable)+1)[::-1] if reverse else range(len(iterable)+1)\n return chain.from_iterable(combinations(iterable, r) for r in rng)\n\n\ndef polygon_winding_number(polygon, point):\n \"\"\"\n Determine the winding number of a 2D polygon about a point.\n \n The code does **not** check if the polygon is simple (no interesecting line\n segments). Algorithm taken from Numerical Recipes Section 21.4.\n\n Args:\n polygon (`numpy.ndarray`_):\n An Nx2 array containing the x,y coordinates of a polygon.\n The points should be ordered either counter-clockwise or\n clockwise.\n point (`numpy.ndarray`_):\n One or more points for the winding number calculation.\n Must be either a 2-element array for a single (x,y) pair,\n or an Nx2 array with N (x,y) points.\n\n Returns:\n :obj:`int`, `numpy.ndarray`_: The winding number of each point with\n respect to the provided polygon. Points inside the polygon have winding\n numbers of 1 or -1; see :func:`point_inside_polygon`.\n\n Raises:\n ValueError:\n Raised if ``polygon`` is not 2D, if ``polygon`` does not have two\n columns, or if the last axis of ``point`` does not have 2 and only 2\n elements.\n \"\"\"\n # Check input shape is for 2D only\n if len(polygon.shape) != 2:\n raise ValueError('Polygon must be an Nx2 array.')\n if polygon.shape[1] != 2:\n raise ValueError('Polygon must be in two dimensions.')\n _point = numpy.atleast_2d(point)\n if _point.shape[1] != 2:\n raise ValueError('Point must contain two elements.')\n\n # Get the winding number\n nvert = polygon.shape[0]\n npnt = _point.shape[0]\n\n dl = numpy.roll(polygon, 1, axis=0)[None,:,:] - _point[:,None,:]\n dr = polygon[None,:,:] - point[:,None,:]\n dx = dl[...,0]*dr[...,1] - dl[...,1]*dr[...,0]\n\n indx_l = dl[...,1] > 0\n indx_r = dr[...,1] > 0\n\n wind = numpy.zeros((npnt, nvert), dtype=int)\n wind[indx_l & numpy.logical_not(indx_r) & (dx < 0)] = -1\n wind[numpy.logical_not(indx_l) & indx_r & (dx > 0)] = 1\n\n return numpy.sum(wind, axis=1)[0] if point.ndim == 1 else numpy.sum(wind, axis=1)\n\n\ndef point_inside_polygon(polygon, point):\n \"\"\"\n Determine if one or more points is inside the provided polygon.\n\n Primarily a wrapper for :func:`polygon_winding_number`, that\n returns True for each point that is inside the polygon.\n\n Args:\n polygon (`numpy.ndarray`_):\n An Nx2 array containing the x,y coordinates of a polygon.\n The points should be ordered either counter-clockwise or\n clockwise.\n point (`numpy.ndarray`_):\n One or more points for the winding number calculation.\n Must be either a 2-element array for a single (x,y) pair,\n or an Nx2 array with N (x,y) points.\n\n Returns:\n :obj:`bool`, `numpy.ndarray`: Boolean indicating whether or not each\n point is within the polygon.\n \"\"\"\n return numpy.absolute(polygon_winding_number(polygon, point)) == 1\n\n\n\n"
] | [
[
"numpy.sum",
"numpy.roll",
"numpy.atleast_2d",
"numpy.zeros",
"numpy.logical_not"
]
] |
chundiliu/slim_for_Cdiscount | [
"ea7f9d56072072c031094c12c803c63591066c6c"
] | [
"generate_cdiscount_predictions.py"
] | [
"import math\nimport tensorflow as tf\nimport os\nimport struct\nimport pdb\nimport numpy as np\nfrom datasets import dataset_factory\nfrom nets import nets_factory\nimport nets.resnet_v2 as resnet_v2\nfrom preprocessing import preprocessing_factory\nslim = tf.contrib.slim\n\ndef merge_predictions(predictions_fn):\n '''\n Merge predictions/logit scores for products that are the same.\n '''\n\n out_f = open(predictions_fn + '_merged', 'wb')\n f = open(predictions_fn, 'r')\n line = f.readline().strip().split()\n curr_id = line[0]\n curr_scores = np.power(np.array([float(x) for x in line[1:]]), 3)\n num_elems = 1\n line = f.readline().strip().split()\n\n while line != []:\n id = line[0]\n # raise elements to the third power, and then take the cubic root\n scores = np.power(np.array([float(x) for x in line[1:]]), 3)\n\n if id == curr_id:\n num_elems += 1\n curr_scores += scores\n else:\n curr_scores = np.cbrt(curr_scores / float(num_elems))\n for score in curr_scores:\n out_f.write(struct.pack('>f', score))\n\n curr_scores = scores\n num_elems = 1\n curr_id = id\n\n line = f.readline().strip().split()\n\n\n curr_scores = np.cbrt(curr_scores / float(num_elems))\n for score in curr_scores:\n out_f.write(struct.pack('>f', score))\n\n out_f.close()\n f.close()\n\n\nif __name__ == '__main__':\n\n checkpoint_dir = '/home/shunan/Code/Data/cdiscount/training'\n dataset_dir = '/home/shunan/Code/Data/cdiscount/tf_records'\n num_classes = 5270\n image_size = 180\n batch_size = 100\n set_name = 'validation'\n data_sizes = {'train': 12195682, 'validation': 175611, 'test': 3095080}\n out_fn = os.path.join(dataset_dir, '{}_predictions.txt'.format(set_name))\n\n checkpoint_file = tf.train.latest_checkpoint(checkpoint_dir)\n\n # loading the dataset\n dataset = dataset_factory.get_dataset('cdiscount', set_name, dataset_dir)\n\n # dataset provider to load data from the dataset.\n provider = slim.dataset_data_provider.DatasetDataProvider(dataset, shuffle=False, common_queue_capacity=2*batch_size,\n common_queue_min=batch_size)\n [image, label, product_id] = provider.get(['image', 'label', 'product_id'])\n\n # Pre-processing step.\n image_preprocessing_fn = preprocessing_factory.get_preprocessing('simple', is_training=False)\n image = image_preprocessing_fn(image, image_size, image_size)\n\n images, labels, product_ids = tf.train.batch([image, label, product_id], batch_size=batch_size, num_threads=1,\n capacity=5 * batch_size)\n\n # Get the model\n # network_fn = nets_factory.get_network_fn('resnet_v2_152', num_classes=num_classes, is_training=False)\n with slim.arg_scope(resnet_v2.resnet_arg_scope(weight_decay=0.)):\n logits, end_points = resnet_v2.resnet_v2_152(images, num_classes=num_classes, is_training=False)\n\n #Obtain the trainable variables and a saver\n variables_to_restore = slim.get_variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n output_f = open(out_fn, 'w')\n\n with tf.Session() as sess:\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, checkpoint_file)\n num_iters = int(math.ceil(data_sizes[set_name] / float(batch_size)))\n num_last_batch = batch_size - ((num_iters * batch_size) - data_sizes[set_name])\n\n for i in range(num_iters):\n output, ids = sess.run([logits, product_ids])\n\n if i == num_iters - 1:\n output = output[:num_last_batch, :]\n ids = ids[:num_last_batch]\n\n for j in range(output.shape[0]):\n vec_str = [str(x) for x in output[j, :]]\n output_f.write(str(ids[j]) + ' ' + ' '.join(vec_str) + '\\n')\n\n output_f.close()"
] | [
[
"tensorflow.global_variables_initializer",
"tensorflow.train.latest_checkpoint",
"tensorflow.train.start_queue_runners",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.train.batch",
"tensorflow.train.Coordinator"
]
] |
jeantardelli/math-with-python | [
"119bbbc62329c0d834d965232239bd3b39116cc1"
] | [
"data-and-statistics/understanding-a-population-using-sampling.py"
] | [
"\"\"\"\nOne of the central problems in statistics is to make estimations — and quantify\nhow good these estimations are — of the distribution of an entire population\ngiven only a small (random) sample. A classic example is to estimate the average\nheight of all the people in a country when measuring the height of a randomly\nselected sample of people. These kinds of problems are particularly interesting\nwhen the true population distribution, by which we usually mean the mean of the\nwhole population, cannot feasibly be measured. In this case, we must rely on our\nknowledge of statistics and a (usually much smaller) randomly selected sample to\nestimate the true population mean and standard deviation, and also quantify how\ngood our estimations are. It is the latter that is the source of confusion,\nmisunderstanding, and misrepresentation of statistics in the wider world.\n\nThis module illustrates how to estimate the population mean and give a\nconfidence interval fo these estimates.\n\"\"\"\nimport math\nimport pandas as pd\n\nfrom scipy import stats\n\nsample_data = pd.Series([\n 172.3, 171.3, 164.7, 162.9, 172.5, 176.3, 174.8, 171.9,\n 176.8, 167.8, 164.5, 179.7, 157.8, 170.6, 189.9, 185. ,\n 172.7, 165.5, 174.5, 171.5])\n\nsample_mean = sample_data.mean()\nsample_std = sample_data.std()\n\nprint(f\"Mean: {sample_mean}, st. dev: {sample_std}\")\n# Mean: 172.15, st. dev: 7.473778724383846\n\nN = sample_data.count()\nstd_err = sample_std/math.sqrt(N)\n\ncv_95, cv_99 = stats.t.ppf([0.975, 0.995], df=N-1)\n\npm_95 = cv_95 * std_err\npm_99 = cv_99 * std_err\nconf_interval_95 = [sample_mean - pm_95, sample_mean + pm_95] \nconf_interval_99 = [sample_mean - pm_99, sample_mean + pm_99]\n\nprint(f\"95% confidence: {conf_interval_95}\")\nprint(f\"99% confidence: {conf_interval_99}\")\n# 95% confidence: [168.65216388659374, 175.64783611340627]\n# 99% confidence: [167.36884119608774, 176.93115880391227]\n"
] | [
[
"pandas.Series",
"scipy.stats.t.ppf"
]
] |
Bhavay192/keras | [
"f1e9c76675981ee6683f54a3ce569212d551d12d"
] | [
"keras/optimizer_v2/rmsprop_test.py"
] | [
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for rmsprop.\"\"\"\n\nimport tensorflow.compat.v2 as tf\n\nimport copy\nimport itertools\nimport math\n\nfrom absl.testing import parameterized\nimport numpy as np\nfrom tensorflow.python.framework import test_util\nfrom keras import combinations\nfrom keras import testing_utils\nfrom keras.optimizer_v2 import learning_rate_schedule\nfrom keras.optimizer_v2 import rmsprop\n\n_DATA_TYPES = [\n tf.half, tf.float32, tf.float64, tf.complex64,\n tf.complex128\n]\n\n_TEST_PARAM_VALUES = [\n # learning_rate, rho, momentum, epsilon, centered\n [0.05, 0.9, 0.0, 1e-3, True],\n [0.05, 0.9, 0.0, 1e-3, False],\n [0.1, 0.9, 0.0, 1e-3, True],\n [0.01, 0.9, 0.0, 1e-5, True],\n [0.01, 0.9, 0.9, 1e-5, True],\n]\n\n_TESTPARAMS = [\n [data_type] + values\n for data_type, values in itertools.product(_DATA_TYPES, _TEST_PARAM_VALUES)\n]\n\n\nclass RMSpropOptimizerTest(tf.test.TestCase, parameterized.TestCase):\n\n def _rmsprop_update_numpy(self, var, g, mg, rms, mom, lr, rho, momentum,\n epsilon, centered):\n rms_t = rms * rho + (1 - rho) * g * g\n if centered:\n mg_t = mg * rho + (1 - rho) * g\n denom_t = rms_t - mg_t * mg_t\n else:\n mg_t = mg\n denom_t = rms_t\n if momentum > 0.:\n mom_t = momentum * mom + lr * g / (np.sqrt(denom_t + epsilon))\n var_t = var - mom_t\n else:\n mom_t = mom\n var_t = var - lr * g / (np.sqrt(denom_t) + epsilon)\n return var_t, mg_t, rms_t, mom_t\n\n def _sparse_rmsprop_update_numpy(self, var, gindexs, gvalues, mg, rms, mom,\n lr, rho, momentum, epsilon, centered):\n mg_t = copy.deepcopy(mg)\n rms_t = copy.deepcopy(rms)\n mom_t = copy.deepcopy(mom)\n var_t = copy.deepcopy(var)\n for i in range(len(gindexs)):\n gindex = gindexs[i]\n gvalue = gvalues[i]\n rms_t[gindex] = rms[gindex] * rho + (1 - rho) * gvalue * gvalue\n if centered:\n mg_t[gindex] = mg_t[gindex] * rho + (1 - rho) * gvalue\n denom_t = rms_t[gindex] - mg_t[gindex] * mg_t[gindex]\n else:\n denom_t = rms_t[gindex]\n if momentum > 0.:\n mom_t[gindex] = momentum * mom[gindex] + lr * gvalue / np.sqrt(denom_t +\n epsilon)\n var_t[gindex] = var[gindex] - mom_t[gindex]\n else:\n mom_t[gindex] = mom[gindex]\n var_t[gindex] = var[gindex] - lr * gvalue / (np.sqrt(denom_t) + epsilon)\n return var_t, mg_t, rms_t, mom_t\n\n def testDense(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n for (dtype, learning_rate, rho, momentum, epsilon, centered) in _TESTPARAMS:\n with tf.compat.v1.get_default_graph().as_default(), testing_utils.use_gpu():\n # Initialize variables for numpy implementation.\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.2], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.2], dtype=dtype.as_numpy_dtype)\n\n var0 = tf.Variable(var0_np, dtype=dtype)\n var1 = tf.Variable(var1_np, dtype=dtype)\n grads0 = tf.constant(grads0_np, dtype=dtype)\n grads1 = tf.constant(grads1_np, dtype=dtype)\n opt = rmsprop.RMSprop(\n learning_rate=learning_rate,\n rho=rho,\n momentum=momentum,\n epsilon=epsilon,\n centered=centered)\n\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n if centered:\n mg0 = opt.get_slot(var0, \"mg\")\n mg1 = opt.get_slot(var1, \"mg\")\n else:\n mg0 = None\n mg1 = None\n\n if momentum > 0.:\n mom0 = opt.get_slot(var0, \"momentum\")\n mom1 = opt.get_slot(var1, \"momentum\")\n else:\n mom0 = None\n mom1 = None\n\n rms0 = opt.get_slot(var0, \"rms\")\n self.assertIsNotNone(rms0)\n rms1 = opt.get_slot(var1, \"rms\")\n self.assertIsNotNone(rms1)\n\n mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n rms0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n rms1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 3 steps of RMSprop\n for _ in range(1, 4):\n self.evaluate(update)\n\n var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(\n var0_np, grads0_np, mg0_np, rms0_np, mom0_np, learning_rate, rho,\n momentum, epsilon, centered)\n var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(\n var1_np, grads1_np, mg1_np, rms1_np, mom1_np, learning_rate, rho,\n momentum, epsilon, centered)\n\n # Validate updated params\n if centered:\n self.assertAllCloseAccordingToType(mg0_np, self.evaluate(mg0))\n self.assertAllCloseAccordingToType(mg1_np, self.evaluate(mg1))\n if momentum > 0.:\n self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))\n self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))\n self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))\n self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n def testDenseWithLearningRateDecay(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n with tf.Graph().as_default():\n var0_np = np.array([1.0, 2.0])\n grads0_np = np.array([0.1, 0.2])\n var1_np = np.array([3.0, 4.0])\n grads1_np = np.array([0.01, 0.2])\n\n var0 = tf.Variable(var0_np)\n var1 = tf.Variable(var1_np)\n grads0 = tf.constant(grads0_np)\n grads1 = tf.constant(grads1_np)\n learning_rate = 0.01\n rho = 0.9\n momentum = 0.0\n epsilon = 1e-7\n centered = False\n decay = 0.5\n opt = rmsprop.RMSprop(\n learning_rate=learning_rate,\n rho=rho,\n momentum=momentum,\n epsilon=epsilon,\n centered=centered,\n decay=decay)\n\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n rms0 = opt.get_slot(var0, \"rms\")\n self.assertIsNotNone(rms0)\n rms1 = opt.get_slot(var1, \"rms\")\n self.assertIsNotNone(rms1)\n if momentum > 0.:\n mom0 = opt.get_slot(var0, \"momentum\")\n mom1 = opt.get_slot(var1, \"momentum\")\n else:\n mom0 = None\n mom1 = None\n\n mg0_np = np.array([0.0, 0.0])\n mg1_np = np.array([0.0, 0.0])\n rms0_np = np.array([0.0, 0.0])\n rms1_np = np.array([0.0, 0.0])\n mom0_np = np.array([0.0, 0.0])\n mom1_np = np.array([0.0, 0.0])\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 4 steps of RMSprop\n for t in range(2):\n self.evaluate(update)\n\n lr = learning_rate / (1 + decay * t)\n var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(\n var0_np, grads0_np, mg0_np, rms0_np, mom0_np, lr, rho, momentum,\n epsilon, centered)\n var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(\n var1_np, grads1_np, mg1_np, rms1_np, mom1_np, lr, rho, momentum,\n epsilon, centered)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))\n self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))\n if momentum > 0.:\n self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))\n self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n def testDenseWithLearningRateInverseTimeDecay(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n with tf.Graph().as_default():\n var0_np = np.array([1.0, 2.0])\n grads0_np = np.array([0.1, 0.2])\n var1_np = np.array([3.0, 4.0])\n grads1_np = np.array([0.01, 0.2])\n\n var0 = tf.Variable(var0_np)\n var1 = tf.Variable(var1_np)\n grads0 = tf.constant(grads0_np)\n grads1 = tf.constant(grads1_np)\n learning_rate = 0.01\n rho = 0.9\n momentum = 0.0\n epsilon = 1e-7\n centered = False\n decay = 0.5\n lr_schedule = learning_rate_schedule.InverseTimeDecay(\n learning_rate, decay_steps=1.0, decay_rate=decay)\n opt = rmsprop.RMSprop(\n learning_rate=lr_schedule,\n rho=rho,\n momentum=momentum,\n epsilon=epsilon,\n centered=centered)\n\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n rms0 = opt.get_slot(var0, \"rms\")\n self.assertIsNotNone(rms0)\n rms1 = opt.get_slot(var1, \"rms\")\n self.assertIsNotNone(rms1)\n if momentum > 0.:\n mom0 = opt.get_slot(var0, \"momentum\")\n mom1 = opt.get_slot(var1, \"momentum\")\n else:\n mom0 = None\n mom1 = None\n\n mg0_np = np.array([0.0, 0.0])\n mg1_np = np.array([0.0, 0.0])\n rms0_np = np.array([0.0, 0.0])\n rms1_np = np.array([0.0, 0.0])\n mom0_np = np.array([0.0, 0.0])\n mom1_np = np.array([0.0, 0.0])\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 4 steps of RMSprop\n for t in range(2):\n self.evaluate(update)\n\n lr = learning_rate / (1 + decay * t)\n var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(\n var0_np, grads0_np, mg0_np, rms0_np, mom0_np, lr, rho, momentum,\n epsilon, centered)\n var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(\n var1_np, grads1_np, mg1_np, rms1_np, mom1_np, lr, rho, momentum,\n epsilon, centered)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))\n self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))\n if momentum > 0.:\n self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))\n self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n def testMinimizeSparseResourceVariable(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n with tf.Graph().as_default():\n for dtype in _DATA_TYPES:\n var0 = tf.Variable([[1.0, 2.0]], dtype=dtype)\n x = tf.constant([[4.0], [5.0]], dtype=dtype)\n\n def loss():\n pred = tf.matmul(tf.compat.v1.nn.embedding_lookup([var0], [0]), x) # pylint: disable=cell-var-from-loop\n return pred * pred\n\n sgd_op = rmsprop.RMSprop(\n learning_rate=1.0, rho=0.0, momentum=0.0, epsilon=0.0,\n centered=False).minimize(\n loss, var_list=[var0])\n self.evaluate(tf.compat.v1.global_variables_initializer())\n # Fetch params to validate initial values\n self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))\n # Run 1 step of sgd\n self.evaluate(sgd_op)\n # Validate updated params\n self.assertAllCloseAccordingToType([[0., 1.]],\n self.evaluate(var0),\n atol=0.01)\n\n def testMinimizeSparseResourceVariableCentered(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n with tf.Graph().as_default():\n for dtype in _DATA_TYPES:\n var0 = tf.Variable([[1.0, 2.0]], dtype=dtype)\n x = tf.constant([[4.0], [5.0]], dtype=dtype)\n\n def loss():\n pred = tf.matmul(tf.compat.v1.nn.embedding_lookup([var0], [0]), x) # pylint: disable=cell-var-from-loop\n return pred * pred\n\n # loss = lambda: pred * pred # pylint: disable=cell-var-from-loop\n sgd_op = rmsprop.RMSprop(\n learning_rate=1.0, rho=0.0, momentum=0.0, epsilon=1.0,\n centered=True).minimize(\n loss, var_list=[var0])\n self.evaluate(tf.compat.v1.global_variables_initializer())\n # Fetch params to validate initial values\n self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))\n # Run 1 step of sgd\n self.evaluate(sgd_op)\n # Validate updated params\n self.assertAllCloseAccordingToType([[-111, -138]],\n self.evaluate(var0),\n atol=0.01)\n\n def testSparse(self):\n # TODO(tanzheny, omalleyt): Fix test in eager mode.\n for (dtype, learning_rate, rho, momentum, epsilon, centered) in _TESTPARAMS:\n with tf.compat.v1.get_default_graph().as_default(), testing_utils.use_gpu():\n # Initialize variables for numpy implementation.\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = tf.Variable(var0_np)\n var1 = tf.Variable(var1_np)\n grads0_np_indices = np.array([0], dtype=np.int32)\n grads0 = tf.IndexedSlices(\n tf.constant(grads0_np),\n tf.constant(grads0_np_indices), tf.constant([1]))\n grads1_np_indices = np.array([1], dtype=np.int32)\n grads1 = tf.IndexedSlices(\n tf.constant(grads1_np),\n tf.constant(grads1_np_indices), tf.constant([1]))\n opt = rmsprop.RMSprop(\n learning_rate=learning_rate,\n rho=rho,\n momentum=momentum,\n epsilon=epsilon,\n centered=centered)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n self.evaluate(tf.compat.v1.global_variables_initializer())\n\n if centered:\n mg0 = opt.get_slot(var0, \"mg\")\n self.assertEqual(mg0 is not None, centered)\n mg1 = opt.get_slot(var1, \"mg\")\n self.assertEqual(mg1 is not None, centered)\n else:\n mg0 = None\n mg1 = None\n rms0 = opt.get_slot(var0, \"rms\")\n self.assertIsNotNone(rms0)\n rms1 = opt.get_slot(var1, \"rms\")\n self.assertIsNotNone(rms1)\n if momentum > 0.:\n mom0 = opt.get_slot(var0, \"momentum\")\n mom1 = opt.get_slot(var1, \"momentum\")\n else:\n mom0 = None\n mom1 = None\n\n mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n rms0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n rms1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 3 steps of RMSprop\n for _ in range(1, 4):\n self.evaluate(update)\n\n var0_np, mg0_np, rms0_np, mom0_np = self._sparse_rmsprop_update_numpy(\n var0_np, grads0_np_indices, grads0_np, mg0_np, rms0_np, mom0_np,\n learning_rate, rho, momentum, epsilon, centered)\n var1_np, mg1_np, rms1_np, mom1_np = self._sparse_rmsprop_update_numpy(\n var1_np, grads1_np_indices, grads1_np, mg1_np, rms1_np, mom1_np,\n learning_rate, rho, momentum, epsilon, centered)\n\n # Validate updated params\n if centered:\n self.assertAllCloseAccordingToType(mg0_np, self.evaluate(mg0))\n self.assertAllCloseAccordingToType(mg1_np, self.evaluate(mg1))\n self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))\n self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))\n if momentum > 0.:\n self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))\n self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @combinations.generate(combinations.combine(mode=[\"eager\"]))\n def testCallableParams(self):\n for dtype in _DATA_TYPES:\n var0 = tf.Variable([1.0, 2.0], dtype=dtype)\n var1 = tf.Variable([3.0, 4.0], dtype=dtype)\n grads0 = tf.constant([0.1, 0.1], dtype=dtype)\n grads1 = tf.constant([0.01, 0.01], dtype=dtype)\n\n learning_rate = lambda: 2.0\n rho = lambda: 0.9\n momentum = lambda: 0.0\n epsilon = 1.0\n opt = rmsprop.RMSprop(learning_rate, rho, momentum, epsilon)\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n # Step 1: the rms accumulators where 1. So we should see a normal\n # update: v -= grad * learning_rate\n opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n # Check the parameters.\n self.assertAllCloseAccordingToType(\n np.array([\n 1.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)),\n 2.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0))\n ]), self.evaluate(var0))\n self.assertAllCloseAccordingToType(\n np.array([\n 3.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)),\n 4.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0))\n ]), self.evaluate(var1))\n # Step 2: the root mean square accumulators contain the previous update.\n opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n # Check the parameters.\n self.assertAllCloseAccordingToType(\n np.array([\n 1.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)) -\n (0.1 * 2.0 / math.sqrt(0.001 * 0.9 + 0.001 + 1.0)),\n 2.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)) -\n (0.1 * 2.0 / math.sqrt(0.001 * 0.9 + 0.001 + 1.0))\n ]), self.evaluate(var0))\n self.assertAllCloseAccordingToType(\n np.array([\n 3.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)) -\n (0.01 * 2.0 / math.sqrt(0.00001 * 0.9 + 1e-5 + 1.0)),\n 4.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)) -\n (0.01 * 2.0 / math.sqrt(0.00001 * 0.9 + 1e-5 + 1.0))\n ]), self.evaluate(var1))\n\n def testConstructRMSpropWithLR(self):\n opt = rmsprop.RMSprop(lr=1.0)\n opt_2 = rmsprop.RMSprop(learning_rate=0.1, lr=1.0)\n opt_3 = rmsprop.RMSprop(learning_rate=0.1)\n self.assertIsInstance(opt.lr, tf.Variable)\n self.assertIsInstance(opt_2.lr, tf.Variable)\n self.assertIsInstance(opt_3.lr, tf.Variable)\n\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose(self.evaluate(opt.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_2.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_3.lr), (0.1))\n\n @combinations.generate(combinations.combine(mode=[\"eager\"]))\n def testSlotsUniqueEager(self):\n v1 = tf.Variable(1.)\n v2 = tf.Variable(1.)\n\n opt = rmsprop.RMSprop(1., momentum=0., centered=False)\n opt.minimize(lambda: v1 + v2, var_list=[v1, v2])\n # There should be iteration, and one unique slot variable for v1 and v2.\n self.assertLen(set({id(v) for v in opt.variables()}), 3)\n self.assertEqual(\n self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))\n\n opt = rmsprop.RMSprop(learning_rate=1., momentum=0.2, centered=False)\n opt.minimize(lambda: v1 + v2, var_list=[v1, v2])\n # There should be iteration, and two unique slot variables for v1 and v2.\n self.assertLen(set({id(v) for v in opt.variables()}), 5)\n self.assertEqual(\n self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))\n\n opt = rmsprop.RMSprop(learning_rate=1., momentum=0.2, centered=True)\n opt.minimize(lambda: v1 + v2, var_list=[v1, v2])\n # There should be iteration, and three unique slot variables for v1 and v2\n self.assertLen(set({id(v) for v in opt.variables()}), 7)\n self.assertEqual(\n self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))\n\n @combinations.generate(combinations.combine(mode=[\"eager\"]))\n def testMomentumProperValue(self):\n with self.assertRaisesRegex(ValueError,\n r\"`momentum` must be between \\[0, 1\\]. \"\n r\"Received: momentum=2.5 \\(of type <class \"\n r\"\\'float\\'>\\).\"):\n rmsprop.RMSprop(1., momentum=2.5, centered=False)\n\n\n@combinations.generate(combinations.combine(mode=[\"graph\", \"eager\"]))\nclass SlotColocationTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.parameters([True, False])\n @test_util.run_gpu_only\n def testRunMinimizeOnGPUForCPUVariables(self, use_resource):\n with tf.device(\"/device:CPU:0\"):\n if use_resource:\n var0 = tf.Variable([1.0, 2.0], dtype=tf.float32)\n var1 = tf.Variable([3.0, 4.0], dtype=tf.float32)\n else:\n var0 = tf.Variable([1.0, 2.0], dtype=tf.float32)\n var1 = tf.Variable([3.0, 4.0], dtype=tf.float32)\n\n def loss():\n return 5 * var0 + 3 * var1\n\n opt = rmsprop.RMSprop(\n learning_rate=1.0, decay=0.9, momentum=0.5, epsilon=1.0)\n\n # Fetch params to validate initial values\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 1 step through optimizer on GPU.\n # Slot variables are created the first time optimizer is used on some\n # variable. This tests that slot variables will be colocated with the base\n # variable.\n with tf.device(\"/device:GPU:0\"):\n # Note that for eager execution, minimize expects a function instead of a\n # Tensor.\n opt_op = opt.minimize(loss, [var0, var1])\n self.evaluate(tf.compat.v1.global_variables_initializer())\n self.evaluate(opt_op)\n\n # Validate updated params, All variables should have decreased.\n self.assertTrue(all(v < 0.0 for v in self.evaluate(var0)),\n msg=\"updated variables: %s\" % self.evaluate(var0))\n self.assertTrue(all(v < 2.0 for v in self.evaluate(var1)),\n msg=\"updated variables: %s\" % self.evaluate(var1))\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] | [
[
"numpy.sqrt",
"tensorflow.compat.v2.compat.v1.nn.embedding_lookup",
"tensorflow.compat.v2.compat.v1.get_default_graph",
"tensorflow.compat.v2.compat.v1.global_variables_initializer",
"tensorflow.compat.v2.Graph",
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.device",
"numpy.array",
"tensorflow.compat.v2.constant",
"tensorflow.compat.v2.Variable"
]
] |
shivampotdar/Artificial-Intelligence-with-Python | [
"00221c3b1a6d8003765d1ca48b5c95f86da375d9"
] | [
"Chapter 10/code/category_predictor.py"
] | [
"from sklearn.datasets import fetch_20newsgroups\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# Define the category map\ncategory_map = {'talk.politics.misc': 'Politics', 'rec.autos': 'Autos', \n 'rec.sport.hockey': 'Hockey', 'sci.electronics': 'Electronics', \n 'sci.med': 'Medicine'}\n\n# Get the training dataset\ntraining_data = fetch_20newsgroups(subset='train', \n categories=category_map.keys(), shuffle=True, random_state=5)\n\n# Build a count vectorizer and extract term counts \ncount_vectorizer = CountVectorizer()\ntrain_tc = count_vectorizer.fit_transform(training_data.data)\nprint(\"\\nDimensions of training data:\", train_tc.shape)\n\n# Create the tf-idf transformer\ntfidf = TfidfTransformer()\ntrain_tfidf = tfidf.fit_transform(train_tc)\n\n# Define test data \ninput_data = [\n 'You need to be careful with cars when you are driving on slippery roads', \n 'A lot of devices can be operated wirelessly',\n 'Players need to be careful when they are close to goal posts',\n 'Political debates help us understand the perspectives of both sides'\n]\n\n# Train a Multinomial Naive Bayes classifier\nclassifier = MultinomialNB().fit(train_tfidf, training_data.target)\n\n# Transform input data using count vectorizer\ninput_tc = count_vectorizer.transform(input_data)\n\n# Transform vectorized data using tfidf transformer\ninput_tfidf = tfidf.transform(input_tc)\n\n# Predict the output categories\npredictions = classifier.predict(input_tfidf)\n\n# Print the outputs\nfor sent, category in zip(input_data, predictions):\n print('\\nInput:', sent, '\\nPredicted category:', \\\n category_map[training_data.target_names[category]])\n\n"
] | [
[
"sklearn.naive_bayes.MultinomialNB",
"sklearn.feature_extraction.text.TfidfTransformer",
"sklearn.feature_extraction.text.CountVectorizer"
]
] |
andrzejmalota/StockPricePrediction | [
"a6d7da353b706fb2d970f2883841db14d896268f"
] | [
"src/trading_simulation/simulation.py"
] | [
"import sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nclass Simulation:\n def __init__(self, init_investment, stock_returns, strategy, predicted_movements=None):\n self.init_investment = init_investment\n self.predicted_movements = predicted_movements\n self.stock_returns = stock_returns\n self.strategy = strategy\n self.action_history = []\n self.account_history = [init_investment]\n self.__actual_investment = 0\n self.step = 0\n self.return_on_investment = 0\n self.profit_on_investment = 0\n\n def start(self):\n for self.step in range(len(self.stock_returns)):\n if self.predicted_movements is not None:\n action = self.strategy.decide(self.predicted_movements[self.step])\n else:\n action = self.strategy.decide(self.step)\n self.__make_transaction(action)\n\n def __make_transaction(self, action):\n self.action_history.append(action)\n if action == 'buy':\n self.__buy()\n elif action == 'hold':\n self.__hold()\n elif action == 'sell':\n self.__sell()\n elif action == 'wait':\n self.__wait()\n else:\n sys.exit('Action not implemented, exiting program!')\n\n def get_investment_performance(self):\n self.return_on_investment = (self.account_history[-1] - self.init_investment) / self.init_investment\n self.profit_on_investment = self.account_history[-1] - self.init_investment\n return {'return': self.return_on_investment,\n 'profit': self.profit_on_investment}\n\n def plot_trading_history(self, stock_prices, date):\n date = date.iloc[-len(stock_prices-1):]\n stock_prices = np.insert(stock_prices, 0, stock_prices[0])\n fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(40, 20))\n ax1.plot(stock_prices, color='black', label='Cena zamknięcia akcji')\n actions = pd.DataFrame(self.action_history)\n buy_idx = actions[actions[0] == 'buy'].index.to_list()\n sell_idx = actions[actions[0] == 'sell'].index.to_list()\n stock_prices = np.array(stock_prices)\n ax1.scatter(buy_idx, stock_prices[buy_idx], color='green', s=40, label='Kupno')\n ax1.scatter(sell_idx, stock_prices[sell_idx], color='red', s=40, label='Sprzedaż')\n ax1.legend()\n ax2.plot(self.account_history[:-1], label='Kapitał')\n plt.xlabel('Krok czasowy')\n ax1.set_ylabel('Cena akcji')\n ax2.set_ylabel('Kapitał')\n ax2.legend()\n plt.show()\n\n def __calculate_daily_profit(self):\n self.__actual_investment += self.__actual_investment * self.stock_returns[self.step]\n\n def __buy(self):\n self.__actual_investment = self.account_history[self.step]\n self.__calculate_daily_profit()\n self.account_history.append(self.__actual_investment)\n\n def __hold(self):\n self.__calculate_daily_profit()\n self.account_history.append(self.__actual_investment)\n\n def __sell(self):\n self.account_history.append(self.__actual_investment)\n self.__actual_investment = 0\n\n def __wait(self):\n self.account_history.append(self.account_history[self.step-1])\n"
] | [
[
"pandas.DataFrame",
"numpy.insert",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.pyplot.xlabel"
]
] |
pranavrajpal/scipy | [
"7dcdeffed53483a60b3e054618520e0f28adeba4",
"859c1061b3d5aa30c4466824049d69edde5499a2"
] | [
"scipy/optimize/tests/test_linprog.py",
"scipy/integrate/_ivp/rk.py"
] | [
"\"\"\"\nUnit test for Linear Programming\n\"\"\"\nimport sys\n\nimport numpy as np\nfrom numpy.testing import (assert_, assert_allclose, assert_equal,\n assert_array_less, assert_warns, suppress_warnings)\nfrom pytest import raises as assert_raises\nfrom scipy.optimize import linprog, OptimizeWarning\nfrom scipy.sparse.linalg import MatrixRankWarning\nfrom scipy.linalg import LinAlgWarning\nimport scipy.sparse\nimport pytest\n\nhas_umfpack = True\ntry:\n from scikits.umfpack import UmfpackWarning\nexcept ImportError:\n has_umfpack = False\n\nhas_cholmod = True\ntry:\n import sksparse\n from sksparse.cholmod import cholesky as cholmod\nexcept ImportError:\n has_cholmod = False\n\n\ndef _assert_iteration_limit_reached(res, maxiter):\n assert_(not res.success, \"Incorrectly reported success\")\n assert_(res.success < maxiter, \"Incorrectly reported number of iterations\")\n assert_equal(res.status, 1, \"Failed to report iteration limit reached\")\n\n\ndef _assert_infeasible(res):\n # res: linprog result object\n assert_(not res.success, \"incorrectly reported success\")\n assert_equal(res.status, 2, \"failed to report infeasible status\")\n\n\ndef _assert_unbounded(res):\n # res: linprog result object\n assert_(not res.success, \"incorrectly reported success\")\n assert_equal(res.status, 3, \"failed to report unbounded status\")\n\n\ndef _assert_unable_to_find_basic_feasible_sol(res):\n # res: linprog result object\n\n # The status may be either 2 or 4 depending on why the feasible solution\n # could not be found. If the undelying problem is expected to not have a\n # feasible solution, _assert_infeasible should be used.\n assert_(not res.success, \"incorrectly reported success\")\n assert_(res.status in (2, 4), \"failed to report optimization failure\")\n\n\ndef _assert_success(res, desired_fun=None, desired_x=None,\n rtol=1e-8, atol=1e-8):\n # res: linprog result object\n # desired_fun: desired objective function value or None\n # desired_x: desired solution or None\n if not res.success:\n msg = \"linprog status {0}, message: {1}\".format(res.status,\n res.message)\n raise AssertionError(msg)\n\n assert_equal(res.status, 0)\n if desired_fun is not None:\n assert_allclose(res.fun, desired_fun,\n err_msg=\"converged to an unexpected objective value\",\n rtol=rtol, atol=atol)\n if desired_x is not None:\n assert_allclose(res.x, desired_x,\n err_msg=\"converged to an unexpected solution\",\n rtol=rtol, atol=atol)\n\n\ndef magic_square(n):\n \"\"\"\n Generates a linear program for which integer solutions represent an\n n x n magic square; binary decision variables represent the presence\n (or absence) of an integer 1 to n^2 in each position of the square.\n \"\"\"\n\n np.random.seed(0)\n M = n * (n**2 + 1) / 2\n\n numbers = np.arange(n**4) // n**2 + 1\n\n numbers = numbers.reshape(n**2, n, n)\n\n zeros = np.zeros((n**2, n, n))\n\n A_list = []\n b_list = []\n\n # Rule 1: use every number exactly once\n for i in range(n**2):\n A_row = zeros.copy()\n A_row[i, :, :] = 1\n A_list.append(A_row.flatten())\n b_list.append(1)\n\n # Rule 2: Only one number per square\n for i in range(n):\n for j in range(n):\n A_row = zeros.copy()\n A_row[:, i, j] = 1\n A_list.append(A_row.flatten())\n b_list.append(1)\n\n # Rule 3: sum of rows is M\n for i in range(n):\n A_row = zeros.copy()\n A_row[:, i, :] = numbers[:, i, :]\n A_list.append(A_row.flatten())\n b_list.append(M)\n\n # Rule 4: sum of columns is M\n for i in range(n):\n A_row = zeros.copy()\n A_row[:, :, i] = numbers[:, :, i]\n A_list.append(A_row.flatten())\n b_list.append(M)\n\n # Rule 5: sum of diagonals is M\n A_row = zeros.copy()\n A_row[:, range(n), range(n)] = numbers[:, range(n), range(n)]\n A_list.append(A_row.flatten())\n b_list.append(M)\n A_row = zeros.copy()\n A_row[:, range(n), range(-1, -n - 1, -1)] = \\\n numbers[:, range(n), range(-1, -n - 1, -1)]\n A_list.append(A_row.flatten())\n b_list.append(M)\n\n A = np.array(np.vstack(A_list), dtype=float)\n b = np.array(b_list, dtype=float)\n c = np.random.rand(A.shape[1])\n\n return A, b, c, numbers\n\n\ndef lpgen_2d(m, n):\n \"\"\" -> A b c LP test: m*n vars, m+n constraints\n row sums == n/m, col sums == 1\n https://gist.github.com/denis-bz/8647461\n \"\"\"\n np.random.seed(0)\n c = - np.random.exponential(size=(m, n))\n Arow = np.zeros((m, m * n))\n brow = np.zeros(m)\n for j in range(m):\n j1 = j + 1\n Arow[j, j * n:j1 * n] = 1\n brow[j] = n / m\n\n Acol = np.zeros((n, m * n))\n bcol = np.zeros(n)\n for j in range(n):\n j1 = j + 1\n Acol[j, j::n] = 1\n bcol[j] = 1\n\n A = np.vstack((Arow, Acol))\n b = np.hstack((brow, bcol))\n\n return A, b, c.ravel()\n\n\ndef very_random_gen(seed=0):\n np.random.seed(seed)\n m_eq, m_ub, n = 10, 20, 50\n c = np.random.rand(n)-0.5\n A_ub = np.random.rand(m_ub, n)-0.5\n b_ub = np.random.rand(m_ub)-0.5\n A_eq = np.random.rand(m_eq, n)-0.5\n b_eq = np.random.rand(m_eq)-0.5\n lb = -np.random.rand(n)\n ub = np.random.rand(n)\n lb[lb < -np.random.rand()] = -np.inf\n ub[ub > np.random.rand()] = np.inf\n bounds = np.vstack((lb, ub)).T\n return c, A_ub, b_ub, A_eq, b_eq, bounds\n\n\ndef nontrivial_problem():\n c = [-1, 8, 4, -6]\n A_ub = [[-7, -7, 6, 9],\n [1, -1, -3, 0],\n [10, -10, -7, 7],\n [6, -1, 3, 4]]\n b_ub = [-3, 6, -6, 6]\n A_eq = [[-10, 1, 1, -8]]\n b_eq = [-4]\n x_star = [101 / 1391, 1462 / 1391, 0, 752 / 1391]\n f_star = 7083 / 1391\n return c, A_ub, b_ub, A_eq, b_eq, x_star, f_star\n\n\ndef l1_regression_prob(seed=0, m=8, d=9, n=100):\n '''\n Training data is {(x0, y0), (x1, y2), ..., (xn-1, yn-1)}\n x in R^d\n y in R\n n: number of training samples\n d: dimension of x, i.e. x in R^d\n phi: feature map R^d -> R^m\n m: dimension of feature space\n '''\n np.random.seed(seed)\n phi = np.random.normal(0, 1, size=(m, d)) # random feature mapping\n w_true = np.random.randn(m)\n x = np.random.normal(0, 1, size=(d, n)) # features\n y = w_true @ (phi @ x) + np.random.normal(0, 1e-5, size=n) # measurements\n\n # construct the problem\n c = np.ones(m+n)\n c[:m] = 0\n A_ub = scipy.sparse.lil_matrix((2*n, n+m))\n idx = 0\n for ii in range(n):\n A_ub[idx, :m] = phi @ x[:, ii]\n A_ub[idx, m+ii] = -1\n A_ub[idx+1, :m] = -1*phi @ x[:, ii]\n A_ub[idx+1, m+ii] = -1\n idx += 2\n A_ub = A_ub.tocsc()\n b_ub = np.zeros(2*n)\n b_ub[0::2] = y\n b_ub[1::2] = -y\n bnds = [(None, None)]*m + [(0, None)]*n\n return c, A_ub, b_ub, bnds\n\n\ndef generic_callback_test(self):\n # Check that callback is as advertised\n last_cb = {}\n\n def cb(res):\n message = res.pop('message')\n complete = res.pop('complete')\n\n assert_(res.pop('phase') in (1, 2))\n assert_(res.pop('status') in range(4))\n assert_(isinstance(res.pop('nit'), int))\n assert_(isinstance(complete, bool))\n assert_(isinstance(message, str))\n\n last_cb['x'] = res['x']\n last_cb['fun'] = res['fun']\n last_cb['slack'] = res['slack']\n last_cb['con'] = res['con']\n\n c = np.array([-3, -2])\n A_ub = [[2, 1], [1, 1], [1, 0]]\n b_ub = [10, 8, 4]\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, callback=cb, method=self.method)\n\n _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])\n assert_allclose(last_cb['fun'], res['fun'])\n assert_allclose(last_cb['x'], res['x'])\n assert_allclose(last_cb['con'], res['con'])\n assert_allclose(last_cb['slack'], res['slack'])\n\n\ndef test_unknown_solvers_and_options():\n c = np.array([-3, -2])\n A_ub = [[2, 1], [1, 1], [1, 0]]\n b_ub = [10, 8, 4]\n\n assert_raises(ValueError, linprog,\n c, A_ub=A_ub, b_ub=b_ub, method='ekki-ekki-ekki')\n assert_raises(ValueError, linprog,\n c, A_ub=A_ub, b_ub=b_ub, method='highs-ekki')\n assert_raises(ValueError, linprog, c, A_ub=A_ub, b_ub=b_ub,\n options={\"rr_method\": 'ekki-ekki-ekki'})\n\n\ndef test_choose_solver():\n # 'highs' chooses 'dual'\n c = np.array([-3, -2])\n A_ub = [[2, 1], [1, 1], [1, 0]]\n b_ub = [10, 8, 4]\n\n res = linprog(c, A_ub, b_ub, method='highs')\n _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])\n\n\nA_ub = None\nb_ub = None\nA_eq = None\nb_eq = None\nbounds = None\n\n################\n# Common Tests #\n################\n\n\nclass LinprogCommonTests:\n \"\"\"\n Base class for `linprog` tests. Generally, each test will be performed\n once for every derived class of LinprogCommonTests, each of which will\n typically change self.options and/or self.method. Effectively, these tests\n are run for many combination of method (simplex, revised simplex, and\n interior point) and options (such as pivoting rule or sparse treatment).\n \"\"\"\n\n ##################\n # Targeted Tests #\n ##################\n\n def test_callback(self):\n generic_callback_test(self)\n\n def test_disp(self):\n # test that display option does not break anything.\n A, b, c = lpgen_2d(20, 20)\n res = linprog(c, A_ub=A, b_ub=b, method=self.method,\n options={\"disp\": True})\n _assert_success(res, desired_fun=-64.049494229)\n\n def test_docstring_example(self):\n # Example from linprog docstring.\n c = [-1, 4]\n A = [[-3, 1], [1, 2]]\n b = [6, 4]\n x0_bounds = (None, None)\n x1_bounds = (-3, None)\n res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),\n options=self.options, method=self.method)\n _assert_success(res, desired_fun=-22)\n\n def test_type_error(self):\n # (presumably) checks that linprog recognizes type errors\n # This is tested more carefully in test__linprog_clean_inputs.py\n c = [1]\n A_eq = [[1]]\n b_eq = \"hello\"\n assert_raises(TypeError, linprog,\n c, A_eq=A_eq, b_eq=b_eq,\n method=self.method, options=self.options)\n\n def test_aliasing_b_ub(self):\n # (presumably) checks that linprog does not modify b_ub\n # This is tested more carefully in test__linprog_clean_inputs.py\n c = np.array([1.0])\n A_ub = np.array([[1.0]])\n b_ub_orig = np.array([3.0])\n b_ub = b_ub_orig.copy()\n bounds = (-4.0, np.inf)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-4, desired_x=[-4])\n assert_allclose(b_ub_orig, b_ub)\n\n def test_aliasing_b_eq(self):\n # (presumably) checks that linprog does not modify b_eq\n # This is tested more carefully in test__linprog_clean_inputs.py\n c = np.array([1.0])\n A_eq = np.array([[1.0]])\n b_eq_orig = np.array([3.0])\n b_eq = b_eq_orig.copy()\n bounds = (-4.0, np.inf)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=3, desired_x=[3])\n assert_allclose(b_eq_orig, b_eq)\n\n def test_non_ndarray_args(self):\n # (presumably) checks that linprog accepts list in place of arrays\n # This is tested more carefully in test__linprog_clean_inputs.py\n c = [1.0]\n A_ub = [[1.0]]\n b_ub = [3.0]\n A_eq = [[1.0]]\n b_eq = [2.0]\n bounds = (-1.0, 10.0)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=2, desired_x=[2])\n\n def test_unknown_options(self):\n c = np.array([-3, -2])\n A_ub = [[2, 1], [1, 1], [1, 0]]\n b_ub = [10, 8, 4]\n\n def f(c, A_ub=None, b_ub=None, A_eq=None,\n b_eq=None, bounds=None, options={}):\n linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=options)\n\n o = {key: self.options[key] for key in self.options}\n o['spam'] = 42\n\n assert_warns(OptimizeWarning, f,\n c, A_ub=A_ub, b_ub=b_ub, options=o)\n\n def test_invalid_inputs(self):\n\n def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):\n linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n # Test ill-formatted bounds\n assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4)])\n assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4), (3, 4, 5)])\n assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, -2), (1, 2)])\n\n # Test other invalid inputs\n assert_raises(ValueError, f, [1, 2], A_ub=[[1, 2]], b_ub=[1, 2])\n assert_raises(ValueError, f, [1, 2], A_ub=[[1]], b_ub=[1])\n assert_raises(ValueError, f, [1, 2], A_eq=[[1, 2]], b_eq=[1, 2])\n assert_raises(ValueError, f, [1, 2], A_eq=[[1]], b_eq=[1])\n assert_raises(ValueError, f, [1, 2], A_eq=[1], b_eq=1)\n\n # this last check doesn't make sense for sparse presolve\n if (\"_sparse_presolve\" in self.options and\n self.options[\"_sparse_presolve\"]):\n return\n # there aren't 3-D sparse matrices\n\n assert_raises(ValueError, f, [1, 2], A_ub=np.zeros((1, 1, 3)), b_eq=1)\n\n def test_sparse_constraints(self):\n # gh-13559: improve error message for sparse inputs when unsupported\n def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):\n linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n np.random.seed(0)\n m = 100\n n = 150\n A_eq = scipy.sparse.rand(m, n, 0.5)\n x_valid = np.random.randn((n))\n c = np.random.randn((n))\n ub = x_valid + np.random.rand((n))\n lb = x_valid - np.random.rand((n))\n bounds = np.column_stack((lb, ub))\n b_eq = A_eq * x_valid\n\n if self.method in {'simplex', 'revised simplex'}:\n # simplex and revised simplex should raise error\n with assert_raises(ValueError, match=f\"Method '{self.method}' \"\n \"does not support sparse constraint matrices.\"):\n linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,\n method=self.method, options=self.options)\n else:\n # other methods should succeed\n options = {**self.options}\n if self.method in {'interior-point'}:\n options['sparse'] = True\n\n res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,\n method=self.method, options=options)\n assert res.success\n\n def test_maxiter(self):\n # test iteration limit w/ Enzo example\n c = [4, 8, 3, 0, 0, 0]\n A = [\n [2, 5, 3, -1, 0, 0],\n [3, 2.5, 8, 0, -1, 0],\n [8, 10, 4, 0, 0, -1]]\n b = [185, 155, 600]\n np.random.seed(0)\n maxiter = 3\n res = linprog(c, A_eq=A, b_eq=b, method=self.method,\n options={\"maxiter\": maxiter})\n _assert_iteration_limit_reached(res, maxiter)\n assert_equal(res.nit, maxiter)\n\n def test_bounds_fixed(self):\n\n # Test fixed bounds (upper equal to lower)\n # If presolve option True, test if solution found in presolve (i.e.\n # number of iterations is 0).\n do_presolve = self.options.get('presolve', True)\n\n res = linprog([1], bounds=(1, 1),\n method=self.method, options=self.options)\n _assert_success(res, 1, 1)\n if do_presolve:\n assert_equal(res.nit, 0)\n\n res = linprog([1, 2, 3], bounds=[(5, 5), (-1, -1), (3, 3)],\n method=self.method, options=self.options)\n _assert_success(res, 12, [5, -1, 3])\n if do_presolve:\n assert_equal(res.nit, 0)\n\n res = linprog([1, 1], bounds=[(1, 1), (1, 3)],\n method=self.method, options=self.options)\n _assert_success(res, 2, [1, 1])\n if do_presolve:\n assert_equal(res.nit, 0)\n\n res = linprog([1, 1, 2], A_eq=[[1, 0, 0], [0, 1, 0]], b_eq=[1, 7],\n bounds=[(-5, 5), (0, 10), (3.5, 3.5)],\n method=self.method, options=self.options)\n _assert_success(res, 15, [1, 7, 3.5])\n if do_presolve:\n assert_equal(res.nit, 0)\n\n def test_bounds_infeasible(self):\n\n # Test ill-valued bounds (upper less than lower)\n # If presolve option True, test if solution found in presolve (i.e.\n # number of iterations is 0).\n do_presolve = self.options.get('presolve', True)\n\n res = linprog([1], bounds=(1, -2), method=self.method, options=self.options)\n _assert_infeasible(res)\n if do_presolve:\n assert_equal(res.nit, 0)\n\n res = linprog([1], bounds=[(1, -2)], method=self.method, options=self.options)\n _assert_infeasible(res)\n if do_presolve:\n assert_equal(res.nit, 0)\n\n res = linprog([1, 2, 3], bounds=[(5, 0), (1, 2), (3, 4)], method=self.method, options=self.options)\n _assert_infeasible(res)\n if do_presolve:\n assert_equal(res.nit, 0)\n\n def test_bounds_infeasible_2(self):\n\n # Test ill-valued bounds (lower inf, upper -inf)\n # If presolve option True, test if solution found in presolve (i.e.\n # number of iterations is 0).\n # For the simplex method, the cases do not result in an\n # infeasible status, but in a RuntimeWarning. This is a\n # consequence of having _presolve() take care of feasibility\n # checks. See issue gh-11618.\n do_presolve = self.options.get('presolve', True)\n simplex_without_presolve = not do_presolve and self.method == 'simplex'\n\n c = [1, 2, 3]\n bounds_1 = [(1, 2), (np.inf, np.inf), (3, 4)]\n bounds_2 = [(1, 2), (-np.inf, -np.inf), (3, 4)]\n\n if simplex_without_presolve:\n def g(c, bounds):\n res = linprog(c, bounds=bounds, method=self.method, options=self.options)\n return res\n\n with pytest.warns(RuntimeWarning):\n with pytest.raises(IndexError):\n g(c, bounds=bounds_1)\n\n with pytest.warns(RuntimeWarning):\n with pytest.raises(IndexError):\n g(c, bounds=bounds_2)\n else:\n res = linprog(c=c, bounds=bounds_1, method=self.method, options=self.options)\n _assert_infeasible(res)\n if do_presolve:\n assert_equal(res.nit, 0)\n res = linprog(c=c, bounds=bounds_2, method=self.method, options=self.options)\n _assert_infeasible(res)\n if do_presolve:\n assert_equal(res.nit, 0)\n\n def test_empty_constraint_1(self):\n c = [-1, -2]\n res = linprog(c, method=self.method, options=self.options)\n _assert_unbounded(res)\n\n def test_empty_constraint_2(self):\n c = [-1, 1, -1, 1]\n bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]\n res = linprog(c, bounds=bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n # Unboundedness detected in presolve requires no iterations\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_empty_constraint_3(self):\n c = [1, -1, 1, -1]\n bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]\n res = linprog(c, bounds=bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[0, 0, -1, 1], desired_fun=-2)\n\n def test_inequality_constraints(self):\n # Minimize linear function subject to linear inequality constraints.\n # http://www.dam.brown.edu/people/huiwang/classes/am121/Archive/simplex_121_c.pdf\n c = np.array([3, 2]) * -1 # maximize\n A_ub = [[2, 1],\n [1, 1],\n [1, 0]]\n b_ub = [10, 8, 4]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-18, desired_x=[2, 6])\n\n def test_inequality_constraints2(self):\n # Minimize linear function subject to linear inequality constraints.\n # http://www.statslab.cam.ac.uk/~ff271/teaching/opt/notes/notes8.pdf\n # (dead link)\n c = [6, 3]\n A_ub = [[0, 3],\n [-1, -1],\n [-2, 1]]\n b_ub = [2, -1, -1]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=5, desired_x=[2 / 3, 1 / 3])\n\n def test_bounds_simple(self):\n c = [1, 2]\n bounds = (1, 2)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[1, 1])\n\n bounds = [(1, 2), (1, 2)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[1, 1])\n\n def test_bounded_below_only_1(self):\n c = np.array([1.0])\n A_eq = np.array([[1.0]])\n b_eq = np.array([3.0])\n bounds = (1.0, None)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=3, desired_x=[3])\n\n def test_bounded_below_only_2(self):\n c = np.ones(3)\n A_eq = np.eye(3)\n b_eq = np.array([1, 2, 3])\n bounds = (0.5, np.inf)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))\n\n def test_bounded_above_only_1(self):\n c = np.array([1.0])\n A_eq = np.array([[1.0]])\n b_eq = np.array([3.0])\n bounds = (None, 10.0)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=3, desired_x=[3])\n\n def test_bounded_above_only_2(self):\n c = np.ones(3)\n A_eq = np.eye(3)\n b_eq = np.array([1, 2, 3])\n bounds = (-np.inf, 4)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))\n\n def test_bounds_infinity(self):\n c = np.ones(3)\n A_eq = np.eye(3)\n b_eq = np.array([1, 2, 3])\n bounds = (-np.inf, np.inf)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))\n\n def test_bounds_mixed(self):\n # Problem has one unbounded variable and\n # another with a negative lower bound.\n c = np.array([-1, 4]) * -1 # maximize\n A_ub = np.array([[-3, 1],\n [1, 2]], dtype=np.float64)\n b_ub = [6, 4]\n x0_bounds = (-np.inf, np.inf)\n x1_bounds = (-3, np.inf)\n bounds = (x0_bounds, x1_bounds)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-80 / 7, desired_x=[-8 / 7, 18 / 7])\n\n def test_bounds_equal_but_infeasible(self):\n c = [-4, 1]\n A_ub = [[7, -2], [0, 1], [2, -2]]\n b_ub = [14, 0, 3]\n bounds = [(2, 2), (0, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n def test_bounds_equal_but_infeasible2(self):\n c = [-4, 1]\n A_eq = [[7, -2], [0, 1], [2, -2]]\n b_eq = [14, 0, 3]\n bounds = [(2, 2), (0, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n def test_bounds_equal_no_presolve(self):\n # There was a bug when a lower and upper bound were equal but\n # presolve was not on to eliminate the variable. The bound\n # was being converted to an equality constraint, but the bound\n # was not eliminated, leading to issues in postprocessing.\n c = [1, 2]\n A_ub = [[1, 2], [1.1, 2.2]]\n b_ub = [4, 8]\n bounds = [(1, 2), (2, 2)]\n\n o = {key: self.options[key] for key in self.options}\n o[\"presolve\"] = False\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n _assert_infeasible(res)\n\n def test_zero_column_1(self):\n m, n = 3, 4\n np.random.seed(0)\n c = np.random.rand(n)\n c[1] = 1\n A_eq = np.random.rand(m, n)\n A_eq[:, 1] = 0\n b_eq = np.random.rand(m)\n A_ub = [[1, 0, 1, 1]]\n b_ub = 3\n bounds = [(-10, 10), (-10, 10), (-10, None), (None, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-9.7087836730413404)\n\n def test_zero_column_2(self):\n np.random.seed(0)\n m, n = 2, 4\n c = np.random.rand(n)\n c[1] = -1\n A_eq = np.random.rand(m, n)\n A_eq[:, 1] = 0\n b_eq = np.random.rand(m)\n\n A_ub = np.random.rand(m, n)\n A_ub[:, 1] = 0\n b_ub = np.random.rand(m)\n bounds = (None, None)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n # Unboundedness detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_zero_row_1(self):\n c = [1, 2, 3]\n A_eq = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]\n b_eq = [0, 3, 0]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=3)\n\n def test_zero_row_2(self):\n A_ub = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]\n b_ub = [0, 3, 0]\n c = [1, 2, 3]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=0)\n\n def test_zero_row_3(self):\n m, n = 2, 4\n c = np.random.rand(n)\n A_eq = np.random.rand(m, n)\n A_eq[0, :] = 0\n b_eq = np.random.rand(m)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n # Infeasibility detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_zero_row_4(self):\n m, n = 2, 4\n c = np.random.rand(n)\n A_ub = np.random.rand(m, n)\n A_ub[0, :] = 0\n b_ub = -np.random.rand(m)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n # Infeasibility detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_singleton_row_eq_1(self):\n c = [1, 1, 1, 2]\n A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]\n b_eq = [1, 2, 2, 4]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n # Infeasibility detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_singleton_row_eq_2(self):\n c = [1, 1, 1, 2]\n A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]\n b_eq = [1, 2, 1, 4]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=4)\n\n def test_singleton_row_ub_1(self):\n c = [1, 1, 1, 2]\n A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]\n b_ub = [1, 2, -2, 4]\n bounds = [(None, None), (0, None), (0, None), (0, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n # Infeasibility detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_singleton_row_ub_2(self):\n c = [1, 1, 1, 2]\n A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]\n b_ub = [1, 2, -0.5, 4]\n bounds = [(None, None), (0, None), (0, None), (0, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=0.5)\n\n def test_infeasible(self):\n # Test linprog response to an infeasible problem\n c = [-1, -1]\n A_ub = [[1, 0],\n [0, 1],\n [-1, -1]]\n b_ub = [2, 2, -5]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n def test_infeasible_inequality_bounds(self):\n c = [1]\n A_ub = [[2]]\n b_ub = 4\n bounds = (5, 6)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n # Infeasibility detected in presolve\n if self.options.get('presolve', True):\n assert_equal(res.nit, 0)\n\n def test_unbounded(self):\n # Test linprog response to an unbounded problem\n c = np.array([1, 1]) * -1 # maximize\n A_ub = [[-1, 1],\n [-1, -1]]\n b_ub = [-1, -2]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n\n def test_unbounded_below_no_presolve_corrected(self):\n c = [1]\n bounds = [(None, 1)]\n\n o = {key: self.options[key] for key in self.options}\n o[\"presolve\"] = False\n\n res = linprog(c=c, bounds=bounds,\n method=self.method,\n options=o)\n if self.method == \"revised simplex\":\n # Revised simplex has a special pathway for no constraints.\n assert_equal(res.status, 5)\n else:\n _assert_unbounded(res)\n\n def test_unbounded_no_nontrivial_constraints_1(self):\n \"\"\"\n Test whether presolve pathway for detecting unboundedness after\n constraint elimination is working.\n \"\"\"\n c = np.array([0, 0, 0, 1, -1, -1])\n A_ub = np.array([[1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, -1]])\n b_ub = np.array([2, -2, 0])\n bounds = [(None, None), (None, None), (None, None),\n (-1, 1), (-1, 1), (0, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n if not self.method.lower().startswith(\"highs\"):\n assert_equal(res.x[-1], np.inf)\n assert_equal(res.message[:36],\n \"The problem is (trivially) unbounded\")\n\n def test_unbounded_no_nontrivial_constraints_2(self):\n \"\"\"\n Test whether presolve pathway for detecting unboundedness after\n constraint elimination is working.\n \"\"\"\n c = np.array([0, 0, 0, 1, -1, 1])\n A_ub = np.array([[1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1]])\n b_ub = np.array([2, -2, 0])\n bounds = [(None, None), (None, None), (None, None),\n (-1, 1), (-1, 1), (None, 0)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n if not self.method.lower().startswith(\"highs\"):\n assert_equal(res.x[-1], -np.inf)\n assert_equal(res.message[:36],\n \"The problem is (trivially) unbounded\")\n\n def test_cyclic_recovery(self):\n # Test linprogs recovery from cycling using the Klee-Minty problem\n # Klee-Minty https://www.math.ubc.ca/~israel/m340/kleemin3.pdf\n c = np.array([100, 10, 1]) * -1 # maximize\n A_ub = [[1, 0, 0],\n [20, 1, 0],\n [200, 20, 1]]\n b_ub = [1, 100, 10000]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[0, 0, 10000], atol=5e-6, rtol=1e-7)\n\n def test_cyclic_bland(self):\n # Test the effect of Bland's rule on a cycling problem\n c = np.array([-10, 57, 9, 24.])\n A_ub = np.array([[0.5, -5.5, -2.5, 9],\n [0.5, -1.5, -0.5, 1],\n [1, 0, 0, 0]])\n b_ub = [0, 0, 1]\n\n # copy the existing options dictionary but change maxiter\n maxiter = 100\n o = {key: val for key, val in self.options.items()}\n o['maxiter'] = maxiter\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n\n if self.method == 'simplex' and not self.options.get('bland'):\n # simplex cycles without Bland's rule\n _assert_iteration_limit_reached(res, o['maxiter'])\n else:\n # other methods, including simplex with Bland's rule, succeed\n _assert_success(res, desired_x=[1, 0, 1, 0])\n # note that revised simplex skips this test because it may or may not\n # cycle depending on the initial basis\n\n def test_remove_redundancy_infeasibility(self):\n # mostly a test of redundancy removal, which is carefully tested in\n # test__remove_redundancy.py\n m, n = 10, 10\n c = np.random.rand(n)\n A_eq = np.random.rand(m, n)\n b_eq = np.random.rand(m)\n A_eq[-1, :] = 2 * A_eq[-2, :]\n b_eq[-1] *= -1\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n #################\n # General Tests #\n #################\n\n def test_nontrivial_problem(self):\n # Problem involves all constraint types,\n # negative resource limits, and rounding issues.\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n\n def test_lpgen_problem(self):\n # Test linprog with a rather large problem (400 variables,\n # 40 constraints) generated by https://gist.github.com/denis-bz/8647461\n A_ub, b_ub, c = lpgen_2d(20, 20)\n\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"Solving system with option 'sym_pos'\")\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-64.049494229)\n\n def test_network_flow(self):\n # A network flow problem with supply and demand at nodes\n # and with costs along directed edges.\n # https://www.princeton.edu/~rvdb/542/lectures/lec10.pdf\n c = [2, 4, 9, 11, 4, 3, 8, 7, 0, 15, 16, 18]\n n, p = -1, 1\n A_eq = [\n [n, n, p, 0, p, 0, 0, 0, 0, p, 0, 0],\n [p, 0, 0, p, 0, p, 0, 0, 0, 0, 0, 0],\n [0, 0, n, n, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, p, p, 0, 0, p, 0],\n [0, 0, 0, 0, n, n, n, 0, p, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, n, n, 0, 0, p],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, n, n, n]]\n b_eq = [0, 19, -16, 33, 0, 0, -36]\n with suppress_warnings() as sup:\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=755, atol=1e-6, rtol=1e-7)\n\n def test_network_flow_limited_capacity(self):\n # A network flow problem with supply and demand at nodes\n # and with costs and capacities along directed edges.\n # http://blog.sommer-forst.de/2013/04/10/\n c = [2, 2, 1, 3, 1]\n bounds = [\n [0, 4],\n [0, 2],\n [0, 2],\n [0, 3],\n [0, 5]]\n n, p = -1, 1\n A_eq = [\n [n, n, 0, 0, 0],\n [p, 0, n, n, 0],\n [0, p, p, 0, n],\n [0, 0, 0, p, p]]\n b_eq = [-4, 0, 0, 4]\n\n with suppress_warnings() as sup:\n # this is an UmfpackWarning but I had trouble importing it\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(RuntimeWarning, \"scipy.linalg.solve\\nIll...\")\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=14)\n\n def test_simplex_algorithm_wikipedia_example(self):\n # https://en.wikipedia.org/wiki/Simplex_algorithm#Example\n c = [-2, -3, -4]\n A_ub = [\n [3, 2, 1],\n [2, 5, 3]]\n b_ub = [10, 15]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-20)\n\n def test_enzo_example(self):\n # https://github.com/scipy/scipy/issues/1779 lp2.py\n #\n # Translated from Octave code at:\n # http://www.ecs.shimane-u.ac.jp/~kyoshida/lpeng.htm\n # and placed under MIT licence by Enzo Michelangeli\n # with permission explicitly granted by the original author,\n # Prof. Kazunobu Yoshida\n c = [4, 8, 3, 0, 0, 0]\n A_eq = [\n [2, 5, 3, -1, 0, 0],\n [3, 2.5, 8, 0, -1, 0],\n [8, 10, 4, 0, 0, -1]]\n b_eq = [185, 155, 600]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=317.5,\n desired_x=[66.25, 0, 17.5, 0, 183.75, 0],\n atol=6e-6, rtol=1e-7)\n\n def test_enzo_example_b(self):\n # rescued from https://github.com/scipy/scipy/pull/218\n c = [2.8, 6.3, 10.8, -2.8, -6.3, -10.8]\n A_eq = [[-1, -1, -1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1],\n [1, 0, 0, 1, 0, 0],\n [0, 1, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 1]]\n b_eq = [-0.5, 0.4, 0.3, 0.3, 0.3]\n\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-1.77,\n desired_x=[0.3, 0.2, 0.0, 0.0, 0.1, 0.3])\n\n def test_enzo_example_c_with_degeneracy(self):\n # rescued from https://github.com/scipy/scipy/pull/218\n m = 20\n c = -np.ones(m)\n tmp = 2 * np.pi * np.arange(1, m + 1) / (m + 1)\n A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))\n b_eq = [0, 0]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=0, desired_x=np.zeros(m))\n\n def test_enzo_example_c_with_unboundedness(self):\n # rescued from https://github.com/scipy/scipy/pull/218\n m = 50\n c = -np.ones(m)\n tmp = 2 * np.pi * np.arange(m) / (m + 1)\n A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))\n b_eq = [0, 0]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_unbounded(res)\n\n def test_enzo_example_c_with_infeasibility(self):\n # rescued from https://github.com/scipy/scipy/pull/218\n m = 50\n c = -np.ones(m)\n tmp = 2 * np.pi * np.arange(m) / (m + 1)\n A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))\n b_eq = [1, 1]\n\n o = {key: self.options[key] for key in self.options}\n o[\"presolve\"] = False\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n _assert_infeasible(res)\n\n def test_basic_artificial_vars(self):\n # Problem is chosen to test two phase simplex methods when at the end\n # of phase 1 some artificial variables remain in the basis.\n # Also, for `method='simplex'`, the row in the tableau corresponding\n # with the artificial variables is not all zero.\n c = np.array([-0.1, -0.07, 0.004, 0.004, 0.004, 0.004])\n A_ub = np.array([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0],\n [0, -1.0, 0, 0, 0, 0], [0, 1.0, 0, 0, 0, 0],\n [1.0, 1.0, 0, 0, 0, 0]])\n b_ub = np.array([3.0, 3.0, 3.0, 3.0, 20.0])\n A_eq = np.array([[1.0, 0, -1, 1, -1, 1], [0, -1.0, -1, 1, -1, 1]])\n b_eq = np.array([0, 0])\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=0, desired_x=np.zeros_like(c),\n atol=2e-6)\n\n def test_optimize_result(self):\n # check all fields in OptimizeResult\n c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(0)\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,\n bounds=bounds, method=self.method, options=self.options)\n assert_(res.success)\n assert_(res.nit)\n assert_(not res.status)\n assert_(res.message == \"Optimization terminated successfully.\")\n assert_allclose(c @ res.x, res.fun)\n assert_allclose(b_eq - A_eq @ res.x, res.con, atol=1e-11)\n assert_allclose(b_ub - A_ub @ res.x, res.slack, atol=1e-11)\n\n #################\n # Bug Fix Tests #\n #################\n\n def test_bug_5400(self):\n # https://github.com/scipy/scipy/issues/5400\n bounds = [\n (0, None),\n (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), (0, 100),\n (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), (0, 900),\n (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)]\n\n f = 1 / 9\n g = -1e4\n h = -3.1\n A_ub = np.array([\n [1, -2.99, 0, 0, -3, 0, 0, 0, -1, -1, 0, -1, -1, 1, 1, 0, 0, 0, 0],\n [1, 0, -2.9, h, 0, -3, 0, -1, 0, 0, -1, 0, -1, 0, 0, 1, 1, 0, 0],\n [1, 0, 0, h, 0, 0, -3, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, 1, 1],\n [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1],\n [0, 1.99, -1, -1, 0, 0, 0, -1, f, f, 0, 0, 0, g, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 2, -1, -1, 0, 0, 0, -1, f, f, 0, g, 0, 0, 0, 0],\n [0, -1, 1.9, 2.1, 0, 0, 0, f, -1, -1, 0, 0, 0, 0, 0, g, 0, 0, 0],\n [0, 0, 0, 0, -1, 2, -1, 0, 0, 0, f, -1, f, 0, 0, 0, g, 0, 0],\n [0, -1, -1, 2.1, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, 0, 0, g, 0],\n [0, 0, 0, 0, -1, -1, 2, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, g]])\n\n b_ub = np.array([\n 0.0, 0, 0, 100, 100, 100, 100, 100, 100, 900, 900, 900, 900, 900,\n 900, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n\n c = np.array([-1.0, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning,\n \"Solving system with option 'sym_pos'\")\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=-106.63507541835018)\n\n def test_bug_6139(self):\n # linprog(method='simplex') fails to find a basic feasible solution\n # if phase 1 pseudo-objective function is outside the provided tol.\n # https://github.com/scipy/scipy/issues/6139\n\n # Note: This is not strictly a bug as the default tolerance determines\n # if a result is \"close enough\" to zero and should not be expected\n # to work for all cases.\n\n c = np.array([1, 1, 1])\n A_eq = np.array([[1., 0., 0.], [-1000., 0., - 1000.]])\n b_eq = np.array([5.00000000e+00, -1.00000000e+04])\n A_ub = -np.array([[0., 1000000., 1010000.]])\n b_ub = -np.array([10000000.])\n bounds = (None, None)\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n _assert_success(res, desired_fun=14.95,\n desired_x=np.array([5, 4.95, 5]))\n\n def test_bug_6690(self):\n # linprog simplex used to violate bound constraint despite reporting\n # success.\n # https://github.com/scipy/scipy/issues/6690\n\n A_eq = np.array([[0, 0, 0, 0.93, 0, 0.65, 0, 0, 0.83, 0]])\n b_eq = np.array([0.9626])\n A_ub = np.array([\n [0, 0, 0, 1.18, 0, 0, 0, -0.2, 0, -0.22],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0.43, 0, 0, 0, 0, 0, 0],\n [0, -1.22, -0.25, 0, 0, 0, -2.06, 0, 0, 1.37],\n [0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0]\n ])\n b_ub = np.array([0.615, 0, 0.172, -0.869, -0.022])\n bounds = np.array([\n [-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73],\n [0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15]\n ]).T\n c = np.array([\n -1.64, 0.7, 1.8, -1.06, -1.16, 0.26, 2.13, 1.53, 0.66, 0.28\n ])\n\n with suppress_warnings() as sup:\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(OptimizeWarning,\n \"Solving system with option 'cholesky'\")\n sup.filter(OptimizeWarning, \"Solving system with option 'sym_pos'\")\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n desired_fun = -1.19099999999\n desired_x = np.array([0.3700, -0.9700, 0.3400, 0.4000, 1.1800,\n 0.5000, 0.4700, 0.0900, 0.3200, -0.7300])\n _assert_success(res, desired_fun=desired_fun, desired_x=desired_x)\n\n # Add small tol value to ensure arrays are less than or equal.\n atol = 1e-6\n assert_array_less(bounds[:, 0] - atol, res.x)\n assert_array_less(res.x, bounds[:, 1] + atol)\n\n def test_bug_7044(self):\n # linprog simplex failed to \"identify correct constraints\" (?)\n # leading to a non-optimal solution if A is rank-deficient.\n # https://github.com/scipy/scipy/issues/7044\n\n A_eq, b_eq, c, N = magic_square(3)\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n desired_fun = 1.730550597\n _assert_success(res, desired_fun=desired_fun)\n assert_allclose(A_eq.dot(res.x), b_eq)\n assert_array_less(np.zeros(res.x.size) - 1e-5, res.x)\n\n def test_bug_7237(self):\n # https://github.com/scipy/scipy/issues/7237\n # linprog simplex \"explodes\" when the pivot value is very\n # close to zero.\n\n c = np.array([-1, 0, 0, 0, 0, 0, 0, 0, 0])\n A_ub = np.array([\n [1., -724., 911., -551., -555., -896., 478., -80., -293.],\n [1., 566., 42., 937., 233., 883., 392., -909., 57.],\n [1., -208., -894., 539., 321., 532., -924., 942., 55.],\n [1., 857., -859., 83., 462., -265., -971., 826., 482.],\n [1., 314., -424., 245., -424., 194., -443., -104., -429.],\n [1., 540., 679., 361., 149., -827., 876., 633., 302.],\n [0., -1., -0., -0., -0., -0., -0., -0., -0.],\n [0., -0., -1., -0., -0., -0., -0., -0., -0.],\n [0., -0., -0., -1., -0., -0., -0., -0., -0.],\n [0., -0., -0., -0., -1., -0., -0., -0., -0.],\n [0., -0., -0., -0., -0., -1., -0., -0., -0.],\n [0., -0., -0., -0., -0., -0., -1., -0., -0.],\n [0., -0., -0., -0., -0., -0., -0., -1., -0.],\n [0., -0., -0., -0., -0., -0., -0., -0., -1.],\n [0., 1., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 1., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 1., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 1., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 1., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0., 1., 0., 0.],\n [0., 0., 0., 0., 0., 0., 0., 1., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0., 1.]\n ])\n b_ub = np.array([\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,\n 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1.])\n A_eq = np.array([[0., 1., 1., 1., 1., 1., 1., 1., 1.]])\n b_eq = np.array([[1.]])\n bounds = [(None, None)] * 9\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=108.568535, atol=1e-6)\n\n def test_bug_8174(self):\n # https://github.com/scipy/scipy/issues/8174\n # The simplex method sometimes \"explodes\" if the pivot value is very\n # close to zero.\n A_ub = np.array([\n [22714, 1008, 13380, -2713.5, -1116],\n [-4986, -1092, -31220, 17386.5, 684],\n [-4986, 0, 0, -2713.5, 0],\n [22714, 0, 0, 17386.5, 0]])\n b_ub = np.zeros(A_ub.shape[0])\n c = -np.ones(A_ub.shape[1])\n bounds = [(0, 1)] * A_ub.shape[1]\n with suppress_warnings() as sup:\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n if self.options.get('tol', 1e-9) < 1e-10 and self.method == 'simplex':\n _assert_unable_to_find_basic_feasible_sol(res)\n else:\n _assert_success(res, desired_fun=-2.0080717488789235, atol=1e-6)\n\n def test_bug_8174_2(self):\n # Test supplementary example from issue 8174.\n # https://github.com/scipy/scipy/issues/8174\n # https://stackoverflow.com/questions/47717012/linprog-in-scipy-optimize-checking-solution\n c = np.array([1, 0, 0, 0, 0, 0, 0])\n A_ub = -np.identity(7)\n b_ub = np.array([[-2], [-2], [-2], [-2], [-2], [-2], [-2]])\n A_eq = np.array([\n [1, 1, 1, 1, 1, 1, 0],\n [0.3, 1.3, 0.9, 0, 0, 0, -1],\n [0.3, 0, 0, 0, 0, 0, -2/3],\n [0, 0.65, 0, 0, 0, 0, -1/15],\n [0, 0, 0.3, 0, 0, 0, -1/15]\n ])\n b_eq = np.array([[100], [0], [0], [0], [0]])\n\n with suppress_warnings() as sup:\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_fun=43.3333333331385)\n\n def test_bug_8561(self):\n # Test that pivot row is chosen correctly when using Bland's rule\n # This was originally written for the simplex method with\n # Bland's rule only, but it doesn't hurt to test all methods/options\n # https://github.com/scipy/scipy/issues/8561\n c = np.array([7, 0, -4, 1.5, 1.5])\n A_ub = np.array([\n [4, 5.5, 1.5, 1.0, -3.5],\n [1, -2.5, -2, 2.5, 0.5],\n [3, -0.5, 4, -12.5, -7],\n [-1, 4.5, 2, -3.5, -2],\n [5.5, 2, -4.5, -1, 9.5]])\n b_ub = np.array([0, 0, 0, 0, 1])\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=self.options,\n method=self.method)\n _assert_success(res, desired_x=[0, 0, 19, 16/3, 29/3])\n\n def test_bug_8662(self):\n # linprog simplex used to report incorrect optimal results\n # https://github.com/scipy/scipy/issues/8662\n c = [-10, 10, 6, 3]\n A_ub = [[8, -8, -4, 6],\n [-8, 8, 4, -6],\n [-4, 4, 8, -4],\n [3, -3, -3, -10]]\n b_ub = [9, -9, -9, -4]\n bounds = [(0, None), (0, None), (0, None), (0, None)]\n desired_fun = 36.0000000000\n\n with suppress_warnings() as sup:\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res1 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n\n # Set boundary condition as a constraint\n A_ub.append([0, 0, -1, 0])\n b_ub.append(0)\n bounds[2] = (None, None)\n\n with suppress_warnings() as sup:\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res2 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n rtol = 1e-5\n _assert_success(res1, desired_fun=desired_fun, rtol=rtol)\n _assert_success(res2, desired_fun=desired_fun, rtol=rtol)\n\n def test_bug_8663(self):\n # exposed a bug in presolve\n # https://github.com/scipy/scipy/issues/8663\n c = [1, 5]\n A_eq = [[0, -7]]\n b_eq = [-6]\n bounds = [(0, None), (None, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[0, 6./7], desired_fun=5*6./7)\n\n def test_bug_8664(self):\n # interior-point has trouble with this when presolve is off\n # tested for interior-point with presolve off in TestLinprogIPSpecific\n # https://github.com/scipy/scipy/issues/8664\n c = [4]\n A_ub = [[2], [5]]\n b_ub = [4, 4]\n A_eq = [[0], [-8], [9]]\n b_eq = [3, 2, 10]\n with suppress_warnings() as sup:\n sup.filter(RuntimeWarning)\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_infeasible(res)\n\n def test_bug_8973(self):\n \"\"\"\n Test whether bug described at:\n https://github.com/scipy/scipy/issues/8973\n was fixed.\n \"\"\"\n c = np.array([0, 0, 0, 1, -1])\n A_ub = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0]])\n b_ub = np.array([2, -2])\n bounds = [(None, None), (None, None), (None, None), (-1, 1), (-1, 1)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n # solution vector x is not unique\n _assert_success(res, desired_fun=-2)\n # HiGHS IPM had an issue where the following wasn't true!\n assert_equal(c @ res.x, res.fun)\n\n def test_bug_8973_2(self):\n \"\"\"\n Additional test for:\n https://github.com/scipy/scipy/issues/8973\n suggested in\n https://github.com/scipy/scipy/pull/8985\n review by @antonior92\n \"\"\"\n c = np.zeros(1)\n A_ub = np.array([[1]])\n b_ub = np.array([-2])\n bounds = (None, None)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[-2], desired_fun=0)\n\n def test_bug_10124(self):\n \"\"\"\n Test for linprog docstring problem\n 'disp'=True caused revised simplex failure\n \"\"\"\n c = np.zeros(1)\n A_ub = np.array([[1]])\n b_ub = np.array([-2])\n bounds = (None, None)\n c = [-1, 4]\n A_ub = [[-3, 1], [1, 2]]\n b_ub = [6, 4]\n bounds = [(None, None), (-3, None)]\n o = {\"disp\": True}\n o.update(self.options)\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n _assert_success(res, desired_x=[10, -3], desired_fun=-22)\n\n def test_bug_10349(self):\n \"\"\"\n Test for redundancy removal tolerance issue\n https://github.com/scipy/scipy/issues/10349\n \"\"\"\n A_eq = np.array([[1, 1, 0, 0, 0, 0],\n [0, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 1],\n [1, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 0],\n [0, 1, 0, 0, 0, 1]])\n b_eq = np.array([221, 210, 10, 141, 198, 102])\n c = np.concatenate((0, 1, np.zeros(4)), axis=None)\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options)\n _assert_success(res, desired_x=[129, 92, 12, 198, 0, 10], desired_fun=92)\n\n def test_bug_10466(self):\n \"\"\"\n Test that autoscale fixes poorly-scaled problem\n \"\"\"\n c = [-8., -0., -8., -0., -8., -0., -0., -0., -0., -0., -0., -0., -0.]\n A_eq = [[1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0.],\n [1., 0., 1., 0., 1., 0., -1., 0., 0., 0., 0., 0., 0.],\n [1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],\n [1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],\n [1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],\n [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0.],\n [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 1., 0.],\n [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1.]]\n\n b_eq = [3.14572800e+08, 4.19430400e+08, 5.24288000e+08,\n 1.00663296e+09, 1.07374182e+09, 1.07374182e+09,\n 1.07374182e+09, 1.07374182e+09, 1.07374182e+09,\n 1.07374182e+09]\n\n o = {}\n # HiGHS methods don't use autoscale option\n if not self.method.startswith(\"highs\"):\n o = {\"autoscale\": True}\n o.update(self.options)\n\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(RuntimeWarning, \"scipy.linalg.solve\\nIll...\")\n sup.filter(RuntimeWarning, \"divide by zero encountered...\")\n sup.filter(RuntimeWarning, \"overflow encountered...\")\n sup.filter(RuntimeWarning, \"invalid value encountered...\")\n sup.filter(LinAlgWarning, \"Ill-conditioned matrix...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n assert_allclose(res.fun, -8589934560)\n\n#########################\n# Method-specific Tests #\n#########################\n\n\nclass LinprogSimplexTests(LinprogCommonTests):\n method = \"simplex\"\n\n\nclass LinprogIPTests(LinprogCommonTests):\n method = \"interior-point\"\n\n\nclass LinprogRSTests(LinprogCommonTests):\n method = \"revised simplex\"\n\n # Revised simplex does not reliably solve these problems.\n # Failure is intermittent due to the random choice of elements to complete\n # the basis after phase 1 terminates. In any case, linprog exists\n # gracefully, reporting numerical difficulties. I do not think this should\n # prevent revised simplex from being merged, as it solves the problems\n # most of the time and solves a broader range of problems than the existing\n # simplex implementation.\n # I believe that the root cause is the same for all three and that this\n # same issue prevents revised simplex from solving many other problems\n # reliably. Somehow the pivoting rule allows the algorithm to pivot into\n # a singular basis. I haven't been able to find a reference that\n # acknowledges this possibility, suggesting that there is a bug. On the\n # other hand, the pivoting rule is quite simple, and I can't find a\n # mistake, which suggests that this is a possibility with the pivoting\n # rule. Hopefully, a better pivoting rule will fix the issue.\n\n def test_bug_5400(self):\n pytest.skip(\"Intermittent failure acceptable.\")\n\n def test_bug_8662(self):\n pytest.skip(\"Intermittent failure acceptable.\")\n\n def test_network_flow(self):\n pytest.skip(\"Intermittent failure acceptable.\")\n\n\nclass LinprogHiGHSTests(LinprogCommonTests):\n def test_callback(self):\n # this is the problem from test_callback\n cb = lambda res: None\n c = np.array([-3, -2])\n A_ub = [[2, 1], [1, 1], [1, 0]]\n b_ub = [10, 8, 4]\n assert_raises(NotImplementedError, linprog, c, A_ub=A_ub, b_ub=b_ub,\n callback=cb, method=self.method)\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, method=self.method)\n _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])\n\n @pytest.mark.parametrize(\"options\",\n [{\"maxiter\": -1},\n {\"disp\": -1},\n {\"presolve\": -1},\n {\"time_limit\": -1},\n {\"dual_feasibility_tolerance\": -1},\n {\"primal_feasibility_tolerance\": -1},\n {\"ipm_optimality_tolerance\": -1},\n {\"simplex_dual_edge_weight_strategy\": \"ekki\"},\n ])\n def test_invalid_option_values(self, options):\n def f(options):\n linprog(1, method=self.method, options=options)\n options.update(self.options)\n assert_warns(OptimizeWarning, f, options=options)\n\n def test_crossover(self):\n c = np.array([1, 1]) * -1 # maximize\n A_ub = np.array([[1, 1]])\n b_ub = [1]\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,\n bounds=bounds, method=self.method, options=self.options)\n # there should be nonzero crossover iterations for IPM (only)\n assert_equal(res.crossover_nit == 0, self.method != \"highs-ipm\")\n\n\n################################\n# Simplex Option-Specific Tests#\n################################\n\n\nclass TestLinprogSimplexDefault(LinprogSimplexTests):\n\n def setup_method(self):\n self.options = {}\n\n def test_bug_5400(self):\n pytest.skip(\"Simplex fails on this problem.\")\n\n def test_bug_7237_low_tol(self):\n # Fails if the tolerance is too strict. Here, we test that\n # even if the solution is wrong, the appropriate error is raised.\n pytest.skip(\"Simplex fails on this problem.\")\n\n def test_bug_8174_low_tol(self):\n # Fails if the tolerance is too strict. Here, we test that\n # even if the solution is wrong, the appropriate warning is issued.\n self.options.update({'tol': 1e-12})\n with pytest.warns(OptimizeWarning):\n super(TestLinprogSimplexDefault, self).test_bug_8174()\n\n\nclass TestLinprogSimplexBland(LinprogSimplexTests):\n\n def setup_method(self):\n self.options = {'bland': True}\n\n def test_bug_5400(self):\n pytest.skip(\"Simplex fails on this problem.\")\n\n def test_bug_8174_low_tol(self):\n # Fails if the tolerance is too strict. Here, we test that\n # even if the solution is wrong, the appropriate error is raised.\n self.options.update({'tol': 1e-12})\n with pytest.raises(AssertionError):\n with pytest.warns(OptimizeWarning):\n super(TestLinprogSimplexBland, self).test_bug_8174()\n\n\nclass TestLinprogSimplexNoPresolve(LinprogSimplexTests):\n\n def setup_method(self):\n self.options = {'presolve': False}\n\n is_32_bit = np.intp(0).itemsize < 8\n is_linux = sys.platform.startswith('linux')\n\n @pytest.mark.xfail(\n condition=is_32_bit and is_linux,\n reason='Fails with warning on 32-bit linux')\n def test_bug_5400(self):\n super(TestLinprogSimplexNoPresolve, self).test_bug_5400()\n\n def test_bug_6139_low_tol(self):\n # Linprog(method='simplex') fails to find a basic feasible solution\n # if phase 1 pseudo-objective function is outside the provided tol.\n # https://github.com/scipy/scipy/issues/6139\n # Without ``presolve`` eliminating such rows the result is incorrect.\n self.options.update({'tol': 1e-12})\n with pytest.raises(AssertionError, match='linprog status 4'):\n return super(TestLinprogSimplexNoPresolve, self).test_bug_6139()\n\n def test_bug_7237_low_tol(self):\n pytest.skip(\"Simplex fails on this problem.\")\n\n def test_bug_8174_low_tol(self):\n # Fails if the tolerance is too strict. Here, we test that\n # even if the solution is wrong, the appropriate warning is issued.\n self.options.update({'tol': 1e-12})\n with pytest.warns(OptimizeWarning):\n super(TestLinprogSimplexNoPresolve, self).test_bug_8174()\n\n def test_unbounded_no_nontrivial_constraints_1(self):\n pytest.skip(\"Tests behavior specific to presolve\")\n\n def test_unbounded_no_nontrivial_constraints_2(self):\n pytest.skip(\"Tests behavior specific to presolve\")\n\n\n#######################################\n# Interior-Point Option-Specific Tests#\n#######################################\n\n\nclass TestLinprogIPDense(LinprogIPTests):\n options = {\"sparse\": False}\n\n\nif has_cholmod:\n class TestLinprogIPSparseCholmod(LinprogIPTests):\n options = {\"sparse\": True, \"cholesky\": True}\n\n\nif has_umfpack:\n class TestLinprogIPSparseUmfpack(LinprogIPTests):\n options = {\"sparse\": True, \"cholesky\": False}\n\n def test_bug_10466(self):\n pytest.skip(\"Autoscale doesn't fix everything, and that's OK.\")\n\n\nclass TestLinprogIPSparse(LinprogIPTests):\n options = {\"sparse\": True, \"cholesky\": False, \"sym_pos\": False}\n\n @pytest.mark.xfail_on_32bit(\"This test is sensitive to machine epsilon level \"\n \"perturbations in linear system solution in \"\n \"_linprog_ip._sym_solve.\")\n def test_bug_6139(self):\n super(TestLinprogIPSparse, self).test_bug_6139()\n\n @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')\n def test_bug_6690(self):\n # Test defined in base class, but can't mark as xfail there\n super(TestLinprogIPSparse, self).test_bug_6690()\n\n def test_magic_square_sparse_no_presolve(self):\n # test linprog with a problem with a rank-deficient A_eq matrix\n A_eq, b_eq, c, N = magic_square(3)\n bounds = (0, 1)\n\n with suppress_warnings() as sup:\n if has_umfpack:\n sup.filter(UmfpackWarning)\n sup.filter(MatrixRankWarning, \"Matrix is exactly singular\")\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n\n o = {key: self.options[key] for key in self.options}\n o[\"presolve\"] = False\n\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n _assert_success(res, desired_fun=1.730550597)\n\n def test_sparse_solve_options(self):\n # checking that problem is solved with all column permutation options\n A_eq, b_eq, c, N = magic_square(3)\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n sup.filter(OptimizeWarning, \"Invalid permc_spec option\")\n o = {key: self.options[key] for key in self.options}\n permc_specs = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A',\n 'COLAMD', 'ekki-ekki-ekki')\n # 'ekki-ekki-ekki' raises warning about invalid permc_spec option\n # and uses default\n for permc_spec in permc_specs:\n o[\"permc_spec\"] = permc_spec\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=o)\n _assert_success(res, desired_fun=1.730550597)\n\n\nclass TestLinprogIPSparsePresolve(LinprogIPTests):\n options = {\"sparse\": True, \"_sparse_presolve\": True}\n\n @pytest.mark.xfail_on_32bit(\"This test is sensitive to machine epsilon level \"\n \"perturbations in linear system solution in \"\n \"_linprog_ip._sym_solve.\")\n def test_bug_6139(self):\n super(TestLinprogIPSparsePresolve, self).test_bug_6139()\n\n def test_enzo_example_c_with_infeasibility(self):\n pytest.skip('_sparse_presolve=True incompatible with presolve=False')\n\n @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')\n def test_bug_6690(self):\n # Test defined in base class, but can't mark as xfail there\n super(TestLinprogIPSparsePresolve, self).test_bug_6690()\n\n\nclass TestLinprogIPSpecific:\n method = \"interior-point\"\n # the following tests don't need to be performed separately for\n # sparse presolve, sparse after presolve, and dense\n\n def test_solver_select(self):\n # check that default solver is selected as expected\n if has_cholmod:\n options = {'sparse': True, 'cholesky': True}\n elif has_umfpack:\n options = {'sparse': True, 'cholesky': False}\n else:\n options = {'sparse': True, 'cholesky': False, 'sym_pos': False}\n A, b, c = lpgen_2d(20, 20)\n res1 = linprog(c, A_ub=A, b_ub=b, method=self.method, options=options)\n res2 = linprog(c, A_ub=A, b_ub=b, method=self.method) # default solver\n assert_allclose(res1.fun, res2.fun,\n err_msg=\"linprog default solver unexpected result\",\n rtol=1e-15, atol=1e-15)\n\n def test_unbounded_below_no_presolve_original(self):\n # formerly caused segfault in TravisCI w/ \"cholesky\":True\n c = [-1]\n bounds = [(None, 1)]\n res = linprog(c=c, bounds=bounds,\n method=self.method,\n options={\"presolve\": False, \"cholesky\": True})\n _assert_success(res, desired_fun=-1)\n\n def test_cholesky(self):\n # use cholesky factorization and triangular solves\n A, b, c = lpgen_2d(20, 20)\n res = linprog(c, A_ub=A, b_ub=b, method=self.method,\n options={\"cholesky\": True}) # only for dense\n _assert_success(res, desired_fun=-64.049494229)\n\n def test_alternate_initial_point(self):\n # use \"improved\" initial point\n A, b, c = lpgen_2d(20, 20)\n with suppress_warnings() as sup:\n sup.filter(RuntimeWarning, \"scipy.linalg.solve\\nIll...\")\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n sup.filter(LinAlgWarning, \"Ill-conditioned matrix...\")\n res = linprog(c, A_ub=A, b_ub=b, method=self.method,\n options={\"ip\": True, \"disp\": True})\n # ip code is independent of sparse/dense\n _assert_success(res, desired_fun=-64.049494229)\n\n def test_bug_8664(self):\n # interior-point has trouble with this when presolve is off\n c = [4]\n A_ub = [[2], [5]]\n b_ub = [4, 4]\n A_eq = [[0], [-8], [9]]\n b_eq = [3, 2, 10]\n with suppress_warnings() as sup:\n sup.filter(RuntimeWarning)\n sup.filter(OptimizeWarning, \"Solving system with option...\")\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options={\"presolve\": False})\n assert_(not res.success, \"Incorrectly reported success\")\n\n\n########################################\n# Revised Simplex Option-Specific Tests#\n########################################\n\n\nclass TestLinprogRSCommon(LinprogRSTests):\n options = {}\n\n def test_cyclic_bland(self):\n pytest.skip(\"Intermittent failure acceptable.\")\n\n def test_nontrivial_problem_with_guess(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=x_star)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n assert_equal(res.nit, 0)\n\n def test_nontrivial_problem_with_unbounded_variables(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n bounds = [(None, None), (None, None), (0, None), (None, None)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=x_star)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n assert_equal(res.nit, 0)\n\n def test_nontrivial_problem_with_bounded_variables(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n bounds = [(None, 1), (1, None), (0, None), (.4, .6)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=x_star)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n assert_equal(res.nit, 0)\n\n def test_nontrivial_problem_with_negative_unbounded_variable(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n b_eq = [4]\n x_star = np.array([-219/385, 582/385, 0, 4/10])\n f_star = 3951/385\n bounds = [(None, None), (1, None), (0, None), (.4, .6)]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=x_star)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n assert_equal(res.nit, 0)\n\n def test_nontrivial_problem_with_bad_guess(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n bad_guess = [1, 2, 3, .5]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=bad_guess)\n assert_equal(res.status, 6)\n\n def test_redundant_constraints_with_guess(self):\n A, b, c, N = magic_square(3)\n p = np.random.rand(*c.shape)\n with suppress_warnings() as sup:\n sup.filter(OptimizeWarning, \"A_eq does not appear...\")\n sup.filter(RuntimeWarning, \"invalid value encountered\")\n sup.filter(LinAlgWarning)\n res = linprog(c, A_eq=A, b_eq=b, method=self.method)\n res2 = linprog(c, A_eq=A, b_eq=b, method=self.method, x0=res.x)\n res3 = linprog(c + p, A_eq=A, b_eq=b, method=self.method, x0=res.x)\n _assert_success(res2, desired_fun=1.730550597)\n assert_equal(res2.nit, 0)\n _assert_success(res3)\n assert_(res3.nit < res.nit) # hot start reduces iterations\n\n\nclass TestLinprogRSBland(LinprogRSTests):\n options = {\"pivot\": \"bland\"}\n\n\n############################################\n# HiGHS-Simplex-Dual Option-Specific Tests #\n############################################\n\n\nclass TestLinprogHiGHSSimplexDual(LinprogHiGHSTests):\n method = \"highs-ds\"\n options = {}\n\n def test_lad_regression(self):\n '''The scaled model should be optimal but unscaled model infeasible.'''\n c, A_ub, b_ub, bnds = l1_regression_prob()\n res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bnds,\n method=self.method, options=self.options)\n assert_equal(res.status, 4)\n assert_('An optimal solution to the scaled '\n 'model was found but' in res.message)\n assert_(res.x is not None)\n assert_(np.all(res.slack > -1e-6))\n assert_(np.all(res.x <= [np.inf if u is None else u for l, u in bnds]))\n assert_(np.all(res.x >= [-np.inf if l is None else l for l, u in bnds]))\n\n\n###################################\n# HiGHS-IPM Option-Specific Tests #\n###################################\n\n\nclass TestLinprogHiGHSIPM(LinprogHiGHSTests):\n method = \"highs-ipm\"\n options = {}\n\n\n###########################\n# Autoscale-Specific Tests#\n###########################\n\n\nclass AutoscaleTests:\n options = {\"autoscale\": True}\n\n test_bug_6139 = LinprogCommonTests.test_bug_6139\n test_bug_6690 = LinprogCommonTests.test_bug_6690\n test_bug_7237 = LinprogCommonTests.test_bug_7237\n\n\nclass TestAutoscaleIP(AutoscaleTests):\n method = \"interior-point\"\n\n def test_bug_6139(self):\n self.options['tol'] = 1e-10\n return AutoscaleTests.test_bug_6139(self)\n\n\nclass TestAutoscaleSimplex(AutoscaleTests):\n method = \"simplex\"\n\n\nclass TestAutoscaleRS(AutoscaleTests):\n method = \"revised simplex\"\n\n def test_nontrivial_problem_with_guess(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=x_star)\n _assert_success(res, desired_fun=f_star, desired_x=x_star)\n assert_equal(res.nit, 0)\n\n def test_nontrivial_problem_with_bad_guess(self):\n c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()\n bad_guess = [1, 2, 3, .5]\n res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,\n method=self.method, options=self.options, x0=bad_guess)\n assert_equal(res.status, 6)\n\n\n###########################\n# Redundancy Removal Tests#\n###########################\n\n\nclass RRTests:\n method = \"interior-point\"\n LCT = LinprogCommonTests\n # these are a few of the existing tests that have redundancy\n test_RR_infeasibility = LCT.test_remove_redundancy_infeasibility\n test_bug_10349 = LCT.test_bug_10349\n test_bug_7044 = LCT.test_bug_7044\n test_NFLC = LCT.test_network_flow_limited_capacity\n test_enzo_example_b = LCT.test_enzo_example_b\n\n\nclass TestRRSVD(RRTests):\n options = {\"rr_method\": \"SVD\"}\n\n\nclass TestRRPivot(RRTests):\n options = {\"rr_method\": \"pivot\"}\n\n\nclass TestRRID(RRTests):\n options = {\"rr_method\": \"ID\"}\n",
"import numpy as np\nfrom .base import OdeSolver, DenseOutput\nfrom .common import (validate_max_step, validate_tol, select_initial_step,\n norm, warn_extraneous, validate_first_step)\nfrom . import dop853_coefficients\n\n# Multiply steps computed from asymptotic behaviour of errors by this.\nSAFETY = 0.9\n\nMIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.\nMAX_FACTOR = 10 # Maximum allowed increase in a step size.\n\n\ndef rk_step(fun, t, y, f, h, A, B, C, K):\n \"\"\"Perform a single Runge-Kutta step.\n\n This function computes a prediction of an explicit Runge-Kutta method and\n also estimates the error of a less accurate method.\n\n Notation for Butcher tableau is as in [1]_.\n\n Parameters\n ----------\n fun : callable\n Right-hand side of the system.\n t : float\n Current time.\n y : ndarray, shape (n,)\n Current state.\n f : ndarray, shape (n,)\n Current value of the derivative, i.e., ``fun(x, y)``.\n h : float\n Step to use.\n A : ndarray, shape (n_stages, n_stages)\n Coefficients for combining previous RK stages to compute the next\n stage. For explicit methods the coefficients at and above the main\n diagonal are zeros.\n B : ndarray, shape (n_stages,)\n Coefficients for combining RK stages for computing the final\n prediction.\n C : ndarray, shape (n_stages,)\n Coefficients for incrementing time for consecutive RK stages.\n The value for the first stage is always zero.\n K : ndarray, shape (n_stages + 1, n)\n Storage array for putting RK stages here. Stages are stored in rows.\n The last row is a linear combination of the previous rows with\n coefficients\n\n Returns\n -------\n y_new : ndarray, shape (n,)\n Solution at t + h computed with a higher accuracy.\n f_new : ndarray, shape (n,)\n Derivative ``fun(t + h, y_new)``.\n\n References\n ----------\n .. [1] E. Hairer, S. P. Norsett G. Wanner, \"Solving Ordinary Differential\n Equations I: Nonstiff Problems\", Sec. II.4.\n \"\"\"\n K[0] = f\n for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):\n dy = np.dot(K[:s].T, a[:s]) * h\n K[s] = fun(t + c * h, y + dy)\n\n y_new = y + h * np.dot(K[:-1].T, B)\n f_new = fun(t + h, y_new)\n\n K[-1] = f_new\n\n return y_new, f_new\n\n\nclass RungeKutta(OdeSolver):\n \"\"\"Base class for explicit Runge-Kutta methods.\"\"\"\n C: np.ndarray = NotImplemented\n A: np.ndarray = NotImplemented\n B: np.ndarray = NotImplemented\n E: np.ndarray = NotImplemented\n P: np.ndarray = NotImplemented\n order: int = NotImplemented\n error_estimator_order: int = NotImplemented\n n_stages: int = NotImplemented\n\n def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,\n rtol=1e-3, atol=1e-6, vectorized=False,\n first_step=None, **extraneous):\n warn_extraneous(extraneous)\n super(RungeKutta, self).__init__(fun, t0, y0, t_bound, vectorized,\n support_complex=True)\n self.y_old = None\n self.max_step = validate_max_step(max_step)\n self.rtol, self.atol = validate_tol(rtol, atol, self.n)\n self.f = self.fun(self.t, self.y)\n if first_step is None:\n self.h_abs = select_initial_step(\n self.fun, self.t, self.y, self.f, self.direction,\n self.error_estimator_order, self.rtol, self.atol)\n else:\n self.h_abs = validate_first_step(first_step, t0, t_bound)\n self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)\n self.error_exponent = -1 / (self.error_estimator_order + 1)\n self.h_previous = None\n\n def _estimate_error(self, K, h):\n return np.dot(K.T, self.E) * h\n\n def _estimate_error_norm(self, K, h, scale):\n return norm(self._estimate_error(K, h) / scale)\n\n def _step_impl(self):\n t = self.t\n y = self.y\n\n max_step = self.max_step\n rtol = self.rtol\n atol = self.atol\n\n min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)\n\n if self.h_abs > max_step:\n h_abs = max_step\n elif self.h_abs < min_step:\n h_abs = min_step\n else:\n h_abs = self.h_abs\n\n step_accepted = False\n step_rejected = False\n\n while not step_accepted:\n if h_abs < min_step:\n return False, self.TOO_SMALL_STEP\n\n h = h_abs * self.direction\n t_new = t + h\n\n if self.direction * (t_new - self.t_bound) > 0:\n t_new = self.t_bound\n\n h = t_new - t\n h_abs = np.abs(h)\n\n y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,\n self.B, self.C, self.K)\n scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol\n error_norm = self._estimate_error_norm(self.K, h, scale)\n\n if error_norm < 1:\n if error_norm == 0:\n factor = MAX_FACTOR\n else:\n factor = min(MAX_FACTOR,\n SAFETY * error_norm ** self.error_exponent)\n\n if step_rejected:\n factor = min(1, factor)\n\n h_abs *= factor\n\n step_accepted = True\n else:\n h_abs *= max(MIN_FACTOR,\n SAFETY * error_norm ** self.error_exponent)\n step_rejected = True\n\n self.h_previous = h\n self.y_old = y\n\n self.t = t_new\n self.y = y_new\n\n self.h_abs = h_abs\n self.f = f_new\n\n return True, None\n\n def _dense_output_impl(self):\n Q = self.K.T.dot(self.P)\n return RkDenseOutput(self.t_old, self.t, self.y_old, Q)\n\n\nclass RK23(RungeKutta):\n \"\"\"Explicit Runge-Kutta method of order 3(2).\n\n This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled\n assuming accuracy of the second-order method, but steps are taken using the\n third-order accurate formula (local extrapolation is done). A cubic Hermite\n polynomial is used for the dense output.\n\n Can be applied in the complex domain.\n\n Parameters\n ----------\n fun : callable\n Right-hand side of the system. The calling signature is ``fun(t, y)``.\n Here ``t`` is a scalar and there are two options for ndarray ``y``.\n It can either have shape (n,), then ``fun`` must return array_like with\n shape (n,). Or alternatively it can have shape (n, k), then ``fun``\n must return array_like with shape (n, k), i.e. each column\n corresponds to a single column in ``y``. The choice between the two\n options is determined by `vectorized` argument (see below).\n t0 : float\n Initial time.\n y0 : array_like, shape (n,)\n Initial state.\n t_bound : float\n Boundary time - the integration won't continue beyond it. It also\n determines the direction of the integration.\n first_step : float or None, optional\n Initial step size. Default is ``None`` which means that the algorithm\n should choose.\n max_step : float, optional\n Maximum allowed step size. Default is np.inf, i.e., the step size is not\n bounded and determined solely by the solver.\n rtol, atol : float and array_like, optional\n Relative and absolute tolerances. The solver keeps the local error\n estimates less than ``atol + rtol * abs(y)``. Here, `rtol` controls a\n relative accuracy (number of correct digits). But if a component of `y`\n is approximately below `atol`, the error only needs to fall within\n the same `atol` threshold, and the number of correct digits is not\n guaranteed. If components of y have different scales, it might be\n beneficial to set different `atol` values for different components by\n passing array_like with shape (n,) for `atol`. Default values are\n 1e-3 for `rtol` and 1e-6 for `atol`.\n vectorized : bool, optional\n Whether `fun` is implemented in a vectorized fashion. Default is False.\n\n Attributes\n ----------\n n : int\n Number of equations.\n status : string\n Current status of the solver: 'running', 'finished' or 'failed'.\n t_bound : float\n Boundary time.\n direction : float\n Integration direction: +1 or -1.\n t : float\n Current time.\n y : ndarray\n Current state.\n t_old : float\n Previous time. None if no steps were made yet.\n step_size : float\n Size of the last successful step. None if no steps were made yet.\n nfev : int\n Number evaluations of the system's right-hand side.\n njev : int\n Number of evaluations of the Jacobian. Is always 0 for this solver as it does not use the Jacobian.\n nlu : int\n Number of LU decompositions. Is always 0 for this solver.\n\n References\n ----------\n .. [1] P. Bogacki, L.F. Shampine, \"A 3(2) Pair of Runge-Kutta Formulas\",\n Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.\n \"\"\"\n order = 3\n error_estimator_order = 2\n n_stages = 3\n C = np.array([0, 1/2, 3/4])\n A = np.array([\n [0, 0, 0],\n [1/2, 0, 0],\n [0, 3/4, 0]\n ])\n B = np.array([2/9, 1/3, 4/9])\n E = np.array([5/72, -1/12, -1/9, 1/8])\n P = np.array([[1, -4 / 3, 5 / 9],\n [0, 1, -2/3],\n [0, 4/3, -8/9],\n [0, -1, 1]])\n\n\nclass RK45(RungeKutta):\n \"\"\"Explicit Runge-Kutta method of order 5(4).\n\n This uses the Dormand-Prince pair of formulas [1]_. The error is controlled\n assuming accuracy of the fourth-order method accuracy, but steps are taken\n using the fifth-order accurate formula (local extrapolation is done).\n A quartic interpolation polynomial is used for the dense output [2]_.\n\n Can be applied in the complex domain.\n\n Parameters\n ----------\n fun : callable\n Right-hand side of the system. The calling signature is ``fun(t, y)``.\n Here ``t`` is a scalar, and there are two options for the ndarray ``y``:\n It can either have shape (n,); then ``fun`` must return array_like with\n shape (n,). Alternatively it can have shape (n, k); then ``fun``\n must return an array_like with shape (n, k), i.e., each column\n corresponds to a single column in ``y``. The choice between the two\n options is determined by `vectorized` argument (see below).\n t0 : float\n Initial time.\n y0 : array_like, shape (n,)\n Initial state.\n t_bound : float\n Boundary time - the integration won't continue beyond it. It also\n determines the direction of the integration.\n first_step : float or None, optional\n Initial step size. Default is ``None`` which means that the algorithm\n should choose.\n max_step : float, optional\n Maximum allowed step size. Default is np.inf, i.e., the step size is not\n bounded and determined solely by the solver.\n rtol, atol : float and array_like, optional\n Relative and absolute tolerances. The solver keeps the local error\n estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a\n relative accuracy (number of correct digits). But if a component of `y`\n is approximately below `atol`, the error only needs to fall within\n the same `atol` threshold, and the number of correct digits is not\n guaranteed. If components of y have different scales, it might be\n beneficial to set different `atol` values for different components by\n passing array_like with shape (n,) for `atol`. Default values are\n 1e-3 for `rtol` and 1e-6 for `atol`.\n vectorized : bool, optional\n Whether `fun` is implemented in a vectorized fashion. Default is False.\n\n Attributes\n ----------\n n : int\n Number of equations.\n status : string\n Current status of the solver: 'running', 'finished' or 'failed'.\n t_bound : float\n Boundary time.\n direction : float\n Integration direction: +1 or -1.\n t : float\n Current time.\n y : ndarray\n Current state.\n t_old : float\n Previous time. None if no steps were made yet.\n step_size : float\n Size of the last successful step. None if no steps were made yet.\n nfev : int\n Number evaluations of the system's right-hand side.\n njev : int\n Number of evaluations of the Jacobian. Is always 0 for this solver as it does not use the Jacobian.\n nlu : int\n Number of LU decompositions. Is always 0 for this solver.\n\n References\n ----------\n .. [1] J. R. Dormand, P. J. Prince, \"A family of embedded Runge-Kutta\n formulae\", Journal of Computational and Applied Mathematics, Vol. 6,\n No. 1, pp. 19-26, 1980.\n .. [2] L. W. Shampine, \"Some Practical Runge-Kutta Formulas\", Mathematics\n of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.\n \"\"\"\n order = 5\n error_estimator_order = 4\n n_stages = 6\n C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])\n A = np.array([\n [0, 0, 0, 0, 0],\n [1/5, 0, 0, 0, 0],\n [3/40, 9/40, 0, 0, 0],\n [44/45, -56/15, 32/9, 0, 0],\n [19372/6561, -25360/2187, 64448/6561, -212/729, 0],\n [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]\n ])\n B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])\n E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,\n 1/40])\n # Corresponds to the optimum value of c_6 from [2]_.\n P = np.array([\n [1, -8048581381/2820520608, 8663915743/2820520608,\n -12715105075/11282082432],\n [0, 0, 0, 0],\n [0, 131558114200/32700410799, -68118460800/10900136933,\n 87487479700/32700410799],\n [0, -1754552775/470086768, 14199869525/1410260304,\n -10690763975/1880347072],\n [0, 127303824393/49829197408, -318862633887/49829197408,\n 701980252875 / 199316789632],\n [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],\n [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])\n\n\nclass DOP853(RungeKutta):\n \"\"\"Explicit Runge-Kutta method of order 8.\n\n This is a Python implementation of \"DOP853\" algorithm originally written\n in Fortran [1]_, [2]_. Note that this is not a literate translation, but\n the algorithmic core and coefficients are the same.\n\n Can be applied in the complex domain.\n\n Parameters\n ----------\n fun : callable\n Right-hand side of the system. The calling signature is ``fun(t, y)``.\n Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:\n It can either have shape (n,); then ``fun`` must return array_like with\n shape (n,). Alternatively it can have shape (n, k); then ``fun``\n must return an array_like with shape (n, k), i.e. each column\n corresponds to a single column in ``y``. The choice between the two\n options is determined by `vectorized` argument (see below).\n t0 : float\n Initial time.\n y0 : array_like, shape (n,)\n Initial state.\n t_bound : float\n Boundary time - the integration won't continue beyond it. It also\n determines the direction of the integration.\n first_step : float or None, optional\n Initial step size. Default is ``None`` which means that the algorithm\n should choose.\n max_step : float, optional\n Maximum allowed step size. Default is np.inf, i.e. the step size is not\n bounded and determined solely by the solver.\n rtol, atol : float and array_like, optional\n Relative and absolute tolerances. The solver keeps the local error\n estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a\n relative accuracy (number of correct digits). But if a component of `y`\n is approximately below `atol`, the error only needs to fall within\n the same `atol` threshold, and the number of correct digits is not\n guaranteed. If components of y have different scales, it might be\n beneficial to set different `atol` values for different components by\n passing array_like with shape (n,) for `atol`. Default values are\n 1e-3 for `rtol` and 1e-6 for `atol`.\n vectorized : bool, optional\n Whether `fun` is implemented in a vectorized fashion. Default is False.\n\n Attributes\n ----------\n n : int\n Number of equations.\n status : string\n Current status of the solver: 'running', 'finished' or 'failed'.\n t_bound : float\n Boundary time.\n direction : float\n Integration direction: +1 or -1.\n t : float\n Current time.\n y : ndarray\n Current state.\n t_old : float\n Previous time. None if no steps were made yet.\n step_size : float\n Size of the last successful step. None if no steps were made yet.\n nfev : int\n Number evaluations of the system's right-hand side.\n njev : int\n Number of evaluations of the Jacobian. Is always 0 for this solver\n as it does not use the Jacobian.\n nlu : int\n Number of LU decompositions. Is always 0 for this solver.\n\n References\n ----------\n .. [1] E. Hairer, S. P. Norsett G. Wanner, \"Solving Ordinary Differential\n Equations I: Nonstiff Problems\", Sec. II.\n .. [2] `Page with original Fortran code of DOP853\n <http://www.unige.ch/~hairer/software.html>`_.\n \"\"\"\n n_stages = dop853_coefficients.N_STAGES\n order = 8\n error_estimator_order = 7\n A = dop853_coefficients.A[:n_stages, :n_stages]\n B = dop853_coefficients.B\n C = dop853_coefficients.C[:n_stages]\n E3 = dop853_coefficients.E3\n E5 = dop853_coefficients.E5\n D = dop853_coefficients.D\n\n A_EXTRA = dop853_coefficients.A[n_stages + 1:]\n C_EXTRA = dop853_coefficients.C[n_stages + 1:]\n\n def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,\n rtol=1e-3, atol=1e-6, vectorized=False,\n first_step=None, **extraneous):\n super(DOP853, self).__init__(fun, t0, y0, t_bound, max_step,\n rtol, atol, vectorized, first_step,\n **extraneous)\n self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,\n self.n), dtype=self.y.dtype)\n self.K = self.K_extended[:self.n_stages + 1]\n\n def _estimate_error(self, K, h): # Left for testing purposes.\n err5 = np.dot(K.T, self.E5)\n err3 = np.dot(K.T, self.E3)\n denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))\n correction_factor = np.ones_like(err5)\n mask = denom > 0\n correction_factor[mask] = np.abs(err5[mask]) / denom[mask]\n return h * err5 * correction_factor\n\n def _estimate_error_norm(self, K, h, scale):\n err5 = np.dot(K.T, self.E5) / scale\n err3 = np.dot(K.T, self.E3) / scale\n err5_norm_2 = np.linalg.norm(err5)**2\n err3_norm_2 = np.linalg.norm(err3)**2\n if err5_norm_2 == 0 and err3_norm_2 == 0:\n return 0.0\n denom = err5_norm_2 + 0.01 * err3_norm_2\n return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))\n\n def _dense_output_impl(self):\n K = self.K_extended\n h = self.h_previous\n for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),\n start=self.n_stages + 1):\n dy = np.dot(K[:s].T, a[:s]) * h\n K[s] = self.fun(self.t_old + c * h, self.y_old + dy)\n\n F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),\n dtype=self.y_old.dtype)\n\n f_old = K[0]\n delta_y = self.y - self.y_old\n\n F[0] = delta_y\n F[1] = h * f_old - delta_y\n F[2] = 2 * delta_y - h * (self.f + f_old)\n F[3:] = h * np.dot(self.D, K)\n\n return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)\n\n\nclass RkDenseOutput(DenseOutput):\n def __init__(self, t_old, t, y_old, Q):\n super(RkDenseOutput, self).__init__(t_old, t)\n self.h = t - t_old\n self.Q = Q\n self.order = Q.shape[1] - 1\n self.y_old = y_old\n\n def _call_impl(self, t):\n x = (t - self.t_old) / self.h\n if t.ndim == 0:\n p = np.tile(x, self.order + 1)\n p = np.cumprod(p)\n else:\n p = np.tile(x, (self.order + 1, 1))\n p = np.cumprod(p, axis=0)\n y = self.h * np.dot(self.Q, p)\n if y.ndim == 2:\n y += self.y_old[:, None]\n else:\n y += self.y_old\n\n return y\n\n\nclass Dop853DenseOutput(DenseOutput):\n def __init__(self, t_old, t, y_old, F):\n super(Dop853DenseOutput, self).__init__(t_old, t)\n self.h = t - t_old\n self.F = F\n self.y_old = y_old\n\n def _call_impl(self, t):\n x = (t - self.t_old) / self.h\n\n if t.ndim == 0:\n y = np.zeros_like(self.y_old)\n else:\n x = x[:, None]\n y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)\n\n for i, f in enumerate(reversed(self.F)):\n y += f\n if i % 2 == 0:\n y *= x\n else:\n y *= 1 - x\n y += self.y_old\n\n return y.T\n"
] | [
[
"numpy.ones",
"numpy.sum",
"numpy.testing.assert_equal",
"numpy.random.seed",
"numpy.testing.assert_warns",
"numpy.vstack",
"numpy.cos",
"numpy.random.rand",
"numpy.identity",
"numpy.eye",
"numpy.zeros",
"numpy.testing.assert_array_less",
"scipy.optimize.linprog",
"numpy.column_stack",
"numpy.arange",
"numpy.hstack",
"numpy.all",
"numpy.array",
"numpy.intp",
"numpy.zeros_like",
"numpy.random.randn",
"numpy.random.exponential",
"numpy.testing.assert_allclose",
"numpy.random.normal",
"numpy.sin",
"numpy.testing.suppress_warnings",
"numpy.testing.assert_"
],
[
"numpy.tile",
"numpy.zeros_like",
"numpy.empty",
"numpy.ones_like",
"numpy.abs",
"numpy.cumprod",
"numpy.nextafter",
"numpy.array",
"numpy.dot",
"numpy.linalg.norm"
]
] |
RodrigoATorres/hermione | [
"c51f5e54a41609099eef48990c7ad7018dcdf41a"
] | [
"hermione/module_templates/__IMPLEMENTED_BASE__/src/predict.py"
] | [
"import pandas as pd\nimport io\nfrom joblib import load\nimport logging\n\nlogging.getLogger().setLevel(logging.INFO)\n\ndef generate_data():\n new_data = pd.DataFrame({\n 'Pclass':[3,2,1],\n 'Sex': ['male', 'female', 'male'],\n 'Age':[4, 22, 28]\n })\n return new_data\n\n\ndef load_model():\n try:\n return load('../output/titanic_model_rf.pkl')\n except:\n try: \n return load('../../output/titanic_model_rf.pkl')\n except:\n logging.error('Model not loaded')\n\n\ndef predict_new(X, probs=True):\n model = load_model()\n p = model.get_preprocessing()\n \n X = p.clean_data(X)\n X = p.categ_encoding(X)\n \n columns = model.get_columns()\n for col in columns:\n if col not in X.columns:\n X[col] = 0\n if probs:\n return model.predict_proba(X)[:,1]\n else:\n return model.predict(X)\n\n\n\nif __name__ == \"__main__\":\n df = generate_data()\n preds = predict_new(df, probs=True)\n logging.info(\"Predictions:\")\n print(preds)\n"
] | [
[
"pandas.DataFrame"
]
] |
bee-hive/nested-policy-rl | [
"56b0be37ed814265cb3ef26ea0a1a62b5cd7f05c"
] | [
"tests/test_networks.py"
] | [
"import torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn as nn\n\n# import sys\n# sys.path.append(\"../simulated_fqi/\")\nfrom simulated_fqi import NFQNetwork, ContrastiveNFQNetwork\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef train(x, y, groups, network, optimizer):\n\n predicted_q_values = network(x, groups).squeeze()\n loss = F.mse_loss(predicted_q_values, y)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return loss.item()\n\n# def test_contrastive_network():\n\n# # Setup agent\n# network = ContrastiveNFQNetwork(state_dim=0, is_contrastive=True, nonlinearity=nn.Identity)\n# optimizer = optim.Rprop(network.parameters())\n\n# # Generate data\n# n, m = 100, 100\n# beta_shared = -1\n# beta_fg = 2.1\n# x_bg, x_fg = np.linspace(-3, 3, m), np.linspace(-3, 3, n)\n# x = np.concatenate([x_bg, x_fg])\n# groups = np.concatenate([np.zeros(m), np.ones(n)])\n# y = beta_shared * x + beta_fg * groups * x# + np.random.normal(scale=0.5, size=m+n)\n\n# x = torch.FloatTensor(x).unsqueeze(1)\n# y = torch.FloatTensor(y)\n# groups = torch.FloatTensor(groups).unsqueeze(1)\n \n# for epoch in range(200):\n\n# loss = train(x, y, groups, network, optimizer)\n \n# # if epoch % 10 == 0:\n# # print(\"Epoch: {:4d}, Loss: {:4f}\".format(epoch, loss))\n\n# network.eval()\n# with torch.no_grad():\n# preds = network(x, groups)\n\n# assert np.allclose(preds.squeeze().numpy(), y.squeeze().numpy(), atol=1e-4)\n # plt.scatter(x, preds, c=groups)\n # plt.show()\n # import ipdb; ipdb.set_trace()\n \nif __name__ == \"__main__\":\n test_contrastive_network()\n"
] | [
[
"torch.nn.functional.mse_loss"
]
] |
SixHeo/IVOS-ATNet | [
"1cf574953a96bd680c518c6362b510fd103ff271"
] | [
"libs/utils_torch.py"
] | [
"import torch\n\ndef combine_masks_with_batch(masks, n_obj, th=0.5, return_as_onehot = False):\n \"\"\" Combine mask for different objects.\n\n Different methods are the following:\n\n * `max_per_pixel`: Computes the final mask taking the pixel with the highest\n probability for every object.\n\n # Arguments\n masks: Tensor with shape[B, nobj, H, W]. H, W on batches must be same\n method: String. Method that specifies how the masks are fused.\n\n # Returns\n [B, 1, H, W]\n \"\"\"\n\n # masks : B, nobj, h, w\n # output : h,w\n marker = torch.argmax(masks, dim=1, keepdim=True) #\n if not return_as_onehot:\n out_mask = torch.unsqueeze(torch.zeros_like(masks)[:,0],1) #[B, 1, H, W]\n for obj_id in range(n_obj):\n try :tmp_mask = (marker == obj_id) * (masks[:,obj_id].unsqueeze(1) > th)\n except: raise NotImplementedError\n out_mask[tmp_mask] = obj_id + 1 # [B, 1, H, W]\n\n if return_as_onehot:\n out_mask = torch.zeros_like(masks) # [B, nobj, H, W]\n for obj_id in range(n_obj):\n try :tmp_mask = (marker == obj_id) * (masks[:,obj_id].unsqueeze(1) > th)\n except: raise NotImplementedError\n out_mask[:, obj_id] = tmp_mask[:,0].type(torch.cuda.FloatTensor)\n\n return out_mask\n"
] | [
[
"torch.zeros_like",
"torch.argmax"
]
] |
muchemwal/models | [
"49fd0a8a61b0e5dab196014bf47de7f62d97c884"
] | [
"tensorflow/super_resolution/syndicai.py"
] | [
"import os\nimport io\nimport time\nimport base64\nimport functools\n\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nfrom helpers import *\nos.environ[\"TFHUB_DOWNLOAD_PROGRESS\"] = \"True\"\n\n\nclass PythonPredictor:\n\n def __init__(self, config):\n # Import TF-Hub module\n self.hub_module = hub.load(\"https://tfhub.dev/captain-pool/esrgan-tf2/1\")\n\n def predict(self, payload):\n # Preprocess image\n hr_image = preprocess_image(payload[\"image_b64\"])\n\n # Run model\n fake_image = self.hub_module(hr_image)\n\n # convert to base64\n img = get_image(tf.squeeze(fake_image))\n im_file = io.BytesIO()\n img.save(im_file, format=\"PNG\")\n im_bytes = base64.b64encode(im_file.getvalue()).decode(\"utf-8\")\n\n return im_bytes\n"
] | [
[
"tensorflow.squeeze"
]
] |
Ricechrispi/sc2_academy | [
"9ffed467fe019262035ac61d10c5cc3ee64a7bb2"
] | [
"sc2_academy/ppo/my_epsilon_greedy_policy.py"
] | [
"# coding=utf-8\n# Copyright 2018 The TF-Agents Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# ------------------------------------------------------------------------------------------\n# DISCLAIMER: This is just a slightly adjusted version of the EpsilonGreedyPolicy in TF-Agents.\n# Most of the code here is directly copied from there.\n# I changed it such that the policy in the epsilon case is not random, but sampled from\n# the original policy distribution.\n# ------------------------------------------------------------------------------------------\n\n\"\"\"Policy implementation that generates epsilon-greedy actions from a policy.\n\nTODO(kbanoop): Make policy state optional in the action method.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Using Type Annotations.\nfrom __future__ import print_function\n\nfrom typing import Optional, Text\n\nimport tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import\nimport tensorflow_probability as tfp\n\nfrom tf_agents.bandits.policies import policy_utilities\nfrom tf_agents.policies import greedy_policy\nfrom tf_agents.policies import tf_policy\nfrom tf_agents.trajectories import policy_step\nfrom tf_agents.typing import types\nfrom tf_agents.utils import nest_utils\n\ntfd = tfp.distributions\n\n\nclass EpsilonGreedyPolicy(tf_policy.TFPolicy):\n \"\"\"Returns epsilon-greedy samples of a given policy.\"\"\"\n\n def __init__(self,\n policy: tf_policy.TFPolicy,\n epsilon: types.FloatOrReturningFloat,\n name: Optional[Text] = None):\n \"\"\"Builds an epsilon-greedy MixturePolicy wrapping the given policy.\n\n Args:\n policy: A policy implementing the tf_policy.TFPolicy interface.\n epsilon: The probability of taking the random action represented as a\n float scalar, a scalar Tensor of shape=(), or a callable that returns a\n float scalar or Tensor.\n name: The name of this policy.\n\n Raises:\n ValueError: If epsilon is invalid.\n \"\"\"\n try:\n observation_and_action_constraint_splitter = (\n policy.observation_and_action_constraint_splitter)\n except AttributeError:\n observation_and_action_constraint_splitter = None\n try:\n accepts_per_arm_features = policy.accepts_per_arm_features\n except AttributeError:\n accepts_per_arm_features = False\n self._greedy_policy = greedy_policy.GreedyPolicy(policy)\n self._epsilon = epsilon\n self._epsilon_policy = self._greedy_policy.wrapped_policy # this is my main change from the original code\n super(EpsilonGreedyPolicy, self).__init__(\n policy.time_step_spec,\n policy.action_spec,\n policy.policy_state_spec,\n policy.info_spec,\n emit_log_probability=policy.emit_log_probability,\n observation_and_action_constraint_splitter=(\n observation_and_action_constraint_splitter),\n name=name)\n\n @property\n def wrapped_policy(self) -> tf_policy.TFPolicy:\n return self._greedy_policy.wrapped_policy\n\n def _variables(self):\n return self._greedy_policy.variables()\n\n def _get_epsilon(self):\n if callable(self._epsilon):\n return self._epsilon()\n else:\n return self._epsilon\n\n def _action(self, time_step, policy_state, seed):\n seed_stream = tfp.util.SeedStream(seed=seed, salt='epsilon_greedy')\n greedy_action = self._greedy_policy.action(time_step, policy_state)\n epsilon_action = self._epsilon_policy.action(time_step, (), seed_stream())\n\n outer_shape = nest_utils.get_outer_shape(time_step, self._time_step_spec)\n rng = tf.random.uniform(\n outer_shape, maxval=1.0, seed=seed_stream(), name='epsilon_rng')\n cond = tf.greater(rng, self._get_epsilon())\n\n # Selects the action/info from the random policy with probability epsilon.\n # TODO(b/133175894): tf.compat.v1.where only supports a condition which is\n # either a scalar or a vector. Use tf.compat.v2 so that it can support any\n # condition whose leading dimensions are the same as the other operands of\n # tf.where.\n outer_ndims = int(outer_shape.shape[0])\n if outer_ndims >= 2:\n raise ValueError(\n 'Only supports batched time steps with a single batch dimension')\n action = tf.nest.map_structure(lambda g, r: tf.compat.v1.where(cond, g, r),\n greedy_action.action, epsilon_action.action)\n\n if greedy_action.info:\n if not epsilon_action.info:\n raise ValueError('Incompatible info field')\n # Note that the objects in PolicyInfo may have different shapes, so we\n # need to call nest_utils.where() on each type of object.\n info = tf.nest.map_structure(lambda x, y: nest_utils.where(cond, x, y),\n greedy_action.info, epsilon_action.info)\n if self._emit_log_probability:\n # At this point, info.log_probability contains the log prob of the\n # action chosen, conditioned on the policy that was chosen. We want to\n # emit the full log probability of the action, so we'll add in the log\n # probability of choosing the policy.\n random_log_prob = tf.nest.map_structure(\n lambda t: tf.math.log(tf.zeros_like(t) + self._get_epsilon()),\n info.log_probability)\n greedy_log_prob = tf.nest.map_structure(\n lambda t: tf.math.log(tf.ones_like(t) - self._get_epsilon()),\n random_log_prob)\n log_prob_of_chosen_policy = nest_utils.where(cond, greedy_log_prob,\n random_log_prob)\n log_prob = tf.nest.map_structure(lambda a, b: a + b,\n log_prob_of_chosen_policy,\n info.log_probability)\n info = policy_step.set_log_probability(info, log_prob)\n # Overwrite bandit policy info type.\n if policy_utilities.has_bandit_policy_type(info, check_for_tensor=True):\n # Generate mask of the same shape as bandit_policy_type (batch_size, 1).\n # This is the opposite of `cond`, which is 1-D bool tensor (batch_size,)\n # that is true when greedy policy was used, otherwise `cond` is false.\n random_policy_mask = tf.reshape(tf.logical_not(cond),\n tf.shape(info.bandit_policy_type))\n bandit_policy_type = policy_utilities.bandit_policy_uniform_mask(\n info.bandit_policy_type, mask=random_policy_mask)\n info = policy_utilities.set_bandit_policy_type(\n info, bandit_policy_type)\n else:\n if epsilon_action.info:\n raise ValueError('Incompatible info field')\n info = ()\n\n # The state of the epsilon greedy policy is the state of the underlying\n # greedy policy (the random policy carries no state).\n # It is commonly assumed that the new policy state only depends only\n # on the previous state and \"time_step\", the action (be it the greedy one\n # or the random one) does not influence the new policy state.\n state = greedy_action.state\n\n return policy_step.PolicyStep(action, state, info)\n\n def _distribution(self, time_step, policy_state):\n raise NotImplementedError(\n 'EpsilonGreedyPolicy does not support distributions yet.')\n"
] | [
[
"tensorflow.shape",
"tensorflow.logical_not",
"tensorflow.ones_like",
"tensorflow.nest.map_structure",
"tensorflow.compat.v1.where",
"tensorflow.zeros_like"
]
] |
ronnith24/NeuralNetworksFromScratch | [
"5c831de8954a4b84fef7b70b16f9d9e6c1cb24b9"
] | [
"NeuralNetwork.py"
] | [
"import numpy as np\n\nclass NeuralNetwork(object):\n def __init__(self, topology, epsilon, numLabels):\n self.theta = []\n self.topology = topology\n self.numLabels = numLabels\n self.gradientChecking = False\n for layer in range(len(self.topology)):\n if layer == 0:\n continue\n self.theta.append(np.random.rand(self.topology[layer], self.topology[layer - 1] + 1) * 2 * epsilon - epsilon)\n \n \n def gradientDescent(self, iters, alpha, lamda, X, Y):\n self.X = X\n self.Y = Y\n for i in range(iters):\n (J, thetaGrad) = self.getCostAndGradient(lamda)\n # gradient checking\n if self.gradientChecking:\n thetaCopy = self.theta.copy()\n for i in range(len(self.topology) - 1):\n for j in range(self.topology[i + 1]):\n for k in range(self.topology[i]):\n EPS = 0.00001\n self.theta[i][j, k] += EPS\n J2 = self.getCostAndGradient(lamda)[0]\n self.theta[i][j, k] -= 2 * EPS\n J1 = self.getCostAndGradient(lamda)[0]\n print(str((J2 - J1) / (2 * EPS) - thetaGrad[i][j, k]))\n self.theta = thetaCopy\n # end\n for layer in range(len(self.topology) - 1):\n self.theta[layer] -= thetaGrad[layer] * alpha\n print(\"Iter \" + str(i) + \": \" + str(J))\n \n \n def predict(self, x):\n x = x.reshape((x.shape[0], 1))\n x = np.concatenate(([[1]], x))\n for layer in range(1, len(self.topology)):\n x = np.matmul(self.theta[layer - 1], x)\n for i in range(x.shape[0]):\n x[i, 0] = self.sigmoid(x[i, 0])\n if layer != len(self.topology) - 1:\n x = np.concatenate(([[1]], x))\n \n prediction = -1\n predictionSurety = -1\n for i in range(self.numLabels):\n if x[i, 0] > predictionSurety:\n prediction = i\n predictionSurety = x[i, 0]\n \n return prediction\n \n \n def getCostAndGradient(self, lamda):\n J = 0\n thetaGrad = []\n for layer in range(len(self.topology)):\n if layer == 0:\n continue\n thetaGrad.append(np.zeros((self.topology[layer], self.topology[layer - 1] + 1)))\n \n m = self.X.shape[0]\n for example in range(m):\n x = self.X[example].copy()\n x = x.reshape((x.shape[0], 1))\n y = np.zeros(self.numLabels)\n y[self.Y[example]] = 1\n y = y.reshape((y.shape[0], 1))\n a = []\n z = []\n delta = []\n \n for layer in range(len(self.topology)):\n if layer == 0:\n a.append(np.concatenate(([[1]], x)))\n z.append(np.concatenate(([[1]], x)))\n delta.append(0)\n continue\n z.append(np.matmul(self.theta[layer - 1], a[layer - 1]))\n a.append(z[layer].copy())\n for i in range(self.topology[layer]):\n a[layer][i, 0] = self.sigmoid(a[layer][i, 0])\n if layer != len(self.topology) - 1:\n a[layer] = np.concatenate(([[1]], a[layer]))\n z[layer] = np.concatenate(([[1]], z[layer]))\n delta.append(0)\n \n for layer in range(len(self.topology) - 1, 0, -1):\n if layer == len(self.topology) - 1:\n delta[layer] = a[layer] - y\n thetaGrad[layer - 1] += np.matmul(delta[layer], a[layer - 1].transpose())\n continue\n \n sigDerZ = z[layer].copy()\n for i in range(self.topology[layer] + 1):\n sigDerZ[i] = self.sigmoidDerivative(sigDerZ[i])\n \n if layer >= len(self.topology) - 2:\n delta[layer] = np.matmul(self.theta[layer].transpose(), delta[layer + 1]) * sigDerZ\n else:\n delta[layer] = np.matmul(self.theta[layer].transpose(), delta[layer + 1][1:, :]) * sigDerZ\n \n thetaGrad[layer - 1] += np.matmul(delta[layer][1:, :], a[layer - 1].transpose())\n \n J += np.sum(-(1 - y) * np.log(1 - a[len(self.topology) - 1])) - np.sum(y * np.log(a[len(self.topology) - 1]))\n \n J /= m\n \n for layer in range(len(self.topology) - 1):\n thetaGrad[layer] *= (1 / m)\n \n for i in range(len(self.topology) - 1):\n for j in range(self.topology[i + 1]):\n for k in range(1, self.topology[i]):\n J += (lamda / (2 * m)) * self.theta[i][j, k] ** 2\n thetaGrad[i][j, k] += (lamda / m) * self.theta[i][j, k]\n \n return (J, thetaGrad)\n \n \n def sigmoid(self, x):\n return 1 / (1 + np.exp(-x))\n \n \n def sigmoidDerivative(self, x):\n sig = self.sigmoid(x)\n return sig * (1 - sig)"
] | [
[
"numpy.matmul",
"numpy.zeros",
"numpy.exp",
"numpy.random.rand",
"numpy.concatenate"
]
] |
swcho84/image-segmentation | [
"ef9b9b3d832e9efe6f43522cc5ca0e17279d6608"
] | [
"image-segmentation/data_generators/kitti/kitti_dataset.py"
] | [
"from collections import namedtuple\n\nimport os\nimport json\nimport numpy as np\n\nfrom tqdm import tqdm\nfrom data_generators.utils import load_image_rgb\n\n# Copied from: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py\n#\n# Cityscapes labels\n#\n#--------------------------------------------------------------------------------\n# Definitions\n#--------------------------------------------------------------------------------\n\n# a label and all meta information\nLabel = namedtuple( 'Label' , [\n\n 'name' , # The identifier of this label, e.g. 'car', 'person', ... .\n # We use them to uniquely name a class\n\n 'id' , # An integer ID that is associated with this label.\n # The IDs are used to represent the label in ground truth images\n # An ID of -1 means that this label does not have an ID and thus\n # is ignored when creating ground truth images (e.g. license plate).\n # Do not modify these IDs, since exactly these IDs are expected by the\n # evaluation server.\n\n 'trainId' , # Feel free to modify these IDs as suitable for your method. Then create\n # ground truth images with train IDs, using the tools provided in the\n # 'preparation' folder. However, make sure to validate or submit results\n # to our evaluation server using the regular IDs above!\n # For trainIds, multiple labels might have the same ID. Then, these labels\n # are mapped to the same class in the ground truth images. For the inverse\n # mapping, we use the label that is defined first in the list below.\n # For example, mapping all void-type classes to the same ID in training,\n # might make sense for some approaches.\n # Max value is 255!\n\n 'category' , # The name of the category that this label belongs to\n\n 'categoryId' , # The ID of this category. Used to create ground truth images\n # on category level.\n\n 'hasInstances', # Whether this label distinguishes between single instances or not\n\n 'ignoreInEval', # Whether pixels having this class as ground truth label are ignored\n # during evaluations or not\n\n 'color' , # The color of this label\n ] )\n\n\ndef label2dict(label):\n return {\n 'name': label.name, 'id': label.id, 'trainId': label.trainId,\n 'category': label.category, 'catId': label.categoryId, 'hasInstances': label.hasInstances,\n 'ignoreInEval': label.ignoreInEval, 'color': label.color\n }\n\n\ndef save_labels(labels, fpath):\n l = []\n for label in labels:\n l.append(label2dict(label))\n\n fp = open(fpath, 'w')\n json.dump(l, fp)\n fp.close()\n\n\ndef load_labels(fpath):\n fp = open(fpath, 'r')\n l = json.load(fp)\n fp.close()\n labels = []\n for item in l:\n labels.append(\n Label(\n item['name'], item['id'], item['trainId'],\n item['category'], item['catId'], item['hasInstances'],\n item['ignoreInEval'], tuple(item['color']))\n )\n return labels\n\n\nclass KittiDataset:\n def __init__(self):\n self.image_ids = []\n\n def load_kitti(self, dataset_dir, subset, tag='simple'):\n 'Initialization'\n assert subset in ['train', 'val'], 'subset must be either train or val but {} is given'.format(subset)\n\n self.labels = load_labels(os.path.join(dataset_dir, 'annotations', 'semantic_{}.json'.format(tag)))\n\n # trainId to colors\n self.trainId2colors = {label.trainId: [] for label in self.labels}\n for label in self.labels:\n self.trainId2colors[label.trainId].append(label.color)\n # trainId to name\n self.trainId2name = {label.trainId: label.name for label in self.labels}\n\n # number of valid trainIds + background class\n self.num_classes = max([label.trainId for label in self.labels if label.trainId >= 0 and label.trainId < 255]) + 2\n self.class_names = [self.trainId2name[i] for i in range(self.num_classes - 1)]\n\n self.image_dir = os.path.join(dataset_dir, subset, 'images')\n self.label_dir = os.path.join(dataset_dir, subset, 'semantic_rgb')\n\n assert os.path.exists(self.image_dir), 'No such directory: {}'.format(self.image_dir)\n assert os.path.exists(self.label_dir), 'No such directory: {}'.format(self.label_dir)\n\n self.image_files = sorted([x for x in os.listdir(self.image_dir) if x.lower().endswith('.png') or x.lower().endswith('.jpg')])\n self.label_files = sorted([x for x in os.listdir(self.label_dir) if x.lower().endswith('.png')])\n\n assert len(self.image_files) == len(self.label_files), \\\n 'image - label size mismatch! There are {} image files and {} label files'.format(len(self.image_files), len(self.label_files))\n\n self.num_images = len(self.image_files)\n self.image_ids = np.arange(self.num_images)\n\n def check_sanity(self):\n for i in tqdm(self.image_ids):\n assert self.image_files[i][:-4] == self.label_files[i][:-4],\\\n 'image - label filename mismatch: {} - {}'.format(self.image_files[i], self.label_files[i])\n img = load_image_rgb(os.path.join(self.image_dir, self.image_files[i]))\n msk = load_image_rgb(os.path.join(self.label_dir, self.label_files[i]))\n assert img.shape == msk.shape,\\\n 'img.shape: {}, msk.shape: {}'.format(img.shape, msk.shape)\n\n def load_image(self, image_id):\n return load_image_rgb(os.path.join(self.image_dir, self.image_files[image_id]))\n\n def load_mask(self, image_id):\n rgb_mask = load_image_rgb(os.path.join(self.label_dir, self.label_files[image_id]))\n mask = np.zeros((rgb_mask.shape[0], rgb_mask.shape[1], self.num_classes - 1))\n for cls in range(self.num_classes - 1):\n colors = self.trainId2colors[cls]\n cls_mask = np.zeros((rgb_mask.shape[0], rgb_mask.shape[1]))\n for color in colors:\n cls_mask = np.logical_or(cls_mask, (rgb_mask == color).all(axis=2))\n mask[:,:,cls] = cls_mask\n return mask\n"
] | [
[
"numpy.arange",
"numpy.zeros"
]
] |
pearcandy/pennylane | [
"dfa35989cd0798496e41999a197bcf0eb26185df"
] | [
"tests/devices/test_default_qubit_jax.py"
] | [
"import pytest\r\n\r\njax = pytest.importorskip(\"jax\", minversion=\"0.2\")\r\njnp = jax.numpy\r\nimport numpy as np\r\nimport pennylane as qml\r\nfrom pennylane.devices.default_qubit_jax import DefaultQubitJax\r\n\r\npytestmark = pytest.mark.usefixtures(\"tape_mode\")\r\n\r\n\r\nclass TestQNodeIntegration:\r\n \"\"\"Integration tests for default.qubit.jax. This test ensures it integrates\r\n properly with the PennyLane UI, in particular the new QNode.\"\"\"\r\n\r\n def test_defines_correct_capabilities(self):\r\n \"\"\"Test that the device defines the right capabilities\"\"\"\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n cap = dev.capabilities()\r\n capabilities = {\r\n \"model\": \"qubit\",\r\n \"supports_finite_shots\": True,\r\n \"supports_tensor_observables\": True,\r\n \"returns_probs\": True,\r\n \"returns_state\": True,\r\n \"supports_reversible_diff\": False,\r\n \"supports_inverse_operations\": True,\r\n \"supports_analytic_computation\": True,\r\n \"passthru_interface\": \"jax\",\r\n }\r\n assert cap == capabilities\r\n\r\n def test_defines_correct_capabilities_directly_from_class(self):\r\n \"\"\"Test that the device defines the right capabilities\"\"\"\r\n\r\n dev = DefaultQubitJax(wires=1)\r\n cap = dev.capabilities()\r\n assert cap[\"supports_reversible_diff\"] == False\r\n assert cap[\"passthru_interface\"] == \"jax\"\r\n\r\n def test_load_device(self):\r\n \"\"\"Test that the plugin device loads correctly\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n assert dev.num_wires == 2\r\n assert dev.shots == 1000\r\n assert dev.analytic\r\n assert dev.short_name == \"default.qubit.jax\"\r\n assert dev.capabilities()[\"passthru_interface\"] == \"jax\"\r\n\r\n def test_qubit_circuit(self, tol):\r\n \"\"\"Test that the device provides the correct\r\n result for a simple circuit.\"\"\"\r\n p = jnp.array(0.543)\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @qml.qnode(dev, interface=\"jax\")\r\n def circuit(x):\r\n qml.RX(x, wires=0)\r\n return qml.expval(qml.PauliY(0))\r\n\r\n expected = -jnp.sin(p)\r\n if not qml.tape_mode_active():\r\n assert isinstance(circuit, qml.qnodes.PassthruQNode)\r\n assert jnp.isclose(circuit(p), expected, atol=tol, rtol=0)\r\n\r\n def test_qubit_circuit_with_jit(self, tol):\r\n \"\"\"Test that the device provides the correct\r\n result for a simple circuit under a jax.jit.\"\"\"\r\n p = jnp.array(0.543)\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @jax.jit\r\n @qml.qnode(dev, interface=\"jax\")\r\n def circuit(x):\r\n qml.RX(x, wires=0)\r\n return qml.expval(qml.PauliY(0))\r\n\r\n expected = -jnp.sin(p)\r\n # Do not test isinstance here since the @jax.jit changes the function\r\n # type.\r\n # Just test that it works and spits our the right value.\r\n assert jnp.isclose(circuit(p), expected, atol=tol, rtol=0)\r\n\r\n def test_correct_state(self, tol):\r\n \"\"\"Test that the device state is correct after applying a\r\n quantum function on the device\"\"\"\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n state = dev.state\r\n expected = jnp.array([1, 0, 0, 0])\r\n assert jnp.allclose(state, expected, atol=tol, rtol=0)\r\n\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def circuit():\r\n qml.Hadamard(wires=0)\r\n qml.RZ(jnp.pi / 4, wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n circuit()\r\n state = dev.state\r\n\r\n amplitude = jnp.exp(-1j * jnp.pi / 8) / jnp.sqrt(2)\r\n\r\n expected = jnp.array([amplitude, 0, jnp.conj(amplitude), 0])\r\n assert jnp.allclose(state, expected, atol=tol, rtol=0)\r\n\r\n def test_correct_state_returned(self, tol):\r\n \"\"\"Test that the device state is correct after applying a\r\n quantum function on the device\"\"\"\r\n if not qml.tape_mode_active():\r\n pytest.skip(\"Only supported in tape mode\")\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def circuit():\r\n qml.Hadamard(wires=0)\r\n qml.RZ(jnp.pi / 4, wires=0)\r\n return qml.state()\r\n\r\n state = circuit()\r\n\r\n amplitude = jnp.exp(-1j * jnp.pi / 8) / jnp.sqrt(2)\r\n\r\n expected = jnp.array([amplitude, 0, jnp.conj(amplitude), 0])\r\n assert jnp.allclose(state, expected, atol=tol, rtol=0)\r\n\r\n def test_sampling_with_jit(self):\r\n \"\"\"Test that sampling works with a jax.jit\"\"\"\r\n @jax.jit\r\n def circuit(key):\r\n dev = qml.device(\"default.qubit.jax\", wires=1, prng_key=key)\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def inner_circuit():\r\n qml.Hadamard(0)\r\n return qml.sample(qml.PauliZ(wires=0))\r\n return inner_circuit()\r\n\r\n a = circuit(jax.random.PRNGKey(0))\r\n b = circuit(jax.random.PRNGKey(0))\r\n c = circuit(jax.random.PRNGKey(1))\r\n np.testing.assert_array_equal(a, b)\r\n assert not np.all(a == c)\r\n\r\n def test_sampling_op_by_op(self):\r\n \"\"\"Test that op-by-op sampling works as a new user would expect\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def circuit():\r\n qml.Hadamard(0)\r\n return qml.sample(qml.PauliZ(wires=0))\r\n\r\n a = circuit()\r\n b = circuit()\r\n assert not np.all(a == b)\r\n\r\n def test_gates_dont_crash(self):\r\n \"\"\"Test for gates that weren't covered by other tests. \"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def circuit():\r\n qml.CRZ(0.0, wires=[0, 1])\r\n qml.CRot(1.0, 0.0, 0.0, wires=[0, 1])\r\n qml.CRY(0.0, wires=[0, 1])\r\n return qml.sample(qml.PauliZ(wires=0))\r\n circuit() # Just don't crash.\r\n\r\n def test_diagonal_doesnt_crash(self):\r\n \"\"\"Test that diagonal gates can be used.\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n @qml.qnode(dev, interface=\"jax\", diff_method=\"backprop\")\r\n def circuit():\r\n qml.DiagonalQubitUnitary(np.array([1.0, 1.0]), wires=0)\r\n return qml.sample(qml.PauliZ(wires=0))\r\n circuit() # Just don't crash.\r\n \r\n\r\nclass TestPassthruIntegration:\r\n \"\"\"Tests for integration with the PassthruQNode\"\"\"\r\n\r\n @pytest.mark.parametrize(\"jacobian_transform\", [jax.jacfwd, jax.jacrev])\r\n def test_jacobian_variable_multiply(self, tol, jacobian_transform):\r\n \"\"\"Test that jacobian of a QNode with an attached default.qubit.jax device\r\n gives the correct result in the case of parameters multiplied by scalars\"\"\"\r\n x = 0.43316321\r\n y = 0.2162158\r\n z = 0.75110998\r\n weights = jnp.array([x, y, z])\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @qml.qnode(dev, interface=\"jax\")\r\n def circuit(p):\r\n qml.RX(3 * p[0], wires=0)\r\n qml.RY(p[1], wires=0)\r\n qml.RX(p[2] / 2, wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n if not qml.tape_mode_active():\r\n assert isinstance(circuit, qml.qnodes.PassthruQNode)\r\n res = circuit(weights)\r\n\r\n expected = jnp.cos(3 * x) * jnp.cos(y) * jnp.cos(z / 2) - jnp.sin(3 * x) * jnp.sin(z / 2)\r\n assert jnp.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n grad_fn = jacobian_transform(circuit, 0)\r\n res = grad_fn(jnp.array(weights))\r\n\r\n expected = jnp.array(\r\n [\r\n -3\r\n * (jnp.sin(3 * x) * jnp.cos(y) * jnp.cos(z / 2) + jnp.cos(3 * x) * jnp.sin(z / 2)),\r\n -jnp.cos(3 * x) * jnp.sin(y) * jnp.cos(z / 2),\r\n -0.5\r\n * (jnp.sin(3 * x) * jnp.cos(z / 2) + jnp.cos(3 * x) * jnp.cos(y) * jnp.sin(z / 2)),\r\n ]\r\n )\r\n\r\n assert jnp.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n @pytest.mark.parametrize(\"jacobian_transform\", [jax.jacfwd, jax.jacrev])\r\n def test_jacobian_repeated(self, tol, jacobian_transform):\r\n \"\"\"Test that jacobian of a QNode with an attached default.qubit.jax device\r\n gives the correct result in the case of repeated parameters\"\"\"\r\n x = 0.43316321\r\n y = 0.2162158\r\n z = 0.75110998\r\n p = jnp.array([x, y, z])\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @qml.qnode(dev, interface=\"jax\")\r\n def circuit(x):\r\n qml.RX(x[1], wires=0)\r\n qml.Rot(x[0], x[1], x[2], wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n res = circuit(p)\r\n\r\n expected = jnp.cos(y) ** 2 - jnp.sin(x) * jnp.sin(y) ** 2\r\n assert jnp.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n grad_fn = jacobian_transform(circuit, 0)\r\n res = grad_fn(p)\r\n\r\n expected = jnp.array(\r\n [-jnp.cos(x) * jnp.sin(y) ** 2, -2 * (jnp.sin(x) + 1) * jnp.sin(y) * jnp.cos(y), 0]\r\n )\r\n assert jnp.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n def test_state_differentiability(self, tol):\r\n \"\"\"Test that the device state can be differentiated\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @qml.qnode(dev, diff_method=\"backprop\", interface=\"jax\")\r\n def circuit(a):\r\n qml.RY(a, wires=0)\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n a = jnp.array(0.54)\r\n\r\n def cost(a):\r\n \"\"\"A function of the device quantum state, as a function\r\n of ijnput QNode parameters.\"\"\"\r\n circuit(a)\r\n res = jnp.abs(dev.state) ** 2\r\n return res[1] - res[0]\r\n\r\n grad = jax.grad(cost)(a)\r\n expected = jnp.sin(a)\r\n assert jnp.allclose(grad, expected, atol=tol, rtol=0)\r\n\r\n def test_prob_differentiability(self, tol):\r\n \"\"\"Test that the device probability can be differentiated\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n @qml.qnode(dev, diff_method=\"backprop\", interface=\"jax\")\r\n def circuit(a, b):\r\n qml.RX(a, wires=0)\r\n qml.RY(b, wires=1)\r\n qml.CNOT(wires=[0, 1])\r\n return qml.probs(wires=[1])\r\n\r\n a = jnp.array(0.54)\r\n b = jnp.array(0.12)\r\n\r\n def cost(a, b):\r\n prob_wire_1 = circuit(a, b).squeeze()\r\n return prob_wire_1[1] - prob_wire_1[0]\r\n\r\n res = cost(a, b)\r\n expected = -jnp.cos(a) * jnp.cos(b)\r\n assert jnp.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n grad = jax.jit(jax.grad(cost, argnums=(0, 1)))(a, b)\r\n expected = [jnp.sin(a) * jnp.cos(b), jnp.cos(a) * jnp.sin(b)]\r\n assert jnp.allclose(grad, expected, atol=tol, rtol=0)\r\n\r\n def test_backprop_gradient(self, tol):\r\n \"\"\"Tests that the gradient of the qnode is correct\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n @qml.qnode(dev, diff_method=\"backprop\", interface=\"jax\")\r\n def circuit(a, b):\r\n qml.RX(a, wires=0)\r\n qml.CRX(b, wires=[0, 1])\r\n return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n a = jnp.array(-0.234)\r\n b = jnp.array(0.654)\r\n\r\n res = circuit(a, b)\r\n expected_cost = 0.5 * (jnp.cos(a) * jnp.cos(b) + jnp.cos(a) - jnp.cos(b) + 1)\r\n assert jnp.allclose(res, expected_cost, atol=tol, rtol=0)\r\n res = jax.grad(lambda x, y: circuit(x, y).reshape(()), argnums=(0, 1))(a, b)\r\n expected_grad = jnp.array(\r\n [-0.5 * jnp.sin(a) * (jnp.cos(b) + 1), 0.5 * jnp.sin(b) * (1 - jnp.cos(a))]\r\n )\r\n assert jnp.allclose(res, expected_grad, atol=tol, rtol=0)\r\n\r\n @pytest.mark.parametrize(\"operation\", [qml.U3, qml.U3.decomposition])\r\n @pytest.mark.parametrize(\"diff_method\", [\"backprop\"])\r\n def test_jax_interface_gradient(self, operation, diff_method, tol):\r\n \"\"\"Tests that the gradient of an arbitrary U3 gate is correct\r\n using the Jax interface, using a variety of differentiation methods.\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n @qml.qnode(dev, diff_method=diff_method, interface=\"jax\")\r\n def circuit(x, weights, w=None):\r\n \"\"\"In this example, a mixture of scalar\r\n arguments, array arguments, and keyword arguments are used.\"\"\"\r\n qml.QubitStateVector(1j * jnp.array([1, -1]) / jnp.sqrt(2), wires=w)\r\n operation(x, weights[0], weights[1], wires=w)\r\n return qml.expval(qml.PauliX(w))\r\n\r\n # Check that the correct QNode type is being used.\r\n if not qml.tape_mode_active():\r\n if diff_method == \"backprop\":\r\n assert isinstance(circuit, qml.qnodes.PassthruQNode)\r\n assert not hasattr(circuit, \"jacobian\")\r\n else:\r\n assert not isinstance(circuit, qml.qnodes.PassthruQNode)\r\n assert hasattr(circuit, \"jacobian\")\r\n\r\n def cost(params):\r\n \"\"\"Perform some classical processing\"\"\"\r\n return (circuit(params[0], params[1:], w=0) ** 2).reshape(())\r\n\r\n theta = 0.543\r\n phi = -0.234\r\n lam = 0.654\r\n\r\n params = jnp.array([theta, phi, lam])\r\n\r\n res = cost(params)\r\n expected_cost = (\r\n jnp.sin(lam) * jnp.sin(phi) - jnp.cos(theta) * jnp.cos(lam) * jnp.cos(phi)\r\n ) ** 2\r\n assert jnp.allclose(res, expected_cost, atol=tol, rtol=0)\r\n\r\n res = jax.grad(cost)(params)\r\n expected_grad = (\r\n jnp.array(\r\n [\r\n jnp.sin(theta) * jnp.cos(lam) * jnp.cos(phi),\r\n jnp.cos(theta) * jnp.cos(lam) * jnp.sin(phi) + jnp.sin(lam) * jnp.cos(phi),\r\n jnp.cos(theta) * jnp.sin(lam) * jnp.cos(phi) + jnp.cos(lam) * jnp.sin(phi),\r\n ]\r\n )\r\n * 2\r\n * (jnp.sin(lam) * jnp.sin(phi) - jnp.cos(theta) * jnp.cos(lam) * jnp.cos(phi))\r\n )\r\n assert jnp.allclose(res, expected_grad, atol=tol, rtol=0)\r\n\r\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"tf\", \"torch\"])\r\n def test_error_backprop_wrong_interface(self, interface, tol):\r\n \"\"\"Tests that an error is raised if diff_method='backprop' but not using\r\n the Jax interface\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=1)\r\n\r\n def circuit(x, w=None):\r\n qml.RZ(x, wires=w)\r\n return qml.expval(qml.PauliX(w))\r\n\r\n error_type = qml.QuantumFunctionError if qml.tape_mode_active() else ValueError\r\n with pytest.raises(\r\n error_type,\r\n match=\"default.qubit.jax only supports diff_method='backprop' when using the jax interface\",\r\n ):\r\n qml.qnode(dev, diff_method=\"backprop\", interface=interface)(circuit)\r\n\r\n\r\nclass TestHighLevelIntegration:\r\n \"\"\"Tests for integration with higher level components of PennyLane.\"\"\"\r\n\r\n def test_template_integration(self):\r\n \"\"\"Test that a PassthruQNode using default.qubit.jax works with templates.\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n @qml.qnode(dev, diff_method=\"backprop\", interface=\"jax\")\r\n def circuit(weights):\r\n qml.templates.StronglyEntanglingLayers(weights, wires=[0, 1])\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n weights = jnp.array(qml.init.strong_ent_layers_normal(n_wires=2, n_layers=2))\r\n\r\n grad = jax.grad(lambda a: circuit(a).reshape(()))(weights)\r\n assert grad.shape == weights.shape\r\n\r\n def test_qnode_collection_integration(self):\r\n \"\"\"Test that a PassthruQNode using default.qubit.jax works with QNodeCollections.\"\"\"\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n def ansatz(weights, **kwargs):\r\n qml.RX(weights[0], wires=0)\r\n qml.RY(weights[1], wires=1)\r\n qml.CNOT(wires=[0, 1])\r\n\r\n obs_list = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliZ(0), qml.PauliZ(0) @ qml.PauliZ(1)]\r\n qnodes = qml.map(ansatz, obs_list, dev, interface=\"jax\")\r\n if not qml.tape_mode_active():\r\n assert qnodes.interface == \"jax\"\r\n\r\n weights = jnp.array([0.1, 0.2])\r\n\r\n def cost(weights):\r\n return jnp.sum(jnp.array(qnodes(weights)))\r\n\r\n grad = jax.grad(cost)(weights)\r\n assert grad.shape == weights.shape\r\n\r\n def test_non_backprop_error(self):\r\n \"\"\"Test that an error is raised in tape mode if the diff method is not backprop\"\"\"\r\n if not qml.tape_mode_active():\r\n pytest.skip(\"Test only applies in tape mode\")\r\n\r\n dev = qml.device(\"default.qubit.jax\", wires=2)\r\n\r\n def circuit(weights):\r\n qml.templates.StronglyEntanglingLayers(weights, wires=[0, 1])\r\n return qml.expval(qml.PauliZ(0))\r\n\r\n qnode = qml.QNode(circuit, dev, interface=\"jax\", diff_method=\"parameter-shift\")\r\n weights = jnp.array(qml.init.strong_ent_layers_normal(n_wires=2, n_layers=2))\r\n\r\n with pytest.raises(qml.QuantumFunctionError, match=\"The JAX interface can only be used with\"):\r\n qnode(weights)\r\n\r\n\r\nclass TestOps:\r\n \"\"\"Unit tests for operations supported by the default.qubit.jax device\"\"\"\r\n\r\n @pytest.mark.parametrize(\"jacobian_transform\", [jax.jacfwd, jax.jacrev])\r\n def test_multirz_jacobian(self, jacobian_transform):\r\n \"\"\"Test that the patched numpy functions are used for the MultiRZ\r\n operation and the jacobian can be computed.\"\"\"\r\n wires = 4\r\n dev = qml.device(\"default.qubit.jax\", wires=wires)\r\n\r\n @qml.qnode(dev, diff_method=\"backprop\", interface=\"jax\")\r\n def circuit(param):\r\n qml.MultiRZ(param, wires=[0, 1])\r\n return qml.probs(wires=list(range(wires)))\r\n\r\n param = 0.3\r\n res = jacobian_transform(circuit)(param)\r\n assert jnp.allclose(res, jnp.zeros(wires ** 2))\r\n\r\n def test_full_subsystem(self, mocker):\r\n \"\"\"Test applying a state vector to the full subsystem\"\"\"\r\n dev = DefaultQubitJax(wires=[\"a\", \"b\", \"c\"])\r\n state = jnp.array([1, 0, 0, 0, 1, 0, 1, 1]) / 2.0\r\n state_wires = qml.wires.Wires([\"a\", \"b\", \"c\"])\r\n\r\n spy = mocker.spy(dev, \"_scatter\")\r\n dev._apply_state_vector(state=state, device_wires=state_wires)\r\n\r\n assert jnp.all(dev._state.flatten() == state)\r\n spy.assert_not_called()\r\n\r\n def test_partial_subsystem(self, mocker):\r\n \"\"\"Test applying a state vector to a subset of wires of the full subsystem\"\"\"\r\n\r\n dev = DefaultQubitJax(wires=[\"a\", \"b\", \"c\"])\r\n state = jnp.array([1, 0, 1, 0]) / jnp.sqrt(2.0)\r\n state_wires = qml.wires.Wires([\"a\", \"c\"])\r\n\r\n spy = mocker.spy(dev, \"_scatter\")\r\n dev._apply_state_vector(state=state, device_wires=state_wires)\r\n res = jnp.sum(dev._state, axis=(1,)).flatten()\r\n\r\n assert jnp.all(res == state)\r\n spy.assert_called()\r\n"
] | [
[
"numpy.array",
"numpy.all",
"numpy.testing.assert_array_equal"
]
] |
RotemBadash/IML.HUJI | [
"2b20d074c159123f61b321a7e84312ab82400949"
] | [
"IMLearn/learners/regressors/polynomial_fitting.py"
] | [
"from __future__ import annotations\nfrom typing import NoReturn\nfrom . import LinearRegression\nfrom ...base import BaseEstimator\nimport numpy as np\n\n\nclass PolynomialFitting(BaseEstimator):\n \"\"\"\n Polynomial Fitting using Least Squares estimation\n \"\"\"\n def __init__(self, k: int) -> PolynomialFitting:\n \"\"\"\n Instantiate a polynomial fitting estimator\n\n Parameters\n ----------\n k : int\n Degree of polynomial to fit\n \"\"\"\n super().__init__()\n self.degree = k\n self.linear_regression_model = LinearRegression(\n include_intercept=False)\n\n def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:\n \"\"\"\n Fit Least Squares model to polynomial transformed samples\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to fit an estimator for\n\n y : ndarray of shape (n_samples, )\n Responses of input data to fit to\n \"\"\"\n x = self.__transform(X)\n self.linear_regression_model.fit(x, y)\n\n def _predict(self, X: np.ndarray) -> np.ndarray:\n \"\"\"\n Predict responses for given samples using fitted estimator\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to predict responses for\n\n Returns\n -------\n responses : ndarray of shape (n_samples, )\n Predicted responses of given samples\n \"\"\"\n x = self.__transform(X)\n return self.linear_regression_model.predict(x)\n\n def _loss(self, X: np.ndarray, y: np.ndarray) -> float:\n \"\"\"\n Evaluate performance under MSE loss function\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Test samples\n\n y : ndarray of shape (n_samples, )\n True labels of test samples\n\n Returns\n -------\n loss : float\n Performance under MSE loss function\n \"\"\"\n x = self.__transform(X)\n return self.linear_regression_model.loss(x, y)\n\n def __transform(self, X: np.ndarray) -> np.ndarray:\n \"\"\"\n Transform given input according to the univariate polynomial\n transformation\n\n Parameters\n ----------\n X: ndarray of shape (n_samples,)\n\n Returns\n -------\n transformed: ndarray of shape (n_samples, k+1)\n Vandermonde matrix of given samples up to degree k\n \"\"\"\n return np.vander(X, N=self.degree+1, increasing=True)"
] | [
[
"numpy.vander"
]
] |
LvJC/cpp-libtorch | [
"4a56dda616bde50423591e7a4d4d7be6a978f6bf"
] | [
"MyModule.py"
] | [
"import torch\nimport torchvision\n\n# An instance of your model.\nmodel = torchvision.models.resnet18()\n\n# An example input you would normally provide to your model's forward() method.\nexample = torch.rand(1, 3, 224, 224)\n\n# Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.\ntraced_script_module = torch.jit.trace(model, example)\n\n# save\ntraced_script_module.save(\"model.pt\")\n"
] | [
[
"torch.rand",
"torch.jit.trace"
]
] |
demarley/leopard | [
"52c5eb2dd732798972d429887c273f8449039c8f"
] | [
"python/deepLearningTorch.py"
] | [
"\"\"\"\nCreated: 16 August 2018\nLast Updated: 16 August 2018\n\nDan Marley\ndaniel.edison.marley@cernSPAMNOT.ch\nTexas A&M University\n-----\n\nClass for performing deep learning in pytorch\n\nDesigned for running on desktop at TAMU\nwith specific set of software installed\n--> not guaranteed to work in CMSSW environment!\n\nDoes not use ROOT directly.\nInstead, this is setup to use flat ntuples\nthat are accessed via uproot.\n\n> UPROOT: https://github.com/scikit-hep/uproot\n> KERAS: https://keras.io/\n> TENSORFLOW: https://www.tensorflow.org/\n> PYTORCH: http://pytorch.org/\n> LWTNN: https://github.com/lwtnn/lwtnn\n\"\"\"\nimport json\nimport util\nimport datetime\nimport collections\n\nfrom deepLearning import DeepLearning\n\nimport uproot\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as tf\nfrom torch.autograd import Variable\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import roc_curve\n\n\nclass LeopardNet(nn.Module):\n \"\"\"Neural Network for Leopard in PyTorch\n Adapted from (16 August 2018)\n https://github.com/thongonary/surf18-tutorial/blob/master/tuto-8-torch.ipynb\n \"\"\"\n def __init__(self,layers):\n super(LeopardNet,self).__init__()\n self.dense = nn.ModuleList()\n for l,layer in enumerate(layers):\n self.dense.append( nn.Linear(layer['in'],layer['out']) )\n \n def forward(self, x): \n \"\"\"All the computation steps of the input are defined in this function\"\"\"\n nlayers = len(self.dense)\n for i,d in enumerate(self.dense):\n x = d(x)\n x = tf.relu(x) if i!=nlayers-1 else tf.sigmoid(x)\n return x\n\n\n\nclass DeepLearningTorch(DeepLearning):\n \"\"\"Deep Learning pytorch class\"\"\"\n def __init__(self):\n DeepLearning.__init__(self)\n\n ## PyTorch objects\n self.loss_fn = None # pytorch loss function\n self.torch_opt = None # pytorch optimizer\n\n def initialize(self): #,config):\n \"\"\"Initialize a few parameters after they've been set by user\"\"\"\n DeepLearning.initialize(self)\n return\n\n\n ## Specific functions to perform training/inference tasks\n def build_model(self):\n \"\"\"Construct the NN model -- only Keras support for now\"\"\"\n self.msg_svc.INFO(\"DLPYTORCH : Build the neural network model\")\n\n ## Declare the model\n layers = []\n layers.append( {'in':int(self.input_dim),'out':int(self.nNodes[0])} )\n for i,n in enumerate(self.nNodes):\n if i==len(self.nNodes)-1: continue\n layers.append( {'in':int(n),'out':int(self.nNodes[i+1])} )\n layers.append( {'in':int(self.nNodes[-1]),'out':self.output_dim} )\n\n self.model = LeopardNet(layers)\n self.model.cuda()\n\n self.loss_fn = torch.nn.BCELoss()\n self.torch_opt = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate) #1e-4)\n\n return\n\n\n def train_epoch(self,X,Y):\n \"\"\"\"\"\"\n losses = []\n for beg_i in range(0, len(X), self.batch_size):\n x_batch = torch.from_numpy(X[beg_i:beg_i+self.batch_size,:])\n y_batch = torch.from_numpy(Y[beg_i:beg_i+self.batch_size])\n x_batch = Variable(x_batch).cuda()\n y_batch = Variable(y_batch).float().unsqueeze_(-1).cuda() # modify dimensions (X,) -> (X,1)\n\n self.torch_opt.zero_grad()\n\n y_hat = self.model(x_batch) # forward\n loss = self.loss_fn(y_hat, y_batch) # compute loss\n loss.backward() # compute gradients\n self.torch_opt.step() # update weights\n\n losses.append(loss.data.cpu().numpy())\n\n return losses\n\n\n\n def train_model(self):\n \"\"\"Setup for training the model using k-fold cross-validation\"\"\"\n X = self.df[self.features].values\n Y = self.df['target'].values\n\n kfold = StratifiedKFold(n_splits=self.kfold_splits, shuffle=True, random_state=seed)\n nsplits = kfold.get_n_splits(X,Y)\n cvpredictions = [] # compare outputs from each cross-validation\n\n self.msg_svc.INFO(\"DLPYTORCH : Fitting K-Fold cross validations\")\n for ind,(train,test) in enumerate(kfold.split(X,Y)):\n self.msg_svc.INFO(\"DLPYTORCH : - Fitting K-Fold {0}\".format(ind))\n\n Y_train = Y[train]\n Y_test = Y[test]\n\n # -- store test/train data from each k-fold as histograms (to compare later)\n h_tests = {}\n h_trains = {}\n for n,v in self.targets.iteritems():\n h_tests[n] = ROOT.TH1D(\"test_\"+n,\"test_\"+n,10,0,10)\n h_trains[n] = ROOT.TH1D(\"train_\"+n,\"train_\"+n,10,0,10)\n\n # fill histogram for each target\n for (n,v) in enumerate(self.targets.iteritems()):\n [h_tests[n].Fill(i) for i in X[test][np.where(Y_test==v)]]\n [h_trains[n].Fill(i) for i in X[train][np.where(Y_train==v)]]\n\n\n ## Fit the model to training data & save the history\n self.model.train()\n e_losses = []\n for t in range(self.epochs):\n e_losses += self.train_epoch(X[train],Y_train)\n self.msg_svc.INFO(\"DLPYTORCH : Epoch {0} -- Loss {1}\".format(t,e_losses[-1]))\n self.histories.append(e_losses)\n\n # evaluate the model\n self.msg_svc.DEBUG(\"DLPYTORCH : Evaluate the model: \")\n self.model.eval()\n\n # Evaluate training sample\n self.msg_svc.INFO(\"DLPYTORCH : Predictions from training sample\")\n train_predictions = self.predict(X[train])\n self.train_predictions.append(train_predictions)\n\n # Evaluate test sample\n self.msg_svc.INFO(\"DLPYTORCH : Predictions from testing sample\")\n test_predictions = self.predict(X[test])\n self.test_predictions.append(test_predictions)\n\n # Make ROC curve from test sample\n self.msg_svc.INFO(\"DLPYTORCH : Make ROC curves\")\n fpr,tpr,_ = roc_curve(Y[test], test_predictions)\n self.fpr.append(fpr)\n self.tpr.append(tpr)\n\n # Plot the predictions to compare test/train\n self.msg_svc.INFO(\"DLPYTORCH : Plot the train/test predictions\")\n self.plotter.prediction(h_trains,h_tests) # compare DNN prediction for different targets\n\n self.msg_svc.INFO(\"DLPYTORCH : Finished K-Fold cross-validation: \")\n self.accuracy = {'mean':np.mean(cvpredictions),'std':np.std(cvpredictions)}\n self.msg_svc.INFO(\"DLPYTORCH : - Accuracy: {0:.2f}% (+/- {1:.2f}%)\".format(np.mean(cvpredictions), np.std(cvpredictions)))\n\n return\n\n\n def predict(self,data=None):\n \"\"\"Return the prediction from a test sample\"\"\"\n self.msg_svc.DEBUG(\"DLPYTORCH : Get the DNN prediction\")\n if data is None:\n self.msg_svc.ERROR(\"DLPYTORCH : predict() given NoneType data. Returning -999.\")\n return -999.\n data = torch.from_numpy(data)\n\n return self.model( Variable(data,volatile=True).cuda() )\n\n def load_model(self,from_lwtnn=False):\n \"\"\"Load existing model to make plots or predictions\"\"\"\n output = self.output_dir+'/'+self.model_name\n self.model.load_state_dict(torch.load(output))\n self.model.eval()\n return\n\n def save_model(self,to_lwtnn=False):\n \"\"\"Save the model for use later\"\"\"\n output = self.output_dir+'/'+self.model_name\n torch.save(self.model.state_dict(),output)\n return\n\n\n## THE END ##\n"
] | [
[
"torch.nn.Linear",
"torch.load",
"sklearn.model_selection.StratifiedKFold",
"torch.nn.functional.sigmoid",
"sklearn.metrics.roc_curve",
"torch.autograd.Variable",
"numpy.std",
"torch.nn.functional.relu",
"torch.from_numpy",
"torch.nn.ModuleList",
"torch.nn.BCELoss",
"numpy.where",
"numpy.mean"
]
] |
THU-DA-6D-Pose-Group/self6dpp | [
"c267cfa55e440e212136a5e9940598720fa21d16"
] | [
"core/csrc/torch_nndistance/test.py"
] | [
"import torch\nimport os.path as osp\nimport sys\nfrom torch.autograd import Variable\n\ncur_dir = osp.dirname(osp.abspath(__file__))\nsys.path.insert(0, cur_dir)\nimport torch_nndistance as NND\n\n\np1 = torch.rand(10, 1000, 3)\np2 = torch.rand(10, 1500, 3)\npoints1 = Variable(p1, requires_grad=True)\npoints2 = p2\npoints1 = points1.cuda()\nprint(points1.requires_grad)\npoints2 = points2.cuda()\ndist1, dist2 = NND.nnd(points1, points2)\nprint(dist1, dist2)\nloss = torch.sum(dist1)\nprint(\"loss\", loss)\nloss.backward()\nprint(points1.grad, points2.grad)\n\nprint(\"====================\")\npoints1 = Variable(p1.cuda(), requires_grad=True)\npoints2 = p2.cuda()\ndist1, dist2 = NND.nnd(points1, points2)\nprint(dist1, dist2)\nloss = torch.sum(dist1)\nprint(\"loss\", loss)\nloss.backward()\nprint(points1.grad, points2.grad)\n"
] | [
[
"torch.sum",
"torch.rand",
"torch.autograd.Variable"
]
] |
gorff/Toric-Code-Correlated-Error-Decoder | [
"c43cf34c22f03334add078f5d02e6604e5c89cba"
] | [
"project/correctiondemos/pythag_test.py"
] | [
"\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport numpy as np\nimport os,sys,inspect\nimport imageio\n\nsys.path.insert(1, os.path.join(sys.path[0], '..')) #go up a dir to import\nimport CodePy2.funmath as funmath\n#import imageio\nn = 1.0\nsizes = [i/n for i in range(33*int(n))]\n\nxvals = sizes\nfilenames = []\nfor expectedlength in sizes:\n yvals = []\n fig = plt.figure()\n for i in sizes:\n variance = 1\n strength = 1\n yvals.append(funmath.getnormval(i,expectedlength,strength,variance))\n maxval = mlab.normpdf(expectedlength, expectedlength, np.sqrt(variance))\n\n #yvals[-1] = yvals[-1]*strength/maxval\n\n plt.plot(xvals,yvals)\n plt.grid(True)\n plt.ylabel('Adjusted weight (A)')\n plt.xlabel('Manhatten distance (M)')\n plt.axis([0, 30, 0, 30])\n plt.title('Gaussian adjusted matching distances')\n plt.suptitle('variance = '+str(variance)+', w = '+str(expectedlength))\n filename = 'gaussian/'+'gaussian-'+str(int(expectedlength*n))+'.png'\n plt.savefig(filename)\n filenames.append(filename)\n plt.close()\n #plt.show()\n#os.system(\"avconv -y -f image2 -i figs/gaussian-%d.png -r 10 -s 800x600 gaussianvideo.avi\")\n\n#turn into gif\nimages = []\nfor filename in filenames:\n images.append(imageio.imread(filename))\nimageio.mimsave('xbar_demo.gif', images)\n"
] | [
[
"matplotlib.pyplot.figure",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.close",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel"
]
] |
SunYanCN/nlp-experiments-in-pytorch | [
"5d05a53146dffd707e4d037230656f980d7be05c"
] | [
"models/Transformer.py"
] | [
"import copy\nimport math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom utils.utils import clones\n\n\nclass LayerNormGoogle(nn.Module):\n def __init__(self, features, epsilon=1e-6):\n super(LayerNormGoogle, self).__init__()\n self.a_2 = nn.Parameter(torch.ones(features))\n self.b_2 = nn.Parameter(torch.zeros(features))\n self.epsilon = epsilon\n\n def forward(self, x):\n mean = x.mean(-1, keepdim=True)\n std = x.std(-1, keepdim=True)\n return self.a_2 * (x - mean) / (std + self.epsilon) + self.b_2\n\n\nclass EncoderBlockGoogle(nn.Module):\n def __init__(self, layer, num_layers):\n super(EncoderBlockGoogle, self).__init__()\n self.layers = clones(layer, num_layers)\n self.norm = LayerNormGoogle(layer.size)\n\n def forward(self, x, mask):\n for layer in self.layers:\n x = layer(x, mask)\n return self.norm(x)\n\n\nclass ResidualConnectionGoogle(nn.Module):\n def __init__(self, size, keep_prob):\n super(ResidualConnectionGoogle, self).__init__()\n self.norm = LayerNormGoogle(size)\n # TODO: Use dropout interface\n self.dropout = nn.Dropout(keep_prob)\n\n def forward(self, input, sublayer):\n return input + self.dropout(sublayer(self.norm(input)))\n\n\nclass EncoderLayerGoogle(nn.Module):\n def __init__(self, size, attention, feed_forward, keep_prob):\n super(EncoderLayerGoogle, self).__init__()\n self.size = size\n self.attention = attention\n self.feed_forward = feed_forward\n # Each encoder layer has two sublayers\n self.sublayer = clones(ResidualConnectionGoogle(size, keep_prob), 2)\n\n def forward(self, x, mask):\n x = self.sublayer[0](x, lambda x: self.attention(x, x, x, mask))\n return self.sublayer[1](x, self.feed_forward)\n\n\nclass EncoderClassifier(nn.Module):\n def __init__(self, embedding, encoder, classifier, device, is_average=True):\n super(EncoderClassifier, self).__init__()\n self.embedding = embedding\n self.encoder = encoder\n self.classifier = classifier\n self.device = device\n self.is_average = is_average\n\n def forward(self, x, mask=None):\n kl_loss = torch.Tensor([0.0])\n # Initial x.size() = [length, batch_size]\n x = x.permute(1, 0)\n # After permute x.size = [batch_size, length]\n x = self.embedding(x)\n if \"cuda\" in str(self.device):\n x = x.cuda()\n kl_loss = kl_loss.cuda()\n x = self.encoder(x, mask)\n if self.is_average:\n # Averaged sentence representation\n x = torch.mean(x, dim=1)\n x = self.classifier(x)\n return x, kl_loss\n\n\nclass Classifier(nn.Module):\n def __init__(self, d_model, d_hidden, num_classes, keep_prob):\n super(Classifier, self).__init__()\n self.linear1 = nn.Linear(d_model, d_hidden)\n self.dropout = nn.Dropout(keep_prob)\n self.relu = nn.ReLU()\n self.linear2 = nn.Linear(d_hidden, num_classes)\n\n def forward(self, x):\n x = self.dropout(self.relu(self.linear1(x)))\n x = self.linear2(x)\n return x\n\n\nclass MultiHeadedAttentionGoogle(nn.Module):\n def __init__(self, heads=8, d_model=512, keep_prob=0.1):\n super(MultiHeadedAttentionGoogle, self).__init__()\n assert d_model % heads == 0\n self.d_k = d_model // heads\n self.heads = heads\n self.linears = clones(nn.Linear(d_model, d_model), 4)\n self.attn = None\n self.dropout = nn.Dropout(keep_prob)\n\n def attention(self, query, key, value, mask=None):\n # Dot product attention\n d_k = query.size(-1)\n scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)\n\n if mask is not None:\n scores = scores.masked_fill(mask == 0, -1e9)\n\n p_attn = F.softmax(scores, dim=-1)\n\n if self.dropout is not None:\n p_attn = self.dropout(p_attn)\n\n return torch.matmul(p_attn, value), p_attn\n\n def forward(self, query, key, value, mask=None):\n num_batches = query.size(0)\n if mask is not None:\n mask = mask.unsqueeze(1)\n\n # Apply linear projection on the input sequence and split the heads.\n query, key, value = [linear(x).view(num_batches, -1, self.heads, self.d_k).transpose(1, 2)\n for linear, x in zip(self.linears, (query, key, value))]\n\n # Apply attention on the projected and splitted vectors\n x, self.attn = self.attention(query, key, value, mask=mask)\n\n # Concat vectors and apply linear\n x = x.transpose(1, 2).contiguous().view(num_batches, -1, self.heads * self.d_k)\n\n return self.linears[-1](x)\n\n\nclass PositionalFeedForwardGoogle(nn.Module):\n def __init__(self, d_model, d_ff, keep_prob=0.1):\n super(PositionalFeedForwardGoogle, self).__init__()\n self.w_1 = nn.Linear(d_model, d_ff)\n self.w_2 = nn.Linear(d_ff, d_model)\n self.dropout = nn.Dropout(keep_prob)\n self.relu = nn.ReLU()\n\n def forward(self, input):\n return self.w_2(self.dropout(self.relu(self.w_1(input))))\n\n\nclass Embeddings(nn.Module):\n def __init__(self, embed_dim, vocab_size, padding_id, use_pretrained_embed, pretrained_weights,\n optional_sqrt_mul=False):\n super(Embeddings, self).__init__()\n # Initialize embeddings\n self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_id).cpu()\n if use_pretrained_embed:\n self.embedding.from_pretrained(pretrained_weights)\n self.embed_dim = embed_dim\n self.optional_sqrt_mul = optional_sqrt_mul\n\n def forward(self, input):\n if self.optional_sqrt_mul:\n return self.embedding(input) * math.sqrt(self.embed_dim)\n else:\n return self.embedding(input)\n\n\nclass PositionalEncodingGoogle(nn.Module):\n def __init__(self, d_model, keep_prob=0.1, max_len=5000):\n super(PositionalEncodingGoogle, self).__init__()\n self.dropout = nn.Dropout(keep_prob)\n\n positional_encoding = torch.zeros(max_len, d_model)\n pos = torch.arange(0., max_len).unsqueeze(1)\n # Log space\n div_term = torch.exp(torch.arange(0., d_model, 2) * (-math.log(10000) / d_model))\n\n positional_encoding[:, 0::2] = torch.sin(pos * div_term)\n positional_encoding[:, 1::2] = torch.cos(pos * div_term)\n\n positional_encoding = positional_encoding.unsqueeze(0)\n self.register_buffer(\"pe\", positional_encoding)\n\n def forward(self, input):\n return self.dropout(input + Variable(self.pe[:, :input.size(1)], requires_grad=False))\n\n\nclass TransformerGoogle:\n def __init__(self, args):\n super(TransformerGoogle, self).__init__()\n\n self.args_common = args[\"common_model_properties\"]\n self.args_specific = args[\"transformer_google\"]\n\n # Device\n self.device = self.args_common[\"device\"]\n\n # Input/Output dimensions\n self.vocab_size = self.args_common[\"vocab_size\"]\n self.embed_dim = self.args_common[\"embed_dim\"]\n self.num_class = self.args_common[\"num_class\"]\n\n # Embedding parameters\n self.padding_id = self.args_common[\"padding_id\"]\n\n # Condition parameters\n self.use_pretrained_embed = self.args_common[\"use_pretrained_embed\"]\n self.use_embed_sqrt_mul = self.args_specific[\"use_embed_sqrt_mul\"]\n\n # Pretrained embedding weights\n self.pretrained_weights = self.args_common[\"pretrained_weights\"]\n\n # Dropout probabilities for each individual part of the full model.\n self.keep_prob_encoder = self.args_specific[\"keep_prob_encoder\"]\n self.keep_prob_pe = self.args_specific[\"keep_prob_pe\"]\n self.kee_prob_pff = self.args_specific[\"keep_prob_pff\"]\n self.keep_prob_attn = self.args_specific[\"keep_prob_attn\"]\n self.keep_prob_clf = self.args_specific[\"keep_prob_clf\"]\n\n # Condition parameter for the transformer type (It only supports classification for now)\n self.transformer_type = self.args_specific[\"transformer_type\"]\n\n # Number of parallel attention layers for MultiHeadedAttention\n self.heads = self.args_specific[\"heads\"]\n\n # Number of encoder layers\n self.num_encoder_layers = self.args_specific[\"num_encoder_layers\"]\n\n # Number of hidden count units for Position-Wise Feed-Forward Network\n self.num_hidden_pos_ff = self.args_specific[\"num_hidden_pos_ff\"]\n\n # Maximum length of an input\n self.max_length = self.args_specific[\"max_length\"]\n\n if self.transformer_type == \"classifier\":\n self.model = self.create_classifier_transformer()\n else:\n raise ValueError(\"Transformer can be created as classifier for now!\")\n\n def create_classifier_transformer(self):\n c = copy.deepcopy\n\n # Initialize individual parts of the full model\n # attention = torch.nn.MultiheadAttention(num_heads=self.heads, embed_dim=self.embed_dim,\n # dropout=self.keep_prob_attn)\n attention = MultiHeadedAttentionGoogle(heads=self.heads, d_model=self.embed_dim, keep_prob=self.keep_prob_attn)\n\n ff = PositionalFeedForwardGoogle(d_model=self.embed_dim, d_ff=self.num_hidden_pos_ff,\n keep_prob=self.kee_prob_pff)\n\n embeddings = Embeddings(self.embed_dim, self.vocab_size, self.padding_id, self.use_pretrained_embed,\n self.pretrained_weights, optional_sqrt_mul=self.use_embed_sqrt_mul)\n\n positional_embeddings = PositionalEncodingGoogle(d_model=self.embed_dim, keep_prob=self.keep_prob_pe,\n max_len=self.max_length)\n\n # Initialize the full model\n model = EncoderClassifier(nn.Sequential(embeddings, c(positional_embeddings)),\n EncoderBlockGoogle(\n EncoderLayerGoogle(self.embed_dim, c(attention), c(ff), self.keep_prob_encoder),\n self.num_encoder_layers),\n Classifier(self.embed_dim, d_hidden=self.embed_dim // 2, num_classes=self.num_class,\n keep_prob=self.keep_prob_clf),\n device=self.device)\n\n # Initialize model parameters\n for p in model.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n return model\n\n\nif __name__ == '__main__':\n print(\"Transformer tests\")\n plt.figure(figsize=(15, 5))\n pe = PositionalEncodingGoogle(20, 0)\n y = pe.forward(Variable(torch.zeros(1, 100, 20)))\n plt.plot(np.arange(100), y[0, :, 4:8].data.numpy())\n plt.legend([\"dim %d\" % p for p in [4, 5, 6, 7]])\n plt.show()\n"
] | [
[
"torch.ones",
"matplotlib.pyplot.legend",
"torch.nn.Linear",
"torch.nn.init.xavier_uniform_",
"torch.cos",
"torch.mean",
"matplotlib.pyplot.figure",
"torch.nn.functional.softmax",
"torch.nn.Embedding",
"numpy.arange",
"torch.sin",
"matplotlib.pyplot.show",
"torch.matmul",
"torch.arange",
"torch.zeros",
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.Tensor"
]
] |
donyori/2018ccf_bdci_inter_fund_correlation_prediction | [
"6e06a3e192e05ae1e9822111cf323eda3a61bf4e"
] | [
"program/model/version/ver1_2.py"
] | [
"from tensorflow import keras\n\nfrom constants import TRADING_DAYS_PER_WEEK, INDEX_RETURN_INDICATOR_NUMBER\nfrom ..constants import *\n\nMODEL_NAME = 'ifcp_model_ver1_2'\nROLLING_WINDOW_SIZE = TRADING_DAYS_PER_WEEK\n\n\ndef build_model():\n fund1_return = keras.Input(shape=(ROLLING_WINDOW_SIZE, 1), name=FUND1_RETURN_NAME)\n fund1_benchmark_return = keras.Input(shape=(ROLLING_WINDOW_SIZE, 1), name=FUND1_BENCHMARK_RETURN_NAME)\n fund2_return = keras.Input(shape=(ROLLING_WINDOW_SIZE, 1), name=FUND2_RETURN_NAME)\n fund2_benchmark_return = keras.Input(shape=(ROLLING_WINDOW_SIZE, 1), name=FUND2_BENCHMARK_RETURN_NAME)\n\n fund1_performance = keras.layers.subtract([fund1_return, fund1_benchmark_return], name='fund1_performance')\n fund2_performance = keras.layers.subtract([fund2_return, fund2_benchmark_return], name='fund2_performance')\n\n fund1_attributes = keras.layers.concatenate(\n [fund1_return, fund1_benchmark_return, fund1_performance], name='fund1_attributes')\n fund2_attributes = keras.layers.concatenate(\n [fund2_return, fund2_benchmark_return, fund2_performance], name='fund2_attributes')\n\n fund_attributes_gru = keras.layers.GRU(\n 12,\n kernel_regularizer=keras.regularizers.l2(0.01),\n recurrent_regularizer=keras.regularizers.l2(0.01),\n activity_regularizer=keras.regularizers.l1(0.01),\n name='fund_attributes_gru',\n )\n\n fund1_attributes_after_gru = fund_attributes_gru(fund1_attributes)\n fund2_attributes_after_gru = fund_attributes_gru(fund2_attributes)\n\n fund_attributes_after_gru = keras.layers.concatenate(\n [fund1_attributes_after_gru, fund2_attributes_after_gru], name='fund_attributes_after_gru')\n\n auxiliary_output = keras.layers.Dense(1, activation='sigmoid', name=AUXILIARY_OUTPUT_NAME)(\n fund_attributes_after_gru)\n\n index_return = keras.Input(shape=(ROLLING_WINDOW_SIZE, INDEX_RETURN_INDICATOR_NUMBER), name=INDEX_RETURN_NAME)\n index_return_gru = keras.layers.GRU(\n 35,\n kernel_regularizer=keras.regularizers.l2(0.01),\n recurrent_regularizer=keras.regularizers.l2(0.01),\n activity_regularizer=keras.regularizers.l1(0.01),\n name='index_return_gru',\n )\n index_return_after_gru = index_return_gru(index_return)\n merge = keras.layers.concatenate([fund_attributes_after_gru, index_return_after_gru], name='merge')\n x = keras.layers.Dense(64, activation='relu',\n kernel_regularizer=keras.regularizers.l2(0.01),\n activity_regularizer=keras.regularizers.l1(0.01))(merge)\n x = keras.layers.Dense(64, activation='relu',\n kernel_regularizer=keras.regularizers.l2(0.01),\n activity_regularizer=keras.regularizers.l1(0.01))(x)\n x = keras.layers.Dense(16, activation='relu',\n kernel_regularizer=keras.regularizers.l2(0.01),\n activity_regularizer=keras.regularizers.l1(0.01))(x)\n main_output = keras.layers.Dense(1, activation='sigmoid', name=MAIN_OUTPUT_NAME)(x)\n\n model = keras.Model(inputs=[\n fund1_return, fund1_benchmark_return, fund2_return, fund2_benchmark_return, index_return],\n outputs=[main_output, auxiliary_output])\n return model\n"
] | [
[
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.layers.subtract",
"tensorflow.keras.Model",
"tensorflow.keras.regularizers.l1",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Input"
]
] |
simonfong6/micro-projects | [
"5be195ea72ce117df6da041446f11c18e102b5df"
] | [
"ml_tutorial/test.py"
] | [
"import svm as SVM\nimport numpy as np\n\ndata_dict = {\t-1:np.array(\t[[10,9,1],\n\t\t\t\t[2,8,1],\n\t\t\t\t[3,8,1],]),\n \n\t\t1:np.array(\t[[5,1,1],\n \t [6,-1,1],\n \t [7,3,1],])}\n\nsvm = SVM.Support_Vector_Machine()\nsvm.fit(data=data_dict)\n\npredict_us = [[0,10,1],\n\t [1,3,1],\n\t [3,4,1],\n\t [3,5,1],\n\t [5,5,1],\n\t [5,6,1],\n\t [6,-5,1],\n\t [5,8,1]]\n\nfor p in predict_us:\n\tsvm.predict(p)\nsvm.visualize()\n\n"
] | [
[
"numpy.array"
]
] |
OnionIoT/tau-lidar-camera | [
"a70b24e18be8e4c5abfe525c6768fbc10a492fd8"
] | [
"examples/distancePlusAmplitude.py"
] | [
"import argparse\nimport numpy as np\nimport cv2\n\nfrom TauLidarCommon.frame import FrameType\nfrom TauLidarCamera.camera import Camera\n\ndef setup(serialPort=None):\n port = None\n camera = None\n\n # if no serial port is specified, scan for available Tau Camera devices\n if serialPort is None:\n ports = Camera.scan() ## Scan for available Tau Camera devices\n\n if len(ports) > 0:\n port = ports[0]\n else:\n port = serialPort\n\n if port is not None:\n Camera.setRange(0, 4500) ## points in the distance range to be colored\n\n camera = Camera.open(port) ## Open the first available Tau Camera\n camera.setModulationChannel(0) ## autoChannelEnabled: 0, channel: 0\n camera.setIntegrationTime3d(0, 1000) ## set integration time 0: 1000\n camera.setMinimalAmplitude(0, 10) ## set minimal amplitude 0: 80\n\n cameraInfo = camera.info()\n\n print(\"\\nToF camera opened successfully:\")\n print(\" model: %s\" % cameraInfo.model)\n print(\" firmware: %s\" % cameraInfo.firmware)\n print(\" uid: %s\" % cameraInfo.uid)\n print(\" resolution: %s\" % cameraInfo.resolution)\n print(\" port: %s\" % cameraInfo.port)\n\n print(\"\\nPress Esc key over GUI or Ctrl-c in terminal to shutdown ...\")\n\n\n cv2.namedWindow('Depth Map')\n cv2.namedWindow('Amplitude')\n\n cv2.moveWindow('Depth Map', 20, 20)\n cv2.moveWindow('Amplitude', 20, 360)\n\n return camera\n\n\ndef run(camera):\n while True:\n frame = camera.readFrame(FrameType.DISTANCE_AMPLITUDE)\n\n if frame:\n mat_depth_rgb = np.frombuffer(frame.data_depth_rgb, dtype=np.uint16, count=-1, offset=0).reshape(frame.height, frame.width, 3)\n mat_depth_rgb = mat_depth_rgb.astype(np.uint8)\n\n mat_amplitude = np.frombuffer(frame.data_amplitude, dtype=np.float32, count=-1, offset=0).reshape(frame.height, frame.width)\n mat_amplitude = mat_amplitude.astype(np.uint8)\n\n # Upscalling the image\n upscale = 4\n depth_img = cv2.resize(mat_depth_rgb, (frame.width*upscale, frame.height*upscale))\n amplitude_img = cv2.resize(mat_amplitude, (frame.width*upscale, frame.height*upscale))\n\n cv2.imshow('Depth Map', depth_img)\n cv2.imshow('Amplitude', amplitude_img)\n\n if cv2.waitKey(1) == 27: break\n\n\ndef cleanup(camera):\n print('\\nShutting down ...')\n cv2.destroyAllWindows()\n camera.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Sample program to demonstrate acquiring frames with both distance / depth and amplitude data from the Tau LiDAR Camera')\n parser.add_argument('--port', metavar='<serial port>', default=None,\n help='Specify a serial port for the Tau Camera')\n args = parser.parse_args()\n\n\n camera = setup(args.port)\n\n if camera:\n try:\n run(camera)\n except Exception as e:\n print(e)\n\n cleanup(camera)\n"
] | [
[
"numpy.frombuffer"
]
] |
R-aryan/Jigsaw-Toxic-Comment-Classification | [
"e5e4da7df379ac1b315f2bde655386180f39c517"
] | [
"backend/services/toxic_comment_jigsaw/application/ai/training/src/train.py"
] | [
"import pandas as pd\nimport numpy as np\nimport torch\n\nfrom sklearn.model_selection import train_test_split\nfrom backend.services.toxic_comment_jigsaw.application.ai.model import BERTClassifier\nfrom backend.services.toxic_comment_jigsaw.application.ai.training.src.dataset import BERTDataset\nfrom backend.services.toxic_comment_jigsaw.application.ai.training.src.preprocess import Preprocess\nfrom backend.services.toxic_comment_jigsaw.application.ai.training.src.engine import Engine\nfrom backend.services.toxic_comment_jigsaw.application.ai.settings import Settings\n\nfrom transformers import AdamW, get_linear_schedule_with_warmup\nfrom torch.utils.data import DataLoader\n\n\nclass Train:\n def __init__(self):\n # initialize required class\n self.settings = Settings\n self.engine = Engine()\n self.preprocess = Preprocess()\n\n # initialize required variables\n self.bert_classifier = None\n self.optimizer = None\n self.scheduler = None\n self.train_data_loader = None\n self.val_data_loader = None\n self.total_steps = None\n self.best_accuracy = 0\n\n def __initialize(self):\n # Instantiate Bert Classifier\n self.bert_classifier = BERTClassifier(freeze_bert=False)\n self.bert_classifier.to(self.settings.DEVICE)\n\n # Create the optimizer\n self.optimizer = AdamW(self.bert_classifier.parameters(),\n lr=5e-5, # Default learning rate\n eps=1e-8 # Default epsilon value\n )\n # Set up the learning rate scheduler\n self.scheduler = get_linear_schedule_with_warmup(self.optimizer,\n num_warmup_steps=0, # Default value\n num_training_steps=self.total_steps)\n\n def crete_data_loaders(self, dataset):\n pass\n\n def load_data(self):\n train_df = pd.read_csv(self.settings.TRAIN_DATA).fillna(\"none\")\n train_df['comment_text'] = train_df['comment_text'].apply(lambda x: self.preprocess.clean_text(x))\n X = list(train_df['comment_text'])\n y = np.array(train_df.loc[:, 'toxic':])\n\n X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.20, random_state=self.settings.RANDOM_STATE)\n\n # training dataset\n train_dataset = BERTDataset(X_train, y_train)\n\n # validation dataset\n val_dataset = BERTDataset(X_val, y_val)\n\n self.train_data_loader = DataLoader(train_dataset,\n batch_size=self.settings.TRAIN_BATCH_SIZE,\n shuffle=True,\n num_workers=self.settings.TRAIN_NUM_WORKERS)\n\n self.val_data_loader = DataLoader(val_dataset,\n batch_size=self.settings.VALID_BATCH_SIZE,\n shuffle=True,\n num_workers=self.settings.VAL_NUM_WORKERS)\n\n self.total_steps = int(len(X_train) / self.settings.TRAIN_BATCH_SIZE * self.settings.EPOCHS)\n\n def train(self):\n for epochs in range(self.settings.EPOCHS):\n\n # calling the training function in engine.py file\n self.engine.train_fn(data_loader=self.train_data_loader,\n model=self.bert_classifier,\n optimizer=self.optimizer,\n device=self.settings.DEVICE,\n schedular=self.scheduler)\n\n # calling the evaluation function from the engine.py file to compute evaluation\n val_loss, val_accuracy = self.engine.eval_fn(data_loader=self.val_data_loader,\n model=self.bert_classifier,\n device=self.settings.DEVICE)\n\n # updating the accuracy\n if val_accuracy > self.best_accuracy:\n torch.save(self.bert_classifier.state_dict(), self.settings.MODEL_PATH)\n self.best_accuracy = val_accuracy\n\n def run(self):\n try:\n print(\"Loading and Preparing the Dataset-----!! \")\n self.load_data()\n print(\"Dataset Successfully Loaded and Prepared-----!! \")\n print()\n print(\"-\" * 70)\n print(\"Loading and Initializing the Bert Model -----!! \")\n self.__initialize()\n print(\"Model Successfully Loaded and Initialized-----!! \")\n print()\n print(\"-\" * 70)\n print(\"------------------Starting Training-----------!!\")\n self.engine.set_seed()\n self.train()\n print(\"Training complete-----!!!\")\n\n except BaseException as ex:\n print(\"Following Exception Occurred---!! \", str(ex))\n\n"
] | [
[
"numpy.array",
"torch.utils.data.DataLoader",
"sklearn.model_selection.train_test_split",
"pandas.read_csv"
]
] |
chensnathan/CARAFE_CUDA | [
"33d3d3af69b24fc679f6a3a071a19070dc46664b"
] | [
"carafe_layer/setup.py"
] | [
"from setuptools import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\nsetup(\n name='carafe_layer_cuda',\n ext_modules=[\n CUDAExtension('carafe_layer_cuda', [\n 'src/carafe_layer_cuda.cpp',\n 'src/carafe_layer_kernel.cu',\n ])\n ],\n cmdclass={\n 'build_ext': BuildExtension\n })\n"
] | [
[
"torch.utils.cpp_extension.CUDAExtension"
]
] |
AU-DATALAB/newsFluxus | [
"20522b2c8c830d2377a9620d149a515baaaa9cf4"
] | [
"src/saffine/detrending_coeff.py"
] | [
"from numpy import *\r\nimport numpy as np\r\n# from numba import jit\r\n\r\n# @jit\r\n\r\ndef detrending_coeff(win_len , order):\r\n\r\n#win_len = 51\r\n#order = 2\r\n\tn = (win_len-1)/2\r\n\tA = mat(ones((win_len,order+1)))\r\n\tx = np.arange(-n , n+1)\r\n\tfor j in range(0 , order + 1):\r\n\t\tA[:,j] = mat(x ** j).T\r\n\r\n\tcoeff_output = (A.T * A).I * A.T\r\n\treturn coeff_output , A\r\n\r\n# coeff_output,A = detrending_coeff(5,2)\r\n# print(coeff_output)\r\n# print(A)\r\n"
] | [
[
"numpy.arange"
]
] |
RedTachyon/OpenTraj | [
"8277f526d714a4e77d0f9f354259ff5b74e59fd2"
] | [
"opentraj/toolkit/loaders/loader_pets.py"
] | [
"# Author: Javad Amirian\n# Email: amiryan.j@gmail.com\n\nimport xml.etree.ElementTree as et\n\nimport numpy as np\nimport pandas as pd\n\nfrom opentraj.toolkit.core.trajdataset import TrajDataset\nfrom opentraj.toolkit.utils.calibration.camera_calibration_tsai import *\n\n\ndef load_pets(path, **kwargs):\n \"\"\"\n :param path: address of annotation file\n :param kwargs:\n :param calib_path: address of calibration file\n :return: TrajectoryDataset object\n \"\"\"\n traj_dataset = TrajDataset()\n\n annot_xtree = et.parse(path)\n annot_xroot = annot_xtree.getroot() # dataset\n\n cp, cc = None, None # calibration parameters\n\n # load calibration\n calib_path = kwargs.get('calib_path', \"\")\n if calib_path:\n cp = CameraParameters()\n cc = CalibrationConstants()\n\n calib_xtree = et.parse(calib_path)\n calib_xroot = calib_xtree.getroot() # Camera\n\n geometry_node = calib_xroot.find(\"Geometry\")\n width = int(geometry_node.attrib[\"width\"])\n height = int(geometry_node.attrib[\"height\"])\n\n cp.Ncx = float(geometry_node.attrib[\"ncx\"])\n cp.Nfx = float(geometry_node.attrib[\"nfx\"])\n cp.dx = float(geometry_node.attrib[\"dx\"])\n cp.dy = float(geometry_node.attrib[\"dy\"])\n cp.dpx = float(geometry_node.attrib[\"dpx\"])\n cp.dpy = float(geometry_node.attrib[\"dpy\"])\n\n intrinsic_node = calib_xroot.find(\"Intrinsic\")\n cc.f = float(intrinsic_node.attrib[\"focal\"])\n cc.kappa1 = float(intrinsic_node.attrib[\"kappa1\"]) # 1st order radial distortion\n\n cp.Cx = float(intrinsic_node.attrib[\"cx\"])\n cp.Cy = float(intrinsic_node.attrib[\"cy\"])\n cp.sx = float(intrinsic_node.attrib[\"sx\"])\n\n extrinsic_node = calib_xroot.find(\"Extrinsic\")\n cc.Tx = float(extrinsic_node.attrib[\"tx\"])\n cc.Ty = float(extrinsic_node.attrib[\"ty\"])\n cc.Tz = float(extrinsic_node.attrib[\"tz\"])\n cc.Rx = float(extrinsic_node.attrib[\"rx\"])\n cc.Ry = float(extrinsic_node.attrib[\"ry\"])\n cc.Rz = float(extrinsic_node.attrib[\"rz\"])\n\n cc.calc_rr() # Calculate Rotation Matrix\n\n loaded_data = [] # frame_id, agent_id, pos_x, pos_y, xc, yc, h, w\n for frame_node in annot_xroot:\n objectlist_node = frame_node.find(\"objectlist\") # .text\n object_nodes = objectlist_node.findall(\"object\")\n frame_id = int(frame_node.attrib.get(\"number\"))\n\n for obj_node in object_nodes:\n agent_id = obj_node.attrib[\"id\"]\n\n box_node = obj_node.find(\"box\")\n xc = float(box_node.attrib[\"xc\"])\n yc = float(box_node.attrib[\"yc\"])\n h = float(box_node.attrib[\"h\"])\n w = float(box_node.attrib[\"w\"])\n\n x_ground = xc\n y_ground = yc + h/2\n\n if cp:\n pos_x, pos_y = image_coord_to_world_coord(x_ground, y_ground, 0, cp, cc)\n else:\n pos_x, pos_y = np.nan, np.nan\n\n loaded_data.append([frame_id, agent_id, pos_x / 1000., pos_y / 1000., xc, yc, h, w])\n\n data_columns = [\"frame_id\", \"agent_id\", \"pos_x\", \"pos_y\",\n \"xc\", \"yc\", \"h\", \"w\"]\n raw_dataset = pd.DataFrame(np.array(loaded_data), columns=data_columns)\n\n traj_dataset.title = kwargs.get('title', \"PETS\")\n\n # copy columns\n traj_dataset.data[[\"frame_id\", \"agent_id\",\n \"pos_x\", \"pos_y\"]] = \\\n raw_dataset[[\"frame_id\", \"agent_id\",\n \"pos_x\", \"pos_y\"]]\n traj_dataset.data[\"scene_id\"] = kwargs.get('scene_id', 0)\n traj_dataset.data[\"label\"] = \"pedestrian\"\n\n # post-process\n fps = kwargs.get('fps', 7)\n sampling_rate = kwargs.get('sampling_rate', 1)\n use_kalman = kwargs.get('use_kalman', False)\n traj_dataset.postprocess(fps=fps, sampling_rate=sampling_rate, use_kalman=use_kalman)\n\n return traj_dataset\n"
] | [
[
"numpy.array"
]
] |
t-brink/pyiron | [
"c07552b54a39e3f036ba395325cd4b372af0f794"
] | [
"pyiron/vasp/potential.py"
] | [
"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport os\nimport posixpath\n\nimport numpy as np\nimport pandas\nimport tables\nimport warnings\nfrom pyiron_base import GenericParameters, Settings\nfrom pyiron.atomistics.job.potentials import PotentialAbstract, find_potential_file_base\n\n__author__ = \"Jan Janssen\"\n__copyright__ = (\n \"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - \"\n \"Computational Materials Design (CM) Department\"\n)\n__version__ = \"1.0\"\n__maintainer__ = \"Jan Janssen\"\n__email__ = \"janssen@mpie.de\"\n__status__ = \"development\"\n__date__ = \"Sep 1, 2017\"\n\ns = Settings()\n\n\nclass VaspPotentialAbstract(PotentialAbstract):\n \"\"\"\n\n Args:\n potential_df:\n default_df:\n selected_atoms:\n \"\"\"\n\n def __init__(self, potential_df=None, default_df=None, selected_atoms=None):\n if potential_df is None:\n potential_df = self._get_potential_df(\n plugin_name=\"vasp\",\n file_name_lst={\"potentials_vasp.csv\"},\n backward_compatibility_name=\"vasppotentials\",\n )\n super(VaspPotentialAbstract, self).__init__(\n potential_df=potential_df,\n default_df=default_df,\n selected_atoms=selected_atoms,\n )\n\n def default(self):\n if self._default_df is not None:\n return pandas.concat(\n [\n self._potential_df[\n (\n self._potential_df[\"Name\"]\n == self._default_df.loc[atom].values[0]\n )\n ]\n for atom in self._selected_atoms\n ]\n )\n return None\n\n def find_default(self, element):\n if isinstance(element, set):\n element = element\n elif isinstance(element, list):\n element = set(element)\n elif isinstance(element, str):\n element = set([element])\n else:\n raise TypeError(\"Only, str, list and set supported!\")\n element_lst = list(element)\n if self._default_df is not None:\n merged_lst = list(set(self._selected_atoms + element_lst))\n return pandas.concat(\n [\n self._potential_df[\n (\n self._potential_df[\"Name\"]\n == self._default_df.loc[atom].values[0]\n )\n ]\n for atom in merged_lst\n ]\n )\n return None\n\n def find(self, element):\n if isinstance(element, set):\n element = element\n elif isinstance(element, list):\n element = set(element)\n elif isinstance(element, str):\n element = set([element])\n else:\n raise TypeError(\"Only, str, list and set supported!\")\n element_lst = list(element)\n merged_lst = list(set(self._selected_atoms + element_lst))\n return pandas.concat(\n [super(VaspPotentialAbstract, self).find({atom}) for atom in merged_lst]\n )\n\n def list(self):\n if len(self._selected_atoms) != 0:\n return pandas.concat(\n [\n super(VaspPotentialAbstract, self).find({atom})\n for atom in self._selected_atoms\n ]\n )\n else:\n return pandas.DataFrame({})\n\n def list_potential_names(self):\n df = self.list()\n if len(df) != 0:\n return list(self.list()[\"Name\"])\n else:\n return []\n\n @staticmethod\n def _return_potential_file(file_name):\n for resource_path in s.resource_paths:\n resource_path_potcar = os.path.join(\n resource_path, \"vasp\", \"potentials\", file_name\n )\n if os.path.exists(resource_path_potcar):\n return resource_path_potcar\n return None\n\n def __dir__(self):\n return [val.replace(\"-\", \"_\") for val in self.list_potential_names()]\n\n def __getitem__(self, item):\n item_replace = item.replace(\"_gga_pbe\", \"-gga-pbe\").replace(\"_lda\", \"-lda\")\n if item_replace in self.list_potential_names():\n df = self.list()\n return self._return_potential_file(\n file_name=list(df[df[\"Name\"] == item_replace][\"Filename\"])[0][0]\n )\n selected_atoms = self._selected_atoms + [item]\n return VaspPotentialAbstract(\n potential_df=self._potential_df,\n default_df=self._default_df,\n selected_atoms=selected_atoms,\n )\n\n\nclass VaspPotentialFile(VaspPotentialAbstract):\n \"\"\"\n The Potential class is derived from the PotentialAbstract class, but instead of loading the potentials from a list,\n the potentials are loaded from a file.\n\n Args:\n xc (str): Exchange correlation functional ['PBE', 'LDA']\n \"\"\"\n\n def __init__(self, xc=None, selected_atoms=None):\n potential_df = self._get_potential_df(\n plugin_name=\"vasp\",\n file_name_lst={\"potentials_vasp.csv\"},\n backward_compatibility_name=\"vasppotentials\",\n )\n if xc == \"PBE\":\n default_df = self._get_potential_default_df(\n plugin_name=\"vasp\",\n file_name_lst={\"potentials_vasp_pbe_default.csv\"},\n backward_compatibility_name=\"defaultvasppbe\",\n )\n potential_df = potential_df[(potential_df[\"Model\"] == \"gga-pbe\")]\n elif xc == \"GGA\":\n default_df = self._get_potential_default_df(\n plugin_name=\"vasp\",\n file_name_lst={\"potentials_vasp_pbe_default.csv\"},\n backward_compatibility_name=\"defaultvasppbe\",\n )\n potential_df = potential_df[(potential_df[\"Model\"] == \"gga-pbe\")]\n elif xc == \"LDA\":\n default_df = self._get_potential_default_df(\n plugin_name=\"vasp\",\n file_name_lst={\"potentials_vasp_lda_default.csv\"},\n backward_compatibility_name=\"defaultvasplda\",\n )\n potential_df = potential_df[(potential_df[\"Model\"] == \"lda\")]\n else:\n raise ValueError(\n 'The exchange correlation functional has to be set and it can either be \"LDA\" or \"PBE\"'\n )\n super(VaspPotentialFile, self).__init__(\n potential_df=potential_df,\n default_df=default_df,\n selected_atoms=selected_atoms,\n )\n\n def add_new_element(self, parent_element, new_element):\n \"\"\"\n Adding a new user defined element with a different POTCAR file. It is assumed that the file exists\n\n Args:\n parent_element (str): Parent element\n new_element (str): Name of the new element (the name of the folder where the new POTCAR file exists\n\n \"\"\"\n ds = self.find_default(element=parent_element)\n ds[\"Species\"].values[0][0] = new_element\n path_list = ds[\"Filename\"].values[0][0].split(\"/\")\n path_list[-2] = new_element\n name_list = ds[\"Name\"].values[0].split(\"-\")\n name_list[0] = new_element\n ds[\"Name\"].values[0] = \"-\".join(name_list)\n ds[\"Filename\"].values[0][0] = \"/\".join(path_list)\n self._potential_df = self._potential_df.append(ds)\n if new_element not in self._default_df.index.values:\n ds = pandas.Series()\n ds.name = new_element\n ds[\"Name\"] = \"-\".join(name_list)\n self._default_df = self._default_df.append(ds)\n else:\n self._default_df.loc[new_element] = \"-\".join(name_list)\n\n\nclass VaspPotential(object):\n \"\"\"\n The Potential class is derived from the PotentialAbstract class, but instead of loading the potentials from a list,\n the potentials are loaded from a file.\n\n Args:\n path (str): path to the potential list\n \"\"\"\n\n def __init__(self, selected_atoms=None):\n self.pbe = VaspPotentialFile(xc=\"PBE\", selected_atoms=selected_atoms)\n self.lda = VaspPotentialFile(xc=\"LDA\", selected_atoms=selected_atoms)\n\n\nclass VaspPotentialSetter(object):\n def __init__(self, element_lst):\n super(VaspPotentialSetter, self).__setattr__(\"_element_lst\", element_lst)\n super(VaspPotentialSetter, self).__setattr__(\n \"_potential_dict\", {el: None for el in element_lst}\n )\n\n def __getattr__(self, item):\n if item in self._element_lst:\n return item\n else:\n raise AttributeError\n\n def __setitem__(self, key, value):\n self.__setattr__(key=key, value=value)\n\n def __setattr__(self, key, value):\n if key in self._element_lst:\n self._potential_dict[key] = value\n else:\n raise AttributeError\n\n def to_dict(self):\n return self._potential_dict\n\n def __repr__(self):\n return self._potential_dict.__repr__()\n\n\ndef find_potential_file(path):\n return find_potential_file_base(\n path=path,\n resource_path_lst=s.resource_paths,\n rel_path=os.path.join(\"vasp\", \"potentials\")\n )\n\n\ndef get_enmax_among_species(symbol_lst, return_list=False, xc=\"PBE\"):\n \"\"\"\n DEPRECATED: Please use `get_enmax_among_potentials`.\n\n Given a list of species symbols, finds the largest applicable encut.\n\n Args:\n symbol_lst (list): The list of species symbols.\n return_list (bool): Whether to return the list of all ENMAX values (in the same order as `species_lst` along with\n the largest value). (Default is False.)\n xc (\"GGA\"/\"PBE\"/\"LDA\"): The exchange correlation functional for which the POTCARs were generated. (Default is \"PBE\".)\n\n Returns:\n (float): The largest ENMAX among the POTCAR files for all the species.\n [optional](list): The ENMAX value corresponding to each species.\n \"\"\"\n warnings.warn((\"get_enmax_among_species is deprecated as of v0.3.0. Please use get_enmax_among_potentials and note \"\n + \"the adjustment to the signature (*args instead of list)\"), DeprecationWarning)\n return get_enmax_among_potentials(*symbol_lst, return_list=return_list, xc=xc)\n\n\ndef get_enmax_among_potentials(*names, return_list=False, xc=\"PBE\"):\n \"\"\"\n Given potential names without XC information or elemental symbols, look over all the corresponding POTCAR files and\n find the largest ENMAX value.\n\n e.g. `get_enmax_among_potentials('Mg', 'Al_GW', 'Ca_pv', 'Ca_sv', xc='LDA')`\n\n Args:\n *names (str): Names of potentials or elemental symbols\n return_list (bool): Whether to return the list of all ENMAX values (in the same order as `names` as a second\n return value after providing the largest value). (Default is False.)\n xc (\"GGA\"/\"PBE\"/\"LDA\"): The exchange correlation functional for which the POTCARs were generated.\n (Default is \"PBE\".)\n\n Returns:\n (float): The largest ENMAX among the POTCAR files for all the requested names.\n [optional](list): The ENMAX value corresponding to each species.\n \"\"\"\n def _get_just_element_from_name(name):\n return name.split('_')[0]\n\n def _get_index_of_exact_match(name, potential_names):\n try:\n return np.argwhere([name == strip_xc_from_potential_name(pn) for pn in potential_names])[0, 0]\n except IndexError:\n raise ValueError(\"Couldn't find {} among potential names for {}\".format(name,\n _get_just_element_from_name(name)))\n\n def _get_potcar_filename(name, exch_corr):\n potcar_table = VaspPotentialFile(xc=exch_corr).find(_get_just_element_from_name(name))\n return potcar_table['Filename'].values[\n _get_index_of_exact_match(name, potcar_table['Name'].values)\n ][0]\n\n enmax_lst = []\n for n in names:\n with open(find_potential_file(path=_get_potcar_filename(n, xc))) as pf:\n for i, line in enumerate(pf):\n if i == 14:\n encut_str = line.split()[2][:-1]\n enmax_lst.append(float(encut_str))\n break\n\n if return_list:\n return max(enmax_lst), enmax_lst\n else:\n return max(enmax_lst)\n\n\ndef strip_xc_from_potential_name(name):\n return name.split('-')[0]\n\n\nclass Potcar(GenericParameters):\n pot_path_dict = {\"GGA\": \"paw-gga-pbe\", \"PBE\": \"paw-gga-pbe\", \"LDA\": \"paw-lda\"}\n\n def __init__(self, input_file_name=None, table_name=\"potcar\"):\n GenericParameters.__init__(\n self,\n input_file_name=input_file_name,\n table_name=table_name,\n val_only=False,\n comment_char=\"#\",\n )\n self._structure = None\n self.electrons_per_atom_lst = list()\n self.max_cutoff_lst = list()\n self.el_path_lst = list()\n self.el_path_dict = dict()\n self.modified_elements = dict()\n\n def potcar_set_structure(self, structure, modified_elements):\n self._structure = structure\n self._set_default_path_dict()\n self._set_potential_paths()\n self.modified_elements = modified_elements\n\n def modify(self, **modify):\n if \"xc\" in modify:\n xc_type = modify[\"xc\"]\n self._set_default_path_dict()\n if xc_type not in self.pot_path_dict:\n raise ValueError(\"xc type not implemented: \" + xc_type)\n GenericParameters.modify(self, **modify)\n if self._structure is not None:\n self._set_potential_paths()\n\n def _set_default_path_dict(self):\n if self._structure is None:\n return\n vasp_potentials = VaspPotentialFile(xc=self.get(\"xc\"))\n for i, el_obj in enumerate(self._structure.get_species_objects()):\n if isinstance(el_obj.Parent, str):\n el = el_obj.Parent\n else:\n el = el_obj.Abbreviation\n if isinstance(el_obj.tags, dict):\n if \"pseudo_potcar_file\" in el_obj.tags.keys():\n new_element = el_obj.tags[\"pseudo_potcar_file\"]\n vasp_potentials.add_new_element(\n parent_element=el, new_element=new_element\n )\n key = vasp_potentials.find_default(el).Species.values[0][0]\n val = vasp_potentials.find_default(el).Name.values[0]\n self[key] = val\n\n def _set_potential_paths(self):\n element_list = (\n self._structure.get_species_symbols()\n ) # .ElementList.getSpecies()\n object_list = self._structure.get_species_objects()\n s.logger.debug(\"element list: {0}\".format(element_list))\n self.el_path_lst = list()\n try:\n xc = self.get(\"xc\")\n except tables.exceptions.NoSuchNodeError:\n xc = self.get(\"xc\")\n s.logger.debug(\"XC: {0}\".format(xc))\n vasp_potentials = VaspPotentialFile(xc=xc)\n for i, el_obj in enumerate(object_list):\n if isinstance(el_obj.Parent, str):\n el = el_obj.Parent\n else:\n el = el_obj.Abbreviation\n if (\n isinstance(el_obj.tags, dict)\n and \"pseudo_potcar_file\" in el_obj.tags.keys()\n ):\n new_element = el_obj.tags[\"pseudo_potcar_file\"]\n vasp_potentials.add_new_element(\n parent_element=el, new_element=new_element\n )\n el_path = find_potential_file(\n path=vasp_potentials.find_default(new_element)[\"Filename\"].values[\n 0\n ][0]\n )\n if not (os.path.isfile(el_path)):\n raise ValueError(\"such a file does not exist in the pp directory\")\n elif el in self.modified_elements.keys():\n new_element = self.modified_elements[el]\n if os.path.isabs(new_element):\n el_path = new_element\n else:\n vasp_potentials.add_new_element(\n parent_element=el, new_element=new_element\n )\n el_path = find_potential_file(\n path=vasp_potentials.find_default(new_element)[\"Filename\"].values[\n 0\n ][0]\n )\n else:\n el_path = find_potential_file(\n path=vasp_potentials.find_default(el)[\"Filename\"].values[0][0]\n )\n\n if not (os.path.isfile(el_path)):\n raise AssertionError()\n pot_name = \"pot_\" + str(i)\n\n if pot_name in self._dataset[\"Parameter\"]:\n try:\n ind = self._dataset[\"Parameter\"].index(pot_name)\n except (ValueError, IndexError):\n indices = np.core.defchararray.find(\n self._dataset[\"Parameter\"], pot_name\n )\n ind = np.where(indices == 0)[0][0]\n self._dataset[\"Value\"][ind] = el_path\n self._dataset[\"Comment\"][ind] = \"\"\n else:\n self._dataset[\"Parameter\"].append(\"pot_\" + str(i))\n self._dataset[\"Value\"].append(el_path)\n self._dataset[\"Comment\"].append(\"\")\n self.el_path_lst.append(el_path)\n\n def write_file(self, file_name, cwd=None):\n \"\"\"\n Args:\n file_name:\n cwd:\n Returns:\n \"\"\"\n self.electrons_per_atom_lst = list()\n self.max_cutoff_lst = list()\n self._set_potential_paths()\n if cwd is not None:\n file_name = posixpath.join(cwd, file_name)\n f = open(file_name, \"w\")\n for el_file in self.el_path_lst:\n with open(el_file) as pot_file:\n for i, line in enumerate(pot_file):\n f.write(line)\n if i == 1:\n self.electrons_per_atom_lst.append(int(float(line)))\n elif i == 14:\n mystr = line.split()[2][:-1]\n self.max_cutoff_lst.append(float(mystr))\n f.close()\n\n def load_default(self):\n file_content = \"\"\"\\\nxc GGA # LDA, GGA\n\"\"\"\n self.load_string(file_content)"
] | [
[
"pandas.Series",
"pandas.DataFrame",
"pandas.concat",
"numpy.core.defchararray.find",
"numpy.where"
]
] |
MECLabTUDA/ACS | [
"bb418c5479a3585138c48c63112352f5cc8f64b1"
] | [
"mp/models/continual/model_utils.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mp.models.segmentation.unet_fepegar import UNet2D\n\n### UNet Wrapper ###\nclass UNet2D_dis(UNet2D):\n r\"\"\"Wrapper for UNet2D to access encoder and decoder seperately.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(UNet2D_dis, self).__init__(*args, **kwargs)\n\n def forward_enc(self, x):\n skip_connections, encoding = self.encoder(x)\n encoding = self.bottom_block(encoding)\n return skip_connections, encoding\n\n def forward_dec(self, skip_connections, encoding):\n x = self.decoder(skip_connections, encoding)\n if self.monte_carlo_layer is not None:\n x = self.monte_carlo_layer(x)\n return self.classifier(x)\n\n### MODULES ###\nclass EncoderStyle(nn.Module):\n r\"\"\"Style Encoder (VAE).\n \"\"\"\n def __init__(self, in_channels):\n super(EncoderStyle, self).__init__()\n\n layers = []\n layers += [ConvBlock(in_channels=in_channels, out_channels=256)]\n layers += [ConvPoolBlock(in_channels=256, out_channels=64, pooling=False)]\n layers += [ConvPoolBlock(in_channels=64, out_channels=128, pooling=True)]\n layers += [ConvPoolBlock(in_channels=128, out_channels=128, pooling=False)]\n layers += [ConvPoolBlock(in_channels=128, out_channels=192, pooling=True)]\n layers += [ConvPoolBlock(in_channels=192, out_channels=192, pooling=False)]\n layers += [ConvPoolBlock(in_channels=192, out_channels=256, pooling=True)]\n\n global_pool = [nn.LeakyReLU(), nn.AdaptiveMaxPool2d(output_size=(3,3))]\n self.global_pool = nn.Sequential(*global_pool)\n\n self.layers = nn.Sequential(*layers)\n\n self.dense_mu = nn.Linear(in_features=3*3*256, out_features=1)\n self.dense_var = nn.Linear(in_features=3*3*256, out_features=1)\n \n def forward(self, x):\n x = self.layers(x)\n x = self.global_pool(x)\n mu = self.dense_mu(x.view(x.shape[0], -1))\n log_var = self.dense_var(x.view(x.shape[0], -1))\n return [mu, log_var]\n\nclass LatentScaler(nn.Module):\n r\"\"\"Scales samples from style encoding to be injected into the generator.\n \"\"\"\n def __init__(self, in_features):\n super(LatentScaler, self).__init__()\n\n layers = [nn.Linear(in_features=in_features, out_features=500), nn.LeakyReLU()]\n layers += [nn.Linear(in_features=500, out_features=1024), nn.LeakyReLU()]\n\n for _ in range(0, 2):\n layers += [nn.Linear(in_features=1024, out_features=1024), nn.LeakyReLU()]\n\n layers += [nn.Linear(in_features=1024, out_features=2560), nn.Tanh()]\n\n self.layers = nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.layers(x).reshape(x.shape[0],10,-1) # 10 occurences a 256 filters\n return x\n\nclass Generator(nn.Module):\n r\"\"\"Generator using content encoding, scaled style encoding (see LatentScaler) and domain_code to generate images.\n \"\"\"\n def __init__(self, in_channels, out_channels, domain_code_size):\n super(Generator, self).__init__()\n\n layers_BCIN = [ResBlockBCIN(in_channels=in_channels, out_channels=in_channels, layer_id=0, stride=1, padding=1, domain_code_size=domain_code_size)]\n for i in range(0,4):\n layers_BCIN += [ResBlockBCIN(in_channels=in_channels, out_channels=in_channels, layer_id=i+1, stride=1, padding=1, domain_code_size=domain_code_size)]\n\n layers = [nn.ConvTranspose2d(in_channels=in_channels, out_channels=in_channels, kernel_size=3, stride=2, padding=1, output_padding=1), nn.ReLU()]\n layers += [nn.ConvTranspose2d(in_channels=in_channels, out_channels=128, kernel_size=3, stride=2, padding=1, output_padding=1), nn.ReLU()]\n layers += [nn.ConvTranspose2d(in_channels=128, out_channels=128, kernel_size=3, stride=2, padding=1, output_padding=1), nn.ReLU()]\n layers += [nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.ReLU()]\n layers += [nn.ConvTranspose2d(in_channels=64, out_channels=out_channels, kernel_size=7, stride=1, padding=3), nn.Sigmoid()]\n \n\n self.layers_BCIN = MultiInSequential(*layers_BCIN)\n self.layers = nn.Sequential(*layers)\n\n def forward(self, content, latent_scale, domain_code):\n content, latent_scale, domain_code = self.layers_BCIN(content, latent_scale, domain_code)\n x = self.layers(content)\n return x\n\nclass DiscriminatorDomain(nn.Module):\n r\"\"\"Domain Discriminator.\n \"\"\"\n def __init__(self, in_channels, domain_code_size, max_channels=512, kernel_size=4, stride=2):\n super(DiscriminatorDomain, self).__init__()\n\n layers = [ConvBlockBCIN(in_channels=in_channels, out_channels=64, kernel_size=kernel_size, stride=stride, domain_code_size=domain_code_size)]\n layers += [ConvBlockBCIN(in_channels=64, out_channels=128, kernel_size=kernel_size, stride=stride, domain_code_size=domain_code_size)]\n layers += [ConvBlockBCIN(in_channels=128, out_channels=max_channels//2, kernel_size=kernel_size, stride=stride, domain_code_size=domain_code_size)]\n layers += [ConvBlockBCIN(in_channels=max_channels//2, out_channels=max_channels, kernel_size=kernel_size, stride=stride, domain_code_size=domain_code_size)]\n layers += [ConvBlockBCIN(in_channels=max_channels, out_channels=1, kernel_size=kernel_size, stride=stride, domain_code_size=domain_code_size, normalization='None')]\n self.layers = MultiInSequential(*layers)\n\n self.linear = nn.Linear(in_features=7**2, out_features=1)\n self.activation = nn.Sigmoid()\n \n def forward(self, x, domain_code):\n x, domain_code = self.layers(x, domain_code)\n x = x.view(x.shape[0],-1)\n x = self.linear(x)\n return x\n\nclass DiscriminatorContent(nn.Module):\n r\"\"\"Unet-style Content Discriminator.\n \"\"\"\n def __init__(self, in_channels, domain_code_size, max_channels=512, kernel_size=3, stride=2):\n super(DiscriminatorContent, self).__init__()\n\n self.in_channels = 16\n self.in_channels_max = 128\n self.out_channels = 32\n self.out_channels_max = 256\n padding = 1\n\n self.conv_0 = nn.Conv2d(in_channels=self.in_channels, out_channels=self.in_channels*2**1, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm_0 = nn.BatchNorm2d(self.in_channels*2**1)\n self.activation_0 = nn.ReLU()\n self.conv_1 = nn.Conv2d(in_channels=self.in_channels*2**1, out_channels=self.in_channels*2**2, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm_1 = nn.BatchNorm2d(self.in_channels*2**2)\n self.activation_1 = nn.ReLU()\n self.conv_2 = nn.Conv2d(in_channels=self.in_channels*2**2, out_channels=self.in_channels*2**3, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm_2 = nn.BatchNorm2d(self.in_channels*2**3)\n self.activation_2 = nn.ReLU()\n self.conv_3 = nn.Conv2d(in_channels=self.in_channels*2**3, out_channels=self.in_channels*2**4, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm_3 = nn.BatchNorm2d(self.in_channels*2**4)\n self.activation_3 = nn.ReLU()\n self.conv_4 = nn.Conv2d(in_channels=self.in_channels*2**4, out_channels=1, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm_4 = nn.BatchNorm2d(1)\n self.activation_4 = nn.ReLU()\n \n self.dense = nn.Linear(in_features = 8**2, out_features=domain_code_size)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, skip_connections, content_x):\n out = self.conv_0(skip_connections[0])\n out = self.norm_0(out)\n out = self.activation_0(out)\n out = self.conv_1(skip_connections[1] + out)\n out = self.norm_1(out)\n out = self.activation_1(out)\n out = self.conv_2(skip_connections[2] + out)\n out = self.norm_2(out)\n out = self.activation_2(out)\n out = self.conv_3(skip_connections[3] + out)\n out = self.norm_3(out)\n out = self.activation_3(out)\n out = self.conv_4(content_x + out)\n out = self.norm_4(out)\n out = self.activation_4(out)\n out = self.dense(out.reshape(content_x.shape[0], -1))\n out = self.softmax(out)\n return out\n \n def center_crop(self, skip_connection, x):\n skip_shape = torch.tensor(skip_connection.shape)\n x_shape = torch.tensor(x.shape)\n crop = skip_shape[2:] - x_shape[2:]\n half_crop = crop // 2\n # If skip_connection is 10, 20, 30 and x is (6, 14, 12)\n # Then pad will be (-2, -2, -3, -3, -9, -9)\n pad = -torch.stack((half_crop, half_crop)).t().flatten()\n skip_connection = F.pad(skip_connection, pad.tolist())\n return skip_connection\n\n### BUILDING BLOCKS ###\nclass ConvBlock(nn.Module):\n r\"\"\"Convolutional Block with normalization and activation.\n \"\"\"\n def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=0, activation=nn.LeakyReLU, normalization='Instance'):\n super(ConvBlock, self).__init__() \n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n \n self.normalization = normalization\n if self.normalization == 'Instance':\n self.norm = nn.InstanceNorm2d(num_features=out_channels, affine=False) # not learnable\n if self.normalization =='BatchNorm':\n self.norm = nn.BatchNorm2d(num_features=out_channels)\n \n self.activation = activation()\n\n def forward(self,x):\n x = self.conv(x)\n if self.normalization in ['Instance', 'BatchNorm']:\n x = self.norm(x)\n x = self.activation(x)\n return x\n\nclass ConvPoolBlock(nn.Module):\n r\"\"\"Convolutional Block with normalization, activation and pooling.\n \"\"\"\n def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=0, pooling=True, activation=nn.LeakyReLU):\n super(ConvPoolBlock, self).__init__()\n\n self.pooling = pooling\n\n self.norm= nn.InstanceNorm2d(num_features=out_channels, affine=False) # not learnable\n self.activation = activation()\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n self.pool = nn.AvgPool2d(kernel_size=kernel_size)\n\n def forward(self, x):\n x = self.norm(x)\n x = self.activation(x)\n x = self.conv(x)\n\n if self.pooling:\n x = self.pool(x)\n return x\n\nclass ConvBlockBCIN(nn.Module):\n r\"\"\"Convolutional Block with BCIN normalization and activation.\n \"\"\"\n def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=0, activation=nn.LeakyReLU, domain_code_size=10, normalization='BCIN'):\n super(ConvBlockBCIN, self).__init__() \n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n self.norm = BCIN(out_channels, domain_code_size) # not learnable\n self.activation = activation()\n\n self.normalization = normalization\n\n def forward(self, x, domain_code):\n x = self.conv(x)\n if self.normalization == 'BCIN': \n x = self.norm(x, domain_code)\n x = self.activation(x)\n return x, domain_code\n\nclass ResBlockIN(nn.Module):\n r\"\"\"Residual Block consisting of two convolutions with skip connection, instance normalization and activation.\n \"\"\"\n def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=0, activation=nn.ReLU):\n super(ResBlockIN, self).__init__()\n self.conv0 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n self.conv1 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n\n self.norm0 = nn.InstanceNorm2d(num_features=out_channels, affine=False) # not learnable\n self.norm1 = nn.InstanceNorm2d(num_features=out_channels, affine=False) # not learnable\n self.activation = activation()\n \n def forward(self, x):\n x_in = x\n x = self.conv0(x)\n x = self.norm0(x)\n x = self.activation(x)\n x = self.conv1(x)\n x = self.norm1(x)\n x += self.center_crop(x_in, x)\n return x\n\n def center_crop(self, skip_connection, x):\n skip_shape = torch.tensor(skip_connection.shape)\n x_shape = torch.tensor(x.shape)\n crop = skip_shape[2:] - x_shape[2:]\n half_crop = crop // 2\n # If skip_connection is 10, 20, 30 and x is (6, 14, 12)\n # Then pad will be (-2, -2, -3, -3, -9, -9)\n pad = -torch.stack((half_crop, half_crop)).t().flatten()\n skip_connection = F.pad(skip_connection, pad.tolist())\n return skip_connection\n\nclass ResBlockBCIN(nn.Module):\n r\"\"\"Residual Block consisting of two convolutions with skip connection, BCIN normalization and activation.\n \"\"\"\n def __init__(self, in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=0, activation=nn.ReLU, domain_code_size=10, layer_id=0):\n super(ResBlockBCIN, self).__init__()\n self.conv0 = nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n self.conv1 = nn.ConvTranspose2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding)\n\n self.norm0 = BCIN(num_features=out_channels, domain_code_size=domain_code_size, affine=True) # learnable\n self.norm1 = BCIN(num_features=out_channels, domain_code_size=domain_code_size, affine=True) # learnable\n self.activation = activation()\n\n self.layer_id = layer_id\n\n def forward(self, x, latent_scale, domain_code):\n \n x_in = x\n x = self.conv0(x)\n x = torch.mul(x, latent_scale[:,self.layer_id*2,:][:,:,None,None])\n x = self.norm0(x, domain_code)\n \n x = self.activation(x)\n\n x = self.conv1(x)\n x = torch.mul(x, latent_scale[:,self.layer_id*2+1,:][:,:,None,None])\n x = self.norm1(x, domain_code)\n\n x += self.center_crop(x_in, x)\n\n return x, latent_scale, domain_code\n\n def center_crop(self, skip_connection, x):\n skip_shape = torch.tensor(skip_connection.shape)\n x_shape = torch.tensor(x.shape)\n crop = skip_shape[2:] - x_shape[2:]\n half_crop = crop // 2\n # If skip_connection is 10, 20, 30 and x is (6, 14, 12)\n # Then pad will be (-2, -2, -3, -3, -9, -9)\n pad = -torch.stack((half_crop, half_crop)).t().flatten()\n skip_connection = F.pad(skip_connection, pad.tolist())\n return skip_connection\n\n### NORMALIZATION ###\nclass BCIN(nn.Module):\n r\"\"\"Central Biasing Instance Normalization\n https://arxiv.org/abs/1806.10050\n \"\"\"\n def __init__(self, num_features, domain_code_size, affine=True, instance_norm=False, batch_norm=False):\n super(BCIN, self).__init__()\n self.W = nn.Parameter(torch.rand(domain_code_size), requires_grad=affine)\n self.b = nn.Parameter(torch.rand(1), requires_grad=affine)\n self.activation = nn.Tanh()\n\n self.instance_norm = instance_norm\n if self.instance_norm:\n print('Using instance_norm instead of BCIN')\n self.i_norm = torch.nn.InstanceNorm2d(num_features=num_features)\n\n self.batch_norm = batch_norm\n if self.instance_norm:\n print('Using batch_norm instead of BCIN')\n self.b_norm = torch.nn.BatchNorm2d(num_features=num_features)\n\n def forward(self, x, domain_code):\n x_var = torch.sqrt(torch.var(x, (1,2,3))) # instance std\n x_mean = torch.mean(x, (1,2,3)) # instance mean\n bias = torch.matmul(domain_code, self.W) * self.b\n bias_scaled = self.activation(bias)\n\n\n if self.instance_norm:\n return self.i_norm(x)\n if self.batch_norm:\n return self.b_norm(x)\n\n return ((x-x_mean[:,None,None,None]) / x_var[:,None,None,None]) + bias_scaled[:,None,None,None]\n\n### HELPER MODULES ###\nclass MultiInSequential(nn.Sequential):\n r\"\"\"Sequential class that allows multiple inputs for forward function\n \"\"\"\n def forward(self, *input):\n for module in self._modules.values():\n input = module(*input)\n return input\n"
] | [
[
"torch.stack",
"torch.rand",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"torch.nn.Sigmoid",
"torch.nn.ConvTranspose2d",
"torch.nn.BatchNorm2d",
"torch.nn.Softmax",
"torch.var",
"torch.nn.AvgPool2d",
"torch.mean",
"torch.nn.AdaptiveMaxPool2d",
"torch.tensor",
"torch.nn.Linear",
"torch.nn.Tanh",
"torch.mul",
"torch.nn.Sequential",
"torch.nn.ReLU",
"torch.matmul",
"torch.nn.LeakyReLU"
]
] |
hashi0203/deep-video-mvs | [
"b3943a9249d522dca3e6cd603e427f611cc7bad5",
"fa14288f149c5af7b2a49092f729f5c4f44517ba"
] | [
"dataset/7scenes-export/7scenes-export-color.py",
"dvmvs/pairnet/run-testing.py"
] | [
"import os\nimport shutil\nfrom multiprocessing.pool import Pool\n\nimport cv2\nimport numpy as np\nfrom functools import partial\nfrom path import Path\n\n\ndef process_scene(input_directory, output_folder):\n K = np.array([[525.0, 0.0, 320.0],\n [0.0, 525.0, 240.0],\n [0.0, 0.0, 1.0]])\n print(\"processing\", input_directory)\n image_filenames = sorted(input_directory.files(\"*color.png\"))\n pose_filenames = sorted(input_directory.files(\"*pose.txt\"))\n\n poses = []\n for pose_filename in pose_filenames:\n pose = np.loadtxt(pose_filename)\n poses.append(pose)\n\n scene = input_directory.split(\"/\")[-2]\n seq = input_directory.split(\"/\")[-1]\n current_output_dir = output_folder / scene + \"-\" + seq\n if os.path.isdir(current_output_dir):\n if os.path.exists(\"{}/poses.txt\".format(current_output_dir)) and os.path.exists(\"{}/K.txt\".format(current_output_dir)):\n return scene\n else:\n shutil.rmtree(current_output_dir)\n\n os.mkdir(current_output_dir)\n os.mkdir(os.path.join(current_output_dir, \"images\"))\n\n output_poses = []\n for current_index in range(len(image_filenames)):\n image = cv2.imread(image_filenames[current_index])\n\n output_poses.append(poses[current_index].ravel().tolist())\n\n cv2.imwrite(\"{}/images/{}.png\".format(current_output_dir, str(current_index).zfill(6)), image, [cv2.IMWRITE_PNG_COMPRESSION, 3])\n\n output_poses = np.array(output_poses)\n np.savetxt(\"{}/poses.txt\".format(current_output_dir), output_poses)\n np.savetxt(\"{}/K.txt\".format(current_output_dir), K)\n\n return scene\n\n\ndef main():\n input_folder = Path(\"/home/share/dataset/7scenes\")\n output_folder = Path(\"/home/nhsmt1123/master-thesis/deep-video-mvs/data/7scenes\")\n\n input_directories = [\n input_folder / \"redkitchen/seq-01\",\n input_folder / \"redkitchen/seq-07\",\n input_folder / \"chess/seq-01\",\n input_folder / \"chess/seq-02\",\n input_folder / \"heads/seq-02\",\n input_folder / \"fire/seq-01\",\n input_folder / \"fire/seq-02\",\n input_folder / \"office/seq-01\",\n input_folder / \"office/seq-03\",\n input_folder / \"pumpkin/seq-03\",\n input_folder / \"pumpkin/seq-06\",\n input_folder / \"stairs/seq-02\",\n input_folder / \"stairs/seq-06\", # train\n input_folder / \"redkitchen/seq-03\",\n input_folder / \"chess/seq-03\",\n input_folder / \"heads/seq-01\",\n input_folder / \"fire/seq-03\",\n input_folder / \"fire/seq-04\",\n input_folder / \"office/seq-02\",\n input_folder / \"pumpkin/seq-01\",\n input_folder / \"stairs/seq-01\"] # test\n\n pool = Pool(6)\n for finished_scene in pool.imap_unordered(partial(process_scene, output_folder=output_folder), input_directories):\n print(\"finished\", finished_scene)\n\n pool.join()\n pool.close()\n\n\nif __name__ == '__main__':\n main()\n",
"import cv2\nimport numpy as np\nimport torch\nfrom path import Path\nfrom tqdm import tqdm\n\nfrom dvmvs.config import Config\nfrom dvmvs.dataset_loader import PreprocessImage, load_image\nfrom dvmvs.pairnet.model import FeatureExtractor, FeatureShrinker, CostVolumeEncoder, CostVolumeDecoder\nfrom dvmvs.utils import cost_volume_fusion, save_results, visualize_predictions, InferenceTimer, get_warp_grid_for_cost_volume_calculation\n\n\ndef predict():\n print(\"System: PAIRNET\")\n\n device = torch.device(\"cuda\")\n feature_extractor = FeatureExtractor()\n feature_shrinker = FeatureShrinker()\n cost_volume_encoder = CostVolumeEncoder()\n cost_volume_decoder = CostVolumeDecoder()\n\n feature_extractor = feature_extractor.to(device)\n feature_shrinker = feature_shrinker.to(device)\n cost_volume_encoder = cost_volume_encoder.to(device)\n cost_volume_decoder = cost_volume_decoder.to(device)\n\n model = [feature_extractor, feature_shrinker, cost_volume_encoder, cost_volume_decoder]\n\n for i in range(len(model)):\n try:\n checkpoint = sorted(Path(\"weights\").files())[i]\n weights = torch.load(checkpoint)\n model[i].load_state_dict(weights)\n model[i].eval()\n print(\"Loaded weights for\", checkpoint)\n except Exception as e:\n print(e)\n print(\"Could not find the checkpoint for module\", i)\n exit(1)\n\n feature_extractor = model[0]\n feature_shrinker = model[1]\n cost_volume_encoder = model[2]\n cost_volume_decoder = model[3]\n\n warp_grid = get_warp_grid_for_cost_volume_calculation(width=int(Config.test_image_width / 2),\n height=int(Config.test_image_height / 2),\n device=device)\n\n scale_rgb = 255.0\n mean_rgb = [0.485, 0.456, 0.406]\n std_rgb = [0.229, 0.224, 0.225]\n\n min_depth = 0.25\n max_depth = 20.0\n n_depth_levels = 64\n\n data_path = Path(Config.test_offline_data_path)\n if Config.test_dataset_name is None:\n keyframe_index_files = sorted((Path(Config.test_offline_data_path) / \"indices\").files())\n else:\n keyframe_index_files = sorted((Path(Config.test_offline_data_path) / \"indices\").files(\"*\" + Config.test_dataset_name + \"*\"))\n for iteration, keyframe_index_file in enumerate(keyframe_index_files):\n keyframing_type, dataset_name, scene_name, _, n_measurement_frames = keyframe_index_file.split(\"/\")[-1].split(\"+\")\n\n scene_folder = data_path / dataset_name / scene_name\n print(\"Predicting for scene:\", dataset_name + \"-\" + scene_name, \" - \", iteration, \"/\", len(keyframe_index_files))\n\n keyframe_index_file_lines = np.loadtxt(keyframe_index_file, dtype=str, delimiter=\"\\n\")\n\n K = np.loadtxt(scene_folder / 'K.txt').astype(np.float32)\n poses = np.fromfile(scene_folder / \"poses.txt\", dtype=float, sep=\"\\n \").reshape((-1, 4, 4))\n image_filenames = sorted((scene_folder / 'images').files(\"*.png\"))\n depth_filenames = sorted((scene_folder / 'depth').files(\"*.png\"))\n\n input_filenames = []\n for image_filename in image_filenames:\n input_filenames.append(image_filename.split(\"/\")[-1])\n\n inference_timer = InferenceTimer()\n\n predictions = []\n reference_depths = []\n with torch.no_grad():\n for i in tqdm(range(0, len(keyframe_index_file_lines))):\n\n keyframe_index_file_line = keyframe_index_file_lines[i]\n\n if keyframe_index_file_line == \"TRACKING LOST\":\n continue\n else:\n current_input_filenames = keyframe_index_file_line.split(\" \")\n current_indices = [input_filenames.index(current_input_filenames[x]) for x in range(len(current_input_filenames))]\n\n reference_index = current_indices[0]\n measurement_indices = current_indices[1:]\n\n reference_pose = poses[reference_index]\n reference_image = load_image(image_filenames[reference_index])\n reference_depth = cv2.imread(depth_filenames[reference_index], -1).astype(float) / 1000.0\n\n preprocessor = PreprocessImage(K=K,\n old_width=reference_image.shape[1],\n old_height=reference_image.shape[0],\n new_width=Config.test_image_width,\n new_height=Config.test_image_height,\n distortion_crop=Config.test_distortion_crop,\n perform_crop=Config.test_perform_crop)\n\n reference_image = preprocessor.apply_rgb(image=reference_image,\n scale_rgb=scale_rgb,\n mean_rgb=mean_rgb,\n std_rgb=std_rgb)\n reference_depth = preprocessor.apply_depth(reference_depth)\n reference_image_torch = torch.from_numpy(np.transpose(reference_image, (2, 0, 1))).float().to(device).unsqueeze(0)\n reference_pose_torch = torch.from_numpy(reference_pose).float().to(device).unsqueeze(0)\n\n measurement_poses_torch = []\n measurement_images_torch = []\n for measurement_index in measurement_indices:\n measurement_image = load_image(image_filenames[measurement_index])\n measurement_image = preprocessor.apply_rgb(image=measurement_image,\n scale_rgb=scale_rgb,\n mean_rgb=mean_rgb,\n std_rgb=std_rgb)\n measurement_image_torch = torch.from_numpy(np.transpose(measurement_image, (2, 0, 1))).float().to(device).unsqueeze(0)\n measurement_pose_torch = torch.from_numpy(poses[measurement_index]).float().to(device).unsqueeze(0)\n measurement_images_torch.append(measurement_image_torch)\n measurement_poses_torch.append(measurement_pose_torch)\n\n full_K_torch = torch.from_numpy(preprocessor.get_updated_intrinsics()).float().to(device).unsqueeze(0)\n\n half_K_torch = full_K_torch.clone().cuda()\n half_K_torch[:, 0:2, :] = half_K_torch[:, 0:2, :] / 2.0\n\n inference_timer.record_start_time()\n\n measurement_feature_halfs = []\n for measurement_image_torch in measurement_images_torch:\n measurement_feature_half, _, _, _ = feature_shrinker(*feature_extractor(measurement_image_torch))\n measurement_feature_halfs.append(measurement_feature_half)\n\n reference_feature_half, reference_feature_quarter, \\\n reference_feature_one_eight, reference_feature_one_sixteen = feature_shrinker(*feature_extractor(reference_image_torch))\n\n cost_volume = cost_volume_fusion(image1=reference_feature_half,\n image2s=measurement_feature_halfs,\n pose1=reference_pose_torch,\n pose2s=measurement_poses_torch,\n K=half_K_torch,\n warp_grid=warp_grid,\n min_depth=min_depth,\n max_depth=max_depth,\n n_depth_levels=n_depth_levels,\n device=device,\n dot_product=True)\n\n skip0, skip1, skip2, skip3, bottom = cost_volume_encoder(features_half=reference_feature_half,\n features_quarter=reference_feature_quarter,\n features_one_eight=reference_feature_one_eight,\n features_one_sixteen=reference_feature_one_sixteen,\n cost_volume=cost_volume)\n\n prediction, _, _, _, _ = cost_volume_decoder(reference_image_torch, skip0, skip1, skip2, skip3, bottom)\n\n inference_timer.record_end_time_and_elapsed_time()\n\n prediction = prediction.cpu().numpy().squeeze()\n reference_depths.append(reference_depth)\n predictions.append(prediction)\n\n if Config.test_visualize:\n visualize_predictions(numpy_reference_image=reference_image,\n numpy_measurement_image=measurement_image,\n numpy_predicted_depth=prediction,\n normalization_mean=mean_rgb,\n normalization_std=std_rgb,\n normalization_scale=scale_rgb)\n\n inference_timer.print_statistics()\n\n system_name = \"{}_{}_{}_{}_{}_dvmvs_pairnet\".format(keyframing_type,\n dataset_name,\n Config.test_image_width,\n Config.test_image_height,\n n_measurement_frames)\n\n save_results(predictions=predictions,\n groundtruths=reference_depths,\n system_name=system_name,\n scene_name=scene_name,\n save_folder=Config.test_result_folder)\n\n\nif __name__ == '__main__':\n predict()\n"
] | [
[
"numpy.array",
"numpy.loadtxt"
],
[
"numpy.fromfile",
"torch.load",
"numpy.transpose",
"torch.no_grad",
"torch.from_numpy",
"torch.device",
"numpy.loadtxt"
]
] |
lukasc-ch/QuantLab | [
"7ddcc51ec1131a58269768cd898ce04e8b49beb6"
] | [
"quantlab/COCO/YOLOv3Tiny/postprocess.py"
] | [
"# Copyright (c) 2019 UniMoRe, Matteo Spallanzani\n\nimport torch\n\nfrom ..utils.utils import xywh2xyxy, bbox_iou\n\n\ndef clip_boxes(boxes):\n boxes[:, [0, 2]] = boxes[:, [0, 2]].clamp(min=0, max=1)\n boxes[:, [1, 3]] = boxes[:, [1, 3]].clamp(min=0, max=1)\n\n\ndef postprocess_pr(pr_outs, conf_thres=0.001, overlap_thres=0.5):\n \"\"\"Restructure YOLOv3Tiny tensors into lists, then filter out non-maximal\n (redundant) annotations from the predictions.\"\"\"\n # pr_outs = [[bs, grid_positions, 85], [bs, 4*grid_positions, 85]]\n # when its two components are concatenated, we get a tensor [bs, 5*gridpositions, 85], which `bs` \"slices\"\n # have to be \"stripped\" to remove redundant components\n # strip each slice (corresponding to a single image in the batch) to get sequences of (possibly) different lengths:\n # the natural data structure to use to collect these sequences is a list\n pr_outs = [p.view(p.size(0), -1, p.size(-1)) for p in pr_outs]\n pr_outs = torch.cat(pr_outs, 1).detach().cpu()\n pr_labels = [None] * len(pr_outs)\n for img_id, pr in enumerate(pr_outs):\n # filter out irrelevant predictions\n pr_cls_prob, pr_cls_id = pr[:, 5:].max(1)\n pr[:, 4] *= pr_cls_prob\n i = (pr[:, 4] > conf_thres) & torch.isfinite(pr).all(1)\n pr = pr[i]\n if len(pr) == 0:\n continue\n pr_cls_prob = pr_cls_prob[i]\n pr_cls_id = pr_cls_id[i].unsqueeze(1).float()\n pr[:, :4] = xywh2xyxy(pr[:, :4])\n pr = torch.cat((pr[:, :5], pr_cls_prob.unsqueeze(1), pr_cls_id), 1)\n pr = pr[(-pr[:, 4]).argsort()]\n detections = []\n for c in pr[:, -1].unique():\n pr_anno_c = pr[pr[:, -1] == c]\n n = len(pr_anno_c)\n if n == 1:\n detections.append(pr_anno_c)\n continue\n elif n > 100:\n pr_anno_c = pr_anno_c[:100]\n while len(pr_anno_c) > 0:\n if len(pr_anno_c) == 1:\n detections.append(pr_anno_c)\n break\n redundant = bbox_iou(pr_anno_c[0], pr_anno_c) > overlap_thres\n weights = pr_anno_c[redundant, 4:5]\n pr_anno_c[0, :4] = (weights * pr_anno_c[redundant, 0:4]).sum(0) / weights.sum()\n detections.append(pr_anno_c[0:1]) # keep leading dimension 1 for 1D tensor\n pr_anno_c = pr_anno_c[~redundant]\n if len(detections) > 0:\n detections = torch.cat(detections)\n clip_boxes(detections[:, :4])\n pr_labels[img_id] = detections[(-detections[:, 4]).argsort()]\n return pr_labels\n\n\ndef postprocess_gt(gt_labels):\n gt_labels = gt_labels.detach().cpu()\n bs = gt_labels[0, 0].to(torch.int)\n gt_labels = [gt_labels[gt_labels[:, 1] == i, 2:] for i in range(bs)]\n return gt_labels\n"
] | [
[
"torch.cat",
"torch.isfinite"
]
] |
NicoSerranoP/PySyft | [
"87fcd566c46fce4c16d363c94396dd26bd82a016"
] | [
"syft/frameworks/torch/mpc/fss.py"
] | [
"\"\"\"\nThis is an implementation of Function Secret Sharing\n\nUseful papers are:\n- Function Secret Sharing- Improvements and Extensions, Boyle 2017\n Link: https://eprint.iacr.org/2018/707.pdf\n- Secure Computation with Preprocessing via Function Secret Sharing, Boyle 2019\n Link: https://eprint.iacr.org/2019/1095\n\nNote that the protocols are quite different in aspect from those papers\n\"\"\"\nimport hashlib\n\nimport torch as th\nimport syft as sy\n\n\nλ = 110 # 6 # 110 or 63 # security parameter\nn = 32 # 8 # 32 # bit precision\ndtype = th.int32\n\nno_wrap = {\"no_wrap\": True}\n\n\ndef initialize_crypto_plans(worker):\n \"\"\"\n This is called manually for the moment, to build the plan used to perform\n Function Secret Sharing on a specific worker.\n \"\"\"\n eq_plan_1 = sy.Plan(\n forward_func=lambda x, y: mask_builder(x, y, \"eq\"),\n owner=worker,\n tags=[\"#fss_eq_plan_1\"],\n is_built=True,\n )\n worker.register_obj(eq_plan_1)\n eq_plan_2 = sy.Plan(\n forward_func=eq_eval_plan, owner=worker, tags=[\"#fss_eq_plan_2\"], is_built=True\n )\n worker.register_obj(eq_plan_2)\n\n comp_plan_1 = sy.Plan(\n forward_func=lambda x, y: mask_builder(x, y, \"comp\"),\n owner=worker,\n tags=[\"#fss_comp_plan_1\"],\n is_built=True,\n )\n worker.register_obj(comp_plan_1)\n comp_plan_2 = sy.Plan(\n forward_func=comp_eval_plan, owner=worker, tags=[\"#fss_comp_plan_2\"], is_built=True\n )\n worker.register_obj(comp_plan_2)\n\n xor_add_plan = sy.Plan(\n forward_func=xor_add_convert_1, owner=worker, tags=[\"#xor_add_1\"], is_built=True\n )\n worker.register_obj(xor_add_plan)\n xor_add_plan = sy.Plan(\n forward_func=xor_add_convert_2, owner=worker, tags=[\"#xor_add_2\"], is_built=True\n )\n worker.register_obj(xor_add_plan)\n\n\ndef request_run_plan(worker, plan_tag, location, return_value, args=(), kwargs={}):\n response_ids = (sy.ID_PROVIDER.pop(),)\n args = (args, response_ids)\n\n response = worker.send_command(\n cmd_name=\"run\",\n target=plan_tag,\n recipient=location,\n return_ids=response_ids,\n return_value=return_value,\n kwargs_=kwargs,\n args_=args,\n )\n return response\n\n\ndef fss_op(x1, x2, type_op=\"eq\"):\n \"\"\"\n Define the workflow for a binary operation using Function Secret Sharing\n\n Currently supported operand are = & <=, respectively corresponding to\n type_op = 'eq' and 'comp'\n\n Args:\n x1: first AST\n x2: second AST\n type_op: type of operation to perform, should be 'eq' or 'comp'\n\n Returns:\n shares of the comparison\n \"\"\"\n\n me = sy.local_worker\n locations = x1.locations\n\n shares = []\n for location in locations:\n args = (x1.child[location.id], x2.child[location.id])\n share = request_run_plan(\n me, f\"#fss_{type_op}_plan_1\", location, return_value=True, args=args\n )\n shares.append(share)\n\n mask_value = sum(shares) % 2 ** n\n\n shares = []\n for i, location in enumerate(locations):\n args = (th.IntTensor([i]), mask_value)\n share = request_run_plan(\n me, f\"#fss_{type_op}_plan_2\", location, return_value=False, args=args\n )\n shares.append(share)\n\n if type_op == \"comp\":\n prev_shares = shares\n shares = []\n for prev_share, location in zip(prev_shares, locations):\n share = request_run_plan(\n me, \"#xor_add_1\", location, return_value=True, args=(prev_share,)\n )\n shares.append(share)\n\n masked_value = shares[0] ^ shares[1] # TODO case >2 workers ?\n\n shares = {}\n for i, prev_share, location in zip(range(len(locations)), prev_shares, locations):\n share = request_run_plan(\n me,\n \"#xor_add_2\",\n location,\n return_value=False,\n args=(th.IntTensor([i]), masked_value),\n )\n shares[location.id] = share\n else:\n shares = {loc.id: share for loc, share in zip(locations, shares)}\n\n response = sy.AdditiveSharingTensor(shares, **x1.get_class_attributes())\n return response\n\n\n# share level\ndef mask_builder(x1, x2, type_op):\n x = x1 - x2\n # Keep the primitive in store as we use it after\n alpha, s_0, *CW = x1.owner.crypto_store.get_keys(\n f\"fss_{type_op}\", n_instances=x1.numel(), remove=False\n )\n return x + alpha.reshape(x.shape)\n\n\n# share level\ndef eq_eval_plan(b, x_masked):\n alpha, s_0, *CW = x_masked.owner.crypto_store.get_keys(\n type_op=\"fss_eq\", n_instances=x_masked.numel(), remove=True\n )\n result_share = DPF.eval(b, x_masked, s_0, *CW)\n return result_share\n\n\n# share level\ndef comp_eval_plan(b, x_masked):\n alpha, s_0, *CW = x_masked.owner.crypto_store.get_keys(\n type_op=\"fss_comp\", n_instances=x_masked.numel(), remove=True\n )\n result_share = DIF.eval(b, x_masked, s_0, *CW)\n return result_share\n\n\ndef xor_add_convert_1(x):\n xor_share, add_share = x.owner.crypto_store.get_keys(\n type_op=\"xor_add_couple\", n_instances=x.numel(), remove=False\n )\n return x ^ xor_share.reshape(x.shape)\n\n\ndef xor_add_convert_2(b, x):\n xor_share, add_share = x.owner.crypto_store.get_keys(\n type_op=\"xor_add_couple\", n_instances=x.numel(), remove=True\n )\n return add_share.reshape(x.shape) * (1 - 2 * x) + x * b\n\n\ndef eq(x1, x2):\n return fss_op(x1, x2, \"eq\")\n\n\ndef le(x1, x2):\n return fss_op(x1, x2, \"comp\")\n\n\nclass DPF:\n \"\"\"Distributed Point Function - used for equality\"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def keygen(n_values=1):\n beta = th.tensor([1], dtype=dtype)\n alpha = th.randint(0, 2 ** n, (n_values,))\n\n α = bit_decomposition(alpha)\n s, t, CW = (\n Array(n + 1, 2, λ, n_values),\n Array(n + 1, 2, n_values),\n Array(n, 2 * (λ + 1), n_values),\n )\n s[0] = randbit(size=(2, λ, n_values))\n t[0] = th.tensor([[0, 1]] * n_values, dtype=th.uint8).t()\n for i in range(0, n):\n g0 = G(s[i, 0])\n g1 = G(s[i, 1])\n # Re-use useless randomness\n sL_0, _, sR_0, _ = split(g0, [λ, 1, λ, 1])\n sL_1, _, sR_1, _ = split(g1, [λ, 1, λ, 1])\n s_rand = (sL_0 ^ sL_1) * α[i] + (sR_0 ^ sR_1) * (1 - α[i])\n\n cw_i = TruthTableDPF(s_rand, α[i])\n CW[i] = cw_i ^ g0 ^ g1\n\n for b in (0, 1):\n τ = [g0, g1][b] ^ (t[i, b] * CW[i])\n τ = τ.reshape(2, λ + 1, n_values)\n # filtered_τ = τ[𝛼[i]] OLD\n α_i = α[i].unsqueeze(0).expand(λ + 1, n_values).unsqueeze(0).long()\n filtered_τ = th.gather(τ, 0, α_i).squeeze(0)\n s[i + 1, b], t[i + 1, b] = split(filtered_τ, [λ, 1])\n\n CW_n = (-1) ** t[n, 1].to(dtype) * (beta - Convert(s[n, 0]) + Convert(s[n, 1]))\n\n return (alpha,) + s[0].unbind() + (CW, CW_n)\n\n @staticmethod\n def eval(b, x, *k_b):\n original_shape = x.shape\n x = x.reshape(-1)\n n_values = x.shape[0]\n x = bit_decomposition(x)\n s, t = Array(n + 1, λ, n_values), Array(n + 1, 1, n_values)\n s[0] = k_b[0]\n # here k[1:] is (CW, CW_n)\n CW = k_b[1].unbind() + (k_b[2],)\n t[0] = b\n for i in range(0, n):\n τ = G(s[i]) ^ (t[i] * CW[i])\n τ = τ.reshape(2, λ + 1, n_values)\n x_i = x[i].unsqueeze(0).expand(λ + 1, n_values).unsqueeze(0).long()\n filtered_τ = th.gather(τ, 0, x_i).squeeze(0)\n s[i + 1], t[i + 1] = split(filtered_τ, [λ, 1])\n flat_result = (-1) ** b * (Convert(s[n]) + t[n].squeeze() * CW[n])\n return flat_result.reshape(original_shape)\n\n\nclass DIF:\n \"\"\"Distributed Interval Function - used for comparison <=\"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def keygen(n_values=1):\n alpha = th.randint(0, 2 ** n, (n_values,))\n α = bit_decomposition(alpha)\n s, t, CW = (\n Array(n + 1, 2, λ, n_values),\n Array(n + 1, 2, n_values),\n Array(n, 2 + 2 * (λ + 1), n_values),\n )\n s[0] = randbit(size=(2, λ, n_values))\n t[0] = th.tensor([[0, 1]] * n_values, dtype=th.uint8).t()\n for i in range(0, n):\n h0 = H(s[i, 0])\n h1 = H(s[i, 1])\n # Re-use useless randomness\n _, _, sL_0, _, sR_0, _ = split(h0, [1, 1, λ, 1, λ, 1])\n _, _, sL_1, _, sR_1, _ = split(h1, [1, 1, λ, 1, λ, 1])\n s_rand = (sL_0 ^ sL_1) * α[i] + (sR_0 ^ sR_1) * (1 - α[i])\n cw_i = TruthTableDIF(s_rand, α[i])\n CW[i] = cw_i ^ h0 ^ h1\n\n for b in (0, 1):\n τ = [h0, h1][b] ^ (t[i, b] * CW[i])\n τ = τ.reshape(2, λ + 2, n_values)\n # filtered_τ = τ[𝛼[i]] OLD\n α_i = α[i].unsqueeze(0).expand(λ + 2, n_values).unsqueeze(0).long()\n filtered_τ = th.gather(τ, 0, α_i).squeeze(0)\n σ_leaf, s[i + 1, b], t[i + 1, b] = split(filtered_τ, [1, λ, 1])\n\n return (alpha,) + s[0].unbind() + (CW,)\n\n @staticmethod\n def eval(b, x, *k_b):\n original_shape = x.shape\n x = x.reshape(-1)\n n_values = x.shape[0]\n x = bit_decomposition(x)\n FnOutput = Array(n + 1, n_values)\n s, t = Array(n + 1, λ, n_values), Array(n + 1, 1, n_values)\n s[0] = k_b[0]\n CW = k_b[1].unbind()\n t[0] = b\n for i in range(0, n):\n τ = H(s[i]) ^ (t[i] * CW[i])\n τ = τ.reshape(2, λ + 2, n_values)\n x_i = x[i].unsqueeze(0).expand(λ + 2, n_values).unsqueeze(0).long()\n filtered_τ = th.gather(τ, 0, x_i).squeeze(0)\n σ_leaf, s[i + 1], t[i + 1] = split(filtered_τ, [1, λ, 1])\n FnOutput[i] = σ_leaf\n\n # Last tour, the other σ is also a leaf:\n FnOutput[n] = t[n]\n flat_result = FnOutput.sum(axis=0) % 2\n return flat_result.reshape(original_shape)\n\n\n# PRG\ndef G(seed):\n assert seed.shape[0] == λ\n seed_t = seed.t().tolist()\n gen_list = []\n for seed_bit in seed_t:\n enc_str = str(seed_bit).encode()\n h = hashlib.sha3_256(enc_str)\n r = h.digest()\n binary_str = bin(int.from_bytes(r, byteorder=\"big\"))[2 : 2 + (2 * (λ + 1))]\n gen_list.append(list(map(int, binary_str)))\n\n return th.tensor(gen_list, dtype=th.uint8).t()\n\n\ndef H(seed):\n assert seed.shape[0] == λ\n seed_t = seed.t().tolist()\n gen_list = []\n for seed_bit in seed_t:\n enc_str = str(seed_bit).encode()\n h = hashlib.sha3_256(enc_str)\n r = h.digest()\n binary_str = bin(int.from_bytes(r, byteorder=\"big\"))[2 : 2 + 2 + (2 * (λ + 1))]\n gen_list.append(list(map(int, binary_str)))\n\n return th.tensor(gen_list, dtype=th.uint8).t()\n\n\ndef Convert(bits):\n bit_pow_lambda = th.flip(2 ** th.arange(λ), (0,)).unsqueeze(-1).to(th.long)\n return (bits.to(th.long) * bit_pow_lambda).sum(dim=0).to(dtype)\n\n\ndef Array(*shape):\n return th.empty(shape, dtype=th.uint8)\n\n\nbit_pow_n = th.flip(2 ** th.arange(n), (0,))\n\n\ndef bit_decomposition(x):\n x = x.unsqueeze(-1)\n z = bit_pow_n & x\n z = z.t()\n return (z > 0).to(th.uint8)\n\n\ndef randbit(size):\n return th.randint(2, size=size)\n\n\ndef concat(*args, **kwargs):\n return th.cat(args, **kwargs)\n\n\ndef split(x, idx):\n return th.split(x, idx)\n\n\ndef TruthTableDPF(s, α_i):\n one = th.ones((1, s.shape[1])).to(th.uint8)\n s_one = concat(s, one)\n Table = th.zeros((2, λ + 1, len(α_i)), dtype=th.uint8)\n for j, el in enumerate(α_i):\n Table[el.item(), :, j] = s_one[:, j]\n return Table.reshape(-1, Table.shape[2])\n\n\ndef TruthTableDIF(s, α_i):\n leafTable = th.zeros((2, 1, len(α_i)), dtype=th.uint8)\n # TODO optimize: just put alpha on first line\n leaf_value = α_i\n for j, el in enumerate(α_i):\n leafTable[(1 - el).item(), 0, j] = leaf_value[j]\n\n one = th.ones((1, s.shape[1])).to(th.uint8)\n s_one = concat(s, one)\n nextTable = th.zeros((2, λ + 1, len(α_i)), dtype=th.uint8)\n for j, el in enumerate(α_i):\n nextTable[el.item(), :, j] = s_one[:, j]\n\n Table = concat(leafTable, nextTable, axis=1)\n Table = Table.reshape(-1, Table.shape[2])\n return Table\n"
] | [
[
"torch.empty",
"torch.ones",
"torch.randint",
"torch.split",
"torch.tensor",
"torch.gather",
"torch.arange",
"torch.IntTensor",
"torch.cat"
]
] |
neurodebian/scikits.image-1 | [
"33206f87c5e0208e7ff0d5910ac082b3353fe04e",
"33206f87c5e0208e7ff0d5910ac082b3353fe04e"
] | [
"skimage/exposure/exposure.py",
"skimage/filter/_gabor.py"
] | [
"import warnings\nimport numpy as np\n\nfrom skimage import img_as_float\nfrom skimage.util.dtype import dtype_range, dtype_limits\nfrom skimage._shared.utils import deprecated\n\n\n__all__ = ['histogram', 'cumulative_distribution', 'equalize',\n 'rescale_intensity', 'adjust_gamma',\n 'adjust_log', 'adjust_sigmoid']\n\n\ndef histogram(image, nbins=256):\n \"\"\"Return histogram of image.\n\n Unlike `numpy.histogram`, this function returns the centers of bins and\n does not rebin integer arrays. For integer arrays, each integer value has\n its own bin, which improves speed and intensity-resolution.\n\n The histogram is computed on the flattened image: for color images, the\n function should be used separately on each channel to obtain a histogram\n for each color channel.\n\n Parameters\n ----------\n image : array\n Input image.\n nbins : int\n Number of bins used to calculate histogram. This value is ignored for\n integer arrays.\n\n Returns\n -------\n hist : array\n The values of the histogram.\n bin_centers : array\n The values at the center of the bins.\n\n Examples\n --------\n >>> from skimage import data, exposure, util\n >>> image = util.img_as_float(data.camera())\n >>> np.histogram(image, bins=2)\n (array([107432, 154712]), array([ 0. , 0.5, 1. ]))\n >>> exposure.histogram(image, nbins=2)\n (array([107432, 154712]), array([ 0.25, 0.75]))\n \"\"\"\n sh = image.shape\n if len(sh) == 3 and sh[-1] < 4:\n warnings.warn(\"This might be a color image. The histogram will be \"\n \"computed on the flattened image. You can instead \"\n \"apply this function to each color channel.\")\n\n # For integer types, histogramming with bincount is more efficient.\n if np.issubdtype(image.dtype, np.integer):\n offset = 0\n if np.min(image) < 0:\n offset = np.min(image)\n hist = np.bincount(image.ravel() - offset)\n bin_centers = np.arange(len(hist)) + offset\n\n # clip histogram to start with a non-zero bin\n idx = np.nonzero(hist)[0][0]\n return hist[idx:], bin_centers[idx:]\n else:\n hist, bin_edges = np.histogram(image.flat, nbins)\n bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2.\n return hist, bin_centers\n\n\ndef cumulative_distribution(image, nbins=256):\n \"\"\"Return cumulative distribution function (cdf) for the given image.\n\n Parameters\n ----------\n image : array\n Image array.\n nbins : int\n Number of bins for image histogram.\n\n Returns\n -------\n img_cdf : array\n Values of cumulative distribution function.\n bin_centers : array\n Centers of bins.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Cumulative_distribution_function\n\n \"\"\"\n hist, bin_centers = histogram(image, nbins)\n img_cdf = hist.cumsum()\n img_cdf = img_cdf / float(img_cdf[-1])\n return img_cdf, bin_centers\n\n\n@deprecated('equalize_hist')\ndef equalize(image, nbins=256):\n return equalize_hist(image, nbins)\n\n\ndef equalize_hist(image, nbins=256):\n \"\"\"Return image after histogram equalization.\n\n Parameters\n ----------\n image : array\n Image array.\n nbins : int\n Number of bins for image histogram.\n\n Returns\n -------\n out : float array\n Image array after histogram equalization.\n\n Notes\n -----\n This function is adapted from [1]_ with the author's permission.\n\n References\n ----------\n .. [1] http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html\n .. [2] http://en.wikipedia.org/wiki/Histogram_equalization\n\n \"\"\"\n image = img_as_float(image)\n cdf, bin_centers = cumulative_distribution(image, nbins)\n out = np.interp(image.flat, bin_centers, cdf)\n return out.reshape(image.shape)\n\n\ndef rescale_intensity(image, in_range=None, out_range=None):\n \"\"\"Return image after stretching or shrinking its intensity levels.\n\n The image intensities are uniformly rescaled such that the minimum and\n maximum values given by `in_range` match those given by `out_range`.\n\n Parameters\n ----------\n image : array\n Image array.\n in_range : 2-tuple (float, float)\n Min and max *allowed* intensity values of input image. If None, the\n *allowed* min/max values are set to the *actual* min/max values in the\n input image.\n out_range : 2-tuple (float, float)\n Min and max intensity values of output image. If None, use the min/max\n intensities of the image data type. See `skimage.util.dtype` for\n details.\n\n Returns\n -------\n out : array\n Image array after rescaling its intensity. This image is the same dtype\n as the input image.\n\n Examples\n --------\n By default, intensities are stretched to the limits allowed by the dtype:\n\n >>> image = np.array([51, 102, 153], dtype=np.uint8)\n >>> rescale_intensity(image)\n array([ 0, 127, 255], dtype=uint8)\n\n It's easy to accidentally convert an image dtype from uint8 to float:\n\n >>> 1.0 * image\n array([ 51., 102., 153.])\n\n Use `rescale_intensity` to rescale to the proper range for float dtypes:\n\n >>> image_float = 1.0 * image\n >>> rescale_intensity(image_float)\n array([ 0. , 0.5, 1. ])\n\n To maintain the low contrast of the original, use the `in_range` parameter:\n\n >>> rescale_intensity(image_float, in_range=(0, 255))\n array([ 0.2, 0.4, 0.6])\n\n If the min/max value of `in_range` is more/less than the min/max image\n intensity, then the intensity levels are clipped:\n\n >>> rescale_intensity(image_float, in_range=(0, 102))\n array([ 0.5, 1. , 1. ])\n\n If you have an image with signed integers but want to rescale the image to\n just the positive range, use the `out_range` parameter:\n\n >>> image = np.array([-10, 0, 10], dtype=np.int8)\n >>> rescale_intensity(image, out_range=(0, 127))\n array([ 0, 63, 127], dtype=int8)\n\n \"\"\"\n dtype = image.dtype.type\n\n if in_range is None:\n imin = np.min(image)\n imax = np.max(image)\n else:\n imin, imax = in_range\n\n if out_range is None:\n omin, omax = dtype_range[dtype]\n if imin >= 0:\n omin = 0\n else:\n omin, omax = out_range\n\n image = np.clip(image, imin, imax)\n\n image = (image - imin) / float(imax - imin)\n return dtype(image * (omax - omin) + omin)\n\n\ndef _assert_non_negative(image):\n\n if np.any(image < 0):\n raise ValueError('Image Correction methods work correctly only on '\n 'images with non-negative values. Use '\n 'skimage.exposure.rescale_intensity.')\n\n\ndef adjust_gamma(image, gamma=1, gain=1):\n \"\"\"Performs Gamma Correction on the input image.\n\n Also known as Power Law Transform.\n This function transforms the input image pixelwise according to the\n equation ``O = I**gamma`` after scaling each pixel to the range 0 to 1.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n gamma : float\n Non negative real number. Default value is 1.\n gain : float\n The constant multiplier. Default value is 1.\n\n Returns\n -------\n out : ndarray\n Gamma corrected output image.\n\n Notes\n -----\n For gamma greater than 1, the histogram will shift towards left and\n the output image will be darker than the input image.\n\n For gamma less than 1, the histogram will shift towards right and\n the output image will be brighter than the input image.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Gamma_correction\n\n \"\"\"\n _assert_non_negative(image)\n dtype = image.dtype.type\n\n if gamma < 0:\n return \"Gamma should be a non-negative real number\"\n\n scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0])\n\n out = ((image / scale) ** gamma) * scale * gain\n return dtype(out)\n\n\ndef adjust_log(image, gain=1, inv=False):\n \"\"\"Performs Logarithmic correction on the input image.\n\n This function transforms the input image pixelwise according to the\n equation ``O = gain*log(1 + I)`` after scaling each pixel to the range 0 to 1.\n For inverse logarithmic correction, the equation is ``O = gain*(2**I - 1)``.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n gain : float\n The constant multiplier. Default value is 1.\n inv : float\n If True, it performs inverse logarithmic correction,\n else correction will be logarithmic. Defaults to False.\n\n Returns\n -------\n out : ndarray\n Logarithm corrected output image.\n\n References\n ----------\n .. [1] http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf\n\n \"\"\"\n _assert_non_negative(image)\n dtype = image.dtype.type\n scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0])\n\n if inv:\n out = (2 ** (image / scale) - 1) * scale * gain\n return dtype(out)\n\n out = np.log2(1 + image / scale) * scale * gain\n return dtype(out)\n\n\ndef adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False):\n \"\"\"Performs Sigmoid Correction on the input image.\n\n Also known as Contrast Adjustment.\n This function transforms the input image pixelwise according to the\n equation ``O = 1/(1 + exp*(gain*(cutoff - I)))`` after scaling each pixel\n to the range 0 to 1.\n\n Parameters\n ----------\n image : ndarray\n Input image.\n cutoff : float\n Cutoff of the sigmoid function that shifts the characteristic curve\n in horizontal direction. Default value is 0.5.\n gain : float\n The constant multiplier in exponential's power of sigmoid function.\n Default value is 10.\n inv : bool\n If True, returns the negative sigmoid correction. Defaults to False.\n\n Returns\n -------\n out : ndarray\n Sigmoid corrected output image.\n\n References\n ----------\n .. [1] Gustav J. Braun, \"Image Lightness Rescaling Using Sigmoidal Contrast\n Enhancement Functions\",\n http://www.cis.rit.edu/fairchild/PDFs/PAP07.pdf\n\n \"\"\"\n _assert_non_negative(image)\n dtype = image.dtype.type\n scale = float(dtype_limits(image, True)[1] - dtype_limits(image, True)[0])\n\n if inv:\n out = (1 - 1 / (1 + np.exp(gain * (cutoff - image/scale)))) * scale\n return dtype(out)\n\n out = (1 / (1 + np.exp(gain * (cutoff - image/scale)))) * scale\n return dtype(out)\n",
"import numpy as np\nfrom scipy import ndimage\n\n\n__all__ = ['gabor_kernel', 'gabor_filter']\n\n\ndef _sigma_prefactor(bandwidth):\n b = bandwidth\n # See http://www.cs.rug.nl/~imaging/simplecell.html\n return 1.0 / np.pi * np.sqrt(np.log(2)/2.0) * (2.0**b + 1) / (2.0**b - 1)\n\n\ndef gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None,\n offset=0):\n \"\"\"Return complex 2D Gabor filter kernel.\n\n Frequency and orientation representations of the Gabor filter are similar\n to those of the human visual system. It is especially suitable for texture\n classification using Gabor filter banks.\n\n Parameters\n ----------\n frequency : float\n Frequency of the harmonic function.\n theta : float\n Orientation in radians. If 0, the harmonic is in the x-direction.\n bandwidth : float\n The bandwidth captured by the filter. For fixed bandwidth, `sigma_x`\n and `sigma_y` will decrease with increasing frequency. This value is\n ignored if `sigma_x` and `sigma_y` are set by the user.\n sigma_x, sigma_y : float\n Standard deviation in x- and y-directions. These directions apply to\n the kernel *before* rotation. If `theta = pi/2`, then the kernel is\n rotated 90 degrees so that `sigma_x` controls the *vertical* direction.\n offset : float, optional\n Phase offset of harmonic function in radians.\n\n Returns\n -------\n g : complex array\n Complex filter kernel.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Gabor_filter\n .. [2] http://mplab.ucsd.edu/tutorials/gabor.pdf\n\n \"\"\"\n if sigma_x is None:\n sigma_x = _sigma_prefactor(bandwidth) / frequency\n if sigma_y is None:\n sigma_y = _sigma_prefactor(bandwidth) / frequency\n\n n_stds = 3\n x0 = np.ceil(max(np.abs(n_stds * sigma_x * np.cos(theta)),\n np.abs(n_stds * sigma_y * np.sin(theta)), 1))\n y0 = np.ceil(max(np.abs(n_stds * sigma_y * np.cos(theta)),\n np.abs(n_stds * sigma_x * np.sin(theta)), 1))\n y, x = np.mgrid[-y0:y0+1, -x0:x0+1]\n\n rotx = x * np.cos(theta) + y * np.sin(theta)\n roty = -x * np.sin(theta) + y * np.cos(theta)\n\n g = np.zeros(y.shape, dtype=np.complex)\n g[:] = np.exp(-0.5 * (rotx**2 / sigma_x**2 + roty**2 / sigma_y**2))\n g /= 2 * np.pi * sigma_x * sigma_y\n g *= np.exp(1j * (2 * np.pi * frequency * rotx + offset))\n\n return g\n\n\ndef gabor_filter(image, frequency, theta=0, bandwidth=1, sigma_x=None,\n sigma_y=None, offset=0, mode='reflect', cval=0):\n \"\"\"Return real and imaginary responses to Gabor filter.\n\n The real and imaginary parts of the Gabor filter kernel are applied to the\n image and the response is returned as a pair of arrays.\n\n Frequency and orientation representations of the Gabor filter are similar\n to those of the human visual system. It is especially suitable for texture\n classification using Gabor filter banks.\n\n Parameters\n ----------\n image : array\n Input image.\n frequency : float\n Frequency of the harmonic function.\n theta : float\n Orientation in radians. If 0, the harmonic is in the x-direction.\n bandwidth : float\n The bandwidth captured by the filter. For fixed bandwidth, `sigma_x`\n and `sigma_y` will decrease with increasing frequency. This value is\n ignored if `sigma_x` and `sigma_y` are set by the user.\n sigma_x, sigma_y : float\n Standard deviation in x- and y-directions. These directions apply to\n the kernel *before* rotation. If `theta = pi/2`, then the kernel is\n rotated 90 degrees so that `sigma_x` controls the *vertical* direction.\n offset : float, optional\n Phase offset of harmonic function in radians.\n\n Returns\n -------\n real, imag : arrays\n Filtered images using the real and imaginary parts of the Gabor filter\n kernel.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Gabor_filter\n .. [2] http://mplab.ucsd.edu/tutorials/gabor.pdf\n\n \"\"\"\n\n g = gabor_kernel(frequency, theta, bandwidth, sigma_x, sigma_y, offset)\n\n filtered_real = ndimage.convolve(image, np.real(g), mode=mode, cval=cval)\n filtered_imag = ndimage.convolve(image, np.imag(g), mode=mode, cval=cval)\n\n return filtered_real, filtered_imag\n"
] | [
[
"numpy.log2",
"numpy.interp",
"numpy.histogram",
"numpy.any",
"numpy.issubdtype",
"numpy.exp",
"numpy.clip",
"numpy.max",
"numpy.min",
"numpy.nonzero"
],
[
"numpy.zeros",
"numpy.cos",
"numpy.exp",
"numpy.log",
"numpy.sin",
"numpy.real",
"numpy.imag"
]
] |
daoran/opendr | [
"bca25f6a43244fe9c219a24576181f94a0726923"
] | [
"tests/sources/tools/perception/object_tracking_2d/deep_sort/test_object_tracking_2d_deep_sort.py"
] | [
"# Copyright 2020-2022 OpenDR European Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport unittest\nimport shutil\nimport torch\nfrom opendr.perception.object_tracking_2d import ObjectTracking2DDeepSortLearner\nfrom opendr.perception.object_tracking_2d import (\n Market1501Dataset,\n Market1501DatasetIterator,\n)\nfrom opendr.perception.object_tracking_2d import (\n MotDataset,\n RawMotWithDetectionsDatasetIterator,\n)\nimport os\n\nDEVICE = os.getenv('TEST_DEVICE') if os.getenv('TEST_DEVICE') else 'cpu'\n\nprint(\"Using device:\", DEVICE)\nprint(\"Using device:\", DEVICE, file=sys.stderr)\n\n\ndef rmfile(path):\n try:\n os.remove(path)\n except OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n\n\ndef rmdir(_dir):\n try:\n shutil.rmtree(_dir)\n except OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n\n\nclass TestObjectTracking2DDeepSortLearner(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.temp_dir = os.path.join(\"tests\", \"sources\", \"tools\",\n \"perception\", \"object_tracking_2d\",\n \"deep_sort\",\n \"deep_sort_temp\")\n\n cls.train_split_paths = {\n \"nano_mot20\": os.path.join(\n \".\", \"src\", \"opendr\", \"perception\", \"object_tracking_2d\",\n \"datasets\", \"splits\", \"nano_mot20.train\"\n )\n }\n\n cls.model_names = [\n \"deep_sort\",\n ]\n\n cls.mot_dataset_path = MotDataset.download_nano_mot20(\n os.path.join(cls.temp_dir, \"mot_dataset\"), True\n ).path\n cls.market1501_dataset_path = Market1501Dataset.download_nano_market1501(\n os.path.join(cls.temp_dir, \"market1501_dataset\"), True\n ).path\n\n print(\"Dataset downloaded\", file=sys.stderr)\n\n for model_name in cls.model_names:\n ObjectTracking2DDeepSortLearner.download(\n model_name, cls.temp_dir\n )\n\n print(\"Models downloaded\", file=sys.stderr)\n\n @classmethod\n def tearDownClass(cls):\n # Clean up downloaded files\n\n rmdir(os.path.join(cls.temp_dir))\n\n def test_fit(self):\n\n def test_model(name):\n dataset = Market1501Dataset(self.market1501_dataset_path)\n\n learner = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n\n starting_param = list(learner.tracker.deepsort.extractor.net.parameters())[0].clone()\n\n learner.fit(\n dataset,\n epochs=2,\n val_epochs=2,\n verbose=True,\n )\n new_param = list(learner.tracker.deepsort.extractor.net.parameters())[0].clone()\n self.assertFalse(torch.equal(starting_param, new_param))\n\n print(\"Fit\", name, \"ok\", file=sys.stderr)\n\n for name in self.model_names:\n test_model(name)\n\n def test_fit_iterator(self):\n def test_model(name):\n dataset = Market1501DatasetIterator(\n os.path.join(self.market1501_dataset_path, \"bounding_box_train\"),\n )\n eval_dataset = Market1501DatasetIterator(\n os.path.join(self.market1501_dataset_path, \"bounding_box_test\"),\n )\n\n learner = ObjectTracking2DDeepSortLearner(\n checkpoint_after_iter=3,\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n\n starting_param = list(learner.tracker.deepsort.extractor.net.parameters())[0].clone()\n\n learner.fit(\n dataset,\n epochs=2,\n val_dataset=eval_dataset,\n val_epochs=2,\n verbose=True,\n )\n new_param = list(learner.tracker.deepsort.extractor.net.parameters())[0].clone()\n self.assertFalse(torch.equal(starting_param, new_param))\n\n print(\"Fit iterator\", name, \"ok\", file=sys.stderr)\n\n for name in self.model_names:\n test_model(name)\n\n def test_eval(self):\n def test_model(name):\n model_path = os.path.join(self.temp_dir, name)\n train_split_paths = {\n \"nano_mot20\": os.path.join(\n \".\", \"src\", \"opendr\", \"perception\", \"object_tracking_2d\",\n \"datasets\", \"splits\", \"nano_mot20.train\"\n )\n }\n\n dataset = RawMotWithDetectionsDatasetIterator(\n self.mot_dataset_path,\n train_split_paths\n )\n\n learner = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n learner.load(model_path, verbose=True)\n result = learner.eval(dataset)\n\n self.assertGreater(len(result[\"mota\"]), 0)\n\n for name in self.model_names:\n test_model(name)\n\n def test_infer(self):\n def test_model(name):\n model_path = os.path.join(self.temp_dir, name)\n train_split_paths = {\n \"nano_mot20\": os.path.join(\n \".\", \"src\", \"opendr\", \"perception\", \"object_tracking_2d\",\n \"datasets\", \"splits\", \"nano_mot20.train\"\n )\n }\n\n dataset = RawMotWithDetectionsDatasetIterator(\n self.mot_dataset_path,\n train_split_paths\n )\n\n learner = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n learner.load(model_path, verbose=True)\n result = learner.infer(dataset[0][0], 1)\n\n self.assertTrue(len(result) > 0)\n\n learner.reset()\n\n result = learner.infer([\n dataset[0][0],\n dataset[1][0],\n ])\n\n self.assertTrue(len(result) == 2)\n self.assertTrue(len(result[0]) > 0)\n\n for name in self.model_names:\n test_model(name)\n\n def test_save(self):\n def test_model(name):\n model_path = os.path.join(self.temp_dir, \"test_save_\" + name)\n save_path = os.path.join(model_path, \"save\")\n\n learner = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n\n learner.save(save_path, True)\n starting_param_1 = list(learner.tracker.deepsort.extractor.net.parameters())[0].clone()\n\n learner2 = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n learner2.load(save_path)\n\n new_param = list(learner2.tracker.deepsort.extractor.net.parameters())[0].clone()\n self.assertTrue(torch.equal(starting_param_1, new_param))\n\n for name in self.model_names:\n test_model(name)\n\n def test_optimize(self):\n def test_model(name):\n model_path = os.path.join(self.temp_dir, name)\n train_split_paths = {\n \"nano_mot20\": os.path.join(\n \".\", \"src\", \"opendr\", \"perception\", \"object_tracking_2d\",\n \"datasets\", \"splits\", \"nano_mot20.train\"\n )\n }\n\n dataset = RawMotWithDetectionsDatasetIterator(\n self.mot_dataset_path,\n train_split_paths\n )\n\n learner = ObjectTracking2DDeepSortLearner(\n temp_path=self.temp_dir,\n device=DEVICE,\n )\n learner.load(model_path, verbose=True)\n learner.optimize()\n result = learner.eval(dataset)\n\n self.assertGreater(len(result[\"mota\"]), 0)\n\n for name in self.model_names:\n test_model(name)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"torch.equal"
]
] |
maxiaoba/rlk | [
"3e23473f6bbc59552b6b2bcd97245e024d7ca95d",
"3e23473f6bbc59552b6b2bcd97245e024d7ca95d",
"3e23473f6bbc59552b6b2bcd97245e024d7ca95d",
"3e23473f6bbc59552b6b2bcd97245e024d7ca95d"
] | [
"tests/DifferentialGame/masac_gnn_gaussian.py",
"tests/Simple/SupLstm/visualize_policy.py",
"tests/MultiDifferentialGame/r2g_gnn11_share_gaussian.py",
"tests/Particle/coma_gaussian.py"
] | [
"import copy\nimport torch.nn as nn\nfrom rlkit.launchers.launcher_util import setup_logger\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.core.ma_eval_util import get_generic_ma_path_information\n\ndef experiment(variant):\n num_agent = variant['num_agent']\n from differential_game import DifferentialGame\n expl_env = DifferentialGame(game_name=args.exp_name)\n eval_env = DifferentialGame(game_name=args.exp_name)\n obs_dim = eval_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n\n from rlkit.torch.networks.graph_builders import FullGraphBuilder\n graph_builder1 = FullGraphBuilder(\n input_node_dim=obs_dim+action_dim,\n num_node=num_agent,\n contain_self_loop=False)\n from rlkit.torch.networks.gnn_networks import GNNNet\n gnn1 = GNNNet(\n graph_builder1,\n node_dim=variant['qf_kwargs']['hidden_dim'],\n conv_type=variant['qf_kwargs']['conv_type'],\n num_conv_layers=1,\n hidden_activation='relu',\n output_activation='relu',\n )\n qf1 = nn.Sequential(\n gnn1,\n nn.Linear(variant['qf_kwargs']['hidden_dim'],1)\n )\n target_qf1 = copy.deepcopy(qf1)\n\n from rlkit.torch.networks.graph_builders import FullGraphBuilder\n graph_builder2 = FullGraphBuilder(\n input_node_dim=obs_dim+action_dim,\n num_node=num_agent,\n contain_self_loop=False)\n from rlkit.torch.networks.gnn_networks import GNNNet\n gnn2 = GNNNet(\n graph_builder2,\n node_dim=variant['qf_kwargs']['hidden_dim'],\n conv_type=variant['qf_kwargs']['conv_type'],\n num_conv_layers=1,\n hidden_activation='relu',\n output_activation='relu',\n )\n qf2 = nn.Sequential(\n gnn2,\n nn.Linear(variant['qf_kwargs']['hidden_dim'],1)\n )\n target_qf2 = copy.deepcopy(qf2)\n\n policy_n, eval_policy_n, expl_policy_n = [], [], []\n for i in range(num_agent):\n from rlkit.torch.networks.layers import SplitLayer\n policy = nn.Sequential(\n nn.Linear(obs_dim,variant['policy_kwargs']['hidden_dim']),\n nn.ReLU(),\n nn.Linear(variant['policy_kwargs']['hidden_dim'],variant['policy_kwargs']['hidden_dim']),\n nn.ReLU(),\n SplitLayer(layers=[nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim),\n nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim)])\n )\n from rlkit.torch.policies.tanh_gaussian_policy import TanhGaussianPolicy\n policy = TanhGaussianPolicy(module=policy)\n from rlkit.torch.policies.make_deterministic import MakeDeterministic\n eval_policy = MakeDeterministic(policy)\n from rlkit.exploration_strategies.base import PolicyWrappedWithExplorationStrategy\n if variant['random_exploration']:\n from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\n expl_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=EpsilonGreedy(expl_env.action_space, prob_random_action=1.0),\n policy=policy,\n )\n else:\n expl_policy = policy\n\n policy_n.append(policy)\n eval_policy_n.append(eval_policy)\n expl_policy_n.append(expl_policy)\n\n from rlkit.samplers.data_collector.ma_path_collector import MAMdpPathCollector\n eval_path_collector = MAMdpPathCollector(eval_env, eval_policy_n)\n expl_path_collector = MAMdpPathCollector(expl_env, expl_policy_n)\n\n from rlkit.data_management.ma_env_replay_buffer import MAEnvReplayBuffer\n replay_buffer = MAEnvReplayBuffer(variant['replay_buffer_size'], expl_env, num_agent=num_agent)\n\n from rlkit.torch.masac.masac_gnn import MASACGNNTrainer\n trainer = MASACGNNTrainer(\n env = expl_env,\n qf1=qf1,\n target_qf1=target_qf1,\n qf2=qf2,\n target_qf2=target_qf2,\n policy_n=policy_n,\n **variant['trainer_kwargs']\n )\n\n from rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n log_path_function=get_generic_ma_path_information,\n **variant['algorithm_kwargs']\n )\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_name', type=str, default='zero_sum')\n parser.add_argument('--log_dir', type=str, default='MASACGNNGaussian')\n parser.add_argument('--conv', type=str, default='GSage')\n parser.add_argument('--hidden', type=int, default=16)\n parser.add_argument('--oa', action='store_true', default=False) # online action\n parser.add_argument('--snl', action='store_true', default=False) # sum n loss\n parser.add_argument('--re', action='store_true', default=False) # random exploration\n parser.add_argument('--alpha', type=float, default=None) # init alpha\n parser.add_argument('--fa', action='store_true', default=False) # fix alpha\n parser.add_argument('--lr', type=float, default=None)\n parser.add_argument('--bs', type=int, default=None)\n parser.add_argument('--epoch', type=int, default=None)\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--snapshot_mode', type=str, default=\"gap_and_last\")\n parser.add_argument('--snapshot_gap', type=int, default=500)\n args = parser.parse_args()\n import os.path as osp\n pre_dir = './Data/'+args.exp_name\n main_dir = args.log_dir\\\n +args.conv\\\n +('hidden'+str(args.hidden))\\\n +('oa' if args.oa else '')\\\n +('snl' if args.snl else '')\\\n +('re' if args.re else '')\\\n +(('alpha'+str(args.alpha)) if args.alpha else '')\\\n +('fa' if args.fa else '')\\\n +(('lr'+str(args.lr)) if args.lr else '')\\\n +(('bs'+str(args.bs)) if args.bs else '')\n log_dir = osp.join(pre_dir,main_dir,'seed'+str(args.seed))\n # noinspection PyTypeChecker\n variant = dict(\n num_agent=2,\n random_exploration=args.re,\n algorithm_kwargs=dict(\n num_epochs=(args.epoch if args.epoch else 100),\n num_eval_steps_per_epoch=100,\n num_trains_per_train_loop=100,\n num_expl_steps_per_train_loop=100,\n min_num_steps_before_training=100,\n max_path_length=100,\n batch_size=(args.bs if args.bs else 256),\n ),\n trainer_kwargs=dict(\n use_soft_update=True,\n tau=1e-2,\n discount=0.99,\n qf_learning_rate=(args.lr if args.lr else 1e-3),\n policy_learning_rate=(args.lr if args.lr else 1e-4),\n online_action=args.oa,\n sum_n_loss=args.snl,\n init_alpha=(args.alpha if args.alpha else 1.),\n use_automatic_entropy_tuning=(not args.fa),\n ),\n qf_kwargs=dict(\n conv_type=args.conv,\n hidden_dim=args.hidden,\n ),\n policy_kwargs=dict(\n hidden_dim=args.hidden,\n ),\n replay_buffer_size=int(1E6),\n )\n import os\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n with open(osp.join(log_dir,'variant.json'),'w') as out_json:\n import json\n json.dump(variant,out_json,indent=2)\n import sys\n cmd_input = 'python ' + ' '.join(sys.argv) + '\\n'\n with open(osp.join(log_dir, 'cmd_input.txt'), 'a') as f:\n f.write(cmd_input)\n setup_logger(args.exp_name+'/'+main_dir, variant=variant,\n snapshot_mode=args.snapshot_mode, snapshot_gap=args.snapshot_gap,\n log_dir=log_dir)\n import numpy as np\n import torch\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n # ptu.set_gpu_mode(True) # optionally set the GPU (default=False)\n experiment(variant)\n",
"import torch\nimport numpy as np\nimport time\nimport pdb\nfrom rlkit.torch.core import eval_np, np_ify\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('--exp_name', type=str, default='SimpleSupLSTM')\nparser.add_argument('--extra_name', type=str, default='obs1int10')\nparser.add_argument('--log_dir', type=str, default='SupLSTMlayer1hidden16')\nparser.add_argument('--file', type=str, default='params')\nparser.add_argument('--epoch', type=int, default=None)\nparser.add_argument('--seed', type=int, default=0)\nargs = parser.parse_args()\n\npre_dir = './Data/'+args.exp_name+args.extra_name\nimport os\ndata_path = '{}/{}/seed{}/{}.pkl'.format(pre_dir,args.log_dir,args.seed,args.file)\ndata = torch.load(data_path,map_location='cpu')\n\npolicy = data['trainer/policy']\n# from rlkit.torch.policies.make_deterministic import MakeDeterministic\n# policy = MakeDeterministic(policy)\n\nif 'trainer/sup_learner' in data.keys():\n\tsup_learner = data['trainer/sup_learner']\nelse:\n\tsup_learner = None\n\nimport sys\nimport json\nwith open('{}/{}/seed{}/variant.json'.format(pre_dir,args.log_dir,args.seed)) as f:\n variant = json.load(f)\nfrom simple_sup_lstm import SimpleSupLSTMEnv\nenv = SimpleSupLSTMEnv(**variant['env_kwargs'])\no = env.reset()\npolicy.reset()\n\nmax_path_length = 10\npath_length = 0\ndone = False\nc_r = 0.\nwhile True:\n\tpath_length += 1\n\ta, agent_info = policy.get_action(o)\n\to, r, done, env_info = env.step(a)\n\n\tif sup_learner:\n\t\tintentions = eval_np(sup_learner, o[None,:])\n\telif hasattr(policy, 'sup_prob'):\n\t\tintentions = eval_np(policy.sup_prob, o[None,:])[0]\n\telse:\n\t\tintentions = None\n\n\tc_r += r\n\tprint(\"step: \",path_length)\n\tprint(\"intentions: \",intentions)\n\tprint(\"a: \",a)\n\tprint(\"env_info: \",env_info)\n\tprint('r: ',r)\n\tprint(done)\n\t# pdb.set_trace()\n\ttime.sleep(0.1)\n\tif path_length > max_path_length or done:\n\t\tprint('c_r: ',c_r)\n\t\tpath_length = 0\n\t\tdone = False\n\t\tc_r = 0.\n\t\tpdb.set_trace()\n\t\to = env.reset()\n\t\tpolicy.reset()",
"import copy\nimport torch.nn as nn\nfrom rlkit.launchers.launcher_util import setup_logger\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.core.ma_eval_util import get_generic_ma_path_information\n\ndef experiment(variant):\n from multi_differential_game import MultiDifferentialGame\n expl_env = MultiDifferentialGame(**variant['env_kwargs'])\n eval_env = MultiDifferentialGame(**variant['env_kwargs'])\n num_agent = expl_env.agent_num\n obs_dim = eval_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n\n from rlkit.torch.networks.graph_builders import FullGraphBuilder\n graph_builder_obs = FullGraphBuilder(\n input_node_dim=obs_dim,\n num_node=num_agent,\n batch_size=variant['algorithm_kwargs']['batch_size'],\n contain_self_loop=False)\n graph_builder_eval = FullGraphBuilder(\n input_node_dim=graph_builder_obs.output_node_dim,\n num_node=num_agent,\n batch_size=variant['algorithm_kwargs']['batch_size'],\n contain_self_loop=False)\n if variant['concat_emb']:\n gnn_out_dim = int(obs_dim + variant['graph_kwargs']['node_dim']*variant['graph_kwargs']['num_conv_layers'])\n else:\n gnn_out_dim = variant['graph_kwargs']['node_dim']\n from rlkit.torch.networks.networks import FlattenMlp\n post_mlp1 = FlattenMlp(input_size=gnn_out_dim,\n output_size=1,\n hidden_sizes=[variant['qf_kwargs']['hidden_dim']]*(variant['qf_kwargs']['num_layer']-1),\n hidden_activation=nn.LeakyReLU(negative_slope=0.2),\n )\n from rlkit.torch.networks.graph_r2g_qnet import R2GQNet\n qf1 = R2GQNet(\n obs_graph_builder=graph_builder_obs,\n eval_graph_builder=graph_builder_eval,\n obs_dim=obs_dim,\n action_dim=action_dim, \n post_mlp=post_mlp1,\n normalize_emb=False,\n output_activation=None,\n concat_emb=variant['concat_emb'],\n **variant['graph_kwargs'],\n )\n target_qf1 = copy.deepcopy(qf1)\n\n post_mlp2 = FlattenMlp(input_size=gnn_out_dim,\n output_size=1,\n hidden_sizes=[variant['qf_kwargs']['hidden_dim']]*(variant['qf_kwargs']['num_layer']-1),\n hidden_activation=nn.LeakyReLU(negative_slope=0.2),\n )\n from rlkit.torch.networks.graph_r2g_qnet import R2GQNet\n qf2 = R2GQNet(\n obs_graph_builder=graph_builder_obs,\n eval_graph_builder=graph_builder_eval,\n obs_dim=obs_dim,\n action_dim=action_dim, \n post_mlp=post_mlp2,\n normalize_emb=False,\n output_activation=None,\n concat_emb=variant['concat_emb'],\n **variant['graph_kwargs'],\n )\n target_qf2 = copy.deepcopy(qf2)\n\n graph_builder_ca = FullGraphBuilder(\n input_node_dim=obs_dim+action_dim,\n num_node=num_agent,\n batch_size=variant['algorithm_kwargs']['batch_size'],\n contain_self_loop=False)\n from rlkit.torch.networks.gnn_networks import GNNNet\n cgca = GNNNet(\n graph_builder_ca,\n hidden_activation='lrelu0.2',\n output_activation='lrelu0.2',\n **variant['graph_kwargs'],\n )\n from rlkit.torch.networks.networks import FlattenMlp\n from rlkit.torch.networks.layers import SplitLayer\n from rlkit.torch.policies.tanh_gaussian_policy import TanhGaussianPolicy\n cactor = nn.Sequential(\n cgca,\n FlattenMlp(input_size=variant['graph_kwargs']['node_dim'],\n output_size=variant['cactor_kwargs']['hidden_dim'],\n hidden_sizes=[variant['cactor_kwargs']['hidden_dim']]*(variant['cactor_kwargs']['num_layer']-1),\n hidden_activation=nn.LeakyReLU(negative_slope=0.2),\n output_activation=nn.LeakyReLU(negative_slope=0.2),\n ),\n nn.LeakyReLU(negative_slope=0.2),\n SplitLayer(layers=[nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim),\n nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim)])\n )\n cactor = TanhGaussianPolicy(module=cactor)\n\n graph_builder_policy = FullGraphBuilder(\n input_node_dim=obs_dim,\n num_node=num_agent,\n batch_size=variant['algorithm_kwargs']['batch_size'],\n contain_self_loop=False)\n shared_gnn = GNNNet(\n graph_builder_policy,\n hidden_activation='lrelu0.2',\n output_activation='lrelu0.2',\n **variant['graph_kwargs'],\n )\n policy_n, expl_policy_n, eval_policy_n = [], [], []\n for i in range(num_agent):\n policy = nn.Sequential(\n FlattenMlp(input_size=variant['graph_kwargs']['node_dim'],\n output_size=variant['policy_kwargs']['hidden_dim'],\n hidden_sizes=[variant['policy_kwargs']['hidden_dim']]*(variant['policy_kwargs']['num_layer']-1),\n hidden_activation=nn.LeakyReLU(negative_slope=0.2),\n output_activation=nn.LeakyReLU(negative_slope=0.2),\n ),\n SplitLayer(layers=[nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim),\n nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim)])\n )\n policy = TanhGaussianPolicy(module=policy)\n from rlkit.torch.policies.make_deterministic import MakeDeterministic\n eval_policy = MakeDeterministic(policy)\n if variant['random_exploration']:\n from rlkit.exploration_strategies.base import PolicyWrappedWithExplorationStrategy\n from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\n expl_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=EpsilonGreedy(expl_env.action_space, prob_random_action=1.0),\n policy=policy,\n )\n else:\n expl_policy = policy\n \n policy_n.append(policy)\n expl_policy_n.append(expl_policy)\n eval_policy_n.append(eval_policy)\n \n from rlkit.samplers.data_collector.ma_path_collector import MAMdpPathCollector\n eval_path_collector = MAMdpPathCollector(eval_env, eval_policy_n, shared_encoder=shared_gnn)\n expl_path_collector = MAMdpPathCollector(expl_env, expl_policy_n, shared_encoder=shared_gnn)\n\n from rlkit.data_management.ma_env_replay_buffer import MAEnvReplayBuffer\n replay_buffer = MAEnvReplayBuffer(variant['replay_buffer_size'], expl_env, num_agent=num_agent)\n\n from rlkit.torch.r2g.r2g_gnn11 import R2GGNNTrainer\n trainer = R2GGNNTrainer(\n env=expl_env,\n qf1=qf1,\n target_qf1=target_qf1,\n qf2=qf2,\n target_qf2=target_qf2,\n cactor=cactor,\n policy_n=policy_n,\n shared_gnn=shared_gnn,\n **variant['trainer_kwargs']\n )\n\n from rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n log_path_function=get_generic_ma_path_information,\n **variant['algorithm_kwargs']\n )\n algorithm.to(ptu.device)\n # save init params\n from rlkit.core import logger\n snapshot = algorithm._get_snapshot()\n file_name = osp.join(logger._snapshot_dir, 'itr_-1.pkl')\n torch.save(snapshot, file_name)\n\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_name', type=str, default='zero_sum')\n parser.add_argument('--num_ag', type=int, default=2)\n parser.add_argument('--gpu', type=int, default=None)\n parser.add_argument('--log_dir', type=str, default='R2GGNN11ShareGaussian')\n parser.add_argument('--conv', type=str, default='GSage')\n parser.add_argument('--layer', type=int, default=2)\n parser.add_argument('--hidden', type=int, default=16)\n parser.add_argument('--glayer', type=int, default=2)\n parser.add_argument('--hnode', type=int, default=16)\n parser.add_argument('--sc', action='store_true', default=False) # skip connection between gnn layers\n parser.add_argument('--ceb', action='store_true', default=False) # concat gnn embeddings from each layer\n parser.add_argument('--ce', action='store_true', default=False) # cactor entropy\n parser.add_argument('--er', action='store_true', default=False) # entropy reward\n parser.add_argument('--re', action='store_true', default=False) # random exploration\n parser.add_argument('--alpha', type=float, default=None) # init alpha\n parser.add_argument('--fa', action='store_true', default=False) # fix alpha\n parser.add_argument('--dcig', action='store_true', default=False) # deterministic cactor in graph\n parser.add_argument('--dna', action='store_true', default=False) # deterministic next action\n parser.add_argument('--lr', type=float, default=None)\n parser.add_argument('--bs', type=int, default=None)\n parser.add_argument('--epoch', type=int, default=None)\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--snapshot_mode', type=str, default=\"gap_and_last\")\n parser.add_argument('--snapshot_gap', type=int, default=100)\n args = parser.parse_args()\n import os.path as osp\n pre_dir = './Data/'+args.exp_name+'_p'+str(args.num_ag)\n main_dir = args.log_dir\\\n +args.conv\\\n +('layer'+str(args.layer))\\\n +('hidden'+str(args.hidden))\\\n +('glayer'+str(args.glayer))\\\n +('hnode'+str(args.hnode))\\\n +('sc' if args.sc else '')\\\n +('ceb' if args.ceb else '')\\\n +('ce' if args.ce else '')\\\n +('er' if args.er else '')\\\n +('re' if args.re else '')\\\n +(('alpha'+str(args.alpha)) if args.alpha else '')\\\n +('fa' if args.fa else '')\\\n +('dcig' if args.dcig else '')\\\n +('dna' if args.dna else '')\\\n +(('lr'+str(args.lr)) if args.lr else '')\\\n +(('bs'+str(args.bs)) if args.bs else '')\n log_dir = osp.join(pre_dir,main_dir,'seed'+str(args.seed))\n # noinspection PyTypeChecker\n variant = dict(\n random_exploration=args.re,\n env_kwargs=dict(\n game_name=args.exp_name,\n agent_num=args.num_ag,\n ),\n algorithm_kwargs=dict(\n num_epochs=(args.epoch+1 if args.epoch else 101),\n num_eval_steps_per_epoch=100,\n num_trains_per_train_loop=100*args.num_ag,\n num_expl_steps_per_train_loop=100*args.num_ag,\n min_num_steps_before_training=100*args.num_ag,\n max_path_length=100,\n batch_size=(args.bs if args.bs else 256),\n ),\n trainer_kwargs=dict(\n use_soft_update=True,\n tau=1e-2,\n discount=0.99,\n qf_learning_rate=(args.lr if args.lr else 1e-3),\n cactor_learning_rate=(args.lr if args.lr else 1e-4),\n policy_learning_rate=(args.lr if args.lr else 1e-4),\n use_entropy_loss=True,\n use_entropy_reward=args.er,\n use_cactor_entropy_loss=args.ce,\n init_alpha=(args.alpha if args.alpha else 1.),\n use_automatic_entropy_tuning=(not args.fa),\n deterministic_cactor_in_graph=args.dcig,\n deterministic_next_action=args.dna,\n ),\n graph_kwargs=dict(\n conv_type=args.conv,\n node_dim=args.hnode,\n num_conv_layers=args.glayer,\n skip_connect=args.sc,\n ),\n concat_emb=args.ceb,\n qf_kwargs=dict(\n hidden_dim=args.hidden,\n num_layer=args.layer,\n ),\n cactor_kwargs=dict(\n hidden_dim=args.hidden,\n num_layer=args.layer,\n ),\n policy_kwargs=dict(\n hidden_dim=args.hidden,\n num_layer=args.layer,\n ),\n replay_buffer_size=int(1E6),\n )\n import os\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n with open(osp.join(log_dir,'variant.json'),'w') as out_json:\n import json\n json.dump(variant,out_json,indent=2)\n import sys\n cmd_input = 'python ' + ' '.join(sys.argv) + '\\n'\n with open(osp.join(log_dir, 'cmd_input.txt'), 'a') as f:\n f.write(cmd_input)\n setup_logger(args.exp_name+'/'+main_dir, variant=variant,\n snapshot_mode=args.snapshot_mode, snapshot_gap=args.snapshot_gap,\n log_dir=log_dir)\n import numpy as np\n import torch\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if isinstance(args.gpu, int):\n print('using gpu ',args.gpu)\n ptu.set_gpu_mode(True, gpu_id=args.gpu)\n experiment(variant)\n",
"import copy\nimport torch.nn as nn\nfrom rlkit.launchers.launcher_util import setup_logger\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.core.ma_eval_util import get_generic_ma_path_information\n\ndef experiment(variant):\n import sys\n sys.path.append(\"./multiagent-particle-envs\")\n from make_env import make_env\n from particle_env_wrapper import ParticleEnv\n expl_env = ParticleEnv(make_env(args.exp_name,discrete_action_space=False,world_args=variant['world_args']))\n eval_env = ParticleEnv(make_env(args.exp_name,discrete_action_space=False,world_args=variant['world_args']))\n num_agent = expl_env.num_agent\n obs_dim = eval_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n\n policy_n, qf_n = [], []\n policy_optimizer_n, qf_optimizer_n = None, None\n for i in range(num_agent):\n from rlkit.torch.networks.networks import FlattenMlp\n from rlkit.torch.networks.layers import SplitLayer\n policy = nn.Sequential(\n FlattenMlp(input_size=obs_dim,\n output_size=variant['policy_kwargs']['hidden_dim'],\n hidden_sizes=[variant['policy_kwargs']['hidden_dim']]*(variant['policy_kwargs']['num_layer']-1),\n ),\n SplitLayer(layers=[nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim),\n nn.Linear(variant['policy_kwargs']['hidden_dim'],action_dim)])\n )\n from rlkit.torch.policies.tanh_gaussian_policy import TanhGaussianPolicy\n policy = TanhGaussianPolicy(module=policy,return_raw_action=True)\n \n qf = FlattenMlp(\n input_size=(obs_dim*num_agent+action_dim*num_agent),\n output_size=1,\n hidden_sizes=[variant['qf_kwargs']['hidden_dim']]*variant['qf_kwargs']['num_layer'],\n )\n\n policy_n.append(policy)\n qf_n.append(qf)\n\n from rlkit.torch.policies.make_deterministic import MakeDeterministic\n eval_policy_n = [MakeDeterministic(policy) for policy in policy_n]\n expl_policy_n = policy_n\n\n from rlkit.samplers.data_collector.ma_path_collector import MAMdpPathCollector\n eval_path_collector = MAMdpPathCollector(eval_env, eval_policy_n)\n expl_path_collector = MAMdpPathCollector(expl_env, expl_policy_n, collect_raw_actions=True)\n\n from rlkit.torch.coma.coma import COMATrainer\n trainer = COMATrainer(\n env = expl_env,\n policy_n=policy_n,\n qf_n=qf_n,\n policy_optimizer_n=policy_optimizer_n,\n qf_optimizer_n=qf_optimizer_n,\n **variant['trainer_kwargs']\n )\n\n from rlkit.torch.torch_rl_algorithm import TorchOnlineRLAlgorithm\n algorithm = TorchOnlineRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n log_path_function=get_generic_ma_path_information,\n **variant['algorithm_kwargs']\n )\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_name', type=str, default='simple')\n parser.add_argument('--boundary', action='store_true', default=False)\n parser.add_argument('--num_ag', type=int, default=None)\n parser.add_argument('--num_adv', type=int, default=None)\n parser.add_argument('--num_l', type=int, default=None)\n parser.add_argument('--mpl', type=int, default=25) # max path length\n parser.add_argument('--log_dir', type=str, default='COMAGaussian')\n parser.add_argument('--layer', type=int, default=2)\n parser.add_argument('--hidden', type=int, default=64)\n parser.add_argument('--mc', type=int, default=1)\n parser.add_argument('--em', type=str, default=None) # entropy method\n parser.add_argument('--ec', type=float, default=0.) # entropy coefficient\n parser.add_argument('--lr', type=float, default=None)\n parser.add_argument('--bs', type=int, default=None)\n parser.add_argument('--epoch', type=int, default=None)\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--snapshot_mode', type=str, default=\"gap_and_last\")\n parser.add_argument('--snapshot_gap', type=int, default=500)\n args = parser.parse_args()\n import os.path as osp\n pre_dir = './Data/'+args.exp_name\\\n +('bd' if args.boundary else '')\\\n +(('ag'+str(args.num_ag)) if args.num_ag else '')\\\n +(('adv'+str(args.num_adv)) if args.num_adv else '')\\\n +(('l'+str(args.num_l)) if args.num_l else '')\\\n +'_mpl'+str(args.mpl)\n main_dir = args.log_dir\\\n +('layer'+str(args.layer))\\\n +('hidden'+str(args.hidden))\\\n +('mc'+str(args.mc))\\\n +(('em'+str(args.em)+'ec'+str(args.ec)) if args.em else '')\\\n +(('lr'+str(args.lr)) if args.lr else '')\\\n +(('bs'+str(args.bs)) if args.bs else '')\n log_dir = osp.join(pre_dir,main_dir,'seed'+str(args.seed))\n # noinspection PyTypeChecker\n variant = dict(\n world_args=dict(\n num_agents=args.num_ag,\n num_adversaries=args.num_adv,\n num_landmarks=args.num_l,\n boundary=([[-1.,-1.],[1.,1.]] if args.boundary else None)\n ),\n algorithm_kwargs=dict(\n num_epochs=(args.epoch+1 if args.epoch else 1001),\n num_eval_steps_per_epoch=1000,\n num_trains_per_train_loop=1,\n num_expl_steps_per_train_loop=1000,\n max_path_length=args.mpl,\n ),\n trainer_kwargs=dict(\n discount=0.99,\n qf_learning_rate=(args.lr if args.lr else 1e-3),\n policy_learning_rate=(args.lr if args.lr else 1e-4),\n max_path_length=args.mpl,\n entropy_method=args.em,\n policy_ent_coeff=args.ec,\n batch_size=(args.bs if args.bs else 256),\n mc_num=args.mc,\n ),\n qf_kwargs=dict(\n num_layer=args.layer,\n hidden_dim=args.hidden,\n ),\n policy_kwargs=dict(\n num_layer=args.layer,\n hidden_dim=args.hidden,\n ),\n )\n import os\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n with open(osp.join(log_dir,'variant.json'),'w') as out_json:\n import json\n json.dump(variant,out_json,indent=2)\n import sys\n cmd_input = 'python ' + ' '.join(sys.argv) + '\\n'\n with open(osp.join(log_dir, 'cmd_input.txt'), 'a') as f:\n f.write(cmd_input)\n setup_logger(args.exp_name+'/'+main_dir, variant=variant,\n snapshot_mode=args.snapshot_mode, snapshot_gap=args.snapshot_gap,\n log_dir=log_dir,text_log_file=None)\n import numpy as np\n import torch\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n # ptu.set_gpu_mode(True) # optionally set the GPU (default=False)\n experiment(variant)\n"
] | [
[
"torch.nn.Linear",
"torch.nn.ReLU",
"torch.manual_seed",
"numpy.random.seed"
],
[
"torch.load"
],
[
"torch.nn.Linear",
"torch.manual_seed",
"torch.save",
"numpy.random.seed",
"torch.nn.LeakyReLU"
],
[
"torch.nn.Linear",
"torch.manual_seed",
"numpy.random.seed"
]
] |
jrsassen/megaman | [
"faccaf267aad0a8b18ec8a705735fd9dd838ca1e"
] | [
"megaman/geometry/tests/test_adjacency.py"
] | [
"# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE\n\nfrom nose import SkipTest\n\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_raises, assert_equal\nfrom scipy.sparse import isspmatrix\nfrom scipy.spatial.distance import cdist, pdist, squareform\n\nfrom megaman.geometry import (Geometry, compute_adjacency_matrix, Adjacency,\n adjacency_methods)\n\n\ntry:\n import pyflann as pyf\n NO_PYFLANN = False\nexcept ImportError:\n NO_PYFLANN = True\n\n\ndef test_adjacency_methods():\n assert_equal(set(adjacency_methods()),\n {'auto', 'pyflann', 'ball_tree',\n 'cyflann', 'brute', 'kd_tree'})\n\n\ndef test_adjacency_input_validation():\n X = np.random.rand(20, 3)\n # need to specify radius or n_neighbors\n assert_raises(ValueError, compute_adjacency_matrix, X)\n # cannot specify both radius and n_neighbors\n assert_raises(ValueError, compute_adjacency_matrix, X,\n radius=1, n_neighbors=10)\n\n\ndef test_adjacency():\n rng = np.random.RandomState(36)\n X = rng.rand(100, 3)\n Gtrue = {}\n\n exact_methods = [m for m in Adjacency.methods()\n if not m.endswith('flann')]\n\n def check_kneighbors(n_neighbors, method):\n if method == 'pyflann' and NO_PYFLANN:\n raise SkipTest(\"pyflann not installed\")\n\n G = compute_adjacency_matrix(X, method=method,\n n_neighbors=n_neighbors)\n assert isspmatrix(G)\n assert G.shape == (X.shape[0], X.shape[0])\n if method in exact_methods:\n assert_allclose(G.toarray(), Gtrue[n_neighbors].toarray())\n\n def check_radius(radius, method):\n if method == 'pyflann' and NO_PYFLANN:\n raise SkipTest(\"pyflann not installed\")\n\n G = compute_adjacency_matrix(X, method=method,\n radius=radius)\n assert isspmatrix(G)\n assert G.shape == (X.shape[0], X.shape[0])\n if method in exact_methods:\n assert_allclose(G.toarray(), Gtrue[radius].toarray())\n\n for n_neighbors in [5, 10, 15]:\n Gtrue[n_neighbors] = compute_adjacency_matrix(X, method='brute',\n n_neighbors=n_neighbors)\n for method in Adjacency.methods():\n yield check_kneighbors, n_neighbors, method\n\n for radius in [0.1, 0.5, 1.0]:\n Gtrue[radius] = compute_adjacency_matrix(X, method='brute',\n radius=radius)\n for method in Adjacency.methods():\n yield check_radius, radius, method\n\n\ndef test_unknown_method():\n X = np.arange(20).reshape((10, 2))\n assert_raises(ValueError, compute_adjacency_matrix, X, 'foo')\n\n\ndef test_all_methods_close():\n rand = np.random.RandomState(36)\n X = rand.randn(10, 2)\n D_true = squareform(pdist(X))\n D_true[D_true > 0.5] = 0\n\n def check_method(method):\n kwargs = {}\n if method == 'pyflann':\n try:\n import pyflann as pyf\n except ImportError:\n raise SkipTest(\"pyflann not installed.\")\n flindex = pyf.FLANN()\n flindex.build_index(X, algorithm='kmeans',\n target_precision=0.9)\n kwargs['flann_index'] = flindex\n this_D = compute_adjacency_matrix(X, method=method, radius=0.5,\n **kwargs)\n assert_allclose(this_D.toarray(), D_true, rtol=1E-5)\n\n for method in ['auto', 'cyflann', 'pyflann', 'brute']:\n yield check_method, method\n\n\ndef test_custom_adjacency():\n class CustomAdjacency(Adjacency):\n name = \"custom\"\n def adjacency_graph(self, X):\n return squareform(pdist(X))\n\n rand = np.random.RandomState(42)\n X = rand.rand(10, 2)\n D = compute_adjacency_matrix(X, method='custom', radius=1)\n assert_allclose(D, cdist(X, X))\n\n Adjacency._remove_from_registry(\"custom\")\n\ndef test_cyflann_index_type():\n rand = np.random.RandomState(36)\n X = rand.randn(10, 2)\n D_true = squareform(pdist(X))\n D_true[D_true > 1.5] = 0\n \n def check_index_type(index_type):\n method = 'cyflann'\n radius = 1.5\n cyflann_kwds = {'index_type':index_type}\n adjacency_kwds = {'radius':radius, 'cyflann_kwds':cyflann_kwds}\n this_D = compute_adjacency_matrix(X=X, method = 'cyflann', **adjacency_kwds)\n assert_allclose(this_D.toarray(), D_true, rtol=1E-5, atol=1E-5)\n \n for index_type in ['kmeans', 'kdtrees']:\n yield check_index_type, index_type"
] | [
[
"numpy.testing.assert_raises",
"scipy.spatial.distance.pdist",
"scipy.spatial.distance.cdist",
"numpy.random.RandomState",
"numpy.arange",
"numpy.random.rand",
"scipy.sparse.isspmatrix"
]
] |
scopatz/PyTables | [
"05a74def785688abd802224a5ba44393a701ebc7",
"05a74def785688abd802224a5ba44393a701ebc7",
"05a74def785688abd802224a5ba44393a701ebc7"
] | [
"bench/create-large-number-objects.py",
"tables/tests/common.py",
"examples/tutorial2.py"
] | [
"\"This creates an HDF5 file with a potentially large number of objects\"\n\nimport sys\nimport numpy\nimport tables\n\nfilename = sys.argv[1]\n\n# Open a new empty HDF5 file\nfileh = tables.open_file(filename, mode=\"w\")\n\n# nlevels -- Number of levels in hierarchy\n# ngroups -- Number of groups on each level\n# ndatasets -- Number of arrays on each group\n# LR: Low ratio groups/datasets\n#nlevels, ngroups, ndatasets = (3, 1, 1000)\n# MR: Medium ratio groups/datasets\nnlevels, ngroups, ndatasets = (3, 10, 100)\n#nlevels, ngroups, ndatasets = (3, 5, 10)\n# HR: High ratio groups/datasets\n#nlevels, ngroups, ndatasets = (30, 10, 10)\n\n# Create an Array to save on disk\na = numpy.array([-1, 2, 4], numpy.int16)\n\ngroup = fileh.root\ngroup2 = fileh.root\nfor k in range(nlevels):\n for j in range(ngroups):\n for i in range(ndatasets):\n # Save the array on the HDF5 file\n fileh.create_array(group2, 'array' + str(i),\n a, \"Signed short array\")\n # Create a new group\n group2 = fileh.create_group(group, 'group' + str(j))\n # Create a new group\n group3 = fileh.create_group(group, 'ngroup' + str(k))\n # Iterate over this new group (group3)\n group = group3\n group2 = group3\n\nfileh.close()\n",
"# -*- coding: utf-8 -*-\n\n########################################################################\n#\n# License: BSD\n# Created: 2005-05-24\n# Author: Ivan Vilata i Balaguer - ivan@selidor.net\n#\n# $Id$\n#\n########################################################################\n\n\"\"\"Utilities for PyTables' test suites.\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport re\nimport sys\nimport time\nimport locale\nimport platform\nimport tempfile\nimport warnings\n\ntry:\n import unittest2 as unittest\nexcept ImportError:\n if sys.version_info < (2, 7):\n raise\n else:\n import unittest\n\nimport numpy\nimport numexpr\n\nimport tables\nfrom tables.utils import detect_number_of_cores\n\nverbose = False\n\"\"\"Show detailed output of the testing process.\"\"\"\n\nheavy = False\n\"\"\"Run all tests even when they take long to complete.\"\"\"\n\nshow_memory = False\n\"\"\"Show the progress of memory consumption.\"\"\"\n\n\ndef parse_argv(argv):\n global verbose, heavy\n\n if 'verbose' in argv:\n verbose = True\n argv.remove('verbose')\n\n if 'silent' in argv: # take care of old flag, just in case\n verbose = False\n argv.remove('silent')\n\n if '--heavy' in argv:\n heavy = True\n argv.remove('--heavy')\n\n return argv\n\n\nzlib_avail = tables.which_lib_version(\"zlib\") is not None\nlzo_avail = tables.which_lib_version(\"lzo\") is not None\nbzip2_avail = tables.which_lib_version(\"bzip2\") is not None\nblosc_avail = tables.which_lib_version(\"blosc\") is not None\n\n\ndef print_heavy(heavy):\n if heavy:\n print(\"\"\"Performing the complete test suite!\"\"\")\n else:\n print(\"\"\"\\\nPerforming only a light (yet comprehensive) subset of the test suite.\nIf you want a more complete test, try passing the --heavy flag to this script\n(or set the 'heavy' parameter in case you are using tables.test() call).\nThe whole suite will take more than 4 hours to complete on a relatively\nmodern CPU and around 512 MB of main memory.\"\"\")\n print('-=' * 38)\n\n\ndef print_versions():\n \"\"\"Print all the versions of software that PyTables relies on.\"\"\"\n\n print('-=' * 38)\n print(\"PyTables version: %s\" % tables.__version__)\n print(\"HDF5 version: %s\" % tables.which_lib_version(\"hdf5\")[1])\n print(\"NumPy version: %s\" % numpy.__version__)\n tinfo = tables.which_lib_version(\"zlib\")\n if numexpr.use_vml:\n # Get only the main version number and strip out all the rest\n vml_version = numexpr.get_vml_version()\n vml_version = re.findall(\"[0-9.]+\", vml_version)[0]\n vml_avail = \"using VML/MKL %s\" % vml_version\n else:\n vml_avail = \"not using Intel's VML/MKL\"\n print(\"Numexpr version: %s (%s)\" % (numexpr.__version__, vml_avail))\n if tinfo is not None:\n print(\"Zlib version: %s (%s)\" % (tinfo[1],\n \"in Python interpreter\"))\n tinfo = tables.which_lib_version(\"lzo\")\n if tinfo is not None:\n print(\"LZO version: %s (%s)\" % (tinfo[1], tinfo[2]))\n tinfo = tables.which_lib_version(\"bzip2\")\n if tinfo is not None:\n print(\"BZIP2 version: %s (%s)\" % (tinfo[1], tinfo[2]))\n tinfo = tables.which_lib_version(\"blosc\")\n if tinfo is not None:\n blosc_date = tinfo[2].split()[1]\n print(\"Blosc version: %s (%s)\" % (tinfo[1], blosc_date))\n blosc_cinfo = tables.blosc_get_complib_info()\n blosc_cinfo = [\n \"%s (%s)\" % (k, v[1]) for k, v in sorted(blosc_cinfo.items())\n ]\n print(\"Blosc compressors: %s\" % ', '.join(blosc_cinfo))\n try:\n from Cython import __version__ as cython_version\n print('Cython version: %s' % cython_version)\n except:\n pass\n print('Python version: %s' % sys.version)\n print('Platform: %s' % platform.platform())\n #if os.name == 'posix':\n # (sysname, nodename, release, version, machine) = os.uname()\n # print('Platform: %s-%s' % (sys.platform, machine))\n print('Byte-ordering: %s' % sys.byteorder)\n print('Detected cores: %s' % detect_number_of_cores())\n print('Default encoding: %s' % sys.getdefaultencoding())\n print('Default FS encoding: %s' % sys.getfilesystemencoding())\n print('Default locale: (%s, %s)' % locale.getdefaultlocale())\n print('-=' * 38)\n\n # This should improve readability whan tests are run by CI tools\n sys.stdout.flush()\n\n\ndef verbosePrint(string, nonl=False):\n \"\"\"Print out the `string` if verbose output is enabled.\"\"\"\n if not verbose:\n return\n if nonl:\n print(string, end=' ')\n else:\n print(string)\n\n\ndef allequal(a, b, flavor=\"numpy\"):\n \"\"\"Checks if two numerical objects are equal.\"\"\"\n\n # print(\"a-->\", repr(a))\n # print(\"b-->\", repr(b))\n if not hasattr(b, \"shape\"):\n # Scalar case\n return a == b\n\n if ((not hasattr(a, \"shape\") or a.shape == ()) and\n (not hasattr(b, \"shape\") or b.shape == ())):\n return a == b\n\n if a.shape != b.shape:\n if verbose:\n print(\"Shape is not equal:\", a.shape, \"!=\", b.shape)\n return 0\n\n # Way to check the type equality without byteorder considerations\n if hasattr(b, \"dtype\") and a.dtype.str[1:] != b.dtype.str[1:]:\n if verbose:\n print(\"dtype is not equal:\", a.dtype, \"!=\", b.dtype)\n return 0\n\n # Rank-0 case\n if len(a.shape) == 0:\n if a[()] == b[()]:\n return 1\n else:\n if verbose:\n print(\"Shape is not equal:\", a.shape, \"!=\", b.shape)\n return 0\n\n # null arrays\n if a.size == 0: # len(a) is not correct for generic shapes\n if b.size == 0:\n return 1\n else:\n if verbose:\n print(\"length is not equal\")\n print(\"len(a.data) ==>\", len(a.data))\n print(\"len(b.data) ==>\", len(b.data))\n return 0\n\n # Multidimensional case\n result = (a == b)\n result = numpy.all(result)\n if not result and verbose:\n print(\"Some of the elements in arrays are not equal\")\n\n return result\n\n\ndef areArraysEqual(arr1, arr2):\n \"\"\"Are both `arr1` and `arr2` equal arrays?\n\n Arguments can be regular NumPy arrays, chararray arrays or\n structured arrays (including structured record arrays). They are\n checked for type and value equality.\n\n \"\"\"\n\n t1 = type(arr1)\n t2 = type(arr2)\n\n if not ((hasattr(arr1, 'dtype') and arr1.dtype == arr2.dtype) or\n issubclass(t1, t2) or issubclass(t2, t1)):\n return False\n\n return numpy.all(arr1 == arr2)\n\n\n# COMPATIBILITY: assertWarns is new in Python 3.2\n# Code copied from the standard unittest.case module (Python 3.4)\nif not hasattr(unittest.TestCase, 'assertWarns'):\n class _BaseTestCaseContext:\n def __init__(self, test_case):\n self.test_case = test_case\n\n def _raiseFailure(self, standardMsg):\n msg = self.test_case._formatMessage(self.msg, standardMsg)\n raise self.test_case.failureException(msg)\n\n class _AssertRaisesBaseContext(_BaseTestCaseContext):\n def __init__(self, expected, test_case, callable_obj=None,\n expected_regex=None):\n _BaseTestCaseContext.__init__(self, test_case)\n self.expected = expected\n self.test_case = test_case\n if callable_obj is not None:\n try:\n self.obj_name = callable_obj.__name__\n except AttributeError:\n self.obj_name = str(callable_obj)\n else:\n self.obj_name = None\n if expected_regex is not None:\n expected_regex = re.compile(expected_regex)\n self.expected_regex = expected_regex\n self.msg = None\n\n def handle(self, name, callable_obj, args, kwargs):\n \"\"\"\n If callable_obj is None, assertRaises/Warns is being used as a\n context manager, so check for a 'msg' kwarg and return self.\n If callable_obj is not None, call it passing args and kwargs.\n \"\"\"\n if callable_obj is None:\n self.msg = kwargs.pop('msg', None)\n return self\n with self:\n callable_obj(*args, **kwargs)\n\n class _AssertWarnsContext(_AssertRaisesBaseContext):\n def __enter__(self):\n for v in sys.modules.values():\n if getattr(v, '__warningregistry__', None):\n v.__warningregistry__ = {}\n self.warnings_manager = warnings.catch_warnings(record=True)\n self.warnings = self.warnings_manager.__enter__()\n warnings.simplefilter(\"always\", self.expected)\n return self\n\n def __exit__(self, exc_type, exc_value, tb):\n self.warnings_manager.__exit__(exc_type, exc_value, tb)\n if exc_type is not None:\n # let unexpected exceptions pass through\n return\n try:\n exc_name = self.expected.__name__\n except AttributeError:\n exc_name = str(self.expected)\n first_matching = None\n for m in self.warnings:\n w = m.message\n if not isinstance(w, self.expected):\n continue\n if first_matching is None:\n first_matching = w\n if (self.expected_regex is not None and\n not self.expected_regex.search(str(w))):\n continue\n # store warning for later retrieval\n self.warning = w\n self.filename = m.filename\n self.lineno = m.lineno\n return\n # Now we simply try to choose a helpful failure message\n if first_matching is not None:\n self._raiseFailure(\n '\"{0}\" does not match \"{1}\"'.format(\n self.expected_regex.pattern, str(first_matching)))\n if self.obj_name:\n self._raiseFailure(\"{0} not triggered by {1}\".format(\n exc_name, self.obj_name))\n else:\n self._raiseFailure(\"{0} not triggered\".format(exc_name))\n\n\nclass PyTablesTestCase(unittest.TestCase):\n def tearDown(self):\n super(PyTablesTestCase, self).tearDown()\n for key in self.__dict__:\n if self.__dict__[key].__class__.__name__ not in ('instancemethod'):\n self.__dict__[key] = None\n\n def _getName(self):\n \"\"\"Get the name of this test case.\"\"\"\n return self.id().split('.')[-2]\n\n def _getMethodName(self):\n \"\"\"Get the name of the method currently running in the test case.\"\"\"\n return self.id().split('.')[-1]\n\n def _verboseHeader(self):\n \"\"\"Print a nice header for the current test method if verbose.\"\"\"\n\n if verbose:\n name = self._getName()\n methodName = self._getMethodName()\n\n title = \"Running %s.%s\" % (name, methodName)\n print('%s\\n%s' % (title, '-' * len(title)))\n\n @classmethod\n def _testFilename(class_, filename):\n \"\"\"Returns an absolute version of the `filename`, taking care of the\n location of the calling test case class.\"\"\"\n modname = class_.__module__\n # When the definitive switch to ``setuptools`` is made,\n # this should definitely use the ``pkg_resouces`` API::\n #\n # return pkg_resources.resource_filename(modname, filename)\n #\n modfile = sys.modules[modname].__file__\n dirname = os.path.dirname(modfile)\n return os.path.join(dirname, filename)\n\n # COMPATIBILITY: assertWarns is new in Python 3.2\n if not hasattr(unittest.TestCase, 'assertWarns'):\n def assertWarns(self, expected_warning, callable_obj=None,\n *args, **kwargs):\n context = _AssertWarnsContext(expected_warning, self, callable_obj)\n return context.handle('assertWarns', callable_obj, args, kwargs)\n\n def _checkEqualityGroup(self, node1, node2, hardlink=False):\n if verbose:\n print(\"Group 1:\", node1)\n print(\"Group 2:\", node2)\n if hardlink:\n self.assertTrue(\n node1._v_pathname != node2._v_pathname,\n \"node1 and node2 have the same pathnames.\")\n else:\n self.assertTrue(\n node1._v_pathname == node2._v_pathname,\n \"node1 and node2 does not have the same pathnames.\")\n self.assertTrue(\n node1._v_children == node2._v_children,\n \"node1 and node2 does not have the same children.\")\n\n def _checkEqualityLeaf(self, node1, node2, hardlink=False):\n if verbose:\n print(\"Leaf 1:\", node1)\n print(\"Leaf 2:\", node2)\n if hardlink:\n self.assertTrue(\n node1._v_pathname != node2._v_pathname,\n \"node1 and node2 have the same pathnames.\")\n else:\n self.assertTrue(\n node1._v_pathname == node2._v_pathname,\n \"node1 and node2 does not have the same pathnames.\")\n self.assertTrue(\n areArraysEqual(node1[:], node2[:]),\n \"node1 and node2 does not have the same values.\")\n\n\nclass TestFileMixin(object):\n h5fname = None\n open_kwargs = {}\n\n def setUp(self):\n super(TestFileMixin, self).setUp()\n #self.h5fname = self._testFilename(self.testfname)\n self.h5file = tables.open_file(\n self.h5fname, title=self._getName(), **self.open_kwargs)\n\n def tearDown(self):\n \"\"\"Close ``h5file``.\"\"\"\n\n self.h5file.close()\n super(TestFileMixin, self).tearDown()\n\n\nclass TempFileMixin(object):\n open_mode = 'w'\n open_kwargs = {}\n\n def _getTempFileName(self):\n return tempfile.mktemp(prefix=self._getName(), suffix='.h5')\n\n def setUp(self):\n \"\"\"Set ``h5file`` and ``h5fname`` instance attributes.\n\n * ``h5fname``: the name of the temporary HDF5 file.\n * ``h5file``: the writable, empty, temporary HDF5 file.\n\n \"\"\"\n\n super(TempFileMixin, self).setUp()\n self.h5fname = self._getTempFileName()\n self.h5file = tables.open_file(\n self.h5fname, self.open_mode, title=self._getName(),\n **self.open_kwargs)\n\n def tearDown(self):\n \"\"\"Close ``h5file`` and remove ``h5fname``.\"\"\"\n\n self.h5file.close()\n self.h5file = None\n os.remove(self.h5fname) # comment this for debugging purposes only\n super(TempFileMixin, self).tearDown()\n\n def _reopen(self, mode='r', **kwargs):\n \"\"\"Reopen ``h5file`` in the specified ``mode``.\n\n Returns a true or false value depending on whether the file was\n reopenend or not. If not, nothing is changed.\n\n \"\"\"\n\n self.h5file.close()\n self.h5file = tables.open_file(self.h5fname, mode, **kwargs)\n return True\n\n\nclass ShowMemTime(PyTablesTestCase):\n tref = time.time()\n \"\"\"Test for showing memory and time consumption.\"\"\"\n\n def test00(self):\n \"\"\"Showing memory and time consumption.\"\"\"\n\n # Obtain memory info (only for Linux 2.6.x)\n for line in open(\"/proc/self/status\"):\n if line.startswith(\"VmSize:\"):\n vmsize = int(line.split()[1])\n elif line.startswith(\"VmRSS:\"):\n vmrss = int(line.split()[1])\n elif line.startswith(\"VmData:\"):\n vmdata = int(line.split()[1])\n elif line.startswith(\"VmStk:\"):\n vmstk = int(line.split()[1])\n elif line.startswith(\"VmExe:\"):\n vmexe = int(line.split()[1])\n elif line.startswith(\"VmLib:\"):\n vmlib = int(line.split()[1])\n print(\"\\nWallClock time:\", time.time() - self.tref)\n print(\"Memory usage: ******* %s *******\" % self._getName())\n print(\"VmSize: %7s kB\\tVmRSS: %7s kB\" % (vmsize, vmrss))\n print(\"VmData: %7s kB\\tVmStk: %7s kB\" % (vmdata, vmstk))\n print(\"VmExe: %7s kB\\tVmLib: %7s kB\" % (vmexe, vmlib))\n\n\n## Local Variables:\n## mode: python\n## py-indent-offset: 4\n## tab-width: 4\n## fill-column: 72\n## End:\n",
"\"\"\"This program shows the different protections that PyTables offer to the user\nin order to insure a correct data injection in tables.\n\nExample to be used in the second tutorial in the User's Guide.\n\n\"\"\"\n\nfrom __future__ import print_function\nimport tables\nimport numpy as np\n\n# Describe a particle record\n\n\nclass Particle(tables.IsDescription):\n name = tables.StringCol(itemsize=16) # 16-character string\n lati = tables.Int32Col() # integer\n longi = tables.Int32Col() # integer\n pressure = tables.Float32Col(shape=(2, 3)) # array of floats\n # (single-precision)\n temperature = tables.Float64Col(shape=(2, 3)) # array of doubles\n # (double-precision)\n\n# Native NumPy dtype instances are also accepted\nEvent = np.dtype([\n (\"name\", \"S16\"),\n (\"TDCcount\", np.uint8),\n (\"ADCcount\", np.uint16),\n (\"xcoord\", np.float32),\n (\"ycoord\", np.float32)\n])\n\n# And dictionaries too (this defines the same structure as above)\n# Event = {\n# \"name\" : StringCol(itemsize=16),\n# \"TDCcount\" : UInt8Col(),\n# \"ADCcount\" : UInt16Col(),\n# \"xcoord\" : Float32Col(),\n# \"ycoord\" : Float32Col(),\n# }\n\n# Open a file in \"w\"rite mode\nfileh = tables.open_file(\"tutorial2.h5\", mode=\"w\")\n# Get the HDF5 root group\nroot = fileh.root\n# Create the groups:\nfor groupname in (\"Particles\", \"Events\"):\n group = fileh.create_group(root, groupname)\n# Now, create and fill the tables in Particles group\ngparticles = root.Particles\n# Create 3 new tables\nfor tablename in (\"TParticle1\", \"TParticle2\", \"TParticle3\"):\n # Create a table\n table = fileh.create_table(\"/Particles\", tablename, Particle,\n \"Particles: \" + tablename)\n # Get the record object associated with the table:\n particle = table.row\n # Fill the table with 257 particles\n for i in range(257):\n # First, assign the values to the Particle record\n particle['name'] = 'Particle: %6d' % (i)\n particle['lati'] = i\n particle['longi'] = 10 - i\n # Detectable errors start here. Play with them!\n particle['pressure'] = np.array(\n i * np.arange(2 * 3)).reshape((2, 4)) # Incorrect\n # particle['pressure'] = array(i*arange(2*3)).reshape((2,3)) # Correct\n # End of errors\n particle['temperature'] = (i ** 2) # Broadcasting\n # This injects the Record values\n particle.append()\n # Flush the table buffers\n table.flush()\n\n# Now, go for Events:\nfor tablename in (\"TEvent1\", \"TEvent2\", \"TEvent3\"):\n # Create a table in Events group\n table = fileh.create_table(root.Events, tablename, Event,\n \"Events: \" + tablename)\n # Get the record object associated with the table:\n event = table.row\n # Fill the table with 257 events\n for i in range(257):\n # First, assign the values to the Event record\n event['name'] = 'Event: %6d' % (i)\n event['TDCcount'] = i % (1 << 8) # Correct range\n # Detectable errors start here. Play with them!\n event['xcoor'] = float(i ** 2) # Wrong spelling\n # event['xcoord'] = float(i**2) # Correct spelling\n event['ADCcount'] = \"sss\" # Wrong type\n # event['ADCcount'] = i * 2 # Correct type\n # End of errors\n event['ycoord'] = float(i) ** 4\n # This injects the Record values\n event.append()\n # Flush the buffers\n table.flush()\n\n# Read the records from table \"/Events/TEvent3\" and select some\ntable = root.Events.TEvent3\ne = [p['TDCcount'] for p in table\n if p['ADCcount'] < 20 and 4 <= p['TDCcount'] < 15]\nprint(\"Last record ==>\", p)\nprint(\"Selected values ==>\", e)\nprint(\"Total selected records ==> \", len(e))\n# Finally, close the file (this also will flush all the remaining buffers!)\nfileh.close()\n"
] | [
[
"numpy.array"
],
[
"numpy.all"
],
[
"numpy.arange",
"numpy.dtype"
]
] |
aljanabim/svea | [
"37d27089237af3777456d7664473ffb811dabf33"
] | [
"src/teleop_tools/mouse_teleop/scripts/mouse_teleop.py"
] | [
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2015 Enrique Fernandez\n# Released under the BSD License.\n#\n# Authors:\n# * Enrique Fernandez\n\nimport Tkinter\n\nimport rospy\nfrom geometry_msgs.msg import Twist, Vector3\n\nimport numpy\n\n\nclass MouseTeleop():\n def __init__(self):\n # Retrieve params:\n self._frequency = rospy.get_param('~frequency', 0.0)\n self._scale = rospy.get_param('~scale', 1.0)\n self._holonomic = rospy.get_param('~holonomic', False)\n\n # Create twist publisher:\n self._pub_cmd = rospy.Publisher('mouse_vel', Twist, queue_size=100)\n\n # Initialize twist components to zero:\n self._v_x = 0.0\n self._v_y = 0.0\n self._w = 0.0\n\n # Initialize mouse position (x, y) to None (unknown); it's initialized\n # when the mouse button is pressed on the _start callback that handles\n # that event:\n self._x = None\n self._y = None\n\n # Create window:\n self._root = Tkinter.Tk()\n self._root.title('Mouse Teleop')\n\n # Make window non-resizable:\n self._root.resizable(0, 0)\n\n # Create canvas:\n self._canvas = Tkinter.Canvas(self._root, bg='white')\n\n # Create canvas objects:\n self._canvas.create_arc(0, 0, 0, 0, fill='red', outline='red',\n width=1, style=Tkinter.PIESLICE, start=90.0, tag='w')\n self._canvas.create_line(0, 0, 0, 0, fill='blue', width=4, tag='v_x')\n\n if self._holonomic:\n self._canvas.create_line(0, 0, 0, 0,\n fill='blue', width=4, tag='v_y')\n\n # Create canvas text objects:\n self._text_v_x = Tkinter.StringVar()\n if self._holonomic:\n self._text_v_y = Tkinter.StringVar()\n self._text_w = Tkinter.StringVar()\n\n self._label_v_x = Tkinter.Label(self._root,\n anchor=Tkinter.W, textvariable=self._text_v_x)\n if self._holonomic:\n self._label_v_y = Tkinter.Label(self._root,\n anchor=Tkinter.W, textvariable=self._text_v_y)\n self._label_w = Tkinter.Label(self._root,\n anchor=Tkinter.W, textvariable=self._text_w)\n\n if self._holonomic:\n self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)\n self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)\n self._text_w.set( 'w = %0.2f deg/s' % self._w)\n else:\n self._text_v_x.set('v = %0.2f m/s' % self._v_x)\n self._text_w.set( 'w = %0.2f deg/s' % self._w)\n\n self._label_v_x.pack()\n if self._holonomic:\n self._label_v_y.pack()\n self._label_w.pack()\n\n # Bind event handlers:\n self._canvas.bind('<Button-1>', self._start)\n self._canvas.bind('<ButtonRelease-1>', self._release)\n\n self._canvas.bind('<Configure>', self._configure)\n\n if self._holonomic:\n self._canvas.bind('<B1-Motion>', self._mouse_motion_linear)\n self._canvas.bind('<Shift-B1-Motion>', self._mouse_motion_angular)\n\n self._root.bind('<Shift_L>', self._change_to_motion_angular)\n self._root.bind('<KeyRelease-Shift_L>',\n self._change_to_motion_linear)\n else:\n self._canvas.bind('<B1-Motion>', self._mouse_motion_angular)\n\n self._canvas.pack()\n\n # If frequency is positive, use synchronous publishing mode:\n if self._frequency > 0.0:\n # Create timer for the given frequency to publish the twist:\n period = rospy.Duration(1.0 / self._frequency)\n\n self._timer = rospy.Timer(period, self._publish_twist)\n\n # Start window event manager main loop:\n self._root.mainloop()\n\n def __del__(self):\n if self._frequency > 0.0:\n self._timer.shutdown()\n\n self._root.quit()\n\n def _start(self, event):\n self._x, self._y = event.y, event.x\n\n self._y_linear = self._y_angular = 0\n\n self._v_x = self._v_y = self._w = 0.0\n\n def _release(self, event):\n self._v_x = self._v_y = self._w = 0.0\n\n self._send_motion()\n\n def _configure(self, event):\n self._width, self._height = event.height, event.width\n\n self._c_x = self._height / 2.0\n self._c_y = self._width / 2.0\n\n self._r = min(self._height, self._width) * 0.25\n\n def _mouse_motion_linear(self, event):\n self._v_x, self._v_y = self._relative_motion(event.y, event.x)\n\n self._send_motion()\n\n def _mouse_motion_angular(self, event):\n self._v_x, self._w = self._relative_motion(event.y, event.x)\n\n self._send_motion()\n\n def _update_coords(self, tag, x0, y0, x1, y1):\n x0 += self._c_x\n y0 += self._c_y\n\n x1 += self._c_x\n y1 += self._c_y\n\n self._canvas.coords(tag, (x0, y0, x1, y1))\n\n def _draw_v_x(self, v):\n x = -v * float(self._width)\n\n self._update_coords('v_x', 0, 0, 0, x)\n\n def _draw_v_y(self, v):\n y = -v * float(self._height)\n\n self._update_coords('v_y', 0, 0, y, 0)\n\n def _draw_w(self, w):\n x0 = y0 = -self._r\n x1 = y1 = self._r\n\n self._update_coords('w', x0, y0, x1, y1)\n\n yaw = w * numpy.rad2deg(self._scale)\n\n self._canvas.itemconfig('w', extent=yaw)\n\n def _send_motion(self):\n v_x = self._v_x * self._scale\n v_y = self._v_y * self._scale\n w = self._w * self._scale\n\n linear = Vector3(v_x, v_y, 0.0)\n angular = Vector3(0.0, 0.0, w)\n\n self._draw_v_x(self._v_x)\n if self._holonomic:\n self._draw_v_y(self._v_y)\n self._draw_w(self._w)\n\n if self._holonomic:\n self._text_v_x.set('v_x = %0.2f m/s' % self._v_x)\n self._text_v_y.set('v_y = %0.2f m/s' % self._v_y)\n self._text_w.set( 'w = %0.2f deg/s' % numpy.rad2deg(self._w))\n else:\n self._text_v_x.set('v = %0.2f m/s' % self._v_x)\n self._text_w.set( 'w = %0.2f deg/s' % numpy.rad2deg(self._w))\n\n twist = Twist(linear, angular)\n self._pub_cmd.publish(twist)\n\n def _publish_twist(self, event):\n self._send_motion()\n\n def _relative_motion(self, x, y):\n dx = self._x - x\n dy = self._y - y\n\n dx /= float(self._width)\n dy /= float(self._height)\n\n dx = max(-1.0, min(dx, 1.0))\n dy = max(-1.0, min(dy, 1.0))\n\n return dx, dy\n\n def _change_to_motion_linear(self, event):\n if self._y is not None:\n y = event.x\n\n self._y_angular = self._y - y\n self._y = self._y_linear + y\n\n def _change_to_motion_angular(self, event):\n if self._y is not None:\n y = event.x\n\n self._y_linear = self._y - y\n self._y = self._y_angular + y\n\n\ndef main():\n rospy.init_node('mouse_teleop')\n\n MouseTeleop()\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n"
] | [
[
"numpy.rad2deg"
]
] |
dnjst/squidpy | [
"ca765d04b9621debb8752d3d4693dd68f6909513"
] | [
"tests/image/test_segmentation.py"
] | [
"from typing import Tuple, Union, Callable, Optional, Sequence\nfrom pytest_mock import MockerFixture\nimport pytest\n\nimport numpy as np\nimport dask.array as da\n\nfrom squidpy.im import (\n segment,\n ImageContainer,\n SegmentationCustom,\n SegmentationWatershed,\n)\nfrom squidpy.im._segment import _SEG_DTYPE\nfrom squidpy._constants._constants import SegmentationBackend\nfrom squidpy._constants._pkg_constants import Key\n\n\ndef dummy_segment(arr: np.ndarray) -> np.ndarray:\n assert isinstance(arr, np.ndarray)\n assert arr.ndim == 3\n return arr[..., 0].astype(np.uint32)\n\n\nclass TestGeneral:\n @pytest.mark.parametrize(\"ndim\", [2, 3])\n def test_input_ndim(self, ndim: int):\n img = np.zeros(shape=(10, 10))\n if ndim == 3:\n img = img[..., np.newaxis]\n sc = SegmentationCustom(dummy_segment)\n\n res = sc.segment(img)\n\n assert isinstance(res, np.ndarray)\n assert res.ndim == 3\n if ndim == 2:\n assert res.shape == img.shape + (1,)\n else:\n assert res.shape == img.shape\n\n def test_segment_invalid_shape(self):\n img = np.zeros(shape=(1, 10, 10, 2))\n sc = SegmentationCustom(dummy_segment)\n\n with pytest.raises(ValueError, match=r\"Expected `2` or `3` dimensions\"):\n sc.segment(img)\n\n def test_segment_container(self):\n img = ImageContainer(np.zeros(shape=(10, 10, 1)), layer=\"image\")\n sc = SegmentationCustom(dummy_segment)\n\n res = sc.segment(img, layer=\"image\", library_id=img[\"image\"].z.values[0])\n\n assert isinstance(res, ImageContainer)\n assert res.shape == img.shape\n assert \"image\" in res\n assert res[\"image\"].dims == img[\"image\"].dims\n\n\nclass TestWatershed:\n @pytest.mark.parametrize(\"thresh\", [None, 0.1, 0.5, 1.0])\n def test_threshold(self, thresh: Optional[float], mocker: MockerFixture):\n img = np.zeros((100, 200), dtype=np.float64)\n img[2:10, 2:10] = 1.0\n img[30:34, 10:16] = 1.0\n img = ImageContainer(img, layer=\"image\")\n\n sw = SegmentationWatershed()\n spy = mocker.spy(sw, \"_segment\")\n\n res = sw.segment(img, layer=\"image\", library_id=img[\"image\"].z.values[0], fn_kwargs={\"thresh\": thresh})\n\n assert isinstance(res, ImageContainer)\n spy.assert_called_once()\n call = spy.call_args_list[0]\n\n assert call[1][\"thresh\"] == thresh\n\n\nclass TestHighLevel:\n def test_invalid_layer(self, small_cont: ImageContainer):\n with pytest.raises(KeyError, match=r\"Image layer `foobar` not found in\"):\n segment(small_cont, layer=\"foobar\")\n\n @pytest.mark.parametrize(\"method\", [\"watershed\", dummy_segment])\n def test_method(self, small_cont: ImageContainer, method: Union[str, Callable]):\n res = segment(small_cont, method=method, copy=True)\n\n assert isinstance(res, ImageContainer)\n assert res.shape == small_cont.shape\n\n if callable(method):\n method = SegmentationBackend.CUSTOM.s\n\n assert Key.img.segment(method) in res\n\n if method in (\"log\", \"dog\", \"dog\"):\n assert res[Key.img.segment(method)].values.max() <= 1\n\n @pytest.mark.parametrize(\"dy\", [11, 0.5, None])\n @pytest.mark.parametrize(\"dx\", [15, 0.1, None])\n def test_size(self, small_cont: ImageContainer, dy: Optional[Union[int, float]], dx: Optional[Union[int, float]]):\n res = segment(small_cont, size=(dy, dx), copy=True)\n\n assert isinstance(res, ImageContainer)\n assert res.shape == small_cont.shape\n\n @pytest.mark.parametrize(\"channel\", [0, 1, 2])\n def test_channel(self, small_cont: ImageContainer, channel: int):\n segment(small_cont, copy=False, layer=\"image\", channel=channel)\n\n assert Key.img.segment(\"watershed\") in small_cont\n np.testing.assert_array_equal(\n list(small_cont[Key.img.segment(\"watershed\")].dims),\n [\"y\", \"x\", \"z\", f\"{small_cont['image'].dims[-1]}:{channel}\"],\n )\n\n def test_all_channels(self, small_cont: ImageContainer):\n def func(arr: np.ndarray):\n assert arr.shape == (small_cont.shape + (n_channels,))\n return np.zeros(arr.shape[:2], dtype=np.uint8)\n\n n_channels = small_cont[\"image\"].sizes[\"channels\"]\n segment(small_cont, copy=False, layer=\"image\", channel=None, method=func, layer_added=\"seg\")\n\n np.testing.assert_array_equal(small_cont[\"seg\"], np.zeros(small_cont.shape + (1, 1)))\n assert small_cont[\"seg\"].dtype == _SEG_DTYPE\n\n @pytest.mark.parametrize(\"key_added\", [None, \"foo\"])\n def test_key_added(self, small_cont: ImageContainer, key_added: Optional[str]):\n res = segment(small_cont, copy=False, layer=\"image\", layer_added=key_added)\n\n assert res is None\n assert Key.img.segment(\"watershed\", layer_added=key_added) in small_cont\n\n def test_passing_kwargs(self, small_cont: ImageContainer):\n def func(chunk: np.ndarray, sentinel: bool = False):\n assert sentinel, \"Sentinel not set.\"\n return np.zeros(chunk[..., 0].shape, dtype=_SEG_DTYPE)\n\n segment(\n small_cont, method=func, layer=\"image\", layer_added=\"bar\", chunks=25, lazy=False, depth=None, sentinel=True\n )\n assert small_cont[\"bar\"].values.dtype == _SEG_DTYPE\n np.testing.assert_array_equal(small_cont[\"bar\"].values, 0)\n\n @pytest.mark.parametrize(\"dask_input\", [False, True])\n @pytest.mark.parametrize(\"chunks\", [25, (50, 50, 1), \"auto\"])\n @pytest.mark.parametrize(\"lazy\", [False, True])\n def test_dask_segment(\n self, small_cont: ImageContainer, dask_input: bool, chunks: Union[int, Tuple[int, ...], str], lazy: bool\n ):\n def func(chunk: np.ndarray):\n if isinstance(chunks, tuple):\n np.testing.assert_array_equal(chunk.shape, [chunks[0] + 2 * d, chunks[1] + 2 * d, 1])\n elif isinstance(chunks, int):\n np.testing.assert_array_equal(chunk.shape, [chunks + 2 * d, chunks + 2 * d, 1])\n\n return np.zeros(chunk[..., 0].shape, dtype=_SEG_DTYPE)\n\n small_cont[\"foo\"] = da.asarray(small_cont[\"image\"].data) if dask_input else small_cont[\"image\"].values\n d = 10 # overlap depth\n assert isinstance(small_cont[\"foo\"].data, da.Array if dask_input else np.ndarray)\n\n segment(small_cont, method=func, layer=\"foo\", layer_added=\"bar\", chunks=chunks, lazy=lazy, depth={0: d, 1: d})\n\n if lazy:\n assert isinstance(small_cont[\"bar\"].data, da.Array)\n small_cont.compute()\n assert isinstance(small_cont[\"foo\"].data, np.ndarray)\n else:\n # make sure we didn't accidentally trigger foo's computation\n assert isinstance(small_cont[\"foo\"].data, da.Array if dask_input else np.ndarray)\n\n assert isinstance(small_cont[\"bar\"].data, np.ndarray)\n assert small_cont[\"bar\"].values.dtype == _SEG_DTYPE\n np.testing.assert_array_equal(small_cont[\"bar\"].values, 0)\n\n def test_copy(self, small_cont: ImageContainer):\n prev_keys = set(small_cont)\n res = segment(small_cont, copy=True, layer=\"image\")\n\n assert isinstance(res, ImageContainer)\n assert set(small_cont) == prev_keys\n assert Key.img.segment(\"watershed\") in res\n\n def test_parallelize(self, small_cont: ImageContainer):\n res1 = segment(small_cont, layer=\"image\", n_jobs=1, copy=True)\n res2 = segment(small_cont, layer=\"image\", n_jobs=2, copy=True)\n\n np.testing.assert_array_equal(\n res1[Key.img.segment(\"watershed\")].values, res2[Key.img.segment(\"watershed\")].values\n )\n\n @pytest.mark.parametrize(\"chunks\", [25, 50])\n def test_blocking(self, small_cont: ImageContainer, chunks: int):\n def func(chunk: np.ndarray):\n labels = np.zeros(chunk[..., 0].shape, dtype=np.uint32)\n labels[0, 0] = 1\n return labels\n\n segment(small_cont, method=func, layer=\"image\", layer_added=\"bar\", chunks=chunks, lazy=False, depth=None)\n # blocks are label from top-left to bottom-right in an ascending order [0, num_blocks - 1]\n # lowest n bits are allocated for block, rest is for the label (i.e. for blocksize=25, we need 16 blocks ids\n # from [0, 15], which can be stored in 4 bits, then we just prepend 1 bit (see the above `func`, resulting\n # in unique 16 labels [10000, 11111]\n\n expected = np.zeros_like(small_cont[\"bar\"].values)\n start = 16 if chunks == 25 else 4\n for i in range(0, 100, chunks):\n for j in range(0, 100, chunks):\n expected[i, j] = start\n start += 1\n\n assert small_cont[\"bar\"].values.dtype == _SEG_DTYPE\n np.testing.assert_array_equal(small_cont[\"bar\"].values, expected)\n\n @pytest.mark.parametrize(\"size\", [None, 11])\n def test_watershed_works(self, size: Optional[int]):\n img_orig = np.zeros((100, 200, 30), dtype=np.float64)\n img_orig[2:10, 2:10] = 1.0\n img_orig[30:34, 10:16] = 1.0\n\n cont = ImageContainer(img_orig, layer=\"image_0\")\n segment(\n img=cont,\n method=\"watershed\",\n layer=\"image_0\",\n layer_added=\"segment\",\n size=size,\n channel=0,\n thresh=0.5,\n )\n # check that blobs are in segments\n assert np.mean(cont.data[\"segment\"].values[img_orig[:, :, 0] > 0] > 0) > 0.5\n\n # for size=10, \"fails with `size=10` due to border effects\"\n # the reason why there is no test for it that inside tox, it \"works\" (i.e. the assertion passes)\n # but outside, the assertion fails, as it should\n\n @pytest.mark.parametrize(\"library_id\", [None, \"3\", [\"1\", \"2\"]])\n def test_library_id(self, cont_4d: ImageContainer, library_id: Optional[Union[str, Sequence[str]]]):\n def func(arr: np.ndarray):\n assert arr.shape == cont_4d.shape + (1,)\n return np.ones(arr[..., 0].shape, dtype=_SEG_DTYPE)\n\n segment(cont_4d, method=func, layer=\"image\", layer_added=\"image_seg\", library_id=library_id, copy=False)\n\n np.testing.assert_array_equal(cont_4d[\"image\"].coords, cont_4d[\"image_seg\"].coords)\n if library_id is None:\n np.testing.assert_array_equal(1, cont_4d[\"image_seg\"])\n else:\n if isinstance(library_id, str):\n library_id = [library_id]\n for lid in library_id:\n np.testing.assert_array_equal(1, cont_4d[\"image_seg\"].sel(z=lid))\n for lid in set(cont_4d.library_ids) - set(library_id):\n # channels have been changed, apply sets to 0\n np.testing.assert_array_equal(0, cont_4d[\"image_seg\"].sel(z=lid))\n"
] | [
[
"numpy.zeros_like",
"numpy.ones",
"numpy.zeros",
"numpy.testing.assert_array_equal",
"numpy.mean"
]
] |
schibsen/MLops_exercises_organized | [
"2c9b386fed7b1e400524905cb68f220caf9d015b"
] | [
"src/models/model.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MyAwesomeModel(nn.Module):\n def __init__(self, n_classes):\n super(MyAwesomeModel, self).__init__()\n\n self.feature_extractor = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=6, kernel_size=4, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=6, out_channels=16, kernel_size=4, stride=1),\n nn.Tanh(),\n nn.AvgPool2d(kernel_size=2),\n nn.Conv2d(in_channels=16, out_channels=120, kernel_size=4, stride=1),\n nn.Tanh(),\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(in_features=120, out_features=84),\n nn.Tanh(),\n nn.Linear(in_features=84, out_features=n_classes),\n )\n\n def forward(self, x, return_features=False):\n x = self.feature_extractor(x)\n x = torch.flatten(x, 1)\n logits = self.classifier(x)\n probs = F.log_softmax(logits, dim=1)\n if return_features:\n return x\n else:\n return probs\n"
] | [
[
"torch.nn.functional.log_softmax",
"torch.nn.Linear",
"torch.flatten",
"torch.nn.Tanh",
"torch.nn.Conv2d",
"torch.nn.AvgPool2d"
]
] |
hugerepo-tianhang/low_dim_update_stable | [
"565f6cbf886d266d0633bc112ccae28f1d116ee1"
] | [
"stable_baselines/cmaes/cma_redo.py"
] | [
"from stable_baselines.ppo2.run_mujoco import eval_return\nimport cma\n\nimport numpy as np\nfrom stable_baselines.low_dim_analysis.eval_util import *\nfrom stable_baselines.low_dim_analysis.common import do_pca, plot_2d, \\\n dump_rows_write_csv, generate_run_dir, do_proj_on_first_n_IPCA, get_allinone_concat_df\nfrom sklearn.decomposition import IncrementalPCA\n\n\nfrom stable_baselines import logger\n\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\nfrom joblib import Parallel, delayed\nfrom matplotlib import pyplot as plt\nimport time\nimport os\nfrom stable_baselines.common.cmd_util import mujoco_arg_parser\nfrom stable_baselines.low_dim_analysis.common_parser import get_common_parser\nfrom numpy import linalg as LA\n\n\n\ndef plot_cma_returns(plot_dir_alg, name, mean_rets, min_rets, max_rets, show):\n\n X = np.arange(len(mean_rets))\n fig, ax = plt.subplots()\n plt.xlabel('num of eval')\n plt.ylabel('mean returns with min and max filled')\n\n ax.plot(X, mean_rets)\n ax.fill_between(X, min_rets, max_rets, alpha=0.5)\n file_path = f\"{plot_dir_alg}/{name}.pdf\"\n if os.path.isfile(file_path):\n os.remove(file_path)\n\n logger.log(f\"saving cma plot to {file_path}\")\n fig.savefig(file_path, dpi=300,\n bbox_inches='tight', format='pdf')\n if show: plt.show()\n\n\n\n\ndef do_cma(cma_args, first_n_pcs, orgin_param, save_dir, starting_coord, var):\n\n tic = time.time()\n\n #TODO better starting locations, record how many samples,\n\n logger.log(f\"CMAES STARTING :{starting_coord}\")\n es = cma.CMAEvolutionStrategy(starting_coord, var)\n total_num_of_evals = 0\n total_num_timesteps = 0\n\n\n mean_rets = []\n min_rets = []\n max_rets = []\n eval_returns = None\n\n optimization_path = []\n while total_num_timesteps < cma_args.cma_num_timesteps and not es.stop():\n solutions = es.ask()\n optimization_path.extend(solutions)\n thetas = [np.matmul(coord, first_n_pcs) + orgin_param for coord in solutions]\n logger.log(f\"current time steps num: {total_num_timesteps} total time steps: {cma_args.cma_num_timesteps}\")\n eval_returns = Parallel(n_jobs=cma_args.cores_to_use) \\\n (delayed(eval_return)(cma_args, save_dir, theta, cma_args.eval_num_timesteps, i) for\n (i, theta) in enumerate(thetas))\n\n\n mean_rets.append(np.mean(eval_returns))\n min_rets.append(np.min(eval_returns))\n max_rets.append(np.max(eval_returns))\n\n\n total_num_of_evals += len(eval_returns)\n total_num_timesteps += cma_args.eval_num_timesteps * len(eval_returns)\n\n logger.log(f\"current eval returns: {str(eval_returns)}\")\n logger.log(f\"total timesteps so far: {total_num_timesteps}\")\n negative_eval_returns = [-r for r in eval_returns]\n\n es.tell(solutions, negative_eval_returns)\n es.logger.add() # write data to disc to be plotted\n es.disp()\n\n toc = time.time()\n logger.log(f\"####################################CMA took {toc-tic} seconds\")\n\n es_logger = es.logger\n\n if not hasattr(es_logger, 'xmean'):\n es_logger.load()\n\n\n n_comp_used = first_n_pcs.shape[0]\n optimization_path_mean = np.vstack((starting_coord, es_logger.xmean[:,5:5+n_comp_used]))\n\n return mean_rets, min_rets, max_rets, np.array(optimization_path), np.array(optimization_path_mean)\n\n\ndef main():\n\n\n import sys\n logger.log(sys.argv)\n common_arg_parser = get_common_parser()\n cma_args, cma_unknown_args = common_arg_parser.parse_known_args()\n\n origin = \"mean_param\"\n\n\n this_run_dir = get_dir_path_for_this_run(cma_args)\n\n traj_params_dir_name = get_full_params_dir(this_run_dir)\n intermediate_data_dir = get_intermediate_data_dir(this_run_dir)\n save_dir = get_save_dir( this_run_dir)\n\n\n if not os.path.exists(intermediate_data_dir):\n os.makedirs(intermediate_data_dir)\n\n cma_run_num, cma_intermediate_data_dir = generate_run_dir(get_cma_returns_dirname, intermediate_dir=intermediate_data_dir, n_comp=cma_args.n_comp_to_use)\n '''\n ==========================================================================================\n get the pc vectors\n ==========================================================================================\n '''\n\n logger.log(\"grab final params\")\n final_file = get_full_param_traj_file_path(traj_params_dir_name, \"final\")\n final_param = pd.read_csv(final_file, header=None).values[0]\n\n\n final_pca = IncrementalPCA(n_components=2) # for sparse PCA to speed up\n\n theta_file = get_full_param_traj_file_path(traj_params_dir_name, 0)\n concat_df = pd.read_csv(theta_file, header=None, chunksize=10000)\n\n\n tic = time.time()\n for chunk in concat_df:\n logger.log(f\"currnet at : {concat_df._currow}\")\n\n if chunk.shape[0] < 2:\n logger.log(f\"last column too few: {chunk.shape[0]}\")\n continue\n final_pca.partial_fit(chunk.values)\n\n toc = time.time()\n logger.log('\\nElapsed time computing the chunked PCA {:.2f} s\\n'\n .format(toc - tic))\n\n logger.log(final_pca.explained_variance_ratio_)\n\n pcs_components = final_pca.components_\n\n first_2_pcs = pcs_components[:2]\n mean_param = final_pca.mean_\n\n origin_param = mean_param\n\n\n theta_file = get_full_param_traj_file_path(traj_params_dir_name, 0)\n concat_df = pd.read_csv(theta_file, header=None, chunksize=10000)\n\n proj_coords = do_proj_on_first_n_IPCA(concat_df, first_2_pcs, origin_param)\n\n\n '''\n ==========================================================================================\n eval all xy coords\n ==========================================================================================\n '''\n\n\n from stable_baselines.low_dim_analysis.common import plot_contour_trajectory, gen_subspace_coords,do_eval_returns, \\\n get_allinone_concat_df, do_proj_on_first_n\n\n from stable_baselines.ppo2.run_mujoco import eval_return\n\n last_proj_coord = do_proj_on_first_n(final_param, first_2_pcs, origin_param)\n starting_coord = last_proj_coord\n\n tic = time.time()\n\n #TODO better starting locations, record how many samples,\n\n logger.log(f\"CMAES STARTING :{starting_coord}\")\n es = cma.CMAEvolutionStrategy(starting_coord, 5)\n total_num_of_evals = 0\n total_num_timesteps = 0\n\n\n mean_rets = []\n min_rets = []\n max_rets = []\n eval_returns = None\n\n optimization_path = []\n while total_num_timesteps < cma_args.cma_num_timesteps and not es.stop():\n solutions = es.ask()\n optimization_path.extend(solutions)\n thetas = [np.matmul(coord, first_2_pcs) + origin_param for coord in solutions]\n logger.log(f\"current time steps num: {total_num_timesteps} total time steps: {cma_args.cma_num_timesteps}\")\n eval_returns = Parallel(n_jobs=cma_args.cores_to_use) \\\n (delayed(eval_return)(cma_args, save_dir, theta, cma_args.eval_num_timesteps, i) for\n (i, theta) in enumerate(thetas))\n\n\n mean_rets.append(np.mean(eval_returns))\n min_rets.append(np.min(eval_returns))\n max_rets.append(np.max(eval_returns))\n\n\n total_num_of_evals += len(eval_returns)\n total_num_timesteps += cma_args.eval_num_timesteps * len(eval_returns)\n\n logger.log(f\"current eval returns: {str(eval_returns)}\")\n logger.log(f\"total timesteps so far: {total_num_timesteps}\")\n negative_eval_returns = [-r for r in eval_returns]\n\n es.tell(solutions, negative_eval_returns)\n es.logger.add() # write data to disc to be plotted\n es.disp()\n\n toc = time.time()\n logger.log(f\"####################################CMA took {toc-tic} seconds\")\n\n es_logger = es.logger\n\n if not hasattr(es_logger, 'xmean'):\n es_logger.load()\n\n\n n_comp_used = first_2_pcs.shape[0]\n optimization_path_mean = np.vstack((starting_coord, es_logger.xmean[:,5:5+n_comp_used]))\n\n\n dump_rows_write_csv(cma_intermediate_data_dir, optimization_path_mean, \"opt_mean_path\")\n\n\n\n plot_dir = get_plot_dir(cma_args)\n cma_plot_dir = get_cma_plot_dir(plot_dir, cma_args.n_comp_to_use, cma_run_num, origin=origin)\n if not os.path.exists(cma_plot_dir):\n os.makedirs(cma_plot_dir)\n\n ret_plot_name = f\"cma return on {cma_args.n_comp_to_use} dim space of real pca plane, \" \\\n f\"explained {np.sum(final_pca.explained_variance_ratio_[:2])}\"\n plot_cma_returns(cma_plot_dir, ret_plot_name, mean_rets, min_rets, max_rets, show=False)\n\n\n\n\n assert proj_coords.shape[1] == 2\n\n xcoordinates_to_eval, ycoordinates_to_eval = gen_subspace_coords(cma_args, np.vstack((proj_coords, optimization_path_mean)).T)\n\n from stable_baselines.ppo2.run_mujoco import eval_return\n thetas_to_eval = [origin_param + x * first_2_pcs[0] + y * first_2_pcs[1] for y in ycoordinates_to_eval for x in\n xcoordinates_to_eval]\n\n tic = time.time()\n\n eval_returns = Parallel(n_jobs=-1, max_nbytes='100M') \\\n (delayed(eval_return)(cma_args, save_dir, theta, cma_args.eval_num_timesteps, i) for (i, theta) in\n enumerate(thetas_to_eval))\n toc = time.time()\n logger.log(f\"####################################1st version took {toc-tic} seconds\")\n\n plot_contour_trajectory(cma_plot_dir, f\"cma redo___{origin}_origin_eval_return_contour_plot\", xcoordinates_to_eval,\n ycoordinates_to_eval, eval_returns, proj_coords[:, 0], proj_coords[:, 1],\n final_pca.explained_variance_ratio_,\n num_levels=25, show=False, sub_alg_path=optimization_path_mean.T)\n\n\n\n opt_mean_path_in_old_basis = [mean_projected_param.dot(first_2_pcs) + mean_param for mean_projected_param in optimization_path_mean]\n distance_to_final = [LA.norm(opt_mean - final_param, ord=2) for opt_mean in opt_mean_path_in_old_basis]\n distance_to_final_plot_name = f\"cma redo distance_to_final over generations \"\n plot_2d(cma_plot_dir, distance_to_final_plot_name, np.arange(len(distance_to_final)), distance_to_final, \"num generation\", \"distance_to_final\", False)\n\n # plot_3d_trajectory(cma_plot_dir, \"end_point_origin_eval_return_3d_plot\", xcoordinates_to_eval, ycoordinates_to_eval,\n # eval_returns, proj_xcoord, proj_ycoord,\n # result[\"explained_variance_ratio\"][:2],\n # num_levels=15, show=False)\n\n\n\nif __name__ == '__main__':\n\n main()\n\n#TODO Give filenames more info to identify which hyperparameter is the data for\n\n"
] | [
[
"numpy.vstack",
"numpy.sum",
"numpy.matmul",
"pandas.read_csv",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.min",
"numpy.max",
"numpy.array",
"sklearn.decomposition.IncrementalPCA",
"numpy.linalg.norm",
"matplotlib.pyplot.xlabel",
"numpy.mean"
]
] |
larsbarring/icclim | [
"f3685c77a1a3aaff58b0d05609380c9387e9aa99"
] | [
"icclim/user_indices/stat.py"
] | [
"from typing import Sequence\n\nimport numpy as np\nimport xarray\nfrom xarray import DataArray\nfrom xclim.indices.run_length import rle_1d\n\n\ndef get_longest_run_start_index(\n arr: DataArray,\n window: int = 1,\n dim: str = \"time\",\n) -> DataArray:\n return xarray.apply_ufunc(\n get_index_of_longest_run,\n arr,\n input_core_dims=[[dim]],\n kwargs={\"window\": window},\n vectorize=True,\n dask=\"parallelized\",\n output_dtypes=[float],\n )\n\n\ndef get_index_of_longest_run(arr: Sequence[bool], window: int = 1) -> int:\n values, rl, pos = rle_1d(arr)\n if not np.any(values) or np.all(values * rl < window): # type:ignore\n return 0\n index_of_max = np.nanargmax(\n np.where(values * rl >= window, rl, np.NaN) # type:ignore\n )\n return pos[index_of_max] # type:ignore\n\n\ndef get_first_occurrence_index(da: DataArray) -> DataArray:\n \"\"\"\n Return the index of the first True value in the 3D booleans array along\n time dimension.\n \"\"\"\n stacked = da.stack(latlon=(\"lat\", \"lon\"))\n res = stacked.argmax(\"time\")\n return res.unstack()\n"
] | [
[
"numpy.any",
"numpy.where",
"numpy.all"
]
] |
Ikerlz/dcd | [
"056e5c4060f9d655ce4f6234b86481ae4b3f7106"
] | [
"DC_method/util.py"
] | [
"import numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nimport itertools\nimport findspark\nimport pyspark\nfrom pyspark.sql.functions import pandas_udf, PandasUDFType\nfrom pyspark.sql.types import *\nimport time\n\n\ndef simulate_sbm_dc_data(sbm_matrix, sample_size=1000, partition_num=10, cluster_num=3):\n \"\"\"\n :param sbm_matrix:\n :param sample_size:\n :param partition_num:\n :param cluster_num:\n :return:\n \"\"\"\n if (sbm_matrix.shape[0] != cluster_num) | \\\n (sbm_matrix.shape[1] != cluster_num) | \\\n (sbm_matrix.shape[0] != sbm_matrix.shape[1]):\n raise Exception(\"sbm_matrix shape Error or the Shape is not equal to Cluster_num\")\n else:\n data_index = [x for x in range(sample_size)]\n data_cluster = np.random.randint(0, cluster_num, sample_size).tolist()\n index_cluster = dict(zip(data_index, data_cluster))\n X = np.empty(shape=[0, 3], dtype=int)\n X = np.append(X, [[0, -1, np.random.randint(0, partition_num, 1)[0]]], axis=0)\n for i in range(1, sample_size):\n p_num = np.random.randint(0, partition_num, 1)[0]\n X = np.append(X, [[i, -1, p_num]], axis=0) # to avoid node lost\n for j in range(i):\n if np.random.binomial(1, sbm_matrix[index_cluster[i], index_cluster[j]], 1):\n X = np.append(X, [[i, j, p_num]], axis=0)\n data_pdf = pd.DataFrame(X, columns=[\"IndexNum1\"] + [\"IndexNum2\"] + [\"PartitionID\"])\n return data_pdf, index_cluster\n\n\ndef get_laplace_matrix(adjacency_matrix, position=\"master\", regularization=False):\n \"\"\"\n :param adjacency_matrix: 邻接矩阵(方阵或长矩阵)\n :param position: master或worker\n :param regularization: 是否进行正则化\n :return: 拉普拉斯矩阵\n \"\"\"\n if regularization:\n if position == \"master\":\n degree = np.sum(adjacency_matrix, axis=1)\n d = np.diag((degree + np.mean(degree)) ** (-0.5)) # 得到度矩阵\n return np.dot(np.dot(d, adjacency_matrix), d)\n\n elif position == \"worker\":\n\n # 2020.7.18 for test\n out_degree = np.sum(adjacency_matrix, axis=1)\n out_degree_matrix = np.diag((out_degree + np.mean(out_degree)) ** (-0.5))\n for i in range(out_degree_matrix.shape[0]):\n if out_degree_matrix[i, i] == np.infty:\n out_degree_matrix[i, i] = 1000\n in_degree = np.sum(adjacency_matrix, axis=0)\n in_degree_matrix = np.diag((in_degree + np.mean(in_degree)) ** (-0.5))\n ###\n laplace_matrix = np.dot(np.dot(out_degree_matrix, adjacency_matrix), in_degree_matrix)\n\n return laplace_matrix\n\n # D = np.diag(np.sum(adjacency_matrix, axis=1) ** (-0.5))\n # F = np.diag(np.sum(adjacency_matrix, axis=0) ** (-0.5))\n # return np.dot(np.dot(D, adjacency_matrix), F) # 得到度矩阵\n\n else:\n raise Exception(\"Input Error: worker or master is expected but {} are given\".format(position))\n else:\n if position == \"master\":\n d = np.diag(np.sum(adjacency_matrix, axis=1) ** (-0.5)) # 得到度矩阵\n return np.dot(np.dot(d, adjacency_matrix), d)\n\n elif position == \"worker\":\n out_degree_matrix = np.diag(np.sum(adjacency_matrix, axis=1) ** (-0.5))\n for i in range(out_degree_matrix.shape[0]):\n if out_degree_matrix[i, i] == np.infty:\n out_degree_matrix[i, i] = 10000\n in_degree_matrix = np.diag(np.sum(adjacency_matrix, axis=0) ** (-0.5))\n laplace_matrix = np.dot(np.dot(out_degree_matrix, adjacency_matrix), in_degree_matrix)\n\n return laplace_matrix\n\n # D = np.diag(np.sum(adjacency_matrix, axis=1) ** (-0.5))\n # F = np.diag(np.sum(adjacency_matrix, axis=0) ** (-0.5))\n # return np.dot(np.dot(D, adjacency_matrix), F) # 得到度矩阵\n\n else:\n raise Exception(\"Input Error: worker or master is expected but {} are given\".format(position))\n\n\ndef get_spectral(laplace_matrix, k, normalization=False, method='svd'):\n \"\"\"\n :param laplace_matrix: 拉普拉斯矩阵\n :param k: 截取SVD后的前k个向量\n :param normalization: 是否归一化\n :param method: 选择用奇异值分解(SVD)还是特征值分解(EVD)\n :return: 得到的谱\n \"\"\"\n if method == 'svd':\n u, _, _ = np.linalg.svd(laplace_matrix)\n spectral = u[:, list(range(k))]\n if normalization:\n row_len = len(u) # 行数\n for i in range(row_len):\n norm2 = np.linalg.norm(spectral[i])\n if norm2:\n spectral[i] = spectral[i] / np.linalg.norm(spectral[i])\n elif method == 'evd':\n e_vals, e_vecs = np.linalg.eig(laplace_matrix)\n sorted_indices = np.argsort(e_vals)\n spectral = e_vecs[:, sorted_indices[:-k-1:-1]]\n if normalization:\n row_len = len(e_vecs) # 行数\n for i in range(row_len):\n norm2 = np.linalg.norm(spectral[i])\n if norm2:\n spectral[i] = spectral[i] / np.linalg.norm(spectral[i])\n else:\n raise ValueError(\"method must be 'svd' or 'evd' but {} is given\".format(method))\n\n return spectral\n\n\ndef worker_clustering(worker_df, cluster_num):\n \"\"\"\n :param worker_df:\n :param method:\n :param cluster_num:\n :return:\n \"\"\"\n node_list = list(set(worker_df[\"IndexNum1\"].tolist()))\n node_num = len(node_list)\n index_list = [x for x in range(node_num)]\n node2index = dict(zip(node_list, index_list))\n adj_matrix = np.zeros((node_num, node_num), dtype=int)\n for i in range(node_num):\n adj_matrix[i][i] = 10\n for row in worker_df.itertuples(index=False, name='Pandas'):\n item1 = getattr(row, \"IndexNum1\")\n item2 = getattr(row, \"IndexNum2\")\n if (item2 in node_list) & (item2 != -1):\n adj_matrix[node2index[item1]][node2index[item2]] = 1\n adj_matrix[node2index[item2]][node2index[item1]] = 1\n\n # first, get the laplace matrix\n laplace_matrix = get_laplace_matrix(adj_matrix,\n position='master',\n regularization=False)\n\n # second, get the spectral\n spectral = get_spectral(laplace_matrix, cluster_num, normalization=False, method='svd')\n\n # third, do k-means in spectral\n model = KMeans(n_clusters=cluster_num)\n model_fit = model.fit(spectral) # do k_means in spectral_transpose\n # cluster_center = model_fit.cluster_centers_ # center points\n cluster_label = list(model_fit.labels_) # labels (cluster information)\n # return\n worker_num = worker_df[\"PartitionID\"].tolist()[0]\n out_df = pd.DataFrame({\"PartitionID\": [worker_num for _ in range(len(node_list))],\n \"IndexNum\": node_list,\n \"ClusterExp\": cluster_label})\n return out_df\n\n\ndef get_accurate(clustering_res_df, cluster_number, error=False):\n \"\"\"\n :param clustering_res_df: a pandas DataFrame about clustering result\n :param cluster_number: the number of the cluster\n (the first column is the index,\n the second column is the right information,\n the third column is the clustering information)\n :param error: if error=True, then return the error rate, else, return the accuracy rate\n :return: the clustering accuracy\n \"\"\"\n if clustering_res_df.shape[1] != 3:\n raise Exception(\"Shape Error: the input DataFrame's column number is not 3\")\n real_dict = {}\n clustering_dict = {}\n for i in range(cluster_number):\n real_df = clustering_res_df.loc[clustering_res_df['ClusterInfo'] == i]\n clustering_df = clustering_res_df.loc[clustering_res_df['ClusterExp'] == i]\n real_dict[i] = real_df['IndexNum'].tolist()\n clustering_dict[i] = clustering_df['IndexNum'].tolist()\n\n accuracy_matrix = np.zeros((cluster_number, cluster_number))\n for i in range(cluster_number):\n for j in range(cluster_number):\n accuracy_matrix[i][j] = len(set(real_dict[i]).intersection(set(clustering_dict[j])))\n # for test\n # print(\"The accuracy matrix is: \\n\", accuracy_matrix)\n case_iterator = itertools.permutations(range(cluster_number), cluster_number)\n\n accurate = 0\n\n for item in case_iterator:\n acc = sum([accuracy_matrix[i][item[i]] for i in range(cluster_number)])\n if acc > accurate:\n accurate = acc\n if not error:\n return accurate / clustering_res_df.shape[0]\n else:\n return 1 - accurate / clustering_res_df.shape[0]\n\n\n\n\n# TODO some SBM matrix\n\n\nsbm_matrix1 = np.array([[0.7, 0.45, 0.45],\n [0.45, 0.7, 0.45],\n [0.45, 0.45, 0.7]])\nsbm_matrix2 = np.array([[0.8, 0.4, 0.4],\n [0.4, 0.8, 0.4],\n [0.4, 0.4, 0.8]])\nsbm_matrix3 = np.array([[0.6, 0.45, 0.45],\n [0.45, 0.6, 0.45],\n [0.45, 0.45, 0.6]])\nsbm_matrix4 = np.array([[0.2, 0.1, 0.1],\n [0.1, 0.2, 0.1],\n [0.1, 0.1, 0.2]])\n\n\n\nif __name__ == '__main__':\n # Model Settings\n sbm_matrix = sbm_matrix4\n sample_size = 1000\n master_num = 100\n worker_per_sub = 20\n partition_num = 50\n cluster_num = 3\n a, b = simulate_sbm_dc_data(sbm_matrix)\n c = worker_clustering(a, 3)\n real_label = []\n for row in c.itertuples(index=False, name='Pandas'):\n item = getattr(row, \"IndexNum\")\n real_label.append(b[item])\n c[\"ClusterInfo\"] = real_label\n print(get_accurate(c, 3))\n print(c)\n # print(a)\n"
] | [
[
"numpy.random.binomial",
"numpy.sum",
"numpy.empty",
"numpy.zeros",
"numpy.append",
"pandas.DataFrame",
"numpy.argsort",
"numpy.linalg.svd",
"sklearn.cluster.KMeans",
"numpy.array",
"numpy.dot",
"numpy.random.randint",
"numpy.linalg.norm",
"numpy.linalg.eig",
"numpy.mean"
]
] |
denix56/fcdd | [
"d110aa8b141dc13f47156da913a6b4f9d64ddc74"
] | [
"python/fcdd/datasets/outlier_exposure/emnist.py"
] | [
"import os.path as pt\n\nimport numpy as np\nimport torchvision.transforms as transforms\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import EMNIST\n\n\ndef ceil(x: float):\n return int(np.ceil(x))\n\n\nclass MyEMNIST(EMNIST):\n \"\"\" Reimplements get_item to transform tensor input to pil image before applying transformation. \"\"\"\n def __getitem__(self, index):\n img, target = self.data[index], self.targets[index]\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = transforms.ToPILImage()(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, target\n\n\nclass OEEMNIST(EMNIST):\n def __init__(self, size: torch.Size, root: str = None, split='letters', limit_var=20): # split = Train\n \"\"\"\n Outlier Exposure dataset for EMNIST.\n :param size: size of the samples in n x c x h x w, samples will be resized to h x w. If n is larger than the\n number of samples available in EMNIST, dataset will be enlarged by repetitions to fit n.\n This is important as exactly n images are extracted per iteration of the data_loader.\n For online supervision n should be set to 1 because only one sample is extracted at a time.\n :param root: root directory where data is found or is to be downloaded to.\n :param split: The dataset has 6 different splits: ``byclass``, ``bymerge``,\n ``balanced``, ``letters``, ``digits`` and ``mnist``. This argument specifies\n which one to use.\n :param limit_var: limits the number of different samples, i.e. randomly chooses limit_var many samples\n from all available ones to be the training data.\n \"\"\"\n assert len(size) == 3 and size[1] == size[2]\n root = pt.join(root, 'emnist', )\n transform = transforms.Compose([\n transforms.Resize((size[1], size[2])),\n transforms.ToTensor()\n ])\n super().__init__(root, split, transform=transform, download=True)\n self.size = size\n self.data = self.data.transpose(1, 2)\n self.idx_to_class = {v: k for k, v in self.class_to_idx.items()}\n if limit_var is not None and limit_var < len(self):\n picks = np.random.choice(np.arange(self.data.size(0)), size=limit_var, replace=False)\n self.data = self.data[picks]\n self.targets = self.targets[picks]\n if limit_var is not None and limit_var > len(self):\n print(\n 'OEEMNIST shall be limited to {} samples, but Cifar100 contains only {} samples, thus using all.'\n .format(limit_var, len(self))\n )\n if len(self) < size[0]:\n rep = ceil(size[0] / len(self))\n old = len(self)\n self.data = self.data.repeat(rep, 1, 1)\n self.targets = self.targets.repeat(rep)\n if rep != size[0] / old:\n import warnings\n warnings.warn(\n 'OEEMNIST has been limited to {} samples. '\n 'Due to the requested size of {}, the dataset will be enlarged. ' \n 'But {} repetitions will make some samples appear more often than others in the dataset, '\n 'because the final size after repetitions is {}, which is cut to {}'\n .format(limit_var, size[0], rep, len(self), size[0])\n )\n\n def data_loader(self):\n return DataLoader(dataset=self, batch_size=self.size[0], shuffle=True, num_workers=0)\n\n def __getitem__(self, index):\n sample, target = super().__getitem__(index)\n sample = sample.squeeze().mul(255).byte()\n\n return sample\n\n"
] | [
[
"torch.utils.data.DataLoader",
"numpy.ceil"
]
] |
ava6969/rgb_stacking_extend | [
"a36f1e35aa796e77201321161056e174966e7707"
] | [
"rgb_stacking/contrib/common.py"
] | [
"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom rgb_stacking.utils.utils import init\n\n\nclass Flatten(nn.Module):\n def forward(self, x):\n return x.view(x.size(0), -1)\n\n\nclass Sum(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, x):\n return torch.sum(x, self.dim)\n\n\nclass Mean(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, x):\n return torch.mean(x, self.dim)\n\n\ndef init_rec(rec):\n for name, param in rec.named_parameters():\n if 'bias' in name:\n nn.init.constant_(param, 0)\n elif 'weight' in name:\n nn.init.orthogonal_(param)\n return rec\n\n\ndef init_(m):\n return init(m, nn.init.orthogonal_, lambda x: nn.init.\n constant_(x, 0), np.sqrt(2))\n\n\n"
] | [
[
"torch.sum",
"torch.nn.init.constant_",
"numpy.sqrt",
"torch.nn.init.orthogonal_",
"torch.mean"
]
] |
SunsetWolf/qlib | [
"89972f6c6f9fa629b4f74093d4ba1e93c9f7a5e5"
] | [
"qlib/contrib/data/highfreq_processor.py"
] | [
"import os\n\nimport numpy as np\nimport pandas as pd\nfrom qlib.data.dataset.processor import Processor\nfrom qlib.data.dataset.utils import fetch_df_by_index\nfrom typing import Dict\n\n\nclass HighFreqTrans(Processor):\n def __init__(self, dtype: str = \"bool\"):\n self.dtype = dtype\n\n def fit(self, df_features):\n pass\n\n def __call__(self, df_features):\n if self.dtype == \"bool\":\n return df_features.astype(np.int8)\n else:\n return df_features.astype(np.float32)\n\n\nclass HighFreqNorm(Processor):\n def __init__(\n self,\n fit_start_time: pd.Timestamp,\n fit_end_time: pd.Timestamp,\n feature_save_dir: str,\n norm_groups: Dict[str, int],\n ):\n\n self.fit_start_time = fit_start_time\n self.fit_end_time = fit_end_time\n self.feature_save_dir = feature_save_dir\n self.norm_groups = norm_groups\n\n def fit(self, df_features) -> None:\n if os.path.exists(self.feature_save_dir) and len(os.listdir(self.feature_save_dir)) != 0:\n return\n os.makedirs(self.feature_save_dir)\n fetch_df = fetch_df_by_index(df_features, slice(self.fit_start_time, self.fit_end_time), level=\"datetime\")\n del df_features\n index = 0\n names = {}\n for name, dim in self.norm_groups.items():\n names[name] = slice(index, index + dim)\n index += dim\n for name, name_val in names.items():\n df_values = fetch_df.iloc(axis=1)[name_val].values\n if name.endswith(\"volume\"):\n df_values = np.log1p(df_values)\n self.feature_mean = np.nanmean(df_values)\n np.save(self.feature_save_dir + name + \"_mean.npy\", self.feature_mean)\n df_values = df_values - self.feature_mean\n self.feature_std = np.nanstd(np.absolute(df_values))\n np.save(self.feature_save_dir + name + \"_std.npy\", self.feature_std)\n df_values = df_values / self.feature_std\n np.save(self.feature_save_dir + name + \"_vmax.npy\", np.nanmax(df_values))\n np.save(self.feature_save_dir + name + \"_vmin.npy\", np.nanmin(df_values))\n return\n\n def __call__(self, df_features):\n if \"date\" in df_features:\n df_features.droplevel(\"date\", inplace=True)\n df_values = df_features.values\n index = 0\n names = {}\n for name, dim in self.norm_groups.items():\n names[name] = slice(index, index + dim)\n index += dim\n for name, name_val in names.items():\n feature_mean = np.load(self.feature_save_dir + name + \"_mean.npy\")\n feature_std = np.load(self.feature_save_dir + name + \"_std.npy\")\n\n if name.endswith(\"volume\"):\n df_values[:, name_val] = np.log1p(df_values[:, name_val])\n df_values[:, name_val] -= feature_mean\n df_values[:, name_val] /= feature_std\n df_features = pd.DataFrame(data=df_values, index=df_features.index, columns=df_features.columns)\n return df_features.fillna(0)\n"
] | [
[
"numpy.save",
"numpy.log1p",
"numpy.load",
"numpy.nanmax",
"numpy.nanmean",
"pandas.DataFrame",
"numpy.nanmin",
"numpy.absolute"
]
] |
hgKwak/SeriesSleepNet- | [
"1e90c3a0ed6244c2b876979194d7cd94056f5c8a"
] | [
"network/cnn.py"
] | [
"import torch\nimport torch.nn as nn\n\nuse_cuda = torch.cuda.is_available()\nclass CNNClassifier(nn.Module):\n def __init__(self, channel, SHHS=False):\n super(CNNClassifier, self).__init__()\n conv1 = nn.Conv2d(1, 10, (1, 200))\n pool1 = nn.MaxPool2d((1, 2))\n if channel == 1:\n conv2 = nn.Conv2d(10, 20, (1, 32))\n conv3 = nn.Conv2d(20, 30, (1, 128))\n conv4 = nn.Conv2d(30, 40, (1, 512))\n freq = 1\n else:\n conv2 = nn.Conv2d(10, 20, (2, 32))\n conv3 = nn.Conv2d(20, 30, (2, 128))\n conv4 = nn.Conv2d(30, 40, (2, 512))\n freq=channel-3\n pool2 = nn.MaxPool2d((1, 2))\n self.conv_module = nn.Sequential(conv1, nn.ReLU(), pool1, conv2, nn.ReLU(), conv3, nn.ReLU(), conv4, nn.ReLU(), pool2)\n\n if SHHS:\n fc1 = nn.Linear(freq * 40 * 553, 100)\n else:\n fc1 = nn.Linear(freq*40*365, 100)\n fc2 = nn.Linear(100, 5)\n\n self.fc_module = nn.Sequential(fc1, nn.ReLU(), fc2)\n\n if use_cuda:\n self.conv_module = self.conv_module.cuda()\n self.fc_module = self.fc_module.cuda()\n\n def forward(self, x, isfc):\n out = self.conv_module(x)\n dim = 1\n for d in out.size()[1:]:\n dim *= d\n if isfc:\n out = out.view(-1, dim)\n out = self.fc_module(out)\n else:\n out = out.permute(0, 3, 2, 1).reshape([-1, 200, 73])\n return out"
] | [
[
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.cuda.is_available",
"torch.nn.Conv2d",
"torch.nn.ReLU"
]
] |
WildflowerSchools/wf-cv-utils | [
"647a2a46e3d6e6e14a1f813d17064cb33a3ced92"
] | [
"cv_utils/core.py"
] | [
"import cv_datetime_utils\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize\nimport json\nimport os\n\ndef compose_transformations(\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2):\n rotation_vector_1 = np.asarray(rotation_vector_1).reshape(3)\n translation_vector_1 = np.asarray(translation_vector_1).reshape(3)\n rotation_vector_2 = np.asarray(rotation_vector_2).reshape(3)\n translation_vector_2 = np.asarray(translation_vector_2).reshape(3)\n rotation_vector_composed, translation_vector_composed = cv.composeRT(\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2)[:2]\n rotation_vector_composed = np.squeeze(rotation_vector_composed)\n translation_vector_composed = np.squeeze(translation_vector_composed)\n return rotation_vector_composed, translation_vector_composed\n\n\ndef invert_transformation(\n rotation_vector,\n translation_vector):\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n translation_vector = np.asarray(translation_vector).reshape(3)\n new_rotation_vector, new_translation_vector = compose_transformations(\n np.array([0.0, 0.0, 0.0]),\n -translation_vector,\n -rotation_vector,\n np.array([0.0, 0.0, 0.0]))\n new_rotation_vector = np.squeeze(new_rotation_vector)\n new_translation_vector = np.squeeze(new_translation_vector)\n return new_rotation_vector, new_translation_vector\n\ndef quaternion_vector_to_rotation_vector(quaternion_vector):\n quaternion_vector = np.asarray(quaternion_vector).reshape(4)\n spatial_vector = quaternion_vector[1:]\n qw = quaternion_vector[0]\n spatial_vector_length = np.linalg.norm(spatial_vector)\n unit_vector = spatial_vector/spatial_vector_length\n theta = 2*np.arctan2(spatial_vector_length, qw)\n rotation_vector = theta*unit_vector\n return rotation_vector\n\ndef quaternion_vector_to_rotation_matrix(quaternion_vector):\n quaternion_tuple = tuple(np.asarray(quaternion_vector).reshape(4))\n qw, qx, qy, qz = quaternion_tuple\n R = np.array([\n [qw**2 + qx**2 - qy**2 - qz**2, 2*(qx*qy - qw*qz), 2*(qw*qy + qx*qz)],\n [2*(qx*qy + qw*qz), qw**2 - qx**2 + qy**2 - qz**2, 2*(qy*qz - qw*qx)],\n [2*(qx*qz - qw*qy), 2*(qw*qx + qy*qz), qw**2 - qx**2 - qy**2 + qz**2]\n ])\n return R\n\ndef rotation_vector_to_rotation_matrix(rotation_vector):\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n rotation_matrix = cv.Rodrigues(rotation_vector)[0]\n return rotation_matrix\n\ndef transform_object_points(\n object_points,\n rotation_vector=np.array([0.0, 0.0, 0.0]),\n translation_vector=np.array([0.0, 0.0, 0.0])):\n object_points = np.asarray(object_points)\n rotation_vector = np.asarray(rotation_vector)\n translation_vector = np.asarray(translation_vector)\n if object_points.size == 0:\n return object_points\n object_points = object_points.reshape((-1, 3))\n rotation_vector = rotation_vector.reshape(3)\n translation_vector = translation_vector.reshape(3)\n transformed_points = np.add(\n np.matmul(\n cv.Rodrigues(rotation_vector)[0],\n object_points.T).T,\n translation_vector.reshape((1, 3)))\n transformed_points = np.squeeze(transformed_points)\n return transformed_points\n\n\ndef generate_camera_pose(\n camera_position=np.array([0.0, 0.0, 0.0]),\n yaw=0.0,\n pitch=0.0,\n roll=0.0):\n # yaw: 0.0 points north (along the positive y-axis), positive angles rotate counter-clockwise\n # pitch: 0.0 is level with the ground, positive angles rotate upward\n # roll: 0.0 is level with the ground, positive angles rotate clockwise\n # All angles in radians\n camera_position = np.asarray(camera_position).reshape(3)\n # First: Move the camera to the specified position\n rotation_vector_1 = np.array([0.0, 0.0, 0.0])\n translation_vector_1 = -camera_position\n # Second: Rotate the camera so when we lower to the specified inclination, it will point in the specified compass direction\n rotation_vector_2 = np.array([0.0, 0.0, -(yaw - np.pi / 2)])\n translation_vector_2 = np.array([0.0, 0.0, 0.0])\n # Third: Lower to the specified inclination\n rotation_vector_2_3 = np.array([(np.pi / 2 - pitch), 0.0, 0.0])\n translation_vector_2_3 = np.array([0.0, 0.0, 0.0])\n # Fourth: Roll the camera by the specified angle\n rotation_vector_2_3_4 = np.array([0.0, 0.0, -roll])\n translation_vector_2_3_4 = np.array([0.0, 0.0, 0.0])\n # Combine these four moves\n rotation_vector_1_2, translation_vector_1_2 = compose_transformations(\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2)\n rotation_vector_1_2_3, translation_vector_1_2_3 = compose_transformations(\n rotation_vector_1_2,\n translation_vector_1_2,\n rotation_vector_2_3,\n translation_vector_2_3)\n rotation_vector, translation_vector = compose_transformations(\n rotation_vector_1_2_3,\n translation_vector_1_2_3,\n rotation_vector_2_3_4,\n translation_vector_2_3_4)\n rotation_vector = np.squeeze(rotation_vector)\n translation_vector = np.squeeze(translation_vector)\n return rotation_vector, translation_vector\n\n\ndef extract_camera_position(\n rotation_vector,\n translation_vector):\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n translation_vector = np.asarray(translation_vector).reshape(3)\n new_rotation_vector, new_translation_vector = compose_transformations(\n rotation_vector,\n translation_vector,\n -rotation_vector,\n np.array([0.0, 0.0, 0.0]))\n camera_position = -np.squeeze(new_translation_vector)\n return camera_position\n\ndef extract_camera_position_rotation_matrix(rotation_matrix, translation_vector):\n rotation_matrix = np.asarray(rotation_matrix).reshape((3,3))\n translation_vector = np.asarray(translation_vector).reshape(3)\n position = np.matmul(rotation_matrix.T, -translation_vector.T)\n return position\n\ndef extract_camera_direction(\n rotation_vector,\n translation_vector):\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n translation_vector = np.asarray(translation_vector).reshape(3)\n camera_direction = np.matmul(\n cv.Rodrigues(-rotation_vector)[0],\n np.array([[0.0], [0.0], [1.0]]))\n camera_direction = np.squeeze(camera_direction)\n return camera_direction\n\n\ndef reconstruct_z_rotation(x, y):\n if x >= 0.0 and y >= 0.0:\n return np.arctan(y / x)\n if x >= 0.0 and y < 0.0:\n return np.arctan(y / x) + 2 * np.pi\n return np.arctan(y / x) + np.pi\n\n\n# Currently unused; needs to be fixed up for cases in which x and/or y are close\n# to zero\ndef extract_yaw_from_camera_direction(\n camera_direction):\n camera_direction = np.asarray(camera_direction).reshape(3)\n yaw = reconstruct_z_rotation(\n camera_direction[0],\n camera_direction[1])\n return yaw\n\n\ndef generate_camera_matrix(\n focal_length,\n principal_point):\n focal_length = np.asarray(focal_length).reshape(2)\n principal_point = np.asarray(principal_point).reshape(2)\n camera_matrix = np.array([\n [focal_length[0], 0, principal_point[0]],\n [0, focal_length[1], principal_point[1]],\n [0, 0, 1.0]])\n return camera_matrix\n\n\ndef generate_projection_matrix(\n camera_matrix,\n rotation_vector,\n translation_vector):\n camera_matrix = np.asarray(camera_matrix).reshape((3, 3))\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n translation_vector = np.asarray(translation_vector).reshape(3)\n projection_matrix = np.matmul(\n camera_matrix,\n np.concatenate((\n cv.Rodrigues(rotation_vector)[0],\n translation_vector.reshape((3, 1))),\n axis=1))\n return(projection_matrix)\n\ndef ground_grid_camera_view(\n image_width,\n image_height,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients=np.array([0.0, 0.0, 0.0, 0.0]),\n fill_image=False,\n step=0.1\n):\n grid_corners = ground_rectangle_camera_view(\n image_width=image_width,\n image_height=image_height,\n rotation_vector=rotation_vector,\n translation_vector=translation_vector,\n camera_matrix=camera_matrix,\n distortion_coefficients=distortion_coefficients,\n fill_image=fill_image\n )\n grid_points = generate_ground_grid(\n grid_corners=grid_corners,\n step=step\n )\n return grid_points\n\ndef ground_rectangle_camera_view(\n image_width,\n image_height,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients=np.array([0.0, 0.0, 0.0, 0.0]),\n fill_image=False\n):\n image_points = np.array([\n [0.0, 0.0],\n [image_width, 0.0],\n [image_width, image_height],\n [0.0, image_height]\n ])\n ground_points=np.empty((4, 3))\n for i in range(4):\n ground_points[i] = ground_point(\n image_point=image_points[i],\n rotation_vector=rotation_vector,\n translation_vector=translation_vector,\n camera_matrix=camera_matrix,\n distortion_coefficients=distortion_coefficients\n )\n x_values_sorted = np.sort(ground_points[:, 0])\n y_values_sorted = np.sort(ground_points[:, 1])\n if fill_image:\n x_min = x_values_sorted[0]\n x_max = x_values_sorted[3]\n y_min = y_values_sorted[0]\n y_max = y_values_sorted[3]\n else:\n x_min = x_values_sorted[1]\n x_max = x_values_sorted[2]\n y_min = y_values_sorted[1]\n y_max = y_values_sorted[2]\n return np.array([\n [x_min, y_min],\n [x_max, y_max]\n ])\n\ndef ground_point(\n image_point,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients=np.array([0.0, 0.0, 0.0, 0.0])\n):\n image_point = np.asarray(image_point)\n rotation_vector = np.asarray(rotation_vector)\n translation_vector = np.asarray(translation_vector)\n camera_matrix = np.asarray(camera_matrix)\n distortion_coefficients = np.asarray(distortion_coefficients)\n image_point = image_point.reshape((2))\n rotation_vector = rotation_vector.reshape(3)\n translation_vector = translation_vector.reshape(3)\n camera_matrix = camera_matrix.reshape((3, 3))\n image_point_undistorted = cv.undistortPoints(\n image_point,\n camera_matrix,\n distortion_coefficients,\n P=camera_matrix\n )\n image_point_undistorted = np.squeeze(image_point_undistorted)\n camera_position = np.matmul(\n cv.Rodrigues(-rotation_vector)[0],\n -translation_vector.T\n ).T\n camera_point_homogeneous = np.matmul(\n np.linalg.inv(camera_matrix),\n np.array([image_point_undistorted[0], image_point_undistorted[1], 1.0]).T\n ).T\n camera_direction = np.matmul(\n cv.Rodrigues(-rotation_vector)[0],\n camera_point_homogeneous.T\n ).T\n theta = -camera_position[2]/camera_direction[2]\n ground_point = camera_position + theta*camera_direction\n return ground_point\n\ndef generate_ground_grid(\n grid_corners,\n step=0.1\n):\n x_grid, y_grid = np.meshgrid(\n np.arange(grid_corners[0, 0], grid_corners[1, 0], step=step),\n np.arange(grid_corners[0, 1], grid_corners[1, 1], step=step)\n )\n grid = np.stack((x_grid, y_grid, np.full_like(x_grid, 0.0)), axis=-1)\n points = grid.reshape((-1, 3))\n return points\n\ndef project_points(\n object_points,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients,\n remove_behind_camera=False,\n remove_outside_frame=False,\n image_corners=None\n):\n object_points = np.asarray(object_points).reshape((-1, 3))\n rotation_vector = np.asarray(rotation_vector).reshape(3)\n translation_vector = np.asarray(translation_vector).reshape(3)\n camera_matrix = np.asarray(camera_matrix).reshape((3, 3))\n distortion_coefficients = np.squeeze(np.asarray(distortion_coefficients))\n if object_points.size == 0:\n return np.zeros((0, 2))\n image_points = cv.projectPoints(\n object_points,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients\n )[0]\n if remove_behind_camera:\n behind_camera_boolean = behind_camera(\n object_points,\n rotation_vector,\n translation_vector\n )\n image_points[behind_camera_boolean] = np.array([np.nan, np.nan])\n if remove_outside_frame:\n outside_frame_boolean = outside_frame(\n object_points,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients,\n image_corners\n )\n image_points[outside_frame_boolean] = np.array([np.nan, np.nan])\n image_points = np.squeeze(image_points)\n return image_points\n\ndef behind_camera(\n object_points,\n rotation_vector,\n translation_vector):\n object_points = np.asarray(object_points)\n rotation_vector = np.asarray(rotation_vector)\n translation_vector = np.asarray(translation_vector)\n if object_points.size == 0:\n return np.zeros((0, 2))\n object_points = object_points.reshape((-1, 3))\n rotation_vector = rotation_vector.reshape(3)\n translation_vector = translation_vector.reshape(3)\n object_points_transformed = transform_object_points(\n object_points,\n rotation_vector,\n translation_vector\n )\n behind_camera_boolean = (object_points_transformed <= 0)[..., 2]\n return behind_camera_boolean\n\ndef outside_frame(\n object_points,\n rotation_vector,\n translation_vector,\n camera_matrix,\n distortion_coefficients,\n image_corners\n):\n object_points = np.asarray(object_points).reshape((-1, 3))\n rotation_vector = np.asarray(rotation_vector)\n translation_vector = np.asarray(translation_vector).reshape(3)\n camera_matrix = np.asarray(camera_matrix).reshape((3,3))\n distortion_coefficients = np.squeeze(np.asarray(distortion_coefficients))\n image_corners = np.asarray(image_corners).reshape((2,2))\n if object_points.size == 0:\n return np.zeros((0, 2))\n image_points = cv.projectPoints(\n object_points,\n rotation_vector,\n translation_vector,\n camera_matrix,\n np.array([0.0, 0.0, 0.0, 0.0])\n )[0]\n image_points = image_points.reshape((-1, 2))\n outside_frame_boolean = (\n (image_points[:, 0] < image_corners[0, 0]) |\n (image_points[:, 0] > image_corners[1, 0]) |\n (image_points[:, 1] < image_corners[0, 1]) |\n (image_points[:, 1] > image_corners[1, 1])\n )\n return outside_frame_boolean\n\n\ndef undistort_points(\n image_points,\n camera_matrix,\n distortion_coefficients):\n image_points = np.asarray(image_points)\n camera_matrix = np.asarray(camera_matrix)\n distortion_coefficients = np.asarray(distortion_coefficients)\n if image_points.size == 0:\n return image_points\n image_points = image_points.reshape((-1, 1, 2))\n camera_matrix = camera_matrix.reshape((3, 3))\n undistorted_points = cv.undistortPoints(\n image_points,\n camera_matrix,\n distortion_coefficients,\n P=camera_matrix)\n undistorted_points = np.squeeze(undistorted_points)\n return undistorted_points\n\n\ndef estimate_camera_pose_from_image_points(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1=np.array([0.0, 0.0, 0.0]),\n translation_vector_1=np.array([0.0, 0.0, 0.0]),\n distance_between_cameras=1.0):\n image_points_1 = np.asarray(image_points_1)\n image_points_2 = np.asarray(image_points_2)\n camera_matrix = np.asarray(camera_matrix)\n rotation_vector_1 = np.asarray(rotation_vector_1)\n translation_vector_1 = np.asarray(translation_vector_1)\n if image_points_1.size == 0 or image_points_2.size == 0:\n raise ValueError('One or both sets of image points appear to be empty')\n image_points_1 = image_points_1.reshape((-1, 2))\n image_points_2 = image_points_2.reshape((-1, 2))\n if image_points_1.shape != image_points_2.shape:\n raise ValueError('Sets of image points do not appear to be the same shape')\n camera_matrix = camera_matrix.reshape((3, 3))\n rotation_vector_1 = rotation_vector_1.reshape(3)\n translation_vector_1 = translation_vector_1.reshape(3)\n essential_matrix, mask = cv.findEssentialMat(\n image_points_1,\n image_points_2,\n camera_matrix)\n relative_rotation_matrix, relative_translation_vector = cv.recoverPose(\n essential_matrix,\n image_points_1,\n image_points_2,\n camera_matrix,\n mask=mask)[1:3]\n relative_rotation_vector = cv.Rodrigues(relative_rotation_matrix)[0]\n relative_translation_vector = relative_translation_vector * distance_between_cameras\n rotation_vector_2, translation_vector_2 = compose_transformations(\n rotation_vector_1,\n translation_vector_1,\n relative_rotation_vector,\n relative_translation_vector)\n rotation_vector_2 = np.squeeze(rotation_vector_2)\n translation_vector_2 = np.squeeze(translation_vector_2)\n return rotation_vector_2, translation_vector_2\n\n\ndef reconstruct_object_points_from_camera_poses(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2):\n image_points_1 = np.asarray(image_points_1)\n image_points_2 = np.asarray(image_points_2)\n camera_matrix = np.asarray(camera_matrix)\n rotation_vector_1 = np.asarray(rotation_vector_1)\n translation_vector_1 = np.asarray(translation_vector_1)\n rotation_vector_2 = np.asarray(rotation_vector_2)\n translation_vector_2 = np.asarray(translation_vector_2)\n if image_points_1.size == 0 or image_points_2.size == 0:\n return np.zeros((0, 3))\n image_points_1 = image_points_1.reshape((-1, 2))\n image_points_2 = image_points_2.reshape((-1, 2))\n if image_points_1.shape != image_points_2.shape:\n raise ValueError('Sets of image points do not appear to be the same shape')\n camera_matrix = camera_matrix.reshape((3, 3))\n rotation_vector_1 = rotation_vector_1.reshape(3)\n translation_vector_1 = translation_vector_1.reshape(3)\n rotation_vector_2 = rotation_vector_2.reshape(3)\n translation_vector_2 = translation_vector_2.reshape(3)\n projection_matrix_1 = generate_projection_matrix(\n camera_matrix,\n rotation_vector_1,\n translation_vector_1)\n projection_matrix_2 = generate_projection_matrix(\n camera_matrix,\n rotation_vector_2,\n translation_vector_2)\n object_points_homogeneous = cv.triangulatePoints(\n projection_matrix_1,\n projection_matrix_2,\n image_points_1.T,\n image_points_2.T)\n object_points = cv.convertPointsFromHomogeneous(\n object_points_homogeneous.T)\n object_points = np.squeeze(object_points)\n return object_points\n\n\ndef reconstruct_object_points_from_relative_camera_pose(\n image_points_1,\n image_points_2,\n camera_matrix,\n relative_rotation_vector,\n relative_translation_vector,\n rotation_vector_1=np.array([[0.0], [0.0], [0.0]]),\n translation_vector_1=np.array([[0.0], [0.0], [0.0]]),\n distance_between_cameras=1.0):\n image_points_1 = np.asarray(image_points_1)\n image_points_2 = np.asarray(image_points_2)\n camera_matrix = np.asarray(camera_matrix)\n relative_rotation_vector = np.asarray(relative_rotation_vector)\n relative_translation_vector = np.asarray(relative_translation_vector)\n rotation_vector_1 = np.asarray(rotation_vector_1)\n translation_vector_1 = np.asarray(translation_vector_1)\n if image_points_1.size == 0 or image_points_2.size == 0:\n return np.zeros((0, 3))\n image_points_1 = image_points_1.reshape((-1, 2))\n image_points_2 = image_points_2.reshape((-1, 2))\n if image_points_1.shape != image_points_2.shape:\n raise ValueError('Sets of image points do not appear to be the same shape')\n camera_matrix = camera_matrix.reshape((3, 3))\n relative_rotation_vector = relative_rotation_vector.reshape(3)\n relative_translation_vector = relative_translation_vector.reshape(3)\n rotation_vector_1 = rotation_vector_1.reshape(3)\n translation_vector_1 = translation_vector_1.reshape(3)\n rotation_vector_2, translation_vector_2 = cv.composeRT(\n rotation_vector_1,\n translation_vector_1,\n relative_rotation_vector,\n relative_translation_vector * distance_between_cameras)[:2]\n object_points = reconstruct_object_points_from_camera_poses(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2)\n return object_points\n\n\ndef reconstruct_object_points_from_image_points(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1=np.array([[0.0], [0.0], [0.0]]),\n translation_vector_1=np.array([[0.0], [0.0], [0.0]]),\n distance_between_cameras=1.0):\n image_points_1 = np.asarray(image_points_1)\n image_points_2 = np.asarray(image_points_2)\n camera_matrix = np.asarray(camera_matrix)\n rotation_vector_1 = np.asarray(rotation_vector_1)\n translation_vector_1 = np.asarray(translation_vector_1)\n if image_points_1.size == 0 or image_points_2.size == 0:\n return np.zeros((0, 3))\n image_points_1 = image_points_1.reshape((-1, 2))\n image_points_2 = image_points_2.reshape((-1, 2))\n if image_points_1.shape != image_points_2.shape:\n raise ValueError('Sets of image points do not appear to be the same shape')\n camera_matrix = camera_matrix.reshape((3, 3))\n rotation_vector_1 = rotation_vector_1.reshape(3)\n translation_vector_1 = translation_vector_1.reshape(3)\n rotation_vector_2, translation_vector_2 = estimate_camera_pose_from_image_points(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1,\n translation_vector_1,\n distance_between_cameras)\n object_points = reconstruct_object_points_from_camera_poses(\n image_points_1,\n image_points_2,\n camera_matrix,\n rotation_vector_1,\n translation_vector_1,\n rotation_vector_2,\n translation_vector_2)\n return object_points\n\n\ndef estimate_camera_pose_from_plane_object_points(\n input_object_points,\n height,\n origin_index,\n x_axis_index,\n y_reference_point,\n y_reference_point_sign,\n distance_calibration_indices,\n calibration_distance):\n input_object_points = np.asarray(input_object_points)\n if input_object_points.size == 0:\n raise ValueError('Obect point array appears to be empty')\n input_object_points = input_object_points.reshape((-1, 3))\n\n scale_factor = np.divide(\n calibration_distance,\n np.linalg.norm(\n np.subtract(\n input_object_points[distance_calibration_indices[0]],\n input_object_points[distance_calibration_indices[1]])))\n\n object_points_1 = np.multiply(\n input_object_points,\n scale_factor)\n\n def objective_function(parameters):\n rotation_x = parameters[0]\n rotation_y = parameters[1]\n translation_z = parameters[2]\n object_points_transformed = transform_object_points(\n object_points_1,\n np.array([rotation_x, rotation_y, 0.0]),\n np.array([0.0, 0.0, translation_z]))\n return np.sum(np.square(object_points_transformed[:, 2] - height))\n\n optimization_solution = scipy.optimize.minimize(\n objective_function,\n np.array([0.0, 0.0, 0.0]))\n\n rotation_x_a = optimization_solution['x'][0]\n rotation_y_a = optimization_solution['x'][1]\n translation_z_a = optimization_solution['x'][2]\n\n rotation_x_rotation_y_a_norm = np.linalg.norm([rotation_x_a, rotation_y_a])\n\n rotation_x_b = rotation_x_a * ((rotation_x_rotation_y_a_norm + np.pi) / rotation_x_rotation_y_a_norm)\n rotation_y_b = rotation_y_a * ((rotation_x_rotation_y_a_norm + np.pi) / rotation_x_rotation_y_a_norm)\n translation_z_b = - translation_z_a\n\n rotation_vector_2_a = np.array([rotation_x_a, rotation_y_a, 0.0])\n translation_vector_2_a = np.array([0.0, 0.0, translation_z_a])\n object_points_2_a = transform_object_points(\n object_points_1,\n rotation_vector_2_a,\n translation_vector_2_a)\n\n rotation_vector_2_b = np.array([rotation_x_b, rotation_y_b, 0.0])\n translation_vector_2_b = np.array([0.0, 0.0, translation_z_b])\n object_points_2_b = transform_object_points(\n object_points_1,\n rotation_vector_2_b,\n translation_vector_2_b)\n\n sign_a = np.sign(\n np.cross(\n np.subtract(\n object_points_2_a[x_axis_index],\n object_points_2_a[origin_index]),\n np.subtract(\n object_points_2_a[y_reference_point],\n object_points_2_a[origin_index]))[2])\n\n sign_b = np.sign(\n np.cross(\n np.subtract(\n object_points_2_b[x_axis_index],\n object_points_2_b[origin_index]),\n np.subtract(\n object_points_2_b[y_reference_point],\n object_points_2_b[origin_index]))[2])\n\n if sign_a == y_reference_point_sign:\n rotation_vector_2 = rotation_vector_2_a\n translation_vector_2 = translation_vector_2_a\n object_points_2 = object_points_2_a\n else:\n rotation_vector_2 = rotation_vector_2_b\n translation_vector_2 = translation_vector_2_b\n object_points_2 = object_points_2_b\n\n xy_shift = - object_points_2[origin_index, :2]\n\n rotation_vector_3 = np.array([0.0, 0.0, 0.0])\n translation_vector_3 = np.array([xy_shift[0], xy_shift[1], 0.0])\n object_points_3 = transform_object_points(\n object_points_2,\n rotation_vector_3,\n translation_vector_3)\n\n final_z_rotation = - reconstruct_z_rotation(\n object_points_3[x_axis_index, 0],\n object_points_3[x_axis_index, 1])\n\n rotation_vector_4 = np.array([0.0, 0.0, final_z_rotation])\n translation_vector_4 = np.array([0.0, 0.0, 0.0])\n object_points_4 = transform_object_points(\n object_points_3,\n rotation_vector_4,\n translation_vector_4)\n\n rotation_vector_2_3, translation_vector_2_3 = compose_transformations(\n rotation_vector_2,\n translation_vector_2,\n rotation_vector_3,\n translation_vector_3)\n\n rotation_vector_2_3_4, translation_vector_2_3_4 = compose_transformations(\n rotation_vector_2_3,\n translation_vector_2_3,\n rotation_vector_4,\n translation_vector_4)\n\n camera_rotation_vector, camera_translation_vector = invert_transformation(\n rotation_vector_2_3_4,\n translation_vector_2_3_4)\n\n return camera_rotation_vector, camera_translation_vector, scale_factor, object_points_4\n\n\ndef estimate_camera_poses_from_plane_image_points(\n image_points_1,\n image_points_2,\n camera_matrix,\n height,\n origin_index,\n x_axis_index,\n y_reference_point,\n y_reference_point_sign,\n distance_calibration_indices,\n calibration_distance):\n image_points_1 = np.asarray(image_points_1)\n image_points_2 = np.asarray(image_points_2)\n camera_matrix = np.asarray(camera_matrix)\n if image_points_1.size == 0 or image_points_2.size == 0:\n raise ValueError('One or both sets of image points appear to be empty')\n image_points_1 = image_points_1.reshape((-1, 2))\n image_points_2 = image_points_2.reshape((-1, 2))\n if image_points_1.shape != image_points_2.shape:\n raise ValueError('Sets of image points do not appear to be the same shape')\n camera_matrix = camera_matrix.reshape((3, 3))\n relative_rotation_vector, relative_translation_vector = estimate_camera_pose_from_image_points(\n image_points_1,\n image_points_2,\n camera_matrix)\n input_object_points = reconstruct_object_points_from_image_points(\n image_points_1,\n image_points_2,\n camera_matrix)\n rotation_vector_1, translation_vector_1, scale_factor = estimate_camera_pose_from_plane_object_points(\n input_object_points,\n height,\n origin_index,\n x_axis_index,\n y_reference_point,\n y_reference_point_sign,\n distance_calibration_indices,\n calibration_distance)[:3]\n rotation_vector_2, translation_vector_2 = compose_transformations(\n rotation_vector_1,\n translation_vector_1,\n relative_rotation_vector,\n relative_translation_vector * scale_factor)\n return rotation_vector_1, translation_vector_1, rotation_vector_2, translation_vector_2\n"
] | [
[
"numpy.arctan2",
"numpy.matmul",
"numpy.sort",
"numpy.multiply",
"numpy.empty",
"numpy.squeeze",
"numpy.zeros",
"numpy.linalg.inv",
"numpy.full_like",
"numpy.arctan",
"numpy.subtract",
"numpy.asarray",
"numpy.arange",
"numpy.array",
"numpy.square",
"numpy.linalg.norm"
]
] |
teomores/kafka-twitter | [
"29d7c48fd1d225e33ec06be9bfed1826fa4d6b60"
] | [
"data_preprocessing/tweet_api.py"
] | [
"# Import the Twython class\nfrom twython import Twython\nimport json\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\n\ntry:\n os.remove('twitter_dataset.csv')\nexcept OSError:\n pass\n\ndef main():\n old_df = pd.read_csv('data/twitter_dataset_2.csv', lineterminator='\\n')\n #first load the dictonary with the top used english words\n with open('improved_dict.txt') as d:\n word_list = d.read()\n\n words = word_list.split('\\n')\n\n\n # Dictonary structure with the fields that we are interested in acquire from the tweets\n dict_ = {'user': [],\n 'text': [],\n 'hashtags': [],\n 'mentions': []\n }\n\n\n # Instantiate an object\n python_tweets = Twython('9Tz9FnZ1PR9AcEvudwC7hqOod', #API Key\n 'Z7upFmGJZE3oAfcb2ZUmRdEeBJJkkYTQ86PuB3iKgWqXFdMFNo') #API Secret\n\n\n #each query has a target word\n queries = []\n for w in words:\n query = {'q': w, #the query word\n 'result_type': 'recent',\n 'count': 100, #100 tweets, which is the maximum limit admitted by Twitter\n 'lang': 'en', #we are interested only in english tweets\n }\n queries.append(query)\n\n #perform the queries to get the tweet and map the JSON in our dictonary\n for q in tqdm(queries[:50]):\n for status in python_tweets.search(**q)['statuses']:\n dict_['user'].append(status['user']['screen_name']) #username\n dict_['text'].append(status['text']) #content of the tweet\n\n #this is necessary cuz the hashtags may be null or there can be more than one\n #this can easily be done with this magical regular expression\n ht = [d['text'] for d in status['entities']['hashtags'] if 'text' in d] #list of hashtags\n dict_['hashtags'].append(ht)\n\n #same thing for the mentions\n ment = [d['screen_name'] for d in status['entities']['user_mentions'] if 'screen_name' in d] #list of mentions\n dict_['mentions'].append(ment)\n\n # Structure data in a pandas DataFrame for easier manipulation\n df = pd.DataFrame(dict_)\n\n df = df.append(old_df)\n df.to_csv('data/twitter_dataset_2.csv', index=False, encoding='utf-8')\n\nif __name__ == '__main__':\n main()\n from time import sleep\n while True:\n sleep(1200)\n main()\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
RaulAstudillo/bocf | [
"cd84eab2d1b4ea5a4bdeeb452df92296afbafb87"
] | [
"GPy/kern/src/static.py"
] | [
"# Copyright (c) 2012, GPy authors (see AUTHORS.txt).\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\n\nfrom .kern import Kern\nimport numpy as np\nfrom ...core.parameterization import Param\nfrom paramz.transformations import Logexp\nfrom paramz.caching import Cache_this\n\nclass Static(Kern):\n def __init__(self, input_dim, variance, active_dims, name):\n super(Static, self).__init__(input_dim, active_dims, name)\n self.variance = Param('variance', variance, Logexp())\n self.link_parameters(self.variance)\n\n def _to_dict(self):\n input_dict = super(Static, self)._to_dict()\n input_dict[\"variance\"] = self.variance.values.tolist()\n return input_dict\n\n def Kdiag(self, X):\n ret = np.empty((X.shape[0],), dtype=np.float64)\n ret[:] = self.variance\n return ret\n\n def gradients_X(self, dL_dK, X, X2=None):\n return np.zeros(X.shape)\n\n def gradients_X_diag(self, dL_dKdiag, X):\n return np.zeros(X.shape)\n\n def gradients_XX(self, dL_dK, X, X2=None):\n if X2 is None:\n X2 = X\n return np.zeros((X.shape[0], X2.shape[0], X.shape[1], X.shape[1]), dtype=np.float64)\n\n def gradients_XX_diag(self, dL_dKdiag, X, cov=False):\n return np.zeros((X.shape[0], X.shape[1], X.shape[1]), dtype=np.float64)\n\n def gradients_Z_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n return np.zeros(Z.shape)\n\n def gradients_qX_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n return np.zeros(variational_posterior.shape), np.zeros(variational_posterior.shape)\n\n def psi0(self, Z, variational_posterior):\n return self.Kdiag(variational_posterior.mean)\n\n def psi1(self, Z, variational_posterior):\n return self.K(variational_posterior.mean, Z)\n\n def psi2(self, Z, variational_posterior):\n K = self.K(variational_posterior.mean, Z)\n return np.einsum('ij,ik->jk',K,K) #K[:,:,None]*K[:,None,:] # NB. more efficient implementations on inherriting classes\n\n def input_sensitivity(self, summarize=True):\n if summarize:\n return super(Static, self).input_sensitivity(summarize=summarize)\n else:\n return np.ones(self.input_dim) * self.variance\n\nclass White(Static):\n def __init__(self, input_dim, variance=1., active_dims=None, name='white'):\n super(White, self).__init__(input_dim, variance, active_dims, name)\n\n def K(self, X, X2=None):\n if X2 is None:\n return np.eye(X.shape[0])*self.variance\n else:\n return np.zeros((X.shape[0], X2.shape[0]))\n\n def psi2(self, Z, variational_posterior):\n return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def psi2n(self, Z, variational_posterior):\n return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n if X2 is None:\n self.variance.gradient = np.trace(dL_dK)\n else:\n self.variance.gradient = 0.\n\n def update_gradients_diag(self, dL_dKdiag, X):\n self.variance.gradient = dL_dKdiag.sum()\n\n def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n self.variance.gradient = dL_dpsi0.sum()\n\nclass WhiteHeteroscedastic(Static):\n def __init__(self, input_dim, num_data, variance=1., active_dims=None, name='white_hetero'):\n \"\"\"\n A heteroscedastic White kernel (nugget/noise).\n It defines one variance (nugget) per input sample.\n\n Prediction excludes any noise learnt by this Kernel, so be careful using this kernel.\n\n You can plot the errors learnt by this kernel by something similar as:\n plt.errorbar(m.X, m.Y, yerr=2*np.sqrt(m.kern.white.variance))\n \"\"\"\n super(Static, self).__init__(input_dim, active_dims, name)\n self.variance = Param('variance', np.ones(num_data) * variance, Logexp())\n self.link_parameters(self.variance)\n\n def Kdiag(self, X):\n if X.shape[0] == self.variance.shape[0]:\n # If the input has the same number of samples as\n # the number of variances, we return the variances\n return self.variance\n return 0.\n\n def K(self, X, X2=None):\n if X2 is None and X.shape[0] == self.variance.shape[0]:\n return np.eye(X.shape[0]) * self.variance\n else:\n return 0.\n\n def psi2(self, Z, variational_posterior):\n return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def psi2n(self, Z, variational_posterior):\n return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n if X2 is None:\n self.variance.gradient = np.diagonal(dL_dK)\n else:\n self.variance.gradient = 0.\n\n def update_gradients_diag(self, dL_dKdiag, X):\n self.variance.gradient = dL_dKdiag\n\n def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n self.variance.gradient = dL_dpsi0\n\nclass Bias(Static):\n def __init__(self, input_dim, variance=1., active_dims=None, name='bias'):\n super(Bias, self).__init__(input_dim, variance, active_dims, name)\n\n def to_dict(self):\n input_dict = super(Bias, self)._to_dict()\n input_dict[\"class\"] = \"GPy.kern.Bias\"\n return input_dict\n\n @staticmethod\n def _from_dict(kernel_class, input_dict):\n useGPU = input_dict.pop('useGPU', None)\n return Bias(**input_dict)\n\n def K(self, X, X2=None):\n shape = (X.shape[0], X.shape[0] if X2 is None else X2.shape[0])\n return np.full(shape, self.variance, dtype=np.float64)\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n self.variance.gradient = dL_dK.sum()\n\n def update_gradients_diag(self, dL_dKdiag, X):\n self.variance.gradient = dL_dKdiag.sum()\n\n def psi2(self, Z, variational_posterior):\n return np.full((Z.shape[0], Z.shape[0]), self.variance*self.variance*variational_posterior.shape[0], dtype=np.float64)\n\n def psi2n(self, Z, variational_posterior):\n ret = np.empty((variational_posterior.mean.shape[0], Z.shape[0], Z.shape[0]), dtype=np.float64)\n ret[:] = self.variance*self.variance\n return ret\n\n def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n if dL_dpsi2.ndim == 2:\n self.variance.gradient = (dL_dpsi0.sum() + dL_dpsi1.sum()\n + 2.*self.variance*dL_dpsi2.sum()*variational_posterior.shape[0])\n else:\n self.variance.gradient = (dL_dpsi0.sum() + dL_dpsi1.sum()\n + 2.*self.variance*dL_dpsi2.sum())\n\nclass Fixed(Static):\n def __init__(self, input_dim, covariance_matrix, variance=1., active_dims=None, name='fixed'):\n \"\"\"\n :param input_dim: the number of input dimensions\n :type input_dim: int\n :param variance: the variance of the kernel\n :type variance: float\n \"\"\"\n super(Fixed, self).__init__(input_dim, variance, active_dims, name)\n self.fixed_K = covariance_matrix\n def K(self, X, X2):\n if X2 is None:\n return self.variance * self.fixed_K\n else:\n return np.zeros((X.shape[0], X2.shape[0]))\n\n def Kdiag(self, X):\n return self.variance * self.fixed_K.diagonal()\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n if X2 is None:\n self.variance.gradient = np.einsum('ij,ij', dL_dK, self.fixed_K)\n else:\n self.variance.gradient = 0\n\n def update_gradients_diag(self, dL_dKdiag, X):\n self.variance.gradient = np.einsum('i,i', dL_dKdiag, np.diagonal(self.fixed_K))\n\n def psi2(self, Z, variational_posterior):\n return np.zeros((Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def psi2n(self, Z, variational_posterior):\n return np.zeros((1, Z.shape[0], Z.shape[0]), dtype=np.float64)\n\n def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):\n self.variance.gradient = dL_dpsi0.sum()\n\nclass Precomputed(Fixed):\n def __init__(self, input_dim, covariance_matrix, variance=1., active_dims=None, name='precomputed'):\n \"\"\"\n Class for precomputed kernels, indexed by columns in X\n\n Usage example:\n\n import numpy as np\n from GPy.models import GPClassification\n from GPy.kern import Precomputed\n from sklearn.cross_validation import LeaveOneOut\n\n n = 10\n d = 100\n X = np.arange(n).reshape((n,1)) # column vector of indices\n y = 2*np.random.binomial(1,0.5,(n,1))-1\n X0 = np.random.randn(n,d)\n k = np.dot(X0,X0.T)\n kern = Precomputed(1,k) # k is a n x n covariance matrix\n\n cv = LeaveOneOut(n)\n ypred = y.copy()\n for train, test in cv:\n m = GPClassification(X[train], y[train], kernel=kern)\n m.optimize()\n ypred[test] = 2*(m.predict(X[test])[0]>0.5)-1\n\n :param input_dim: the number of input dimensions\n :type input_dim: int\n :param variance: the variance of the kernel\n :type variance: float\n \"\"\"\n assert input_dim==1, \"Precomputed only implemented in one dimension. Use multiple Precomputed kernels to have more dimensions by making use of active_dims\"\n super(Precomputed, self).__init__(input_dim, covariance_matrix, variance, active_dims, name)\n\n @Cache_this(limit=2)\n def _index(self, X, X2):\n if X2 is None:\n i1 = i2 = X.astype('int').flat\n else:\n i1, i2 = X.astype('int').flat, X2.astype('int').flat\n return self.fixed_K[i1,:][:,i2]\n\n def K(self, X, X2=None):\n return self.variance * self._index(X, X2)\n\n def Kdiag(self, X):\n return self.variance * self._index(X,None).diagonal()\n\n def update_gradients_full(self, dL_dK, X, X2=None):\n self.variance.gradient = np.einsum('ij,ij', dL_dK, self._index(X, X2))\n\n def update_gradients_diag(self, dL_dKdiag, X):\n self.variance.gradient = np.einsum('i,ii', dL_dKdiag, self._index(X, None))\n"
] | [
[
"numpy.ones",
"numpy.eye",
"numpy.empty",
"numpy.zeros",
"numpy.trace",
"numpy.einsum",
"numpy.diagonal",
"numpy.full"
]
] |
jacenkow/inside | [
"6f860420644b50b78981158a59ceed8cdbd209bf"
] | [
"inside/pipelines/clevr.py"
] | [
"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 Grzegorz Jacenków.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n\"\"\"Training and evaluation pipeline for the networks.\"\"\"\n\nimport csv\nimport os\n\nimport tensorflow as tf\nfrom tensorflow.keras.metrics import Mean\n\nfrom inside import config\nfrom inside.callbacks import setup_callbacks\nfrom inside.constructor import setup_comet_ml, setup_model\nfrom inside.loaders import CLEVR\nfrom inside.metrics import DiceScore\n\n\ndef _write_results(logs):\n \"\"\"Write final logs to a CSV file.\"\"\"\n w = csv.writer(open(os.path.join(\n config.EXPERIMENT_FOLDER, \"results.csv\"), \"w\"))\n for key, val in logs.items():\n w.writerow([key, val])\n\n\nclass Pipeline:\n def __init__(self):\n # Model.\n self.model = setup_model()\n\n # Comet.ml experiment.\n self.comet_ml = setup_comet_ml()\n\n # Testing metrics.\n self.test_dice = DiceScore(name=\"testing_dice\")\n self.test_loss = Mean(name=\"testing_loss\")\n\n # Training metrics.\n self.training_dice = DiceScore(name=\"training_dice\")\n self.training_loss = Mean(name=\"training_loss\")\n\n # Callbacks.\n self.cl, self.es, self.mc, self.pp = setup_callbacks()\n self.cl.model, self.es.model, self.mc.model = \\\n self.model, self.model, self.model\n\n self.pp.model = self.model\n self.pp.comet_ml = self.comet_ml\n\n def fit(self):\n \"\"\"Train the model.\"\"\"\n # Toy dataset.\n loader = CLEVR()\n train_ds, valid_ds, test_ds = loader.load()\n\n with self.comet_ml.train():\n self.cl.on_train_begin()\n self.es.on_train_begin()\n self.mc.on_train_begin()\n self.pp.on_train_begin()\n\n for epoch in range(config.EXPERIMENT_EPOCHS):\n self.comet_ml.set_epoch(epoch)\n\n for images, labels in train_ds:\n self.train_step(images, labels)\n\n for batch, (images, labels) in enumerate(valid_ds):\n self.test_step(images, labels)\n\n if not batch: # Log only first mini-batch from an epoch.\n self.pp.on_epoch_end(epoch, images, labels)\n\n # Get results.\n logs = {\n \"dice\": self.training_dice.result().numpy(),\n \"loss\": self.training_loss.result().numpy(),\n \"validation_dice\": self.test_dice.result().numpy(),\n \"validation_loss\": self.test_loss.result().numpy(),\n }\n\n template = (\"Epoch {}. Training Loss: {}. Training Dice: {}. \"\n \"Validation Loss: {}. Validation Dice: {}.\")\n\n print(template.format(epoch + 1,\n logs['loss'],\n logs['dice'],\n logs['validation_loss'],\n logs['validation_dice']))\n\n # Log metrics.\n self.comet_ml.log_metrics(logs, epoch=epoch)\n self.cl.on_epoch_end(epoch, logs)\n self.es.on_epoch_end(epoch, logs)\n self.mc.on_epoch_end(epoch, logs)\n\n # Reset the metrics for the next epoch.\n self.training_dice.reset_states()\n self.training_loss.reset_states()\n self.test_dice.reset_states()\n self.test_loss.reset_states()\n\n # Early stopping criterion.\n if self.es.model.stop_training:\n self.cl.on_train_end()\n self.es.on_train_end()\n self.mc.on_train_end()\n break\n\n with self.comet_ml.test():\n for batch, (images, labels) in enumerate(test_ds):\n self.test_step(images, labels)\n\n if not batch:\n self.pp.on_test_end(images, labels)\n\n # Get results.\n logs = {\n \"dice\": self.test_dice.result().numpy(),\n \"loss\": self.test_loss.result().numpy(),\n }\n\n print(\"Test Loss: {}. Test Dice: {}.\".format(\n logs['loss'], logs['dice']))\n\n # Log metrics.\n self.comet_ml.log_metrics(logs)\n _write_results(logs)\n\n @tf.function\n def train_step(self, images, labels):\n with tf.GradientTape() as tape:\n predictions = self.model.inference(images)\n loss = self.model.loss(labels, predictions)\n\n gradients = tape.gradient(loss, self.model.trainable_variables)\n self.model.optimiser.apply_gradients(\n zip(gradients, self.model.trainable_variables))\n\n self.training_loss(loss)\n self.training_dice(labels, predictions)\n\n @tf.function\n def test_step(self, images, labels):\n predictions = self.model.inference(images)\n t_loss = self.model.loss(labels, predictions)\n\n self.test_loss(t_loss)\n self.test_dice(labels, predictions)\n"
] | [
[
"tensorflow.GradientTape",
"tensorflow.keras.metrics.Mean"
]
] |
BaratiLab/GAMD | [
"7de91526f1c8c06ea005920e6a55c3cf031c26b2"
] | [
"dataset/generate_tip4p_data.py"
] | [
"from openmmtools import testsystems\nfrom simtk.openmm.app import *\nimport simtk.unit as unit\n\nimport logging\n\nimport numpy as np\n\nfrom openmmtools.constants import kB\nfrom openmmtools import respa, utils\n\nlogger = logging.getLogger(__name__)\n\n# Energy unit used by OpenMM unit system\nfrom openmmtools import states, integrators\nimport time\nimport numpy as np\nimport sys\nimport os\n\n\ndef get_rotation_matrix():\n \"\"\" Randomly rotate the point clouds to augument the dataset\n rotation is per shape based along up direction\n Input:\n Nx3 array, original point clouds\n Return:\n Nx3 array, rotated point clouds\n \"\"\"\n angles = np.random.uniform(-1.0, 1.0, size=(3,)) * np.pi\n print(f'Using angle: {angles}')\n Rx = np.array([[1., 0, 0],\n [0, np.cos(angles[0]), -np.sin(angles[0])],\n [0, np.sin(angles[0]), np.cos(angles[0])]], dtype=np.float32)\n Ry = np.array([[np.cos(angles[1]), 0, np.sin(angles[1])],\n [0, 1, 0],\n [-np.sin(angles[1]), 0, np.cos(angles[1])]], dtype=np.float32)\n Rz = np.array([[np.cos(angles[2]), -np.sin(angles[2]), 0],\n [np.sin(angles[2]), np.cos(angles[2]), 0],\n [0, 0, 1]], dtype=np.float32)\n rotation_matrix = np.matmul(Rz, np.matmul(Ry, Rx))\n\n return rotation_matrix\n\ndef center_positions(pos):\n offset = np.mean(pos, axis=0)\n return pos - offset, offset\n\n\nBOX_SCALE = 2\nDT = 2\nfor seed in range(10):\n print(f'Running seed: {seed}')\n\n waterbox = testsystems.WaterBox(\n box_edge=2 * unit.nanometers,\n model='tip4pew')\n [topology, system, positions] = [waterbox.topology, waterbox.system, waterbox.positions]\n\n R = get_rotation_matrix()\n positions = positions.value_in_unit(unit.angstrom)\n positions, off = center_positions(positions)\n positions = np.matmul(positions, R)\n positions += off\n positions += np.random.randn(positions.shape[0], positions.shape[1]) * 0.005\n positions *= unit.angstrom\n\n p_num = positions.shape[0] // 3\n timestep = DT * unit.femtoseconds\n temperature = 300 * unit.kelvin\n chain_length = 10\n friction = 1. / unit.picosecond\n num_mts = 5\n num_yoshidasuzuki = 5\n\n integrator = integrators.NoseHooverChainVelocityVerletIntegrator(system,\n temperature,\n friction,\n timestep, chain_length, num_mts, num_yoshidasuzuki)\n\n simulation = Simulation(topology, system, integrator)\n simulation.context.setPositions(positions)\n simulation.context.setVelocitiesToTemperature(temperature)\n\n simulation.minimizeEnergy(tolerance=1*unit.kilojoule/unit.mole)\n simulation.step(1)\n\n os.makedirs(f'./water_data_tip4p/', exist_ok=True)\n dataReporter_gt = StateDataReporter(f'./log_nvt_tip4p_{seed}.txt', 50, totalSteps=50000,\n step=True, time=True, speed=True, progress=True, elapsedTime=True, remainingTime=True,\n potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True,\n separator='\\t')\n simulation.reporters.append(dataReporter_gt)\n for t in range(1000):\n if (t+1)%100 == 0:\n print(f'Finished {(t+1)*50} steps')\n state = simulation.context.getState(getPositions=True,\n getVelocities=True,\n getForces=True,\n enforcePeriodicBox=True)\n pos = state.getPositions(asNumpy=True).value_in_unit(unit.angstrom)\n vel = state.getVelocities(asNumpy=True).value_in_unit(unit.meter / unit.second)\n force = state.getForces(asNumpy=True).value_in_unit(unit.kilojoules_per_mole/unit.nanometer)\n\n np.savez(f'./water_data_tip4p/data_{seed}_{t}.npz',\n pos=pos,\n vel=vel,\n forces=force)\n simulation.step(50)\n\n\n"
] | [
[
"numpy.random.uniform",
"numpy.matmul",
"numpy.savez",
"numpy.random.randn",
"numpy.cos",
"numpy.sin",
"numpy.mean"
]
] |
Intelligent-Systems-Lab/ISL-BCFL | [
"42ceb86708a76e28b31c22b33c15ee9a6a745ec7"
] | [
"script/app/agg.py"
] | [
"import os\n# import torch\nimport argparse\nimport base64\nimport sys\nimport io\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n\ndef fullmodel2base64(model):\n buffer = io.BytesIO()\n torch.save(model, buffer)\n bg = buffer.getvalue()\n return base64.b64encode(bg).decode()\n\ndef base642fullmodel(modbase64):\n inputrpc = bytes(modbase64.encode())\n inputrpc_ = base64.b64decode(inputrpc)\n loadmodel = torch.load(io.BytesIO(inputrpc_))\n return loadmodel\n\n\nmodel_list = []\n\nf = open(sys.argv[1], \"r\")\n\nmodels = f.read().split(\",\")\n\nf.close()\n\nprint(models)\n\nfor m in models:\n model_list.append(base642fullmodel(m))\n\nnew_model_state = model_list[0].state_dict()\n\n#sum the weight of the model\nfor m in model_list[1:]:\n state_m = m.state_dict()\n for key in state_m:\n new_model_state[key] += state_m[key]\n\n#average the model weight\nfor key in new_model_state:\n new_model_state[key] /= len(model_list)\n\n\nnew_model = model_list[0]\nnew_model.load_state_dict(new_model_state)\n\noutput = fullmodel2base64(new_model)\n\nprint(output)\n"
] | [
[
"torch.save"
]
] |
lanagarmire/granatumx | [
"3dee3a8fb2ba851c31a9f6338aef1817217769f9"
] | [
"g_packages/deepImpute/docker/deepimpute/deepimpute/multinet.py"
] | [
"import os\nimport numpy as np\nimport pandas as pd\nimport binascii\nimport warnings\nimport tempfile\nfrom math import ceil\nfrom multiprocessing import cpu_count, sharedctypes\nfrom multiprocessing.pool import Pool\nfrom sklearn.metrics import r2_score\n\nfrom deepimpute.net import Net\nfrom deepimpute.normalizer import Normalizer\nfrom deepimpute.util import get_input_genes,get_target_genes\nfrom deepimpute.util import score_model\n\ndef newCoreInitializer(arr_to_populate):\n global sharedArray\n sharedArray = arr_to_populate\n\ndef trainNet(in_out, NN_param_i, data_i, labels):\n features, targets = in_out\n\n net = Net(**NN_param_i)\n net.fit(data_i, targetGenes=targets, predictorGenes=features, labels=labels)\n\n # retrieve the array\n params = list(NN_param_i.keys()) + ['targetGenes', 'NNid', 'predictorGenes']\n args2return = [(attr, getattr(net, attr)) for attr in params]\n return {k: v if k[0] != '_' else (k[1:], v) for k, v in args2return}\n\ndef predictNet(data_i, NN_param_i, labels):\n net = Net(**NN_param_i)\n data_i_ok = pd.DataFrame(np.reshape(data_i, list(map(len, labels))),\n index=labels[0], columns=labels[1])\n return net.predict(data_i_ok)\n\ndef trainOrPredict(args):\n in_out, NN_param_i, labels, mode = args\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', RuntimeWarning)\n data_i = np.ctypeslib.as_array(sharedArray)\n if mode == \"predict\":\n return predictNet(data_i, NN_param_i, labels)\n return trainNet(in_out, NN_param_i, data_i, labels)\n\n\nclass MultiNet(object):\n def __init__(self, n_cores=4, predictorLimit=10, preproc='log_or_exp', runDir=os.path.join(tempfile.gettempdir(),'run'), seed=0, **NN_params):\n self._maxcores = n_cores\n self.predictorLimit = predictorLimit\n self.norm = Normalizer.fromName(preproc)\n self.runDir = runDir\n self.seed = seed\n self.NN_params = NN_params\n self.seed = seed\n self.NN_params['seed'] = seed\n\n if 'dims' not in self.NN_params.keys():\n self.NN_params['dims'] = [20,500]\n\n @property\n def maxcores(self):\n if self._maxcores == 'all':\n return cpu_count()\n else:\n return self._maxcores\n\n @maxcores.setter\n def maxcores(self, value):\n self._maxcores = value\n\n def get_params(self, deep=False):\n return self.__dict__\n\n def setIDandRundir(self,data):\n # set runID\n runID = binascii.b2a_hex(os.urandom(5))\n if type(runID) is bytes:\n runID = runID.decode()\n self.NN_params['runDir'] = os.path.join(self.runDir, str(runID))\n\n def getCores(self,NN_genes):\n n_runs = int(ceil(1.*len(NN_genes) / self.NN_params['dims'][1]))\n n_cores = min(self.maxcores, n_runs)\n self.NN_params['n_cores'] = max(1, int(self.maxcores / n_cores))\n return n_runs,n_cores\n\n def fit(self, data, NN_lim='auto', cell_subset=None):\n np.random.seed(seed=self.seed)\n\n df = pd.DataFrame(data)\n\n self.setIDandRundir(df)\n\n # Change the output dimension if the data has too few genes\n if df.shape[1] < self.NN_params['dims'][1]:\n self.NN_params['dims'][1] = df.shape[1]\n\n # Choose genes to impute\n genes_sort = df.quantile(.99).sort_values(ascending=False)\n NN_genes = get_target_genes(genes_sort,NN_lim=NN_lim)\n\n df_to_impute = df[NN_genes]\n\n n_runs,n_cores = self.getCores(NN_genes)\n\n\n # ------------------------# Subnetworks #------------------------#\n\n predictors = np.intersect1d(genes_sort.index[genes_sort>self.predictorLimit], NN_genes)\n print('Using {} genes as potential predictors'.format(len(predictors)))\n\n n_choose = int(len(NN_genes)/self.NN_params['dims'][1])\n\n subGenelists = np.random.choice(NN_genes,\n [n_choose, self.NN_params['dims'][1]],\n replace=False).tolist()\n if n_choose < n_runs:\n # Special case: for the last run, the output layer will have less nodes\n selectedGenes = np.reshape(subGenelists, -1)\n subGenelists.append(np.setdiff1d(NN_genes, selectedGenes).tolist())\n\n # ------------------------# Extracting input genes #------------------------#\n\n corrMatrix = 1 - np.abs(pd.DataFrame(np.corrcoef(df_to_impute.T),\n index=NN_genes, columns=NN_genes)[predictors])\n\n in_out_genes = get_input_genes(df_to_impute,self.NN_params['dims'],distanceMatrix=corrMatrix,\n targets=subGenelists,predictorLimit=self.predictorLimit)\n\n # ------------------------# Subsets for fitting #------------------------#\n\n n_cells = df_to_impute.shape[0]\n\n if type(cell_subset) is float or cell_subset == 1:\n n_cells = int(cell_subset * n_cells)\n\n elif type(cell_subset) is int:\n n_cells = cell_subset\n\n self.trainCells = df_to_impute.sample(n_cells,replace=False).index\n\n print('Starting training with {} cells ({:.1%}) on {} threads ({} cores/thread).'.\n format(n_cells, 1.*n_cells/df_to_impute.shape[0], n_cores, self.NN_params['n_cores']))\n\n # -------------------# Preprocessing (if any) #--------------------#\n\n df_to_impute = self.norm.fit(df_to_impute).transform(df_to_impute)\n\n # -------------------# Share matrix between subprocesses #--------------------#\n\n ''' Create memory chunk and put the matrix in it '''\n idx, cols = self.trainCells, df_to_impute.columns\n trainData = df_to_impute.loc[self.trainCells, :].values\n\n ''' Parallelize process with shared array '''\n childJobs = [(in_out, self.NN_params, (idx, cols), 'train')\n for in_out in in_out_genes]\n\n output_dicts = self.runOnMultipleCores(n_cores, trainData.flatten(), childJobs)\n\n self.networks = []\n for dictionnary in output_dicts:\n self.networks.append(Net(**dictionnary))\n\n return self\n\n def runOnMultipleCores(self, cores, data, childJobs):\n sharedArray = sharedctypes.RawArray('d', data)\n\n pool = Pool(processes=cores, initializer=newCoreInitializer, initargs=(sharedArray,))\n output_dicts = pool.map(trainOrPredict, childJobs)\n pool.close()\n pool.join()\n return output_dicts\n\n\n def predict(self, data, imputed_only=False, restore_pos_values=True):\n\n df = pd.DataFrame(data)\n\n ''' Create memory chunk and put the matrix in it '''\n idx, cols = df.index, df.columns\n df_norm = self.norm.fit(df).transform(df).values.flatten()\n\n ''' Parallelize process with shared array '''\n childJobs = [((12, 15), net.__dict__, (idx, cols), 'predict')\n for net in self.networks]\n\n output_dicts = self.runOnMultipleCores(self.maxcores, df_norm, childJobs)\n\n Y_imputed = pd.concat(output_dicts, axis=1)\n Y_not_imputed = df[[gene for gene in df.columns if gene not in Y_imputed.columns]]\n Y_total = self.norm.transform(pd.concat([Y_imputed, Y_not_imputed], axis=1)[df.columns],\n rev=True)\n if restore_pos_values:\n Y_total = Y_total.mask(df>0,df)\n if imputed_only:\n Y_total = Y_total[Y_imputed.columns]\n\n if type(data) == type(pd.DataFrame()):\n return Y_total\n else:\n return Y_total.values\n\n def score(self, data, metric=r2_score):\n imputedGenes = list(zip(*[ net.targetGenes for net in self.networks ]))\n return score_model(self,pd.DataFrame(data),metric=r2_score, cols=imputedGenes)\n"
] | [
[
"numpy.intersect1d",
"pandas.DataFrame",
"numpy.random.seed",
"numpy.reshape",
"numpy.random.choice",
"numpy.setdiff1d",
"pandas.concat",
"numpy.ctypeslib.as_array",
"numpy.corrcoef"
]
] |
XinChCh/singa | [
"93fd9da72694e68bfe3fb29d0183a65263d238a1"
] | [
"test/python/test_tensor.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# =============================================================================\nfrom __future__ import division\n\nimport math\nimport unittest\nimport random\nimport numpy as np\n\nfrom singa import tensor\nfrom singa import singa_wrap as singa_api\nfrom singa import autograd\n\nfrom cuda_helper import gpu_dev, cpu_dev\n\n\nclass TestTensorMethods(unittest.TestCase):\n\n def setUp(self):\n self.shape = (2, 3)\n self.t = tensor.Tensor(self.shape)\n self.s = tensor.Tensor(self.shape)\n self.t.set_value(0)\n self.s.set_value(0)\n\n def test_tensor_fields(self):\n t = self.t\n shape = self.shape\n self.assertTupleEqual(t.shape, shape)\n self.assertEqual(t.shape[0], shape[0])\n self.assertEqual(t.shape[1], shape[1])\n self.assertEqual(tensor.product(shape), 2 * 3)\n self.assertEqual(t.ndim(), 2)\n self.assertEqual(t.size(), 2 * 3)\n self.assertEqual(t.memsize(), 2 * 3 * tensor.sizeof(tensor.float32))\n self.assertFalse(t.is_transpose())\n\n def test_unary_operators(self):\n t = self.t\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 0.0)\n t += 1.23\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 1.23)\n t -= 0.23\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 1.23 - 0.23)\n t *= 2.5\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], (1.23 - 0.23) * 2.5)\n t /= 2\n self.assertAlmostEqual(\n tensor.to_numpy(t)[0, 0], (1.23 - 0.23) * 2.5 / 2)\n\n def test_binary_operators(self):\n t = self.t\n t += 3.2\n s = self.s\n s += 2.1\n a = t + s\n self.assertAlmostEqual(tensor.to_numpy(a)[0, 0], 3.2 + 2.1, 5)\n a = t - s\n self.assertAlmostEqual(tensor.to_numpy(a)[0, 0], 3.2 - 2.1, 5)\n a = t * s\n self.assertAlmostEqual(tensor.to_numpy(a)[0, 0], 3.2 * 2.1, 5)\n ''' not implemented yet\n a = t / s\n self.assertAlmostEqual(tensor.to_numpy(a)[0,0], 3.2/2.1, 5)\n '''\n\n def test_comparison_operators(self):\n t = self.t\n t += 3.45\n a = t < 3.45\n self.assertEqual(tensor.to_numpy(a)[0, 0], 0)\n a = t <= 3.45\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n a = t > 3.45\n self.assertEqual(tensor.to_numpy(a)[0, 0], 0)\n a = t >= 3.45\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n a = t == 3.45\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n a = tensor.lt(t, 3.45)\n self.assertEqual(tensor.to_numpy(a)[0, 0], 0)\n a = tensor.le(t, 3.45)\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n a = tensor.gt(t, 3.45)\n self.assertEqual(tensor.to_numpy(a)[0, 0], 0)\n a = tensor.ge(t, 3.45)\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n a = tensor.eq(t, 3.45)\n self.assertEqual(tensor.to_numpy(a)[0, 0], 1)\n\n def test_tensor_copy(self):\n t = tensor.Tensor((2, 3))\n t += 1.23\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 1.23)\n tc = t.copy()\n tdc = t.deepcopy()\n self.assertAlmostEqual(tensor.to_numpy(tc)[0, 0], 1.23)\n self.assertAlmostEqual(tensor.to_numpy(tdc)[0, 0], 1.23)\n t += 1.23\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 2.46)\n self.assertAlmostEqual(tensor.to_numpy(tc)[0, 0], 2.46)\n self.assertAlmostEqual(tensor.to_numpy(tdc)[0, 0], 1.23)\n\n def test_copy_data(self):\n t = self.t\n t += 1.23\n s = self.s\n s += 5.43\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 1.23)\n tensor.copy_data_to_from(t, s, 2)\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 0], 5.43, 5)\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 1], 5.43, 5)\n self.assertAlmostEqual(tensor.to_numpy(t)[0, 2], 1.23)\n\n def test_global_method(self):\n t = self.t\n t += 12.34\n a = tensor.log(t)\n self.assertAlmostEqual(tensor.to_numpy(a)[0, 0], math.log(12.34))\n\n def test_random(self):\n x = tensor.Tensor((1000,))\n x.gaussian(1, 0.01)\n self.assertAlmostEqual(tensor.average(x), 1, 3)\n\n def test_radd(self):\n x = tensor.Tensor((3,))\n x.set_value(1)\n y = 1 + x\n self.assertEqual(tensor.average(y), 2.)\n\n def test_rsub(self):\n x = tensor.Tensor((3,))\n x.set_value(1)\n y = 1 - x\n self.assertEqual(tensor.average(y), 0.)\n\n def test_rmul(self):\n x = tensor.Tensor((3,))\n x.set_value(1)\n y = 2 * x\n self.assertEqual(tensor.average(y), 2.)\n\n def test_rdiv(self):\n x = tensor.Tensor((3,))\n x.set_value(1)\n y = 2 / x\n self.assertEqual(tensor.average(y), 2.)\n\n def matmul_high_dim_helper(self, dev):\n configs = [\n [(1, 12, 7, 64), (1, 12, 64, 7)],\n [(1, 7, 768), (768, 768)],\n ]\n print()\n for config in configs:\n X = np.random.random(config[0]).astype(np.float32)\n x = tensor.from_numpy(X)\n x.to_device(dev)\n\n W = np.random.random(config[1]).astype(np.float32)\n w = tensor.from_numpy(W)\n w.to_device(dev)\n\n y_t = np.matmul(X, W)\n y = autograd.matmul(x, w)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), y_t, 3)\n\n def test_matmul_high_dim_cpu(self):\n self.matmul_high_dim_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_matmul_high_dim_gpu(self):\n self.matmul_high_dim_helper(gpu_dev)\n\n def test_tensor_inplace_api(self):\n \"\"\" tensor inplace methods alter internal state and also return self\n \"\"\"\n x = tensor.Tensor((3,))\n y = x.set_value(1)\n self.assertTrue(y is x)\n\n x = tensor.Tensor((3,))\n y = x.uniform(1, 2)\n self.assertTrue(y is x)\n\n x = tensor.Tensor((3,))\n y = x.bernoulli(1)\n self.assertTrue(y is x)\n\n x = tensor.Tensor((3,))\n y = x.gaussian(1, 2)\n self.assertTrue(y is x)\n\n def test_numpy_convert(self):\n a = np.asarray([[1, 0, 0], [0, 1, 0]], dtype=np.int)\n t = tensor.from_numpy(a)\n b = tensor.to_numpy(t)\n self.assertEqual(np.sum(a - b), 0)\n\n a = np.asarray([[1, 0, 0], [0, 1, 0]], dtype=np.float32)\n t = tensor.from_numpy(a)\n b = tensor.to_numpy(t)\n self.assertEqual(np.sum(a - b), 0.)\n\n def test_transpose(self):\n a = np.array(\n [1.1, 1.1, 1.1, 1.1, 1.4, 1.3, 1.1, 1.6, 1.1, 1.1, 1.1, 1.2])\n a = np.reshape(a, (2, 3, 2))\n ta = tensor.from_numpy(a)\n\n A1 = np.transpose(a)\n tA1 = tensor.transpose(ta)\n TA1 = tensor.to_numpy(tA1)\n A2 = np.transpose(a, [0, 2, 1])\n tA2 = tensor.transpose(ta, [0, 2, 1])\n TA2 = tensor.to_numpy(tA2)\n\n np.testing.assert_array_almost_equal(TA1, A1)\n np.testing.assert_array_almost_equal(TA2, A2)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_gpu_6d_transpose(self,dev=gpu_dev):\n s0 = (2,3,4,5,6,7)\n axes1=[5,4,3,2,1,0]\n s1 = (2,7,6,5,4,3)\n s2 = (2,4,3,5,7,6)\n a = np.random.random(s1)\n\n ta = tensor.from_numpy(a)\n ta.to_device(dev)\n\n ta = tensor.reshape(ta,s1)\n ta = tensor.transpose(ta,axes1)\n ta = tensor.reshape(ta,s2)\n\n a = np.reshape(a,s1)\n a = np.transpose(a,axes1)\n a = np.reshape(a,s2)\n\n np.testing.assert_array_almost_equal(tensor.to_numpy(ta), a)\n\n def test_einsum(self):\n\n a = np.array(\n [1.1, 1.1, 1.1, 1.1, 1.4, 1.3, 1.1, 1.6, 1.1, 1.1, 1.1, 1.2])\n a = np.reshape(a, (2, 3, 2))\n ta = tensor.from_numpy(a)\n\n res1 = np.einsum('kij,kij->kij', a, a)\n tres1 = tensor.einsum('kij,kij->kij', ta, ta)\n Tres1 = tensor.to_numpy(tres1)\n res2 = np.einsum('kij,kih->kjh', a, a)\n tres2 = tensor.einsum('kij,kih->kjh', ta, ta)\n Tres2 = tensor.to_numpy(tres2)\n\n self.assertAlmostEqual(np.sum(Tres1 - res1), 0., places=3)\n self.assertAlmostEqual(np.sum(Tres2 - res2), 0., places=3)\n\n def test_repeat(self):\n\n a = np.array(\n [1.1, 1.1, 1.1, 1.1, 1.4, 1.3, 1.1, 1.6, 1.1, 1.1, 1.1, 1.2])\n a = np.reshape(a, (2, 3, 2))\n ta = tensor.from_numpy(a)\n\n ta_repeat1 = tensor.repeat(ta, 2, axis=None)\n a_repeat1 = np.repeat(a, 2, axis=None)\n Ta_repeat1 = tensor.to_numpy(ta_repeat1)\n ta_repeat2 = tensor.repeat(ta, 4, axis=1)\n a_repeat2 = np.repeat(a, 4, axis=1)\n Ta_repeat2 = tensor.to_numpy(ta_repeat2)\n\n self.assertAlmostEqual(np.sum(Ta_repeat1 - a_repeat1), 0., places=3)\n self.assertAlmostEqual(np.sum(Ta_repeat2 - a_repeat2), 0., places=3)\n\n def test_sum(self):\n a = np.array(\n [1.1, 1.1, 1.1, 1.1, 1.4, 1.3, 1.1, 1.6, 1.1, 1.1, 1.1, 1.2])\n a = np.reshape(a, (2, 3, 2))\n ta = tensor.from_numpy(a)\n\n a_sum0 = np.sum(a)\n ta_sum0 = tensor.sum(ta)\n Ta_sum0 = tensor.to_numpy(ta_sum0)\n a_sum1 = np.sum(a, axis=1)\n ta_sum1 = tensor.sum(ta, axis=1)\n Ta_sum1 = tensor.to_numpy(ta_sum1)\n a_sum2 = np.sum(a, axis=2)\n ta_sum2 = tensor.sum(ta, axis=2)\n Ta_sum2 = tensor.to_numpy(ta_sum2)\n\n self.assertAlmostEqual(np.sum(a_sum0 - Ta_sum0), 0., places=3)\n self.assertAlmostEqual(np.sum(a_sum1 - Ta_sum1), 0., places=3)\n self.assertAlmostEqual(np.sum(a_sum2 - Ta_sum2), 0., places=3)\n\n def test_tensordot(self):\n a = np.array(\n [1.1, 1.1, 1.1, 1.1, 1.4, 1.3, 1.1, 1.6, 1.1, 1.1, 1.1, 1.2])\n a = np.reshape(a, (2, 3, 2))\n\n ta = tensor.from_numpy(a)\n\n res1 = np.tensordot(a, a, axes=1)\n tres1 = tensor.tensordot(ta, ta, axes=1)\n Tres1 = tensor.to_numpy(tres1)\n self.assertAlmostEqual(np.sum(Tres1 - res1), 0., places=3)\n np.testing.assert_array_almost_equal(Tres1, res1)\n\n res2 = np.tensordot(a, a, axes=([0, 1], [2, 1]))\n tres2 = tensor.tensordot(ta, ta, axes=([0, 1], [2, 1]))\n np.testing.assert_array_almost_equal(tensor.to_numpy(tres2), res2)\n\n def test_reshape(self):\n a = np.array([[[1.1, 1.1, 1.4], [1.1, 1.1, 1.1]],\n [[1.1, 1.1, 1.3], [1.6, 1.1, 1.2]]])\n ta = tensor.from_numpy(a)\n tb = tensor.reshape(ta, [2, 6])\n self.assertAlmostEqual(tb.shape[0], 2., places=3)\n self.assertAlmostEqual(tb.shape[1], 6., places=3)\n np.testing.assert_array_almost_equal(tensor.to_numpy(tb),\n a.reshape((2, 6)))\n\n def test_transpose_then_reshape(self):\n a = np.array([[[1.1, 1.1], [1.1, 1.1], [1.4, 1.3]],\n [[1.1, 1.6], [1.1, 1.1], [1.1, 1.2]]])\n TRANSPOSE_AXES = (2, 0, 1)\n RESHAPE_DIMS = (2, 6)\n\n ta = tensor.from_numpy(a)\n ta = ta.transpose(TRANSPOSE_AXES)\n ta = ta.reshape(RESHAPE_DIMS)\n\n np.testing.assert_array_almost_equal(\n tensor.to_numpy(ta),\n np.reshape(a.transpose(TRANSPOSE_AXES), RESHAPE_DIMS))\n\n def _concatenate_helper(self, dev):\n np1 = np.random.random([5, 6, 7, 8]).astype(np.float32)\n np2 = np.random.random([5, 6, 7, 1]).astype(np.float32)\n np3 = np.concatenate((np1, np2), axis=3)\n\n t1 = tensor.Tensor(device=dev, data=np1)\n t2 = tensor.Tensor(device=dev, data=np2)\n\n t3 = tensor.concatenate((t1, t2), 3)\n\n np.testing.assert_array_almost_equal(tensor.to_numpy(t3), np3)\n\n def test_concatenate_cpu(self):\n self._concatenate_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_concatenate_gpu(self):\n self._concatenate_helper(gpu_dev)\n\n def _subscription_helper(self, dev):\n np1 = np.random.random((5, 5, 5, 5)).astype(np.float32)\n sg_tensor = tensor.Tensor(device=dev, data=np1)\n sg_tensor_ret = sg_tensor[1:3, :, 1:, :-1]\n np.testing.assert_array_almost_equal((tensor.to_numpy(sg_tensor_ret)),\n np1[1:3, :, 1:, :-1])\n\n def test_subscription_cpu(self):\n self._subscription_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_subscription_gpu(self):\n self._subscription_helper(gpu_dev)\n\n def _ceil_helper(self, dev):\n\n np1 = np.random.random([5, 6, 7, 8]).astype(np.float32)\n np1 = np1 * 10\n np2 = np.ceil(np1)\n\n t1 = tensor.Tensor(device=dev, data=np1)\n\n t2 = tensor.ceil(t1)\n\n np.testing.assert_array_almost_equal(tensor.to_numpy(t2), np2)\n\n def test_ceil_cpu(self):\n self._ceil_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_ceil_gpu(self):\n self._ceil_helper(gpu_dev)\n\n def _astype_helper(self, dev):\n shape1 = [2, 3]\n shape2 = [3, 2]\n\n np_flt = np.random.random(shape1).astype(np.float32)\n np_flt = np_flt * 10 - 5\n\n np_int = np_flt.astype(np.int32)\n np_flt2 = np_int.astype(np.float32)\n\n t2 = tensor.Tensor(device=dev, data=np_flt)\n t2 = t2.as_type('int')\n np.testing.assert_array_almost_equal(tensor.to_numpy(t2), np_int)\n\n t1 = t2.reshape(shape2)\n np.testing.assert_array_almost_equal(tensor.to_numpy(t1),\n np_int.reshape(shape2))\n\n t1 = t1.as_type('float')\n np.testing.assert_array_almost_equal(tensor.to_numpy(t1),\n np_flt2.reshape(shape2))\n\n def test_astype_cpu(self):\n self._astype_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_astype_gpu(self):\n self._astype_helper(gpu_dev)\n\n def _3d_matmul_helper(self, dev):\n np_x1 = np.random.randn(2, 3, 4).astype(np.float32)\n np_x2 = np.random.randn(2, 4, 3).astype(np.float32)\n x1 = tensor.from_numpy(np_x1)\n x1.to_device(dev)\n x2 = tensor.from_numpy(np_x2)\n x2.to_device(dev)\n y = autograd.matmul(x1, x2)\n np_y = np.matmul(np_x1, np_x2)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), np_y)\n\n np_x1 = np.random.randn(2, 3, 4).astype(np.float32)\n np_x2 = np.random.randn(2, 4, 5).astype(np.float32)\n x1 = tensor.from_numpy(np_x1)\n x1.to_device(dev)\n x2 = tensor.from_numpy(np_x2)\n x2.to_device(dev)\n y = autograd.matmul(x1, x2)\n np_y = np.matmul(np_x1, np_x2)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), np_y)\n\n def test_3d_matmul_cpu(self):\n self._3d_matmul_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_3d_matmul_gpu(self):\n self._3d_matmul_helper(gpu_dev)\n\n def _4d_matmul_helper(self, dev):\n np_x1 = np.random.randn(2, 12, 256, 64).astype(np.float32)\n np_x2 = np.random.randn(2, 12, 64, 256).astype(np.float32)\n x1 = tensor.from_numpy(np_x1)\n x1.to_device(dev)\n x2 = tensor.from_numpy(np_x2)\n x2.to_device(dev)\n y = autograd.matmul(x1, x2)\n np_y = np.matmul(np_x1, np_x2)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), np_y)\n\n np_x1 = np.random.randn(2, 12, 256, 64).astype(np.float32)\n np_x2 = np.random.randn(2, 12, 64, 1024).astype(np.float32)\n x1 = tensor.from_numpy(np_x1)\n x1.to_device(dev)\n x2 = tensor.from_numpy(np_x2)\n x2.to_device(dev)\n y = autograd.matmul(x1, x2)\n np_y = np.matmul(np_x1, np_x2)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), np_y)\n\n def test_4d_matmul_cpu(self):\n self._4d_matmul_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_4d_matmul_gpu(self):\n self._4d_matmul_helper(gpu_dev)\n\n def _matmul_transpose_helper(self, dev):\n\n X = np.random.random((1, 256, 12, 64)).astype(np.float32)\n x = tensor.from_numpy(X)\n x.to_device(dev)\n\n W = np.random.random((1, 256, 12, 64)).astype(np.float32)\n w = tensor.from_numpy(W)\n w.to_device(dev)\n\n X = np.transpose(X, (0, 2, 1, 3))\n W = np.transpose(W, (0, 2, 1, 3))\n W = np.transpose(W, (0, 1, 3, 2))\n Y = np.matmul(X, W)\n\n x = autograd.transpose(x, (0, 2, 1, 3))\n w = autograd.transpose(w, (0, 2, 1, 3))\n w = autograd.transpose(w, (0, 1, 3, 2))\n y = autograd.matmul(x, w)\n\n np.testing.assert_array_almost_equal(tensor.to_numpy(x), X)\n np.testing.assert_array_almost_equal(tensor.to_numpy(w), W)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), Y)\n\n def test_matmul_transpose_cpu(self):\n self._matmul_transpose_helper(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_matmul_transpose_gpu(self):\n self._matmul_transpose_helper(gpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_gaussian_gpu(self, dev=gpu_dev):\n x = tensor.Tensor((3, 5, 3, 5), device=dev)\n x.gaussian(0, 1)\n x = tensor.Tensor((4, 5, 3, 2), device=dev)\n x.gaussian(0, 1)\n\n def _kfloat32_int(self, dev=gpu_dev):\n np.random.seed(0)\n x_val = np.random.random((2, 3)).astype(np.float32) * 10\n x = tensor.from_numpy(x_val)\n x.to_device(dev)\n scalar = np.random.random((1,))[0] * 100\n y = x + scalar\n self.assertEqual(y.dtype, tensor.float32)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), x_val + scalar)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_kfloat32_int_gpu(self):\n self._kfloat32_int(gpu_dev)\n\n def test_kfloat32_int_cpu(self):\n self._kfloat32_int(cpu_dev)\n\n def _kint_float(self, dev=gpu_dev):\n np.random.seed(0)\n x_val = np.random.randint(0, 10, (2, 3))\n x = tensor.from_numpy(x_val)\n x.to_device(dev)\n scalar = random.random() * 100\n y = x + scalar\n self.assertEqual(y.dtype, tensor.float32)\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), x_val + scalar, 5)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_kint_float_gpu(self):\n self._kint_float(gpu_dev)\n\n def test_kint_float_cpu(self):\n self._kint_float(cpu_dev)\n\n def _kint_kint(self, dev=gpu_dev):\n a_np = np.array([[[17, 4, 9, 22, 18], [-9, 9, -1, -1, 4],\n [1, 14, 7, 1, 4], [3, 14, -2, 3, -8]],\n [[-25, 6, 8, -7, 22], [-14, 0, -1, 15, 14],\n [1, 3, -8, -19, -3], [1, 12, 12, -3, -3]],\n [[-10, -14, -17, 19, -5], [-4, -12, 7, -16, -2],\n [-8, 3, -5, -11, 0], [4, 0, 3, -6, -3]]],\n dtype=np.int32)\n b_np = np.array([[[-6, -3, -8, -17, 1], [-4, -16, 4, -9, 0],\n [7, 1, 11, -12, 4], [-6, -8, -5, -3, 0]],\n [[-11, 9, 4, -15, 14], [18, 11, -1, -10, 10],\n [-4, 12, 2, 9, 3], [7, 0, 17, 1, 4]],\n [[18, -13, -12, 9, -11], [19, -4, -7, 19, 14],\n [18, 9, -8, 19, -2], [8, 9, -1, 6, 9]]],\n dtype=np.int32)\n ta = tensor.from_numpy(a_np)\n tb = tensor.from_numpy(b_np)\n ta.to_device(dev)\n tb.to_device(dev)\n y = ta - tb\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), a_np - b_np)\n\n def test_kint_kint_cpu(self, dev=cpu_dev):\n self._kint_kint(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_kint_kint_gpu(self, dev=gpu_dev):\n self._kint_kint(gpu_dev)\n\n def _kint_kint_bc(self, dev=gpu_dev):\n a_np = np.array([[[17, 4, 9, 22, 18], [-9, 9, -1, -1, 4],\n [1, 14, 7, 1, 4], [3, 14, -2, 3, -8]],\n [[-25, 6, 8, -7, 22], [-14, 0, -1, 15, 14],\n [1, 3, -8, -19, -3], [1, 12, 12, -3, -3]],\n [[-10, -14, -17, 19, -5], [-4, -12, 7, -16, -2],\n [-8, 3, -5, -11, 0], [4, 0, 3, -6, -3]]],\n dtype=np.int32)\n b_np = np.array([[-6, -3, -8, -17, 1], [-4, -16, 4, -9, 0],\n [7, 1, 11, -12, 4], [-6, -8, -5, -3, 0]],\n dtype=np.int32)\n ta = tensor.from_numpy(a_np)\n tb = tensor.from_numpy(b_np)\n ta.to_device(dev)\n tb.to_device(dev)\n y = ta - tb\n np.testing.assert_array_almost_equal(tensor.to_numpy(y), a_np - b_np)\n\n def test_kint_kint_bc_cpu(self, dev=cpu_dev):\n self._kint_kint_bc(cpu_dev)\n\n @unittest.skipIf(not singa_api.USE_CUDA, 'CUDA is not enabled')\n def test_kint_kint_bc_gpu(self, dev=gpu_dev):\n self._kint_kint_bc(gpu_dev)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"numpy.sum",
"numpy.matmul",
"numpy.transpose",
"numpy.ceil",
"numpy.einsum",
"numpy.reshape",
"numpy.random.seed",
"numpy.asarray",
"numpy.repeat",
"numpy.random.randn",
"numpy.random.random",
"numpy.tensordot",
"numpy.testing.assert_array_almost_equal",
"numpy.array",
"numpy.concatenate",
"numpy.random.randint"
]
] |
hyperfraise/action-detection | [
"a3ee263ed701ed251cd0a79830ef796889ff366e"
] | [
"ssn_dataset.py"
] | [
"import torch.utils.data as data\n\nimport os\nimport os.path\nfrom numpy.random import randint\nfrom ops.io import load_proposal_file\nfrom transforms import *\nfrom ops.utils import temporal_iou\n\n\nclass SSNInstance:\n def __init__(\n self,\n start_frame,\n end_frame,\n video_frame_count,\n fps=1,\n label=None,\n best_iou=None,\n overlap_self=None,\n ):\n self.start_frame = start_frame\n self.end_frame = min(end_frame, video_frame_count)\n self._label = label\n self.fps = fps\n\n self.coverage = (end_frame - start_frame) / video_frame_count\n\n self.best_iou = best_iou\n self.overlap_self = overlap_self\n\n self.loc_reg = None\n self.size_reg = None\n\n def compute_regression_targets(self, gt_list, fg_thresh):\n if self.best_iou < fg_thresh:\n # background proposals do not need this\n return\n\n # find the groundtruth instance with the highest IOU\n ious = [\n temporal_iou(\n (self.start_frame, self.end_frame), (gt.start_frame, gt.end_frame)\n )\n for gt in gt_list\n ]\n best_gt_id = np.argmax(ious)\n\n best_gt = gt_list[best_gt_id]\n\n prop_center = (self.start_frame + self.end_frame) / 2\n gt_center = (best_gt.start_frame + best_gt.end_frame) / 2\n\n prop_size = self.end_frame - self.start_frame + 1\n gt_size = best_gt.end_frame - best_gt.start_frame + 1\n\n # get regression target:\n # (1). center shift propotional to the proposal duration\n # (2). logarithm of the groundtruth duration over proposal duraiton\n\n self.loc_reg = (gt_center - prop_center) / prop_size\n try:\n self.size_reg = math.log(gt_size / prop_size)\n except:\n print((gt_size, prop_size, self.start_frame, self.end_frame))\n raise\n\n @property\n def start_time(self):\n return self.start_frame / self.fps\n\n @property\n def end_time(self):\n return self.end_frame / self.fps\n\n @property\n def label(self):\n return self._label if self._label is not None else -1\n\n @property\n def regression_targets(self):\n return [self.loc_reg, self.size_reg] if self.loc_reg is not None else [0, 0]\n\n\nclass SSNVideoRecord:\n def __init__(self, prop_record):\n self._data = prop_record\n\n frame_count = int(self._data[1])\n\n # build instance record\n self.gt = [\n SSNInstance(\n int(x[1]), int(x[2]), frame_count, label=int(x[0]), best_iou=1.0\n )\n for x in self._data[2]\n if int(x[2]) > int(x[1])\n ]\n\n self.gt = list([x for x in self.gt if x.start_frame < frame_count])\n\n self.proposals = [\n SSNInstance(\n int(x[3]),\n int(x[4]),\n frame_count,\n label=int(x[0]),\n best_iou=float(x[1]),\n overlap_self=float(x[2]),\n )\n for x in self._data[3]\n if int(x[4]) > int(x[3])\n ]\n\n self.proposals = list(\n [x for x in self.proposals if x.start_frame < frame_count]\n )\n\n @property\n def id(self):\n return self._data[0]\n\n @property\n def num_frames(self):\n return int(self._data[1])\n\n def get_fg(self, fg_thresh, with_gt=True):\n fg = [p for p in self.proposals if p.best_iou > fg_thresh]\n if with_gt:\n fg.extend(self.gt)\n\n for x in fg:\n x.compute_regression_targets(self.gt, fg_thresh)\n return fg\n\n def get_negatives(\n self,\n incomplete_iou_thresh,\n bg_iou_thresh,\n bg_coverage_thresh=0.01,\n incomplete_overlap_thresh=0.7,\n ):\n\n tag = [0] * len(self.proposals)\n\n incomplete_props = []\n background_props = []\n\n for i in range(len(tag)):\n if (\n self.proposals[i].best_iou < incomplete_iou_thresh\n and self.proposals[i].overlap_self > incomplete_overlap_thresh\n ):\n tag[i] = 1 # incomplete\n incomplete_props.append(self.proposals[i])\n\n for i in range(len(tag)):\n if (\n tag[i] == 0\n and self.proposals[i].best_iou < bg_iou_thresh\n and self.proposals[i].coverage > bg_coverage_thresh\n ):\n background_props.append(self.proposals[i])\n return incomplete_props, background_props\n\n\nclass SSNDataSet(data.Dataset):\n def __init__(\n self,\n root_path,\n prop_file=None,\n body_seg=5,\n aug_seg=2,\n video_centric=True,\n new_length=1,\n modality=\"RGB\",\n image_tmpl=\"img_{:05d}.jpg\",\n transform=None,\n random_shift=True,\n test_mode=False,\n prop_per_video=8,\n fg_ratio=1,\n bg_ratio=1,\n incomplete_ratio=6,\n fg_iou_thresh=0.7,\n bg_iou_thresh=0.01,\n incomplete_iou_thresh=0.3,\n bg_coverage_thresh=0.02,\n incomplete_overlap_thresh=0.7,\n gt_as_fg=True,\n reg_stats=None,\n test_interval=6,\n verbose=True,\n exclude_empty=True,\n epoch_multiplier=1,\n ):\n\n self.root_path = root_path\n self.prop_file = prop_file\n self.verbose = verbose\n\n self.body_seg = body_seg\n self.aug_seg = aug_seg\n self.video_centric = video_centric\n self.exclude_empty = exclude_empty\n self.epoch_multiplier = epoch_multiplier\n\n self.new_length = new_length\n self.modality = modality\n self.image_tmpl = image_tmpl\n self.transform = transform\n self.random_shift = random_shift\n self.test_mode = test_mode\n self.test_interval = test_interval\n\n self.fg_iou_thresh = fg_iou_thresh\n self.incomplete_iou_thresh = incomplete_iou_thresh\n self.bg_iou_thresh = bg_iou_thresh\n\n self.bg_coverage_thresh = bg_coverage_thresh\n self.incomplete_overlap_thresh = incomplete_overlap_thresh\n\n self.starting_ratio = 0.5\n self.ending_ratio = 0.5\n\n self.gt_as_fg = gt_as_fg\n\n denum = fg_ratio + bg_ratio + incomplete_ratio\n\n self.fg_per_video = int(prop_per_video * (fg_ratio / denum))\n self.bg_per_video = int(prop_per_video * (bg_ratio / denum))\n self.incomplete_per_video = (\n prop_per_video - self.fg_per_video - self.bg_per_video\n )\n\n self._parse_prop_file(stats=reg_stats)\n\n def _load_image(self, directory, idx):\n if self.modality == \"RGB\" or self.modality == \"RGBDiff\":\n return [\n Image.open(\n os.path.join(directory, self.image_tmpl.format(idx))\n ).convert(\"RGB\")\n ]\n elif self.modality == \"Flow\":\n x_img = Image.open(\n os.path.join(directory, self.image_tmpl.format(\"x\", idx))\n ).convert(\"L\")\n y_img = Image.open(\n os.path.join(directory, self.image_tmpl.format(\"y\", idx))\n ).convert(\"L\")\n\n return [x_img, y_img]\n\n def _parse_prop_file(self, stats=None):\n prop_info = load_proposal_file(self.prop_file)\n\n self.video_list = [SSNVideoRecord(p) for p in prop_info]\n\n if self.exclude_empty:\n self.video_list = list([x for x in self.video_list if len(x.gt) > 0])\n\n self.video_dict = {v.id: v for v in self.video_list}\n\n # construct three pools:\n # 1. Foreground\n # 2. Background\n # 3. Incomplete\n\n self.fg_pool = []\n self.bg_pool = []\n self.incomp_pool = []\n\n for v in self.video_list:\n self.fg_pool.extend(\n [(v.id, prop) for prop in v.get_fg(self.fg_iou_thresh, self.gt_as_fg)]\n )\n\n incomp, bg = v.get_negatives(\n self.incomplete_iou_thresh,\n self.bg_iou_thresh,\n self.bg_coverage_thresh,\n self.incomplete_overlap_thresh,\n )\n\n self.incomp_pool.extend([(v.id, prop) for prop in incomp])\n self.bg_pool.extend([(v.id, prop) for prop in bg])\n\n if stats is None:\n self._compute_regresssion_stats()\n else:\n self.stats = stats\n\n if self.verbose:\n print(\n (\n \"\"\"\n \n SSNDataset: Proposal file {prop_file} parsed.\n \n There are {pnum} usable proposals from {vnum} videos.\n {fnum} foreground proposals\n {inum} incomplete_proposals\n {bnum} background_proposals\n \n Sampling config:\n FG/BG/INC: {fr}/{br}/{ir}\n Video Centric: {vc}\n \n Epoch size multiplier: {em}\n \n Regression Stats:\n Location: mean {stats[0][0]:.05f} std {stats[1][0]:.05f}\n Duration: mean {stats[0][1]:.05f} std {stats[1][1]:.05f}\n \"\"\".format(\n prop_file=self.prop_file,\n pnum=len(self.fg_pool)\n + len(self.bg_pool)\n + len(self.incomp_pool),\n fnum=len(self.fg_pool),\n inum=len(self.incomp_pool),\n bnum=len(self.bg_pool),\n fr=self.fg_per_video,\n br=self.bg_per_video,\n ir=self.incomplete_per_video,\n vnum=len(self.video_dict),\n vc=self.video_centric,\n stats=self.stats,\n em=self.epoch_multiplier,\n )\n )\n )\n else:\n print(\n (\n \"\"\"\n SSNDataset: Proposal file {prop_file} parsed. \n \"\"\".format(\n prop_file=self.prop_file\n )\n )\n )\n\n def _video_centric_sampling(self, video):\n\n fg = video.get_fg(self.fg_iou_thresh, self.gt_as_fg)\n incomp, bg = video.get_negatives(\n self.incomplete_iou_thresh,\n self.bg_iou_thresh,\n self.bg_coverage_thresh,\n self.incomplete_overlap_thresh,\n )\n\n def sample_video_proposals(\n proposal_type, video_id, video_pool, requested_num, dataset_pool\n ):\n if len(video_pool) == 0:\n # if there is nothing in the video pool, go fetch from the dataset pool\n return [\n (dataset_pool[x], proposal_type)\n for x in np.random.choice(\n len(dataset_pool), requested_num, replace=False\n )\n ]\n else:\n replicate = len(video_pool) < requested_num\n idx = np.random.choice(\n len(video_pool), requested_num, replace=replicate\n )\n return [((video_id, video_pool[x]), proposal_type) for x in idx]\n\n out_props = []\n out_props.extend(\n sample_video_proposals(0, video.id, fg, self.fg_per_video, self.fg_pool)\n ) # sample foreground\n out_props.extend(\n sample_video_proposals(\n 1, video.id, incomp, self.incomplete_per_video, self.incomp_pool\n )\n ) # sample incomp.\n out_props.extend(\n sample_video_proposals(2, video.id, bg, self.bg_per_video, self.bg_pool)\n ) # sample background\n\n return out_props\n\n def _random_sampling(self):\n out_props = []\n\n out_props.extend(\n [\n (x, 0)\n for x in np.random.choice(\n self.fg_pool, self.fg_per_video, replace=False\n )\n ]\n )\n out_props.extend(\n [\n (x, 1)\n for x in np.random.choice(\n self.incomp_pool, self.incomplete_per_video, replace=False\n )\n ]\n )\n out_props.extend(\n [\n (x, 2)\n for x in np.random.choice(\n self.bg_pool, self.bg_per_video, replace=False\n )\n ]\n )\n\n return out_props\n\n def _sample_indices(self, valid_length, num_seg):\n \"\"\"\n\n :param record: VideoRecord\n :return: list\n \"\"\"\n\n average_duration = (valid_length + 1) // num_seg\n if average_duration > 0:\n # normal cases\n offsets = np.multiply(list(range(num_seg)), average_duration) + randint(\n average_duration, size=num_seg\n )\n elif valid_length > num_seg:\n offsets = np.sort(randint(valid_length, size=num_seg))\n else:\n offsets = np.zeros((num_seg,))\n\n return offsets\n\n def _get_val_indices(self, valid_length, num_seg):\n\n if valid_length > num_seg:\n tick = valid_length / float(num_seg)\n offsets = np.array([int(tick / 2.0 + tick * x) for x in range(num_seg)])\n else:\n offsets = np.zeros((num_seg,))\n\n return offsets\n\n def _sample_ssn_indices(self, prop, frame_cnt):\n start_frame = prop.start_frame + 1\n end_frame = prop.end_frame\n\n duration = end_frame - start_frame + 1\n assert duration != 0, (prop.start_frame, prop.end_frame, prop.best_iou)\n valid_length = duration - self.new_length\n\n valid_starting = max(1, start_frame - int(duration * self.starting_ratio))\n valid_ending = min(\n frame_cnt - self.new_length + 1,\n end_frame + int(duration * self.ending_ratio),\n )\n\n valid_starting_length = start_frame - valid_starting - self.new_length + 1\n valid_ending_length = valid_ending - end_frame - self.new_length + 1\n\n starting_scale = (valid_starting_length + self.new_length - 1) / (\n duration * self.starting_ratio\n )\n ending_scale = (valid_ending_length + self.new_length - 1) / (\n duration * self.ending_ratio\n )\n\n # get starting\n starting_offsets = (\n self._sample_indices(valid_starting_length, self.aug_seg)\n if self.random_shift\n else self._get_val_indices(valid_starting_length, self.aug_seg)\n ) + valid_starting\n course_offsets = (\n self._sample_indices(valid_length, self.body_seg)\n if self.random_shift\n else self._get_val_indices(valid_length, self.body_seg)\n ) + start_frame\n ending_offsets = (\n self._sample_indices(valid_ending_length, self.aug_seg)\n if self.random_shift\n else self._get_val_indices(valid_ending_length, self.aug_seg)\n ) + end_frame\n\n offsets = np.concatenate((starting_offsets, course_offsets, ending_offsets))\n stage_split = [\n self.aug_seg,\n self.aug_seg + self.body_seg,\n self.aug_seg * 2 + self.body_seg,\n ]\n return offsets, starting_scale, ending_scale, stage_split\n\n def _load_prop_data(self, prop):\n\n # read frame count\n frame_cnt = self.video_dict[prop[0][0]].num_frames\n\n # sample segment indices\n prop_indices, starting_scale, ending_scale, stage_split = self._sample_ssn_indices(\n prop[0][1], frame_cnt\n )\n\n # turn prop into standard format\n\n # get label\n if prop[1] == 0:\n label = prop[0][1].label\n elif prop[1] == 1:\n label = prop[0][1].label # incomplete\n elif prop[1] == 2:\n label = 0 # background\n else:\n raise ValueError()\n frames = []\n for idx, seg_ind in enumerate(prop_indices):\n p = int(seg_ind)\n for x in range(self.new_length):\n frames.extend(self._load_image(prop[0][0], min(frame_cnt, p + x)))\n\n # get regression target\n if prop[1] == 0:\n reg_targets = prop[0][1].regression_targets\n reg_targets = (\n (reg_targets[0] - self.stats[0][0]) / self.stats[1][0],\n (reg_targets[1] - self.stats[0][1]) / self.stats[1][1],\n )\n else:\n reg_targets = (0.0, 0.0)\n\n return (\n frames,\n label,\n reg_targets,\n starting_scale,\n ending_scale,\n stage_split,\n prop[1],\n )\n\n def _compute_regresssion_stats(self):\n if self.verbose:\n print(\"computing regression target normalizing constants\")\n targets = []\n for video in self.video_list:\n fg = video.get_fg(self.fg_iou_thresh, False)\n for p in fg:\n targets.append(list(p.regression_targets))\n\n self.stats = np.array((np.mean(targets, axis=0), np.std(targets, axis=0)))\n\n def get_test_data(self, video, test_interval, gen_batchsize=4):\n props = video.proposals\n video_id = video.id\n frame_cnt = video.num_frames\n frame_ticks = (\n np.arange(0, frame_cnt - self.new_length, test_interval, dtype=np.int) + 1\n )\n\n num_sampled_frames = len(frame_ticks)\n\n # avoid empty proposal list\n if len(props) == 0:\n props.append(SSNInstance(0, frame_cnt - 1, frame_cnt))\n\n # process proposals to subsampled sequences\n rel_prop_list = []\n proposal_tick_list = []\n scaling_list = []\n for proposal in props:\n rel_prop = proposal.start_frame / frame_cnt, proposal.end_frame / frame_cnt\n rel_duration = rel_prop[1] - rel_prop[0]\n rel_starting_duration = rel_duration * self.starting_ratio\n rel_ending_duration = rel_duration * self.ending_ratio\n rel_starting = rel_prop[0] - rel_starting_duration\n rel_ending = rel_prop[1] + rel_ending_duration\n\n real_rel_starting = max(0.0, rel_starting)\n real_rel_ending = min(1.0, rel_ending)\n\n starting_scaling = (rel_prop[0] - real_rel_starting) / rel_starting_duration\n ending_scaling = (real_rel_ending - rel_prop[1]) / rel_ending_duration\n\n proposal_ticks = (\n int(real_rel_starting * num_sampled_frames),\n int(rel_prop[0] * num_sampled_frames),\n int(rel_prop[1] * num_sampled_frames),\n int(real_rel_ending * num_sampled_frames),\n )\n\n rel_prop_list.append(rel_prop)\n proposal_tick_list.append(proposal_ticks)\n scaling_list.append((starting_scaling, ending_scaling))\n\n # load frames\n # Since there are many frames for each video during testing, instead of returning the read frames,\n # we return a generator which gives the frames in small batches, this lower the memory burden\n # and runtime overhead. Usually setting batchsize=4 would fit most cases.\n def frame_gen(batchsize):\n frames = []\n cnt = 0\n for idx, seg_ind in enumerate(frame_ticks):\n p = int(seg_ind)\n for x in range(self.new_length):\n frames.extend(self._load_image(video_id, min(frame_cnt, p + x)))\n cnt += 1\n\n if cnt % batchsize == 0:\n frames = self.transform(frames)\n yield frames\n frames = []\n\n if len(frames):\n frames = self.transform(frames)\n yield frames\n\n return (\n frame_gen(gen_batchsize),\n len(frame_ticks),\n torch.from_numpy(np.array(rel_prop_list)),\n torch.from_numpy(np.array(proposal_tick_list)),\n torch.from_numpy(np.array(scaling_list)),\n )\n\n def get_training_data(self, index):\n if self.video_centric:\n video = self.video_list[index]\n props = self._video_centric_sampling(video)\n else:\n props = self._random_sampling()\n\n out_frames = []\n out_prop_len = []\n out_prop_scaling = []\n out_prop_type = []\n out_prop_labels = []\n out_prop_reg_targets = []\n out_stage_split = []\n for idx, p in enumerate(props):\n prop_frames, prop_label, reg_targets, starting_scale, ending_scale, stage_split, prop_type = self._load_prop_data(\n p\n )\n\n processed_frames = self.transform(prop_frames)\n out_frames.append(processed_frames)\n out_prop_len.append(self.body_seg + 2 * self.aug_seg)\n out_prop_scaling.append([starting_scale, ending_scale])\n out_prop_labels.append(prop_label)\n out_prop_reg_targets.append(reg_targets)\n out_prop_type.append(prop_type)\n out_stage_split.append(stage_split)\n\n out_prop_len = torch.from_numpy(np.array(out_prop_len))\n out_prop_scaling = torch.from_numpy(\n np.array(out_prop_scaling, dtype=np.float32)\n )\n out_prop_labels = torch.from_numpy(np.array(out_prop_labels))\n out_prop_reg_targets = torch.from_numpy(\n np.array(out_prop_reg_targets, dtype=np.float32)\n )\n out_prop_type = torch.from_numpy(np.array(out_prop_type))\n out_stage_split = torch.from_numpy(np.array(out_stage_split))\n out_frames = torch.cat(out_frames)\n return (\n out_frames,\n out_prop_len,\n out_prop_scaling,\n out_prop_type,\n out_prop_labels,\n out_prop_reg_targets,\n out_stage_split,\n )\n\n def get_all_gt(self):\n gt_list = []\n for video in self.video_list:\n vid = video.id\n gt_list.extend(\n [\n [\n vid,\n x.label - 1,\n x.start_frame / video.num_frames,\n x.end_frame / video.num_frames,\n ]\n for x in video.gt\n ]\n )\n return gt_list\n\n def __getitem__(self, index):\n real_index = index % len(self.video_list)\n if self.test_mode:\n return self.get_test_data(self.video_list[real_index], self.test_interval)\n else:\n return self.get_training_data(real_index)\n\n def __len__(self):\n return len(self.video_list) * self.epoch_multiplier\n"
] | [
[
"numpy.random.randint"
]
] |
delldu/EDSR | [
"98752b57a3091e693c523e710380d369f9913041"
] | [
"src/model/vdsr.py"
] | [
"from model import common\n\nimport torch.nn as nn\nimport torch.nn.init as init\n\nurl = {\n 'r20f64': ''\n}\n\ndef make_model(args, parent=False):\n return VDSR(args)\n\nclass VDSR(nn.Module):\n def __init__(self, args, conv=common.default_conv):\n super(VDSR, self).__init__()\n\n n_resblocks = args.n_resblocks\n n_feats = args.n_feats\n kernel_size = 3\n url_name = 'r{}f{}'.format(n_resblocks, n_feats)\n if url_name in url:\n self.url = url[url_name]\n else:\n self.url = None\n\n self.sub_mean = common.MeanShift(args.rgb_range)\n self.add_mean = common.MeanShift(args.rgb_range, sign=1)\n\n def basic_block(in_channels, out_channels, act):\n return common.BasicBlock(\n conv, in_channels, out_channels, kernel_size,\n bias=True, bn=False, act=act\n )\n\n # define body module\n m_body = []\n m_body.append(basic_block(args.n_colors, n_feats, nn.ReLU(True)))\n for _ in range(n_resblocks - 2):\n m_body.append(basic_block(n_feats, n_feats, nn.ReLU(True)))\n m_body.append(basic_block(n_feats, args.n_colors, None))\n\n self.body = nn.Sequential(*m_body)\n\n def forward(self, x):\n x = self.sub_mean(x)\n res = self.body(x)\n res += x\n x = self.add_mean(res)\n\n return x \n\n\n# cd ..(src), export PYTHONPATH=`pwd`\n# if __name__ == '__main__':\n# import torch\n# import utility\n# from option import args\n\n# torch.manual_seed(args.seed)\n# checkpoint = utility.checkpoint(args)\n\n# print(args)\n# model = VDSR(args)\n# print(model)\n"
] | [
[
"torch.nn.ReLU",
"torch.nn.Sequential"
]
] |
NunoEdgarGFlowHub/PyBaMM | [
"4e4e1ab8c488b0c0a6efdb9934c5ac59e947a190",
"4e4e1ab8c488b0c0a6efdb9934c5ac59e947a190"
] | [
"tests/unit/test_parameters/test_current_functions.py",
"pybamm/expression_tree/binary_operators.py"
] | [
"#\n# Tests for current input functions\n#\nimport pybamm\nimport numbers\nimport unittest\nimport numpy as np\n\n\nclass TestCurrentFunctions(unittest.TestCase):\n def test_constant_current(self):\n # test simplify\n current = pybamm.electrical_parameters.current_with_time\n parameter_values = pybamm.ParameterValues(\n {\n \"Typical current [A]\": 2,\n \"Typical timescale [s]\": 1,\n \"Current function [A]\": 2,\n }\n )\n processed_current = parameter_values.process_symbol(current)\n self.assertIsInstance(processed_current.simplify(), pybamm.Scalar)\n\n def test_get_current_data(self):\n # test process parameters\n dimensional_current = pybamm.electrical_parameters.dimensional_current_with_time\n parameter_values = pybamm.ParameterValues(\n {\n \"Typical current [A]\": 2,\n \"Typical timescale [s]\": 1,\n \"Current function [A]\": \"[current data]car_current\",\n }\n )\n dimensional_current_eval = parameter_values.process_symbol(dimensional_current)\n\n def current(t):\n return dimensional_current_eval.evaluate(t=t)\n\n standard_tests = StandardCurrentFunctionTests([current], always_array=True)\n standard_tests.test_all()\n\n def test_user_current(self):\n # create user-defined sin function\n def my_fun(t, A, omega):\n return A * pybamm.sin(2 * np.pi * omega * t)\n\n # choose amplitude and frequency\n A = pybamm.electrical_parameters.I_typ\n omega = pybamm.Parameter(\"omega\")\n\n def current(t):\n return my_fun(t, A, omega)\n\n # set and process parameters\n parameter_values = pybamm.ParameterValues(\n {\n \"Typical current [A]\": 2,\n \"Typical timescale [s]\": 1,\n \"omega\": 3,\n \"Current function [A]\": current,\n }\n )\n dimensional_current = pybamm.electrical_parameters.dimensional_current_with_time\n dimensional_current_eval = parameter_values.process_symbol(dimensional_current)\n\n def user_current(t):\n return dimensional_current_eval.evaluate(t=t)\n\n # check output types\n standard_tests = StandardCurrentFunctionTests([user_current])\n standard_tests.test_all()\n\n # check output correct value\n time = np.linspace(0, 3600, 600)\n np.testing.assert_array_almost_equal(\n user_current(time), 2 * np.sin(2 * np.pi * 3 * time)\n )\n\n\nclass StandardCurrentFunctionTests(object):\n def __init__(self, function_list, always_array=False):\n self.function_list = function_list\n self.always_array = always_array\n\n def test_output_type(self):\n for function in self.function_list:\n if self.always_array is True:\n assert isinstance(function(0), np.ndarray)\n else:\n assert isinstance(function(0), numbers.Number)\n assert isinstance(function(np.zeros(3)), np.ndarray)\n assert isinstance(function(np.zeros([3, 3])), np.ndarray)\n\n def test_all(self):\n self.test_output_type()\n\n\nif __name__ == \"__main__\":\n print(\"Add -v for more debug output\")\n import sys\n\n if \"-v\" in sys.argv:\n debug = True\n pybamm.settings.debug_mode = True\n unittest.main()\n",
"#\n# Binary operator classes\n#\nimport pybamm\n\nimport numpy as np\nimport numbers\nfrom scipy.sparse import issparse, csr_matrix\n\n\ndef is_scalar_zero(expr):\n \"\"\"\n Utility function to test if an expression evaluates to a constant scalar zero\n \"\"\"\n if expr.is_constant():\n result = expr.evaluate_ignoring_errors(t=None)\n return isinstance(result, numbers.Number) and result == 0\n else:\n return False\n\n\ndef is_matrix_zero(expr):\n \"\"\"\n Utility function to test if an expression evaluates to a constant matrix zero\n \"\"\"\n if expr.is_constant():\n result = expr.evaluate_ignoring_errors(t=None)\n return (issparse(result) and result.count_nonzero() == 0) or (\n isinstance(result, np.ndarray) and np.all(result == 0)\n )\n else:\n return False\n\n\ndef is_scalar_one(expr):\n \"\"\"\n Utility function to test if an expression evaluates to a constant scalar one\n \"\"\"\n if expr.is_constant():\n result = expr.evaluate_ignoring_errors(t=None)\n return isinstance(result, numbers.Number) and result == 1\n else:\n return False\n\n\ndef is_matrix_one(expr):\n \"\"\"\n Utility function to test if an expression evaluates to a constant matrix one\n \"\"\"\n if expr.is_constant():\n result = expr.evaluate_ignoring_errors(t=None)\n return (issparse(result) and np.all(result.toarray() == 1)) or (\n isinstance(result, np.ndarray) and np.all(result == 1)\n )\n else:\n return False\n\n\ndef zeros_of_shape(shape):\n \"\"\"\n Utility function to create a scalar zero, or a vector or matrix of zeros of\n the correct shape\n \"\"\"\n if shape == ():\n return pybamm.Scalar(0)\n else:\n if len(shape) == 1 or shape[1] == 1:\n return pybamm.Vector(np.zeros(shape))\n else:\n return pybamm.Matrix(csr_matrix(shape))\n\n\nclass BinaryOperator(pybamm.Symbol):\n \"\"\"A node in the expression tree representing a binary operator (e.g. `+`, `*`)\n\n Derived classes will specify the particular operator\n\n **Extends**: :class:`Symbol`\n\n Parameters\n ----------\n\n name : str\n name of the node\n left : :class:`Symbol` or :class:`Number`\n lhs child node (converted to :class:`Scalar` if Number)\n right : :class:`Symbol` or :class:`Number`\n rhs child node (converted to :class:`Scalar` if Number)\n\n \"\"\"\n\n def __init__(self, name, left, right):\n left, right = self.format(left, right)\n\n domain = self.get_children_domains(left.domain, right.domain)\n auxiliary_domains = self.get_children_auxiliary_domains([left, right])\n super().__init__(\n name,\n children=[left, right],\n domain=domain,\n auxiliary_domains=auxiliary_domains,\n )\n self.left = self.children[0]\n self.right = self.children[1]\n\n def format(self, left, right):\n \"Format children left and right into compatible form\"\n # Turn numbers into scalars\n if isinstance(left, numbers.Number):\n left = pybamm.Scalar(left)\n if isinstance(right, numbers.Number):\n right = pybamm.Scalar(right)\n\n # Check both left and right are pybamm Symbols\n if not (isinstance(left, pybamm.Symbol) and isinstance(right, pybamm.Symbol)):\n raise NotImplementedError(\n \"\"\"'{}' not implemented for symbols of type {} and {}\"\"\".format(\n self.__class__.__name__, type(left), type(right)\n )\n )\n\n # Do some broadcasting in special cases, to avoid having to do this manually\n if left.domain != [] and right.domain != []:\n if (\n left.domain != right.domain\n and \"secondary\" in right.auxiliary_domains\n and left.domain == right.auxiliary_domains[\"secondary\"]\n ):\n left = pybamm.PrimaryBroadcast(left, right.domain)\n if (\n right.domain != left.domain\n and \"secondary\" in left.auxiliary_domains\n and right.domain == left.auxiliary_domains[\"secondary\"]\n ):\n right = pybamm.PrimaryBroadcast(right, left.domain)\n\n return left, right\n\n def __str__(self):\n \"\"\" See :meth:`pybamm.Symbol.__str__()`. \"\"\"\n return \"{!s} {} {!s}\".format(self.left, self.name, self.right)\n\n def get_children_domains(self, ldomain, rdomain):\n \"Combine domains from children in appropriate way\"\n if ldomain == rdomain:\n return ldomain\n elif ldomain == []:\n return rdomain\n elif rdomain == []:\n return ldomain\n else:\n raise pybamm.DomainError(\n \"\"\"\n children must have same (or empty) domains, but left.domain is '{}'\n and right.domain is '{}'\n \"\"\".format(\n ldomain, rdomain\n )\n )\n\n def new_copy(self):\n \"\"\" See :meth:`pybamm.Symbol.new_copy()`. \"\"\"\n\n # process children\n new_left = self.left.new_copy()\n new_right = self.right.new_copy()\n\n # make new symbol, ensure domain(s) remain the same\n out = self._binary_new_copy(new_left, new_right)\n out.copy_domains(self)\n\n return out\n\n def _binary_new_copy(self, left, right):\n \"Default behaviour for new_copy\"\n return self.__class__(left, right)\n\n def evaluate(self, t=None, y=None, y_dot=None, inputs=None, known_evals=None):\n \"\"\" See :meth:`pybamm.Symbol.evaluate()`. \"\"\"\n if known_evals is not None:\n id = self.id\n try:\n return known_evals[id], known_evals\n except KeyError:\n left, known_evals = self.left.evaluate(t, y, y_dot, inputs, known_evals)\n right, known_evals = self.right.evaluate(\n t, y, y_dot, inputs, known_evals\n )\n value = self._binary_evaluate(left, right)\n known_evals[id] = value\n return value, known_evals\n else:\n left = self.left.evaluate(t, y, y_dot, inputs)\n right = self.right.evaluate(t, y, y_dot, inputs)\n return self._binary_evaluate(left, right)\n\n def _evaluate_for_shape(self):\n \"\"\" See :meth:`pybamm.Symbol.evaluate_for_shape()`. \"\"\"\n left = self.children[0].evaluate_for_shape()\n right = self.children[1].evaluate_for_shape()\n return self._binary_evaluate(left, right)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" Calculate the jacobian of a binary operator. \"\"\"\n raise NotImplementedError\n\n def _binary_simplify(self, new_left, new_right):\n \"\"\" Simplify a binary operator. Default behaviour: unchanged\"\"\"\n return self._binary_new_copy(new_left, new_right)\n\n def _binary_evaluate(self, left, right):\n \"\"\" Perform binary operation on nodes 'left' and 'right'. \"\"\"\n raise NotImplementedError\n\n def evaluates_on_edges(self, dimension):\n \"\"\" See :meth:`pybamm.Symbol.evaluates_on_edges()`. \"\"\"\n return self.left.evaluates_on_edges(dimension) or self.right.evaluates_on_edges(\n dimension\n )\n\n\nclass Power(BinaryOperator):\n \"\"\"A node in the expression tree representing a `**` power operator\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(\"**\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n # apply chain rule and power rule\n base, exponent = self.orphans\n # derivative if variable is in the base\n diff = exponent * (base ** (exponent - 1)) * base.diff(variable)\n # derivative if variable is in the exponent (rare, check separately to avoid\n # unecessarily big tree)\n if any(variable.id == x.id for x in exponent.pre_order()):\n diff += (base ** exponent) * pybamm.log(base) * exponent.diff(variable)\n return diff\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # apply chain rule and power rule\n left, right = self.orphans\n if left.evaluates_to_number() and right.evaluates_to_number():\n return pybamm.Scalar(0)\n elif right.evaluates_to_number():\n return (right * left ** (right - 1)) * left_jac\n elif left.evaluates_to_number():\n return (left ** right * pybamm.log(left)) * right_jac\n else:\n return (left ** (right - 1)) * (\n right * left_jac + left * pybamm.log(left) * right_jac\n )\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n # don't raise RuntimeWarning for NaNs\n with np.errstate(invalid=\"ignore\"):\n return left ** right\n\n def _binary_simplify(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_simplify()`. \"\"\"\n\n # anything to the power of zero is one\n if is_scalar_zero(right):\n return pybamm.Scalar(1)\n\n # zero to the power of anything is zero\n if is_scalar_zero(left):\n return pybamm.Scalar(0)\n\n # anything to the power of one is itself\n if is_scalar_one(right):\n return left\n\n return self.__class__(left, right)\n\n\nclass Addition(BinaryOperator):\n \"\"\"A node in the expression tree representing an addition operator\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(\"+\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n return self.left.diff(variable) + self.right.diff(variable)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n return left_jac + right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n return left + right\n\n def _binary_simplify(self, left, right):\n \"\"\"\n See :meth:`pybamm.BinaryOperator._binary_simplify()`.\n\n Note\n ----\n We check for scalars first, then matrices. This is because\n (Zero Matrix) + (Zero Scalar)\n should return (Zero Matrix), not (Zero Scalar).\n \"\"\"\n\n # anything added by a scalar zero returns the other child\n if is_scalar_zero(left):\n return right\n if is_scalar_zero(right):\n return left\n # Check matrices after checking scalars\n if is_matrix_zero(left):\n if isinstance(right, pybamm.Scalar):\n return pybamm.Array(right.value * np.ones(left.shape_for_testing))\n else:\n return right\n if is_matrix_zero(right):\n if isinstance(left, pybamm.Scalar):\n return pybamm.Array(left.value * np.ones(right.shape_for_testing))\n else:\n return left\n\n return pybamm.simplify_addition_subtraction(self.__class__, left, right)\n\n\nclass Subtraction(BinaryOperator):\n \"\"\"A node in the expression tree representing a subtraction operator\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n\n super().__init__(\"-\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n return self.left.diff(variable) - self.right.diff(variable)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n return left_jac - right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n return left - right\n\n def _binary_simplify(self, left, right):\n \"\"\"\n See :meth:`pybamm.BinaryOperator._binary_simplify()`.\n\n Note\n ----\n We check for scalars first, then matrices. This is because\n (Zero Matrix) - (Zero Scalar)\n should return (Zero Matrix), not -(Zero Scalar).\n \"\"\"\n\n # anything added by a scalar zero returns the other child\n if is_scalar_zero(left):\n return -right\n if is_scalar_zero(right):\n return left\n # Check matrices after checking scalars\n if is_matrix_zero(left):\n if isinstance(right, pybamm.Scalar):\n return pybamm.Array(-right.value * np.ones(left.shape_for_testing))\n else:\n return -right\n if is_matrix_zero(right):\n if isinstance(left, pybamm.Scalar):\n return pybamm.Array(left.value * np.ones(right.shape_for_testing))\n else:\n return left\n\n return pybamm.simplify_addition_subtraction(self.__class__, left, right)\n\n\nclass Multiplication(BinaryOperator):\n \"\"\"\n A node in the expression tree representing a multiplication operator\n (Hadamard product). Overloads cases where the \"*\" operator would usually return a\n matrix multiplication (e.g. scipy.sparse.coo.coo_matrix)\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n\n super().__init__(\"*\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n # apply product rule\n left, right = self.orphans\n return left.diff(variable) * right + left * right.diff(variable)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # apply product rule\n left, right = self.orphans\n if left.evaluates_to_number() and right.evaluates_to_number():\n return pybamm.Scalar(0)\n elif left.evaluates_to_number():\n return left * right_jac\n elif right.evaluates_to_number():\n return right * left_jac\n else:\n return right * left_jac + left * right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n\n if issparse(left):\n return csr_matrix(left.multiply(right))\n elif issparse(right):\n # Hadamard product is commutative, so we can switch right and left\n return csr_matrix(right.multiply(left))\n else:\n return left * right\n\n def _binary_simplify(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_simplify()`. \"\"\"\n\n # simplify multiply by scalar zero, being careful about shape\n if is_scalar_zero(left):\n return zeros_of_shape(right.shape_for_testing)\n if is_scalar_zero(right):\n return zeros_of_shape(left.shape_for_testing)\n\n # if one of the children is a zero matrix, we have to be careful about shapes\n if is_matrix_zero(left) or is_matrix_zero(right):\n shape = (left * right).shape\n return zeros_of_shape(shape)\n\n # anything multiplied by a scalar one returns itself\n if is_scalar_one(left):\n return right\n if is_scalar_one(right):\n return left\n\n return pybamm.simplify_multiplication_division(self.__class__, left, right)\n\n\nclass MatrixMultiplication(BinaryOperator):\n \"\"\"A node in the expression tree representing a matrix multiplication operator\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n\n super().__init__(\"@\", left, right)\n\n def diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol.diff()`. \"\"\"\n # We shouldn't need this\n raise NotImplementedError(\n \"diff not implemented for symbol of type 'MatrixMultiplication'\"\n )\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # We only need the case where left is an array and right\n # is a (slice of a) state vector, e.g. for discretised spatial\n # operators of the form D @ u (also catch cases of (-D) @ u)\n left, right = self.orphans\n if isinstance(left, pybamm.Array) or (\n isinstance(left, pybamm.Negate) and isinstance(left.child, pybamm.Array)\n ):\n left = pybamm.Matrix(csr_matrix(left.evaluate()))\n return left @ right_jac\n else:\n raise NotImplementedError(\n \"\"\"jac of 'MatrixMultiplication' is only\n implemented for left of type 'pybamm.Array',\n not {}\"\"\".format(\n left.__class__\n )\n )\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n return left @ right\n\n def _binary_simplify(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_simplify()`. \"\"\"\n if is_matrix_zero(left) or is_matrix_zero(right):\n shape = (left @ right).shape\n return zeros_of_shape(shape)\n\n return pybamm.simplify_multiplication_division(self.__class__, left, right)\n\n\nclass Division(BinaryOperator):\n \"\"\"A node in the expression tree representing a division operator\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(\"/\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n # apply quotient rule\n top, bottom = self.orphans\n return (top.diff(variable) * bottom - top * bottom.diff(variable)) / bottom ** 2\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # apply quotient rule\n left, right = self.orphans\n if left.evaluates_to_number() and right.evaluates_to_number():\n return pybamm.Scalar(0)\n elif left.evaluates_to_number():\n return -left / right ** 2 * right_jac\n elif right.evaluates_to_number():\n return left_jac / right\n else:\n return (right * left_jac - left * right_jac) / right ** 2\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n\n if issparse(left):\n return csr_matrix(left.multiply(1 / right))\n else:\n if isinstance(right, numbers.Number) and right == 0:\n # don't raise RuntimeWarning for NaNs\n with np.errstate(invalid=\"ignore\"):\n return left * np.inf\n else:\n return left / right\n\n def _binary_simplify(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_simplify()`. \"\"\"\n\n # zero divided by zero returns nan scalar\n if is_scalar_zero(left) and is_scalar_zero(right):\n return pybamm.Scalar(np.nan)\n\n # zero divided by anything returns zero (being careful about shape)\n if is_scalar_zero(left):\n return zeros_of_shape(right.shape_for_testing)\n\n # matrix zero divided by anything returns matrix zero (i.e. itself)\n if is_matrix_zero(left):\n return left\n\n # anything divided by zero returns inf\n if is_scalar_zero(right):\n if left.shape_for_testing == ():\n return pybamm.Scalar(np.inf)\n else:\n return pybamm.Array(np.inf * np.ones(left.shape_for_testing))\n\n # anything divided by one is itself\n if is_scalar_one(right):\n return left\n\n return pybamm.simplify_multiplication_division(self.__class__, left, right)\n\n\nclass Inner(BinaryOperator):\n \"\"\"\n A node in the expression tree which represents the inner (or dot) product. This\n operator should be used to take the inner product of two mathematical vectors\n (as opposed to the computational vectors arrived at post-discretisation) of the\n form v = v_x e_x + v_y e_y + v_z e_z where v_x, v_y, v_z are scalars\n and e_x, e_y, e_z are x-y-z-directional unit vectors. For v and w mathematical\n vectors, inner product returns v_x * w_x + v_y * w_y + v_z * w_z. In addition,\n for some spatial discretisations mathematical vector quantities (such as\n i = grad(phi) ) are evaluated on a different part of the grid to mathematical\n scalars (e.g. for finite volume mathematical scalars are evaluated on the nodes but\n mathematical vectors are evaluated on cell edges). Therefore, inner also transfers\n the inner product of the vector onto the scalar part of the grid if required\n by a particular discretisation.\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(\"inner product\", left, right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n # apply product rule\n left, right = self.orphans\n return left.diff(variable) * right + left * right.diff(variable)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # apply product rule\n left, right = self.orphans\n if left.evaluates_to_number() and right.evaluates_to_number():\n return pybamm.Scalar(0)\n elif left.evaluates_to_number():\n return left * right_jac\n elif right.evaluates_to_number():\n return right * left_jac\n else:\n return right * left_jac + left * right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n\n if issparse(left):\n return left.multiply(right)\n elif issparse(right):\n # Hadamard product is commutative, so we can switch right and left\n return right.multiply(left)\n else:\n return left * right\n\n def _binary_simplify(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_simplify()`. \"\"\"\n\n # simplify multiply by scalar zero, being careful about shape\n if is_scalar_zero(left):\n return zeros_of_shape(right.shape_for_testing)\n if is_scalar_zero(right):\n return zeros_of_shape(left.shape_for_testing)\n\n # if one of the children is a zero matrix, we have to be careful about shapes\n if is_matrix_zero(left) or is_matrix_zero(right):\n shape = (left * right).shape\n return zeros_of_shape(shape)\n\n # anything multiplied by a scalar one returns itself\n if is_scalar_one(left):\n return right\n if is_scalar_one(right):\n return left\n\n return pybamm.simplify_multiplication_division(self.__class__, left, right)\n\n def evaluates_on_edges(self, dimension):\n \"\"\" See :meth:`pybamm.Symbol.evaluates_on_edges()`. \"\"\"\n return False\n\n\ndef inner(left, right):\n \"\"\"\n Return inner product of two symbols.\n \"\"\"\n return pybamm.Inner(left, right)\n\n\nclass Heaviside(BinaryOperator):\n \"\"\"A node in the expression tree representing a heaviside step function.\n\n Adding this operation to the rhs or algebraic equations in a model can often cause a\n discontinuity in the solution. For the specific cases listed below, this will be\n automatically handled by the solver. In the general case, you can explicitly tell\n the solver of discontinuities by adding a :class:`Event` object with\n :class:`EventType` DISCONTINUITY to the model's list of events.\n\n In the case where the Heaviside function is of the form `pybamm.t < x`, `pybamm.t <=\n x`, `x < pybamm.t`, or `x <= pybamm.t`, where `x` is any constant equation, this\n DISCONTINUITY event will automatically be added by the solver.\n\n **Extends:** :class:`BinaryOperator`\n \"\"\"\n\n def __init__(self, name, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(name, left, right)\n\n def diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol.diff()`. \"\"\"\n # Heaviside should always be multiplied by something else so hopefully don't\n # need to worry about shape\n return pybamm.Scalar(0)\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n # Heaviside should always be multiplied by something else so hopefully don't\n # need to worry about shape\n return pybamm.Scalar(0)\n\n\nclass EqualHeaviside(Heaviside):\n \"A heaviside function with equality (return 1 when left = right)\"\n\n def __init__(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator.__init__()`. \"\"\"\n super().__init__(\"<=\", left, right)\n\n def __str__(self):\n \"\"\" See :meth:`pybamm.Symbol.__str__()`. \"\"\"\n return \"{!s} <= {!s}\".format(self.left, self.right)\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n # don't raise RuntimeWarning for NaNs\n with np.errstate(invalid=\"ignore\"):\n return left <= right\n\n\nclass NotEqualHeaviside(Heaviside):\n \"A heaviside function without equality (return 0 when left = right)\"\n\n def __init__(self, left, right):\n super().__init__(\"<\", left, right)\n\n def __str__(self):\n \"\"\" See :meth:`pybamm.Symbol.__str__()`. \"\"\"\n return \"{!s} < {!s}\".format(self.left, self.right)\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n # don't raise RuntimeWarning for NaNs\n with np.errstate(invalid=\"ignore\"):\n return left < right\n\n\nclass Minimum(BinaryOperator):\n \" Returns the smaller of two objects \"\n\n def __init__(self, left, right):\n super().__init__(\"minimum\", left, right)\n\n def __str__(self):\n \"\"\" See :meth:`pybamm.Symbol.__str__()`. \"\"\"\n return \"minimum({!s}, {!s})\".format(self.left, self.right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n left, right = self.orphans\n return (left <= right) * left.diff(variable) + (left > right) * right.diff(\n variable\n )\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n left, right = self.orphans\n return (left <= right) * left_jac + (left > right) * right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n # don't raise RuntimeWarning for NaNs\n return np.minimum(left, right)\n\n\nclass Maximum(BinaryOperator):\n \" Returns the smaller of two objects \"\n\n def __init__(self, left, right):\n super().__init__(\"maximum\", left, right)\n\n def __str__(self):\n \"\"\" See :meth:`pybamm.Symbol.__str__()`. \"\"\"\n return \"maximum({!s}, {!s})\".format(self.left, self.right)\n\n def _diff(self, variable):\n \"\"\" See :meth:`pybamm.Symbol._diff()`. \"\"\"\n left, right = self.orphans\n return (left >= right) * left.diff(variable) + (left < right) * right.diff(\n variable\n )\n\n def _binary_jac(self, left_jac, right_jac):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_jac()`. \"\"\"\n left, right = self.orphans\n return (left >= right) * left_jac + (left < right) * right_jac\n\n def _binary_evaluate(self, left, right):\n \"\"\" See :meth:`pybamm.BinaryOperator._binary_evaluate()`. \"\"\"\n # don't raise RuntimeWarning for NaNs\n return np.maximum(left, right)\n\n\ndef minimum(left, right):\n \"\"\"\n Returns the smaller of two objects. Not to be confused with :meth:`pybamm.min`,\n which returns min function of child.\n \"\"\"\n return pybamm.simplify_if_constant(Minimum(left, right), keep_domains=True)\n\n\ndef maximum(left, right):\n \"\"\"\n Returns the larger of two objects. Not to be confused with :meth:`pybamm.max`,\n which returns max function of child.\n \"\"\"\n return pybamm.simplify_if_constant(Maximum(left, right), keep_domains=True)\n\n\ndef source(left, right, boundary=False):\n \"\"\"A convinience function for creating (part of) an expression tree representing\n a source term. This is necessary for spatial methods where the mass matrix\n is not the identity (e.g. finite element formulation with piecwise linear\n basis functions). The left child is the symbol representing the source term\n and the right child is the symbol of the equation variable (currently, the\n finite element formulation in PyBaMM assumes all functions are constructed\n using the same basis, and the matrix here is constructed accoutning for the\n boundary conditions of the right child). The method returns the matrix-vector\n product of the mass matrix (adjusted to account for any Dirichlet boundary\n conditions imposed the the right symbol) and the discretised left symbol.\n\n Parameters\n ----------\n\n left : :class:`Symbol`\n The left child node, which represents the expression for the source term.\n right : :class:`Symbol`\n The right child node. This is the symbol whose boundary conditions are\n accounted for in the construction of the mass matrix.\n boundary : bool, optional\n If True, then the mass matrix should is assembled over the boundary,\n corresponding to a source term which only acts on the boundary of the\n domain. If False (default), the matrix is assembled over the entire domain,\n corresponding to a source term in the bulk.\n\n \"\"\"\n # Broadcast if left is number\n if isinstance(left, numbers.Number):\n left = pybamm.PrimaryBroadcast(left, \"current collector\")\n\n if left.domain != [\"current collector\"] or right.domain != [\"current collector\"]:\n raise pybamm.DomainError(\n \"\"\"'source' only implemented in the 'current collector' domain,\n but symbols have domains {} and {}\"\"\".format(\n left.domain, right.domain\n )\n )\n if boundary:\n return pybamm.BoundaryMass(right) @ left\n else:\n return pybamm.Mass(right) @ left\n"
] | [
[
"numpy.sin",
"numpy.linspace",
"numpy.zeros"
],
[
"numpy.ones",
"numpy.zeros",
"scipy.sparse.issparse",
"scipy.sparse.csr_matrix",
"numpy.errstate",
"numpy.all",
"numpy.maximum",
"numpy.minimum"
]
] |
YongLiuLab/BrainRadiomicsTools | [
"19b440acd554ee920857c306442b6d2c411dca88"
] | [
"Core/hippoSeg/LiviaNet/startTraining.py"
] | [
"\"\"\" \nCopyright (c) 2016, Jose Dolz .All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\n\nJose Dolz. Dec, 2016.\nemail: jose.dolz.upv@gmail.com\nLIVIA Department, ETS, Montreal.\n\"\"\"\n\nimport os\n\nimport numpy as np\nfrom Modules.IO.sampling import getSamplesSubepoch\n\nfrom Modules.General.Utils import dump_model_to_gzip_file\nfrom Modules.General.Utils import getImagesSet\nfrom Modules.General.Utils import load_model_from_gzip_file\nfrom Modules.Parsers.parsersUtils import parserConfigIni\nfrom startTesting import segmentVolume\n\n\ndef startTraining(networkModelName,configIniName):\n print (\" ************************************************ STARTING TRAINING **************************************************\")\n print (\" ********************** Starting training model (Reading parameters) **********************\")\n\n myParserConfigIni = parserConfigIni()\n \n myParserConfigIni.readConfigIniFile(configIniName,1)\n \n # Image type (0: Nifti, 1: Matlab)\n imageType = myParserConfigIni.imageTypesTrain\n\n print (\" --- Do training in {} epochs with {} subEpochs each...\".format(myParserConfigIni.numberOfEpochs, myParserConfigIni.numberOfSubEpochs))\n print (\"-------- Reading Images names used in training/validation -------------\")\n##-----##\n # from sklearn.model_selection import KFold\n # import numpy as np\n # y1 = myParserConfigIni.indexesForTraining\n # #x1 = myParserConfigIni.indexesForValidation\n # kf = KFold(n_splits= 5)\n #\n # for train_index, test_index in kf.split(y1):\n # print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n # y, x = np.array(y1)[train_index], np.array(y1)[test_index]\n##-----##\n # from sklearn.model_selection import LeavePOut\n # lpo = LeavePOut(p=5)\n # y1 = myParserConfigIni.indexesForTraining\n # for train, test in lpo.split(y1):\n # y, x = np.array(y1)[train], np.array(y1)[test]\n##-----train##\n from sklearn.cross_validation import LeaveOneOut\n loo = LeaveOneOut(4)\n y1 = myParserConfigIni.indexesForTraining\n x1 = myParserConfigIni.indexesForValidation\n for train_index, test_index in loo:\n print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n y, x = np.array(y1)[train_index], np.array(y1)[test_index]\n##------he\n # from sklearn.model_selection import train_test_split\n # X_train, X_test, Y_train, Y_test = train_test_split(DataX, DataY, test_size=0.2)\n\n # -- Get list of images used for training -- #\n\n (imageNames_Train, names_Train) = getImagesSet(myParserConfigIni.imagesFolder,y) # Images\n (groundTruthNames_Train, gt_names_Train) = getImagesSet(myParserConfigIni.GroundTruthFolder,y) # Ground truth\n (roiNames_Train, roi_names_Train) = getImagesSet(myParserConfigIni.ROIFolder,y) # ROI\n\n # -- Get list of images used for validation -- #\n (imageNames_Val, names_Val) = getImagesSet(myParserConfigIni.imagesFolder,x) # Images\n (groundTruthNames_Val, gt_names_Val) = getImagesSet(myParserConfigIni.GroundTruthFolder,x) # Ground truth\n (roiNames_Val, roi_names_Val) = getImagesSet(myParserConfigIni.ROIFolder,x) # ROI\n\n # Print names\n print (\" ================== Images for training ================\")\n for i in range(0,len(names_Train)):\n if len(roi_names_Train) > 0:\n print(\" Image({}): {} | GT: {} | ROI {} \".format(i,names_Train[i], gt_names_Train[i], roi_names_Train[i] ))\n else:\n print(\" Image({}): {} | GT: {} \".format(i,names_Train[i], gt_names_Train[i] ))\n print (\" ================== Images for validation ================\")\n for i in range(0,len(names_Val)):\n if len(roi_names_Train) > 0:\n print(\" Image({}): {} | GT: {} | ROI {} \".format(i,names_Val[i], gt_names_Val[i], roi_names_Val[i] ))\n else:\n print(\" Image({}): {} | GT: {} \".format(i,names_Val[i], gt_names_Val[i]))\n print (\" ===============================================================\")\n \n # --------------- Load my LiviaNet3D object --------------- \n print (\" ... Loading model from {}\".format(networkModelName))\n myLiviaNet3D = load_model_from_gzip_file(networkModelName)\n print (\" ... Network architecture successfully loaded....\")\n\n # Asign parameters to loaded Net\n myLiviaNet3D.numberOfEpochs = myParserConfigIni.numberOfEpochs\n myLiviaNet3D.numberOfSubEpochs = myParserConfigIni.numberOfSubEpochs\n myLiviaNet3D.numberOfSamplesSupEpoch = myParserConfigIni.numberOfSamplesSupEpoch\n myLiviaNet3D.firstEpochChangeLR = myParserConfigIni.firstEpochChangeLR\n myLiviaNet3D.frequencyChangeLR = myParserConfigIni.frequencyChangeLR\n \n numberOfEpochs = myLiviaNet3D.numberOfEpochs\n numberOfSubEpochs = myLiviaNet3D.numberOfSubEpochs\n numberOfSamplesSupEpoch = myLiviaNet3D.numberOfSamplesSupEpoch\n \n # --------------- -------------- --------------- \n # --------------- Start TRAINING --------------- \n # --------------- -------------- --------------- \n # Get sample dimension values\n receptiveField = myLiviaNet3D.receptiveField\n sampleSize_Train = myLiviaNet3D.sampleSize_Train\n\n trainingCost = []\n\n if myParserConfigIni.applyPadding == 1:\n applyPadding = True\n else:\n applyPadding = False\n \n learningRateModifiedEpoch = 0\n \n # Run over all the (remaining) epochs and subepochs\n for e_i in xrange(numberOfEpochs):\n # Recover last trained epoch\n numberOfEpochsTrained = myLiviaNet3D.numberOfEpochsTrained\n \n print(\" ============== EPOCH: {}/{} =================\".format(numberOfEpochsTrained+1,numberOfEpochs))\n\n costsOfEpoch = []\n \n for subE_i in xrange(numberOfSubEpochs): \n epoch_nr = subE_i+1\n print (\" --- SubEPOCH: {}/{}\".format(epoch_nr,myLiviaNet3D.numberOfSubEpochs))\n\n # Get all the samples that will be used in this sub-epoch\n [imagesSamplesAll,\n gt_samplesAll] = getSamplesSubepoch(numberOfSamplesSupEpoch,\n imageNames_Train,\n groundTruthNames_Train,\n roiNames_Train,\n imageType,\n sampleSize_Train,\n receptiveField,\n applyPadding\n )\n\n # Variable that will contain weights for the cost function\n # --- In its current implementation, all the classes have the same weight\n weightsCostFunction = np.ones(myLiviaNet3D.n_classes, dtype='float32')\n \n numberBatches = len(imagesSamplesAll) / myLiviaNet3D.batch_Size \n \n myLiviaNet3D.trainingData_x.set_value(imagesSamplesAll, borrow=True)\n myLiviaNet3D.trainingData_y.set_value(gt_samplesAll, borrow=True)\n \n costsOfBatches = []\n evalResultsSubepoch = np.zeros([ myLiviaNet3D.n_classes, 4 ], dtype=\"int32\")\n \n for b_i in xrange(numberBatches):\n # TODO: Make a line that adds a point at each trained batch (Or percentage being updated)\n costErrors = myLiviaNet3D.networkModel_Train(b_i, weightsCostFunction)\n meanBatchCostError = costErrors[0]\n costsOfBatches.append(meanBatchCostError)\n myLiviaNet3D.updateLayersMatricesBatchNorm() \n\n \n #======== Calculate and Report accuracy over subepoch\n meanCostOfSubepoch = sum(costsOfBatches) / float(numberBatches)\n print(\" ---------- Cost of this subEpoch: {}\".format(meanCostOfSubepoch))\n \n # Release data\n myLiviaNet3D.trainingData_x.set_value(np.zeros([1,1,1,1,1], dtype=\"float32\"))\n myLiviaNet3D.trainingData_y.set_value(np.zeros([1,1,1,1], dtype=\"float32\"))\n\n # Get mean cost epoch\n costsOfEpoch.append(meanCostOfSubepoch)\n\n meanCostOfEpoch = sum(costsOfEpoch) / float(numberOfSubEpochs)\n \n # Include the epoch cost to the main training cost and update current mean \n trainingCost.append(meanCostOfEpoch)\n currentMeanCost = sum(trainingCost) / float(str( e_i + 1))\n \n print(\" ---------- Training on Epoch #\" + str(e_i) + \" finished ----------\" )\n print(\" ---------- Cost of Epoch: {} / Mean training error {}\".format(meanCostOfEpoch,currentMeanCost))\n print(\" -------------------------------------------------------- \" )\n \n # ------------- Update Learning Rate if required ----------------#\n\n if e_i >= myLiviaNet3D.firstEpochChangeLR :\n if learningRateModifiedEpoch == 0:\n currentLR = myLiviaNet3D.learning_rate.get_value()\n newLR = currentLR / 2.0\n myLiviaNet3D.learning_rate.set_value(newLR)\n print(\" ... Learning rate has been changed from {} to {}\".format(currentLR, newLR))\n learningRateModifiedEpoch = e_i\n else:\n if (e_i) == (learningRateModifiedEpoch + myLiviaNet3D.frequencyChangeLR):\n currentLR = myLiviaNet3D.learning_rate.get_value()\n newLR = currentLR / 2.0\n myLiviaNet3D.learning_rate.set_value(newLR)\n print(\" ... Learning rate has been changed from {} to {}\".format(currentLR, newLR))\n learningRateModifiedEpoch = e_i\n \n # ---------------------- Start validation ---------------------- #\n \n numberImagesToSegment = len(imageNames_Val)\n print(\" ********************** Starting validation **********************\")\n\n # Run over the images to segment \n for i_d in xrange(numberImagesToSegment) :\n print(\"------------- Segmenting subject: {} ....total: {}/{}... -------------\".format(names_Val[i_d],str(i_d+1),str(numberImagesToSegment)))\n strideValues = myLiviaNet3D.lastLayer.outputShapeTest[2:]\n \n segmentVolume(myLiviaNet3D,\n i_d,\n imageNames_Val, # Full path\n names_Val, # Only image name\n groundTruthNames_Val,\n roiNames_Val,\n imageType,\n applyPadding,\n receptiveField, \n sampleSize_Train,\n strideValues,\n myLiviaNet3D.batch_Size,\n 0 # Validation (0) or testing (1)\n )\n \n \n print(\" ********************** Validation DONE ********************** \")\n\n # ------ In this point the training is done at Epoch n ---------#\n # Increase number of epochs trained\n myLiviaNet3D.numberOfEpochsTrained += 1\n\n # --------------- Save the model --------------- \n BASE_DIR = os.getcwd()\n path_Temp = os.path.join(BASE_DIR,'outputFiles')\n netFolderName = os.path.join(path_Temp,myLiviaNet3D.folderName)\n netFolderName = os.path.join(netFolderName,'Networks')\n\n modelFileName = netFolderName + \"/\" + myLiviaNet3D.networkName + \"_Epoch\" + str (myLiviaNet3D.numberOfEpochsTrained)\n dump_model_to_gzip_file(myLiviaNet3D, modelFileName)\n \n strFinal = \" Network model saved in \" + netFolderName + \" as \" + myLiviaNet3D.networkName + \"_Epoch\" + str (myLiviaNet3D.numberOfEpochsTrained)\n print (strFinal)\n\n print(\"................ The whole Training is done.....\")\n print(\" ************************************************************************************ \")\n"
] | [
[
"numpy.array",
"numpy.ones",
"numpy.zeros",
"sklearn.cross_validation.LeaveOneOut"
]
] |
T3p/policy-optimization | [
"77006545779823737c4ca3b19e9d80506015c132"
] | [
"potion/envs/minigolf.py"
] | [
"from numbers import Number\n\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\nimport math as m\nfrom scipy.stats import norm\n\n\"\"\"\nMinigolf task.\nReferences\n----------\n - Penner, A. R. \"The physics of putting.\" Canadian Journal of Physics 80.2 (2002): 83-96.\n\"\"\"\n\n\nclass MiniGolf(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 30\n }\n\n def __init__(self):\n self.min_pos = 0.0\n self.max_pos = 20.0\n self.min_action = 1e-5\n self.max_action = 10.0\n self.putter_length = 1.0 # [0.7:1.0]\n self.friction = 0.131 # [0.065:0.196]\n self.hole_size = 0.10 # [0.10:0.15]\n self.sigma_noise = 0.3\n self.ball_radius = 0.02135\n self.min_variance = 1e-2 # Minimum variance for computing the densities\n\n # gym attributes\n self.viewer = None\n low = np.array([self.min_pos])\n high = np.array([self.max_pos])\n self.action_space = spaces.Box(low=self.min_action,\n high=self.max_action,\n shape=(1,), dtype=float)\n self.observation_space = spaces.Box(low=low, high=high, dtype=float)\n\n # initialize state\n self.seed()\n self.reset()\n\n def setParams(self, env_param):\n self.putter_length = env_param[0]\n self.friction = env_param[1]\n self.hole_size = env_param[2]\n self.sigma_noise = m.sqrt(env_param[-1])\n\n def step(self, action, render=False):\n action = np.clip(action, self.min_action, self.max_action / 2)\n\n noise = 10\n while abs(noise) > 1:\n noise = self.np_random.randn() * self.sigma_noise\n u = action * self.putter_length * (1 + noise)\n\n deceleration = 5 / 7 * self.friction * 9.81\n\n t = u / deceleration\n xn = self.state - u * t + 0.5 * deceleration * t ** 2\n\n reward = 0\n done = True\n if self.state > 0:\n reward = -1\n done = False\n elif self.state < -4:\n reward = -100\n\n self.state = xn\n\n return self.get_state(), float(reward), done, {'state': self.get_state(), 'action': action, 'danger': float(self.state) < -4}\n\n # Custom param for transfer\n\n def getEnvParam(self):\n return np.asarray([np.ravel(self.putter_length), np.ravel(self.friction), np.ravel(self.hole_size),\n np.ravel(self.sigma_noise ** 2)])\n\n def reset(self, state=None):\n if state is None:\n self.state = np.array([self.np_random.uniform(low=self.min_pos,\n high=self.max_pos)])\n else:\n self.state = np.array(state)\n\n return self.get_state()\n\n def get_state(self):\n return np.array(self.state)\n\n def get_true_state(self):\n \"\"\"For testing purposes\"\"\"\n return np.array(self.state)\n\n def clip_state(self, state):\n return state\n # return np.clip(state, self.min_pos, self.max_pos)\n\n def clip_action(self, action):\n return action\n # return np.clip(action, self.min_action, self.max_action)\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def getDensity_old(self, env_parameters, state, action, next_state):\n\n if state < next_state:\n return 0\n\n action = np.clip(action, self.min_action, self.max_action / 2)\n action = 1e-8 if action == 0 else action\n\n putter_length = env_parameters[0]\n friction = env_parameters[1]\n sigma_noise = env_parameters[-1]\n deceleration = 5 / 7 * friction * 9.81\n\n u = np.sqrt(2 * deceleration * (state - next_state))\n noise = (u / (action * putter_length) - 1) / sigma_noise\n\n return norm.pdf(noise)\n\n def density_old(self, env_parameters, state, action, next_state):\n \"\"\"\n :param env_parameters: list of env_params\n :param state: NxTx1\n :param action: NxT\n :param next_state: NxTx1\n :return: pdf NxTx1xn_param\n \"\"\"\n assert state.ndim == 4 and action.ndim == 3 and next_state.ndim == 4\n\n mask = state < next_state\n action = np.clip(action, self.min_action, self.max_action / 2)\n action[action == 0] = 1e-8\n pdf = np.zeros((state.shape[0], state.shape[1], 1, env_parameters.shape[0]))\n diff = np.abs(state - next_state) # take the abs for the sqrt, but mask negative values later\n\n for i in range(env_parameters.shape[0]):\n deceleration = 5 / 7 * env_parameters[i, 1] * 9.81\n u = np.sqrt(2 * deceleration * diff[:, :, :, i])\n noise = (u / (action[:, :, np.newaxis, i] * env_parameters[i, 0]) - 1) / env_parameters[i, -1]\n pdf[:, :, :, i] = norm.pdf(noise) * (1 - mask[:, :, :, i]) # set to zero impossible transitions\n\n return pdf[:, :, 0, :]\n\n def densityCurrent_old(self, state, action, next_state):\n \"\"\"\n :param state: NxTx1\n :param action: NxT\n :param next_state: NxTx1\n :return: pdf NxTx1xn_param\n \"\"\"\n\n assert state.ndim == 3 and action.ndim == 2 and next_state.ndim == 3\n\n mask = state < next_state\n action = np.clip(action, self.min_action, self.max_action / 2)\n action[action == 0] = 1e-8\n diff = np.abs(state - next_state) # take the abs for the sqrt, but mask negative values later\n\n deceleration = 5 / 7 * self.friction * 9.81\n u = np.sqrt(2 * deceleration * diff)\n noise = (u / (action[:, :, np.newaxis] * self.putter_length) - 1) / self.sigma_noise\n pdf = norm.pdf(noise) * (1 - mask) # set to zero impossible transitions\n\n return pdf[:, :, 0]\n\n def stepDenoisedCurrent_old(self, state, action):\n \"\"\"\n Computes steps without noise.\n \"\"\"\n\n assert state.ndim == 3 and action.ndim == 2\n\n action = np.clip(action, self.min_action, self.max_action / 2)[:, :, np.newaxis]\n u = action * self.putter_length\n deceleration = 5 / 7 * self.friction * 9.81\n t = u / deceleration\n return state - u * t + 0.5 * deceleration * t ** 2\n\n def stepDenoisedCurrent(self, state, action):\n \"\"\"\n Computes the mean transitions.\n \"\"\"\n\n assert state.ndim == 3 and action.ndim == 2\n\n action = np.clip(action, self.min_action, self.max_action / 2)[:, :, np.newaxis]\n u = action * self.putter_length\n deceleration = 5 / 7 * self.friction * 9.81\n return state - 0.5 * u ** 2 * (1 + self.sigma_noise ** 2) / deceleration\n\n def variance(self, action):\n \"\"\"\n Next-state variance given the action\n \"\"\"\n\n assert action.ndim == 2\n\n deceleration = 5 / 7 * self.friction * 9.81\n action = np.clip(action, self.min_action, self.max_action / 2)\n k = action ** 2 * self.putter_length ** 2 / (2 * deceleration)\n return 2 * k ** 2 * self.sigma_noise ** 2 * (self.sigma_noise ** 2 + 2) + self.min_variance\n\n def densityCurrent(self, state, action, next_state):\n \"\"\"\n :param state: NxTx1\n :param action: NxT\n :param next_state: NxTx1\n :return: pdf NxTx1xn_param\n \"\"\"\n\n assert state.ndim == 3 and action.ndim == 2 and next_state.ndim == 3\n\n mean_ns = self.stepDenoisedCurrent(state, action)\n var_ns = self.variance(action)\n return norm.pdf((next_state - mean_ns)[:, :, 0] / np.sqrt(var_ns))\n\n def density(self, env_parameters, state, action, next_state):\n \"\"\"\n :param env_parameters: list of env_params\n :param state: NxTx1\n :param action: NxT\n :param next_state: NxTx1\n :return: pdf NxTx1xn_param\n \"\"\"\n assert state.ndim == 4 and action.ndim == 3 and next_state.ndim == 4\n\n action = np.clip(action, self.min_action, self.max_action / 2)\n pdf = np.zeros((state.shape[0], state.shape[1], 1, env_parameters.shape[0]))\n\n for i in range(env_parameters.shape[0]):\n deceleration = 5 / 7 * env_parameters[i, 1] * 9.81\n k = action ** 2 * env_parameters[i, 0] ** 2 / (2 * deceleration)\n\n # Compute mean next-state\n mean_ns = state[:, :, :, i] - k[:, :, np.newaxis, i] * (1 + env_parameters[i, -1])\n # Compute variance next-state\n var_ns = 2 * k[:, :, np.newaxis, i] ** 2 * env_parameters[i, -1] * (\n env_parameters[i, -1] + 2) + self.min_variance\n\n pdf[:, :, :, i] = norm.pdf((next_state[:, :, :, i] - mean_ns) / np.sqrt(var_ns))\n\n return pdf[:, :, 0, :]\n\n\nclass ComplexMiniGolf(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 30\n }\n\n def __init__(self):\n self.horizon = 20\n self.gamma = 0.99\n\n self.min_pos = 0.0\n self.max_pos = 20.0\n self.min_action = 1e-5\n self.max_action = 10.0\n self.putter_length = 1.0 # [0.7:1.0]\n # self.friction = 0.131 # [0.065:0.196]\n self.friction_low = 0.131\n self.friction_high = 0.19 # 0.190\n self.hole_size = 0.10 # [0.10:0.15]\n self.sigma_noise = 0.3\n self.ball_radius = 0.02135\n self.min_variance = 1e-2 # Minimum variance for computing the densities\n\n # gym attributes\n self.viewer = None\n low = np.array([self.min_pos])\n high = np.array([self.max_pos])\n self.action_space = spaces.Box(low=self.min_action,\n high=self.max_action,\n shape=(1,))\n self.observation_space = spaces.Box(low=low, high=high)\n\n # initialize state\n self.seed()\n self.reset()\n\n def setParams(self, env_param):\n self.putter_length = env_param[0]\n self.friction = env_param[1]\n self.hole_size = env_param[2]\n self.sigma_noise = m.sqrt(env_param[-1])\n\n def computeFriction(self, state):\n # if state < (self.max_pos - self.min_pos) / 3:\n # friction = self.friction_low\n # elif state < (self.max_pos - self.min_pos) * 2 / 3:\n # friction = self.friction_low\n # else:\n # friction = self.friction_high\n # return friction\n delta_f = self.friction_high - self.friction_low\n delta_p = self.max_pos - self.min_pos\n return self.friction_low + (delta_f / delta_p) * state\n\n def step(self, action, render=False):\n action = np.clip(action, self.min_action, self.max_action / 2)\n\n noise = 10\n while abs(noise) > 1:\n noise = self.np_random.randn() * self.sigma_noise\n u = action * self.putter_length * (1 + noise)\n\n friction = self.computeFriction(self.state)\n\n deceleration = 5 / 7 * friction * 9.81\n\n t = u / deceleration\n xn = self.state - u * t + 0.5 * deceleration * t ** 2\n\n # reward = 0\n # done = True\n # if u < v_min:\n # reward = -1\n # done = False\n # elif u > v_max:\n # reward = -100\n\n reward = 0\n done = True\n if self.state > 0:\n reward = -1\n done = False\n elif self.state < -4:\n reward = -100\n\n state = self.state\n self.state = xn\n\n # TODO the last three values should not be used\n return self.get_state(), float(reward), done, {\"state\": state, \"next_state\": self.state, \"action\": action}\n\n # Custom param for transfer\n\n def getEnvParam(self):\n return np.asarray([np.ravel(self.putter_length), np.ravel(self.friction), np.ravel(self.hole_size),\n np.ravel(self.sigma_noise ** 2)])\n\n def reset(self, state=None):\n # TODO change reset\n if state is None:\n self.state = np.array([self.np_random.uniform(low=self.min_pos,\n high=self.max_pos)])\n else:\n self.state = np.array(state)\n\n return self.get_state()\n\n def get_state(self):\n return np.array(self.state)\n\n def get_true_state(self):\n \"\"\"For testing purposes\"\"\"\n return np.array(self.state)\n\n def clip_state(self, state):\n return state\n # return np.clip(state, self.min_pos, self.max_pos)\n\n def clip_action(self, action):\n return action\n # return np.clip(action, self.min_action, self.max_action)\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def reward(self, state, action, next_state):\n # FIXME: two problems. (1,probably fixed) When the next_state is less than state. (2) reward of -100 is never returned\n friction = self.computeFriction(state)\n deceleration = 5 / 7 * friction * 9.81\n\n u = np.sqrt(2 * deceleration * max((state - next_state), 0))\n\n v_min = np.sqrt(10 / 7 * friction * 9.81 * state)\n v_max = np.sqrt((2 * self.hole_size - self.ball_radius) ** 2 * (9.81 / (2 * self.ball_radius)) + v_min ** 2)\n\n reward = 0\n done = True\n if u < v_min:\n reward = -1\n done = False\n elif u > v_max:\n reward = -100\n\n return reward, done"
] | [
[
"numpy.sqrt",
"numpy.zeros",
"scipy.stats.norm.pdf",
"numpy.abs",
"numpy.ravel",
"numpy.clip",
"numpy.array"
]
] |
jenildesai25/WebScrapping | [
"41937094a7963d53ab09e3ceff055dca4a95f13f"
] | [
"WebScraping2.py"
] | [
"\n# Online References used :\n# https://github.com/imadmali/movie-scraper/blob/master/MojoLinkExtract.py\n# https://www.crummy.com/software/BeautifulSoup/bs4/doc/\n# https://nycdatascience.com/blog/student-works/scraping-box-office-mojo/\n# https://www.youtube.com/watch?v=XQgXKtPSzUI\n# https://www.youtube.com/watch?v=aIPqt-OdmS0\n# https://www.youtube.com/watch?v=XQgXKtPSzUI\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os\nimport requests\nimport glob\nimport re\n\n\n\ndef scrape_data_for_actors():\n file_path = os.path.join(os.path.join(os.environ['USERPROFILE']),\n 'Desktop') # This is written in order to save the txt file in the user's specified location on the machine\n file_path = os.path.join(file_path,\n 'BoxOfficeMojo2_virti_bipin') # Folder name to be created where the file will be stored\n if not os.path.exists(str(file_path)):\n os.mkdir(str(file_path)) # If path does not exist create the path\n os.chdir(file_path) # Change the directory of the file path\n\n if len(glob.glob(\n \"*\")) != 0: # The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell\n file_list = glob.glob(\"*\")\n for file in file_list:\n os.remove(file)\n\n # The url of the BoxOffice Mojo to be scraped\n url = 'https://www.boxofficemojo.com/people/?view=Actor&pagenum=1&sort=sumgross&order=DESC&&p=.htm'\n pages_data = [] # List to store the pages data\n total_pages = []\n response = requests.get(url) # Get the response of the url after passing the user input\n soup = BeautifulSoup(response.content,\n 'html.parser') # Using the beautiful soup library to parse the html content and format it\n for page in soup.find_all('a', href=lambda href: href and \"page\" in href): # find the href in a tags\n pages_data.append(page['href']) # append the data in the pages_data list\n for page in pages_data:\n if 'page' in page: # If \"page\" found in href\n index = page.find('page') # Take the index of that page if found\n\n # print(\"Index\", index)\n if page[index:index + 10] not in total_pages:\n # For extracting the total number of pages\n total_pages.append(page[\n index:index + 10]) # for example : page=2 so in order to get the total number of pages and iterate through it it goes from 1 till end of pages for pagination\n # print(\"Total Pages\", total_pages)\n average_gross_list = []\n for num in range(1, len(total_pages) + 1, 1):\n try:\n url = 'https://www.boxofficemojo.com/people/?view=Actor&pagenum={}&sort=sumgross&order=DESC&&p=.htm'.format(num) # This one works well\n # Get the Response\n print(\"Page number {}\".format(num))\n response_from_url = requests.get(url)\n html = response_from_url.text\n soup = BeautifulSoup(html,\n 'lxml') # lxml is a pretty extensive library written for parsing XML and HTML documents very quickly\n table = soup.find('table', {\"cellspacing\": \"1\"})\n # Using dataframes\n df = pd.read_html(str(table),skiprows=1)\n df = df[0]\n\n df = df.iloc[:, :6] # This is used to slice the dataframe to cut off the date sections.\n df.columns = ['rank', 'person', 'total gross', 'number of movies', 'Average', 'number 1 picture']\n df['id'] = ''\n\n id_list = []\n title_list = df['rank'].tolist()\n new_index = [i for i in range(1,len(title_list)+1)]\n df.index = new_index\n for link in soup.findAll('a', {'href': re.compile(\"\\?id=\")}):\n id_list.append(link.get('href'))\n\n id_list = [x.split('=')[1] for x in id_list]\n id_list = [x.split('.')[0] for x in id_list]\n id_list = id_list[1:]\n id_dict = dict(zip(title_list, id_list))\n\n for index in df.index:\n df.loc[index, 'id'] = id_dict[df.loc[index, 'rank']]\n\n df.to_csv(\"actors.csv\", index=False, mode='a')\n\n except Exception as e:\n print(e)\n continue\n\n\n file_list = glob.glob(\"*.csv\")\n df_container = []\n\n for file in file_list:\n df = pd.read_csv(file)\n df_container.append(df)\n\n df_combined = pd.concat(df_container)\n df_combined.to_csv(\"actors.txt\", index=False, sep=\"\\t\")\n\n df = pd.read_csv(\"actors.txt\", sep=\"\\t\")\n\n # Data Cleaning\n df['Average'] = df['Average'].apply(lambda x: x.replace('$', '')) # replace dollar signs\n df['Average'] = df['Average'].apply(lambda x: x.replace(',', '')) # replace commas\n\n df['Average'] = pd.to_numeric(df['Average'], errors='coerce')\n\n df = df.sort_values(by='Average', ascending=False)\n\n actor_with_highest_average_earning = df.iloc[0]['person']\n\n print(\"actor(s) with the highest average earnings per movie is {}\".format(actor_with_highest_average_earning))\n new_df = pd.read_csv(\"actors.txt\", sep=\"\\t\")\n\n new_df['number of movies'] = pd.to_numeric(new_df['number of movies'], errors='coerce')\n\n actor_most_movies = new_df.loc[new_df['number of movies'].idxmax()].person\n print(\"actor(s) with the maximum number of movies is {}\".format(actor_most_movies))\n\nif __name__ == '__main__':\n scrape_data_for_actors()\n"
] | [
[
"pandas.read_csv",
"pandas.concat",
"pandas.to_numeric"
]
] |
IKupriyanov-HORIS/lets-plot-docs | [
"30fd31cb03dc649a03518b0c9348639ebfe09d53"
] | [
"docs/_downloads/e0051c6e37b730111a06abd85529e288/plot__2d_distributions.py"
] | [
"\"\"\"\r\n2D Distributions\r\r\n================\r\r\n\r\r\nSome plots visualize a transformation of the original data set. Use a\r\r\nstat parameter to choose a common transformation to visualize.\r\r\n\r\r\nEach stat creates additional variables to map aesthetics to. These\r\r\nvariables use a common ..name.. syntax.\r\r\n\r\r\nLook at the examples of 2D distributions below.\r\r\n\r\n\"\"\"\r\n\r\n# sphinx_gallery_thumbnail_path = \"gallery_py\\_stats\\_2d_distributions.png\"\r\n\r\nimport pandas as pd\r\n\r\nfrom lets_plot import *\r\nLetsPlot.setup_html()\r\n\r\n# %%\r\n\r\ndf = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv')\r\n\r\n# %%\r\n\r\nw, h = 400, 300\r\np = ggplot(df, aes('cty', 'hwy')) + ggsize(w, h)\r\np11 = p + geom_bin2d() + ggtitle('geom=\"bin2d\" + default stat')\r\np12 = p + geom_point(aes(color='..count..'), stat='bin2d', size=3, shape=15) + \\\r\n ggtitle('geom=\"point\" + stat=\"bin2d\"')\r\np21 = p + geom_density2d() + ggtitle('geom=\"density2d\" + default stat')\r\np22 = p + geom_point(stat='density2d', size=.5) + ggtitle('geom=\"point\" + stat=\"density2d\"')\r\n\r\nbunch = GGBunch()\r\nbunch.add_plot(p11, 0, 0)\r\nbunch.add_plot(p12, w, 0)\r\nbunch.add_plot(p21, 0, h)\r\nbunch.add_plot(p22, w, h)\r\nbunch"
] | [
[
"pandas.read_csv"
]
] |