code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
#!/usr/bin/python3 # -*- coding: utf-8 -*- ##===-----------------------------------------------------------------------------*- Python -*-===## ## ## S E R I A L B O X ## ## This file is distributed under terms of BSD license. ## See LICENSE.txt for more information. ## ##===------------------------------------------------------------------------------------------===## ## ## This example demonstrates the asynchronous API of Serialbox which can improve the throughput of ## read operations. ## ##===------------------------------------------------------------------------------------------===## # # First, we have to make sure Python finds the Serialbox module. Alternatively, you can also set the # environment variable PYTHONPATH. # import os import sys import time sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../python') sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../src/serialbox-python') # # Import Serialbox # import serialbox as ser import numpy as np def main(): N = 512; M = 512; K = 80 savepoint = ser.Savepoint('sp') # # First, we write some data to disk ... # serializer_write = ser.Serializer(ser.OpenModeKind.Write, "./async", "Field", "Binary") field_1 = np.random.rand(N, M, K) field_2 = np.random.rand(N, M, K) field_3 = np.random.rand(N, M, K) field_4 = np.random.rand(N, M, K) field_5 = np.random.rand(N, M, K) field_6 = np.random.rand(N, M, K) serializer_write.write('field_1', savepoint, field_1) serializer_write.write('field_2', savepoint, field_2) serializer_write.write('field_3', savepoint, field_3) serializer_write.write('field_4', savepoint, field_4) serializer_write.write('field_5', savepoint, field_5) serializer_write.write('field_6', savepoint, field_6) # # ... and read it again. # serializer_read = ser.Serializer(ser.OpenModeKind.Read, "./async", "Field", "Binary") start = time.time() field_1_rd = serializer_read.read('field_1', savepoint) field_2_rd = serializer_read.read('field_2', savepoint) field_3_rd = serializer_read.read('field_3', savepoint) field_4_rd = serializer_read.read('field_4', savepoint) field_5_rd = serializer_read.read('field_5', savepoint) field_6_rd = serializer_read.read('field_6', savepoint) print("Serializer.read : %8.2f s" % (time.time() - start)) # # Read operations are usually embarrassingly parallel and we can leverage this parallelism by # launching the operations asynchronously. If the archive is not thread-safe or if the library # was not configured with `SERIALBOX_ASYNC_API` the method falls back to synchronous execution. # To synchronize the tasks in the end, we can add a blocking Serializer.wait_for_all(). # start = time.time() field_1_rd_async = serializer_read.read_async('field_1', savepoint) field_2_rd_async = serializer_read.read_async('field_2', savepoint) field_3_rd_async = serializer_read.read_async('field_3', savepoint) field_4_rd_async = serializer_read.read_async('field_4', savepoint) field_5_rd_async = serializer_read.read_async('field_5', savepoint) field_6_rd_async = serializer_read.read_async('field_6', savepoint) serializer_read.wait_for_all() print("Serializer.read_async : %8.2f s" % (time.time() - start)) # # Finally, we verify the read operations actually do the same. # assert(np.allclose(field_1_rd, field_1_rd_async)) assert(np.allclose(field_2_rd, field_2_rd_async)) assert(np.allclose(field_3_rd, field_3_rd_async)) assert(np.allclose(field_4_rd, field_4_rd_async)) assert(np.allclose(field_5_rd, field_5_rd_async)) assert(np.allclose(field_6_rd, field_6_rd_async)) # # Remove directory # import shutil shutil.rmtree("./async") if __name__ == '__main__': main()
[ "numpy.allclose", "numpy.random.rand", "shutil.rmtree", "os.path.realpath", "time.time", "serialbox.Savepoint", "serialbox.Serializer" ]
[((1139, 1158), 'serialbox.Savepoint', 'ser.Savepoint', (['"""sp"""'], {}), "('sp')\n", (1152, 1158), True, 'import serialbox as ser\n'), ((1244, 1312), 'serialbox.Serializer', 'ser.Serializer', (['ser.OpenModeKind.Write', '"""./async"""', '"""Field"""', '"""Binary"""'], {}), "(ser.OpenModeKind.Write, './async', 'Field', 'Binary')\n", (1258, 1312), True, 'import serialbox as ser\n'), ((1330, 1353), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1344, 1353), True, 'import numpy as np\n'), ((1369, 1392), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1383, 1392), True, 'import numpy as np\n'), ((1408, 1431), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1422, 1431), True, 'import numpy as np\n'), ((1447, 1470), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1461, 1470), True, 'import numpy as np\n'), ((1486, 1509), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1500, 1509), True, 'import numpy as np\n'), ((1525, 1548), 'numpy.random.rand', 'np.random.rand', (['N', 'M', 'K'], {}), '(N, M, K)\n', (1539, 1548), True, 'import numpy as np\n'), ((1974, 2041), 'serialbox.Serializer', 'ser.Serializer', (['ser.OpenModeKind.Read', '"""./async"""', '"""Field"""', '"""Binary"""'], {}), "(ser.OpenModeKind.Read, './async', 'Field', 'Binary')\n", (1988, 2041), True, 'import serialbox as ser\n'), ((2057, 2068), 'time.time', 'time.time', ([], {}), '()\n', (2066, 2068), False, 'import time\n'), ((2931, 2942), 'time.time', 'time.time', ([], {}), '()\n', (2940, 2942), False, 'import time\n'), ((3587, 3628), 'numpy.allclose', 'np.allclose', (['field_1_rd', 'field_1_rd_async'], {}), '(field_1_rd, field_1_rd_async)\n', (3598, 3628), True, 'import numpy as np\n'), ((3642, 3683), 'numpy.allclose', 'np.allclose', (['field_2_rd', 'field_2_rd_async'], {}), '(field_2_rd, field_2_rd_async)\n', (3653, 3683), True, 'import numpy as np\n'), ((3697, 3738), 'numpy.allclose', 'np.allclose', (['field_3_rd', 'field_3_rd_async'], {}), '(field_3_rd, field_3_rd_async)\n', (3708, 3738), True, 'import numpy as np\n'), ((3752, 3793), 'numpy.allclose', 'np.allclose', (['field_4_rd', 'field_4_rd_async'], {}), '(field_4_rd, field_4_rd_async)\n', (3763, 3793), True, 'import numpy as np\n'), ((3807, 3848), 'numpy.allclose', 'np.allclose', (['field_5_rd', 'field_5_rd_async'], {}), '(field_5_rd, field_5_rd_async)\n', (3818, 3848), True, 'import numpy as np\n'), ((3862, 3903), 'numpy.allclose', 'np.allclose', (['field_6_rd', 'field_6_rd_async'], {}), '(field_6_rd, field_6_rd_async)\n', (3873, 3903), True, 'import numpy as np\n'), ((3969, 3993), 'shutil.rmtree', 'shutil.rmtree', (['"""./async"""'], {}), "('./async')\n", (3982, 3993), False, 'import shutil\n'), ((864, 890), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (880, 890), False, 'import os\n'), ((941, 967), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (957, 967), False, 'import os\n'), ((2487, 2498), 'time.time', 'time.time', ([], {}), '()\n', (2496, 2498), False, 'import time\n'), ((3469, 3480), 'time.time', 'time.time', ([], {}), '()\n', (3478, 3480), False, 'import time\n')]
''' File: discretizer.py Description: function definition History: Date Programmer SAR# - Description ---------- ---------- ---------------------------- Author: <NAME> 29Apr2016 - Created ''' import numpy as np from . import pinm as pinm from stl import mesh from mpl_toolkits import mplot3d from matplotlib import pyplot from matplotlib import colors as Colors from matplotlib.widgets import Button import matplotlib.cm as cmx def stlImport(filePath,coords): # Create a new plot figure = pyplot.figure() pyplot.subplots_adjust(bottom=0.2) axes = mplot3d.Axes3D(figure) # Load the STL files and add the vectors to the plot modelMesh = mesh.Mesh.from_file(filePath) indexedTri=[] for n in range(len(modelMesh.vectors)): indexedTri.append(mplot3d.art3d.Poly3DCollection([modelMesh.vectors[n]],facecolors='b')) axes.add_collection3d(indexedTri[n]) indexedTri[0].set_facecolor('k') scale = modelMesh.points.flatten(-1) axes.auto_scale_xyz(scale, scale, scale) callback = DomainSelector(indexedTri) axprev = pyplot.axes([0.7, 0.05, 0.1, 0.075]) axnext = pyplot.axes([0.81, 0.05, 0.1, 0.075]) axselect = pyplot.axes([0.05, 0.05, 0.15, 0.075]) axaddToDomain = pyplot.axes([0.05, 0.85, 0.15, 0.075]) axswapSelected = pyplot.axes([0.8, 0.85, 0.15, 0.075]) bnext = Button(axnext, 'Next') bnext.on_clicked(callback.next) bprev = Button(axprev, 'Previous') bprev.on_clicked(callback.prev) bselect = Button(axselect, '(un)Select') bselect.on_clicked(callback.select) baddToDomain = Button(axaddToDomain, 'Add Domain') baddToDomain.on_clicked(callback.addToDomain) bswapSelected = Button(axswapSelected, 'Swap Selected') bswapSelected.on_clicked(callback.swapSelected) # Show the plot to the screen #pyplot.connect('key_press_event', callback.keyPressed) pyplot.show() maindomain=pinm.Domain('') subdomain=[] for domainNumber in range(callback.domainCount): subdomain.append(pinm.Domain('')) maindomain.addNode(subdomain[domainNumber]) normalVector=[] vertices=[] minvert={} maxvert={} for n in range(len(modelMesh.normals)): normalVector.append({}) vertices.append([]) for keyIndex in range(len(coords)): normalVector[n][coords[keyIndex]]=modelMesh.normals[n][keyIndex] for m in range(3): temp_vert={} for keyIndex in range(len(coords)): if coords[keyIndex] not in minvert: minvert[coords[keyIndex]]=modelMesh.vectors[n][m][keyIndex] else: minvert[coords[keyIndex]]=min(minvert[coords[keyIndex]],modelMesh.vectors[n][m][keyIndex]) if coords[keyIndex] not in maxvert: maxvert[coords[keyIndex]]=modelMesh.vectors[n][m][keyIndex] else: maxvert[coords[keyIndex]]=max(maxvert[coords[keyIndex]],modelMesh.vectors[n][m][keyIndex]) temp_vert[coords[keyIndex]]=modelMesh.vectors[n][m][keyIndex] vertices[n].append(temp_vert) domainVertices=[] for n in range(8): temp_domainVertices={} for key in range(len(coords)): if (key==0 and (n in [1,2,5,6])) or (key==1 and (n in [2,3,6,7])) or (key==2 and (n in [4,5,6,7])): temp_domainVertices[coords[key]]=maxvert[coords[key]] else: temp_domainVertices[coords[key]]=minvert[coords[key]] domainVertices.append(temp_domainVertices) for n in range(len(callback.domainInfo)): temp_sub2domain=pinm.Domain('',norm=normalVector[n]) temp_sub2domain.setCentroid(vertices[n]) subdomain[callback.domainInfo[n]].addNode(temp_sub2domain) maindomain.setCentroid(domainVertices) return (maindomain,subdomain) def createMainDomain(minvert,maxvert,coords): maindomain=pinm.Domain('') domainVertices=[] for n in range(8): temp_domainVertices={} for key in range(len(coords)): if (key==0 and (n in [1,2,5,6])) or (key==1 and (n in [2,3,6,7])) or (key==2 and (n in [4,5,6,7])): temp_domainVertices[coords[key]]=maxvert[coords[key]] else: temp_domainVertices[coords[key]]=minvert[coords[key]] domainVertices.append(temp_domainVertices) maindomain.setCentroid(domainVertices) return maindomain def filterNodes(domainList,nodalDistribution,closeness=0.2): #first in list is prioritized to keep nodes=[] for domain in domainList: for node in domain.nodes(): nodes.append(node) for n in range(len(nodes)): if nodes[n].domain!=None: nodalSpacing=nodalDistribution(nodes[n].pos) closeNodalSpacing=multiplyDictionary(nodalSpacing,closeness) linkedNodes=findNodes(nodes[n].pos,domainList,distance=closeNodalSpacing,searchDepth=-1.) for temp_linkNode in linkedNodes: if temp_linkNode is not nodes[n]: temp_domain=temp_linkNode.domain temp_domain.removeNode(temp_linkNode) temp_linkNode.domain=None while len(temp_domain.subDomain)==0: if temp_domain.superDomain==None: break else: temp2_domain=temp_domain.superDomain temp2_domain.removeNode(temp_domain) temp_domain=temp2_domain return; def secondaryLinkNode(targetNode,primarylinkIdentifier,secondarylinkIdentifier='secondary'): nodes=[] targetNode.addLink(secondarylinkIdentifier,targetNode) for node in targetNode.link[primarylinkIdentifier]: for temp_node in node.link[primarylinkIdentifier]: targetNode.addLink(secondarylinkIdentifier,node) return; def primaryLinkNodes(domainList,nodalDistribution,linkIdentifier='primary',closeness=1.5):#influence is function with dictionary input and output nodes=[] for domain in domainList: for node in domain.nodes(): nodes.append(node) for n in range(len(nodes)): nodalSpacing=nodalDistribution(nodes[n].pos) expandedNodalSpacing=multiplyDictionary(nodalSpacing,closeness) linkedNodes=findNodes(nodes[n].pos,domainList,distance=expandedNodalSpacing,searchDepth=-1.) addNodesToLink=[] for temp_linkNode in linkedNodes: if temp_linkNode is not nodes[n]: addNodesToLink.append(temp_linkNode) addNodesToLink.insert(0,nodes[n]) nodes[n].addLink(linkIdentifier,addNodesToLink) return; def duplicateNode(coordinateIdentifier,value,nodePorting,newNodes,domainList,targetDomain): nodeInDomain=[] for domain in domainList: if type(domain) is pinm.Node: new_pos=node.pos.copy() new_pos[coordinateIdentifier]=value newNode=pinm.Node(new_pos) tempCopy=domain.variable.copy() for key in tempCopy: newNode.addvariable(key,tempCopy[key]) newNode.addLink('copied from',domain) tempCopy=node.linkBasis.copy() for key in tempCopy: newNode.setLinkBasis(key,tempCopy[key]) newNode.setNorm(node.norm.copy()) newNode.setNormLink(node.normLink) for n in range(len(node.material)): newNode.addMaterial(n,node.material[n]) tempCopy=node.variableLink.copy() for key in tempCopy: newNode.setVariableLink(key,tempCopy[key]) nodePorting[domain]=newNode newNodes.append(newNode) nodeInDomain.append(newNode) else: newDomain=pinm.Domain('') newDomain.pos=domain.pos.copy() newDomain.maxDistance=domain.maxDistance.copy() newDomain.pos[coordinateIdentifier]=value newDomain.maxDistance[coordinateIdentifier]=0. nodeInDomain.append(newDomain) duplicateNode(coordinateIdentifier,value,nodePorting,newNodes,domain.subDomain,newDomain) targetDomain.addNode(nodeInDomain) return nodeInDomain def extrudeDimension(domainList,coordinateIdentifier,valueList,prevLinkIdentifier='',nextLinkIdentifier=''): newDomain=[] prevNodes=[] for m in range(len(valueList)): newNodes=[] nodePorting={} newDomain.append([]) for domain in domainList: tempDomain=pinm.Domain('') tempDomain.pos=domain.pos.copy() tempDomain.maxDistance=domain.maxDistance.copy() tempDomain.pos[coordinateIdentifier]=value tempDomain.maxDistance[coordinateIdentifier]=0. newDomain[-1].append(tempDomain) duplicateNode(coordinateIdentifier,value,nodePorting,newNodes,domain.subDomain,tempDomain) for new_node in newNodes: for temp_linkIdentifier in new_node.link['copied from'][0].link: if temp_linkIdentifier!='copied from': tempList=[] for linkNode in new_node.link['copied from'][0].link[temp_linkIdentifier]: tempList.append(nodePorting[linkNode]) new_node.addLink(temp_linkIdentifier,tempList) if (prevLinkIdentifier!='' or nextLinkIdentifier!='') and len(prevNodes)!=0: for n in range(len(newNodes)): if prevLinkIdentifier!='': prevNodes[n].addLink(linkIdentifier,newNodes[n]) if nextLinkIdentifier!='': newNodes[n].addLink(linkIdentifier,prevNodes[n]) prevNodes=newNodes[:] return newDomain def arrangeExtrudeDimension(domainList,coordinateIdentifier,valueList,prevLinkIdentifier='',nextLinkIdentifier='',newDomainNameAddOn=' new',firstDomainNameAddOn='',lastDomainNameAddOn=''): nameList=[] for domain in domainList: nameList.append(domain.name) subDomain=extrudeDimension(domainList,coordinateIdentifier,valueList,prevLinkIdentifier=prevLinkIdentifier,nextLinkIdentifier=nextLinkIdentifier) newDomain=[] startDomain=[] endDomain=[] for n in range(len(subDomain[0])): startCount=0 endCountReduce=0 if firstDomainNameAddOn!='': if firstDomainNameAddOn!=lastDomainNameAddOn: subDomain[0][n].setDomainName(nameList[n]+firstDomainNameAddOn) startDomain.append(subDomain[0][n]) startCount=1 if lastDomainNameAddOn!='': if firstDomainNameAddOn!=lastDomainNameAddOn: subDomain[-1][n].setDomainName(nameList[n]+lastDomainNameAddOn) else: domainGroup=pinm.Domain(nameList[n]+firstDomainNameAddOn) domainGroup.addNode([subDomain[0][n],subDomain[-1][n]]) endDomain.append(subDomain[-1][n]) endCountReduce=1 leftOverDomain=[] for m in range(startCount,len(subDomain)-endCountReduce): leftOverDomain.append(subDomain[m][n]) if len(leftOverDomain)!=0: tempDomain=pinm.Domain(nameList[n]+newDomainNameAddOn) tempDomain.addNode(leftOverDomain) newDomain.append(tempDomain) return (newDomain,startDomain,endDomain) def meshSurfaceDomainTriangle(subDomain,nodalDistribution): for domain in subDomain: for sub2domain in domain.subDomain: toBeFurtherMeshed=meshTriangleSpliting(sub2domain,nodalDistribution) while len(toBeFurtherMeshed)>0: copy_toBeFurtherMeshed=toBeFurtherMeshed toBeFurtherMeshed=[] for new_domain in copy_toBeFurtherMeshed: for temp_domain in meshTriangleSpliting(new_domain,nodalDistribution): toBeFurtherMeshed.append(temp_domain) return; def meshMainDomain(mainDomain,boundaryDomainList,nodalDistribution,meshOuterNode=False): innerNodesDomain=pinm.Domain('') innerNodesDomain.setCentroid(mainDomain.vertices) mainDomain.addNode(innerNodesDomain) toBeFurtherMeshed=meshVolume(innerNodesDomain,boundaryDomainList,nodalDistribution,meshOuter=meshOuterNode) while len(toBeFurtherMeshed)>0: copy_toBeFurtherMeshed=toBeFurtherMeshed toBeFurtherMeshed=[] for new_domain in copy_toBeFurtherMeshed: for temp_domain in meshVolume(new_domain,boundaryDomainList,nodalDistribution,meshOuter=meshOuterNode): toBeFurtherMeshed.append(temp_domain) return innerNodesDomain def meshTriangleSpliting(domain,nodalDistribution): #nodalDistribution is a function with both i/o dictionary objects toBeFurtherMeshed=[] subDomain=[] #check for odd triangle sidelength=[0.,0.,0.] maxSideLength=0. minSideLength=float('inf') maxSideIndex=-1 minSideIndex=-1 for n in range(len(domain.vertices)): for coord in domain.vertices[0]: sidelength[n]+=(domain.vertices[n][coord]-domain.vertices[n-1][coord])**2. sidelength[n]=np.sqrt(sidelength[n]) if sidelength[n]>maxSideLength: maxSideLength=sidelength[n] maxSideIndex=n if sidelength[n]<minSideLength: minSideLength=sidelength[n] minSideIndex=n NodeSpacing=nodalDistribution(domain.pos) newPoint=multiplyDictionary(addDictionary([domain.vertices[maxSideIndex],domain.vertices[maxSideIndex-1]]),0.5) tri1Domain=pinm.Domain('',norm=domain.normalVector) tri1Domain.setCentroid([newPoint,domain.vertices[maxSideIndex],domain.vertices[maxSideIndex-2]]) tri2Domain=pinm.Domain('',norm=domain.normalVector) tri2Domain.setCentroid([newPoint,domain.vertices[maxSideIndex-2],domain.vertices[maxSideIndex-1]]) temp_total=0. for coord in NodeSpacing: temp_total+=NodeSpacing[coord]**2. nodeDis=np.sqrt(temp_total) if nodeDis<(sum(sidelength)/3.): subDomain.append(tri1Domain) subDomain.append(tri2Domain) toBeFurtherMeshed.append(tri1Domain) toBeFurtherMeshed.append(tri2Domain) else: subDomain.append(pinm.Node(tri1Domain.pos,norm=domain.normalVector)) subDomain.append(pinm.Node(tri2Domain.pos,norm=domain.normalVector)) domain.addNode(subDomain) return toBeFurtherMeshed def meshVolume(domain,boundaryDomainList,nodalDistribution,meshOuter=False): #nodalDistribution is a function with both i/o dictionary objects if meshOuter: meshOuterCoef=-1. else: meshOuterCoef=1. NodeSpacing=nodalDistribution(domain.pos) addNodeInstead=1 for coord in domain.maxDistance: if domain.maxDistance[coord]>NodeSpacing[coord]: addNodeInstead=0 centerPlane=[] centerPlaneMidPoints=[] for n in range(4): centerPlane.append(multiplyDictionary(addDictionary([domain.vertices[n],domain.vertices[4+n]]),0.5)) for n in range(3): centerPlaneMidPoints.append(multiplyDictionary(addDictionary([centerPlane[n],centerPlane[n+1]]),0.5)) centerPlaneMidPoints.append(multiplyDictionary(addDictionary([centerPlane[3],centerPlane[0]]),0.5)) planeCentroid=[] midPoints=[] for m in range(2): midPoints.append([]) for n in range(3): midPoints[m].append(multiplyDictionary(addDictionary([domain.vertices[m*4+n],domain.vertices[m*4+n+1]]),0.5)) midPoints[m].append(multiplyDictionary(addDictionary([domain.vertices[m*4+3],domain.vertices[m*4]]),0.5)) for m in range(2): planeCentroid.append(multiplyDictionary(addDictionary([midPoints[m][0],midPoints[m][2]]),0.5)) subDomain=[] toBeFurtherMeshed=[] for m in range(2): for n in range(4): temp_subdomain=pinm.Domain('') temp_vertices=[midPoints[m][n-1],domain.vertices[4*m+n],midPoints[m][n],planeCentroid[m], centerPlaneMidPoints[n-1],centerPlane[n],centerPlaneMidPoints[n],domain.pos] temp_subdomain.setCentroid(temp_vertices) temp_boundaryNode=findNodes(temp_subdomain.pos,boundaryDomainList) distancebetween={} for coord in temp_boundaryNode.pos: distancebetween[coord]=np.absolute(temp_boundaryNode.pos[coord]-temp_subdomain.pos[coord]) boundaryNodes=findNodes(temp_subdomain.pos,boundaryDomainList,distance=distancebetween) innerNode=True for boundaryNode in boundaryNodes: boundaryNodeCentroid=boundaryNode.pos boundaryNodeNorm=boundaryNode.norm dotProduct=0. normamplitude=0. for coords in temp_subdomain.pos: dotProduct+= (temp_subdomain.pos[coords]-boundaryNodeCentroid[coords])*boundaryNodeNorm[coords] normamplitude+=boundaryNodeNorm[coords]**2. dotProduct=dotProduct/np.sqrt(normamplitude) for coords in temp_subdomain.maxDistance: if (temp_subdomain.maxDistance[coords]*(1-addNodeInstead))<(meshOuterCoef*dotProduct): innerNode=False break if innerNode==False: break if innerNode: if addNodeInstead==1: temp_node=pinm.Node(temp_subdomain.pos,norm=domain.normalVector) subDomain.append(temp_node) else: toBeFurtherMeshed.append(temp_subdomain) subDomain.append(temp_subdomain) domain.addNode(subDomain) return toBeFurtherMeshed; def findNodes(position,domainList,distance=None,searchDepth=-1.):#assign search depth to -1 for nodes temp_searchDepth=searchDepth if distance==None: findNearest=True else: findNearest=False if findNearest: referenceDomain=None minDistanceSq=float("inf") otherDomain=[] for domain in domainList: temp_distSq=0. if bool(domain.pos): for coords in position: temp_distSq+=(position[coords]-domain.pos[coords])**2. if minDistanceSq>temp_distSq: minDistanceSq=temp_distSq referenceDomain=domain else: for allDomain in domain.subDomain: otherDomain.append(allDomain) if len(otherDomain)!=0: if type(referenceDomain) is pinm.Domain: for includeDomain in referenceDomain.subDomain: otherDomain.append(includeDomain) elif type(referenceDomain) is pinm.Node: otherDomain.append(referenceDomain) nodes=findNodes(position,otherDomain,searchDepth=temp_searchDepth) elif (type(referenceDomain) is not pinm.Node) and searchDepth!=0: nodes=findNodes(position,referenceDomain.subDomain,searchDepth=(temp_searchDepth-1)) else: nodes=referenceDomain return nodes else: nodes=[] for domain in domainList: toAdd=True if bool(domain.pos): if type(domain) is not pinm.Node: maxDistance=domain.maxDistance else: maxDistance={} for coords in position: maxDistance[coords]=0. for coords in position: if np.absolute(position[coords]-domain.pos[coords])>(maxDistance[coords]+distance[coords]): toAdd=False if toAdd: if type(domain) is not pinm.Node: for temp_nodes in findNodes(position,domain.subDomain,distance): nodes.append(temp_nodes) else: nodes.append(domain) return nodes def addDictionary(a): result={} for dicts in a: for key in dicts: if key in result: result[key]+=dicts[key] else: result[key]=dicts[key] return result def multiplyDictionary(a,b): result={} for key in a: result[key]=a[key]*b return result def plotNodes(nodes,coordinate=['x','y','z'],variableIdentifier='',complex='real'): figure = pyplot.figure() axes = mplot3d.Axes3D(figure) coordinateKey=[] var=[] numOfNodes=len(nodes) coords=np.zeros((3,numOfNodes)) for n in range(numOfNodes): for m in range(len(coords)): coords[m][n]=nodes[n].pos[coordinate[m]] if variableIdentifier!='': if complex=='real': var.append(nodes[n].variable[variableIdentifier].real) elif complex=='imag': var.append(nodes[n].variable[variableIdentifier].imag) elif complex=='abs': var.append(np.absolute(nodes[n].variable[variableIdentifier])) if variableIdentifier!='': cm = pyplot.get_cmap('jet') cNorm = Colors.Normalize(vmin=min(var), vmax=max(var)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) axes.scatter(coords[0], coords[1], coords[2],c=scalarMap.to_rgba(var)) scalarMap.set_array(var) figure.colorbar(scalarMap) else: axes.scatter(coords[0], coords[1], coords[2]) pyplot.show() class DomainSelector: def __init__(self,collectionList): self.ind = 0 self.collectionList=collectionList self.selectedIndex=[] self.domainInfo=[] self.domainCount=1 self.end=False self.keyFunc={'l':self.nextFunc, 'k':self.prevFunc, 's':self.selectFunc, 'a':self.addToDomainFunc} for n in collectionList: self.selectedIndex.append(False) self.domainInfo.append(0) self.maxIndex=len(collectionList)-1 def next(self, event): self.nextFunc() def prev(self, event): self.prevFunc() def select(self, event): self.selectFunc() self.nextFunc() def addToDomain(self, event): self.addToDomainFunc() def swapSelected(self, event): self.swapSelectedFunc() # def keyPressed(self,event): # self.keyFunc[event.key]() #find code error def nextFunc(self): if not(self.end): if self.selectedIndex[self.ind]: self.collectionList[self.ind].set_facecolor('g') else: self.collectionList[self.ind].set_facecolor('b') self.ind += 1 if self.ind>self.maxIndex: self.ind = 0 while self.domainInfo[self.ind]!=0: self.ind += 1 if self.ind>self.maxIndex: self.ind = 0 if self.selectedIndex[self.ind]: self.collectionList[self.ind].set_facecolor('r') else: self.collectionList[self.ind].set_facecolor('k') pyplot.draw() def prevFunc(self): if not(self.end): if self.selectedIndex[self.ind]: self.collectionList[self.ind].set_facecolor('g') else: self.collectionList[self.ind].set_facecolor('b') self.ind -= 1 if self.ind<0: self.ind = self.maxIndex while self.domainInfo[self.ind]!=0: self.ind -= 1 if self.ind<0: self.ind = self.maxIndex if self.selectedIndex[self.ind]: self.collectionList[self.ind].set_facecolor('r') else: self.collectionList[self.ind].set_facecolor('k') pyplot.draw() def selectFunc(self): if not(self.end): if self.selectedIndex[self.ind]: self.collectionList[self.ind].set_facecolor('k') self.selectedIndex[self.ind]=False else: self.collectionList[self.ind].set_facecolor('r') self.selectedIndex[self.ind]=True pyplot.draw() def addToDomainFunc(self): for n in range(len(self.selectedIndex)): if self.selectedIndex[n]: self.selectedIndex[n]=False self.domainInfo[n]=self.domainCount self.collectionList[n].set_facecolor('none') self.domainCount +=1 self.end=True for n in range(len(self.domainInfo)): if self.domainInfo[n]==0: self.ind = n self.collectionList[self.ind].set_facecolor('k') self.end=False break pyplot.draw() def swapSelectedFunc(self): for n in range(len(self.selectedIndex)): if self.domainInfo[n]==0: if self.selectedIndex[n]: self.selectedIndex[n]=False if n==self.ind: self.collectionList[n].set_facecolor('k') else: self.collectionList[n].set_facecolor('b') else: self.selectedIndex[n]=True if n==self.ind: self.collectionList[n].set_facecolor('r') else: self.collectionList[n].set_facecolor('g') pyplot.draw()
[ "mpl_toolkits.mplot3d.art3d.Poly3DCollection", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.draw", "numpy.sqrt", "matplotlib.pyplot.show", "numpy.absolute", "matplotlib.widgets.Button", "matplotlib.pyplot.figure", "numpy.zeros", "matplotlib.pyplot.axes", "matplotlib.cm.ScalarMappable", "matplotlib.pyplot.get_cmap", "mpl_toolkits.mplot3d.Axes3D", "stl.mesh.Mesh.from_file" ]
[((522, 537), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {}), '()\n', (535, 537), False, 'from matplotlib import pyplot\n'), ((542, 576), 'matplotlib.pyplot.subplots_adjust', 'pyplot.subplots_adjust', ([], {'bottom': '(0.2)'}), '(bottom=0.2)\n', (564, 576), False, 'from matplotlib import pyplot\n'), ((588, 610), 'mpl_toolkits.mplot3d.Axes3D', 'mplot3d.Axes3D', (['figure'], {}), '(figure)\n', (602, 610), False, 'from mpl_toolkits import mplot3d\n'), ((684, 713), 'stl.mesh.Mesh.from_file', 'mesh.Mesh.from_file', (['filePath'], {}), '(filePath)\n', (703, 713), False, 'from stl import mesh\n'), ((1119, 1155), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.7, 0.05, 0.1, 0.075]'], {}), '([0.7, 0.05, 0.1, 0.075])\n', (1130, 1155), False, 'from matplotlib import pyplot\n'), ((1169, 1206), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.81, 0.05, 0.1, 0.075]'], {}), '([0.81, 0.05, 0.1, 0.075])\n', (1180, 1206), False, 'from matplotlib import pyplot\n'), ((1222, 1260), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.05, 0.05, 0.15, 0.075]'], {}), '([0.05, 0.05, 0.15, 0.075])\n', (1233, 1260), False, 'from matplotlib import pyplot\n'), ((1281, 1319), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.05, 0.85, 0.15, 0.075]'], {}), '([0.05, 0.85, 0.15, 0.075])\n', (1292, 1319), False, 'from matplotlib import pyplot\n'), ((1341, 1378), 'matplotlib.pyplot.axes', 'pyplot.axes', (['[0.8, 0.85, 0.15, 0.075]'], {}), '([0.8, 0.85, 0.15, 0.075])\n', (1352, 1378), False, 'from matplotlib import pyplot\n'), ((1391, 1413), 'matplotlib.widgets.Button', 'Button', (['axnext', '"""Next"""'], {}), "(axnext, 'Next')\n", (1397, 1413), False, 'from matplotlib.widgets import Button\n'), ((1462, 1488), 'matplotlib.widgets.Button', 'Button', (['axprev', '"""Previous"""'], {}), "(axprev, 'Previous')\n", (1468, 1488), False, 'from matplotlib.widgets import Button\n'), ((1539, 1569), 'matplotlib.widgets.Button', 'Button', (['axselect', '"""(un)Select"""'], {}), "(axselect, '(un)Select')\n", (1545, 1569), False, 'from matplotlib.widgets import Button\n'), ((1629, 1664), 'matplotlib.widgets.Button', 'Button', (['axaddToDomain', '"""Add Domain"""'], {}), "(axaddToDomain, 'Add Domain')\n", (1635, 1664), False, 'from matplotlib.widgets import Button\n'), ((1735, 1774), 'matplotlib.widgets.Button', 'Button', (['axswapSelected', '"""Swap Selected"""'], {}), "(axswapSelected, 'Swap Selected')\n", (1741, 1774), False, 'from matplotlib.widgets import Button\n'), ((1930, 1943), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (1941, 1943), False, 'from matplotlib import pyplot\n'), ((14065, 14084), 'numpy.sqrt', 'np.sqrt', (['temp_total'], {}), '(temp_total)\n', (14072, 14084), True, 'import numpy as np\n'), ((20515, 20530), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {}), '()\n', (20528, 20530), False, 'from matplotlib import pyplot\n'), ((20542, 20564), 'mpl_toolkits.mplot3d.Axes3D', 'mplot3d.Axes3D', (['figure'], {}), '(figure)\n', (20556, 20564), False, 'from mpl_toolkits import mplot3d\n'), ((20634, 20659), 'numpy.zeros', 'np.zeros', (['(3, numOfNodes)'], {}), '((3, numOfNodes))\n', (20642, 20659), True, 'import numpy as np\n'), ((21549, 21562), 'matplotlib.pyplot.show', 'pyplot.show', ([], {}), '()\n', (21560, 21562), False, 'from matplotlib import pyplot\n'), ((13247, 13269), 'numpy.sqrt', 'np.sqrt', (['sidelength[n]'], {}), '(sidelength[n])\n', (13254, 13269), True, 'import numpy as np\n'), ((21180, 21202), 'matplotlib.pyplot.get_cmap', 'pyplot.get_cmap', (['"""jet"""'], {}), "('jet')\n", (21195, 21202), False, 'from matplotlib import pyplot\n'), ((21286, 21325), 'matplotlib.cm.ScalarMappable', 'cmx.ScalarMappable', ([], {'norm': 'cNorm', 'cmap': 'cm'}), '(norm=cNorm, cmap=cm)\n', (21304, 21325), True, 'import matplotlib.cm as cmx\n'), ((24903, 24916), 'matplotlib.pyplot.draw', 'pyplot.draw', ([], {}), '()\n', (24914, 24916), False, 'from matplotlib import pyplot\n'), ((25591, 25604), 'matplotlib.pyplot.draw', 'pyplot.draw', ([], {}), '()\n', (25602, 25604), False, 'from matplotlib import pyplot\n'), ((802, 872), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'mplot3d.art3d.Poly3DCollection', (['[modelMesh.vectors[n]]'], {'facecolors': '"""b"""'}), "([modelMesh.vectors[n]], facecolors='b')\n", (832, 872), False, 'from mpl_toolkits import mplot3d\n'), ((23238, 23251), 'matplotlib.pyplot.draw', 'pyplot.draw', ([], {}), '()\n', (23249, 23251), False, 'from matplotlib import pyplot\n'), ((23952, 23965), 'matplotlib.pyplot.draw', 'pyplot.draw', ([], {}), '()\n', (23963, 23965), False, 'from matplotlib import pyplot\n'), ((24324, 24337), 'matplotlib.pyplot.draw', 'pyplot.draw', ([], {}), '()\n', (24335, 24337), False, 'from matplotlib import pyplot\n'), ((16417, 16486), 'numpy.absolute', 'np.absolute', (['(temp_boundaryNode.pos[coord] - temp_subdomain.pos[coord])'], {}), '(temp_boundaryNode.pos[coord] - temp_subdomain.pos[coord])\n', (16428, 16486), True, 'import numpy as np\n'), ((17095, 17117), 'numpy.sqrt', 'np.sqrt', (['normamplitude'], {}), '(normamplitude)\n', (17102, 17117), True, 'import numpy as np\n'), ((19654, 19704), 'numpy.absolute', 'np.absolute', (['(position[coords] - domain.pos[coords])'], {}), '(position[coords] - domain.pos[coords])\n', (19665, 19704), True, 'import numpy as np\n'), ((21084, 21134), 'numpy.absolute', 'np.absolute', (['nodes[n].variable[variableIdentifier]'], {}), '(nodes[n].variable[variableIdentifier])\n', (21095, 21134), True, 'import numpy as np\n')]
import csv import json import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': formats = ['png', 'pdf', 'svg', 'eps'] metrics = [ {'gmetric': 'groc', 'lmetric': 'lroc', 'metric': 'AUC'}, {'gmetric': 'gauc', 'lmetric': 'lauc', 'metric': 'PRAUC'}, ] datasets = [ {'name': 'HCC', 'file': '../../results/evaluation/hcc_multi_sites_100_each.csv'}, {'name': 'ILPD', 'file': '../../results/evaluation/ilpd_multi_sites_100_each.csv'}, {'name': 'LTD', 'file': '../../results/evaluation/tumor_multi_sites_100_each.csv'}, {'name': 'BCD', 'file': '../../results/evaluation/diag_multi_sites_100_each.csv'}, ] for metric in metrics: gmetric = metric['gmetric'] lmetric = metric['lmetric'] metric = metric['metric'] for ds in datasets: file = ds['file'] name = ds['name'] title = f'{name} | Multiple Local Models' stats = {} xs = ['1', '2', '5', '10', '20', '50', '100'] with open(file, newline='') as csvfile: data = csv.reader(csvfile, delimiter=';') headers = next(data) gauc_idx = headers.index(gmetric) lauc_idx = headers.index(lmetric) for row in data: stat = stats.get(row[1]) if not stat: stat = { gmetric: [], lmetric: [], } stats[row[1]] = stat # xs.append(row[1]) gvals = json.loads(row[gauc_idx]) lvals = json.loads(row[lauc_idx]) stat[gmetric].append(gvals) if len(lvals) > 0: stat[lmetric].extend(lvals) else: stat[lmetric].append(gvals) # datainfo = str(len(stats['100'][gmetric])) # title += ' | ' + datainfo y_gauc_median = [np.median(stats[x][gmetric]) for x in xs] y_gauc_q25 = [np.quantile(stats[x][gmetric], 0.25) for x in xs] y_gauc_q75 = [np.quantile(stats[x][gmetric], 0.75) for x in xs] y_lauc_median = [np.median(stats[x][lmetric]) for x in xs] y_lauc_q25 = [np.quantile(stats[x][lmetric], 0.25) for x in xs] y_lauc_q75 = [np.quantile(stats[x][lmetric], 0.75) for x in xs] xs = [int(x) for x in xs] regular_col = '#b0b0b0' global_col = '#424ef5' local_col = '#f57542' alpha_mean = 1.0 alpha_q = 0.25 alpha_area = 0.2 fig = plt.figure(figsize=(6, 4.5)) ax = fig.add_subplot() ax.hlines(y_gauc_q25[0], 1, 100, linestyles='dotted', colors=[regular_col]) ax.hlines(y_gauc_median[0], 1, 100, label='Centralized', colors=[regular_col]) ax.hlines(y_gauc_q75[0], 1, 100, linestyles='dotted', colors=[regular_col]) ax.fill_between(xs, y_gauc_q25, y_gauc_median, color=global_col, alpha=alpha_area) ax.fill_between(xs, y_gauc_q75, y_gauc_median, color=global_col, alpha=alpha_area) ax.fill_between(xs, y_lauc_q25, y_lauc_median, color=local_col, alpha=alpha_area) ax.fill_between(xs, y_lauc_q75, y_lauc_median, color=local_col, alpha=alpha_area) ax.plot(xs, y_gauc_q25, '_', color=global_col, alpha=alpha_q) ax.plot(xs, y_gauc_median, '.', label='Combined', color=global_col, alpha=alpha_mean) ax.plot(xs, y_gauc_q75, '_', color=global_col, alpha=alpha_q) ax.plot(xs, y_lauc_q25, '_', color=local_col, alpha=alpha_q) ax.plot(xs, y_lauc_median, '.', label='Local', color=local_col, alpha=alpha_mean) ax.plot(xs, y_lauc_q75, '_', color=local_col, alpha=alpha_q) plt.yticks([0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) plt.xscale('log') plt.xticks([1, 2, 5, 10, 20, 50, 100], ['Centralized', '2', '5', '10', '20', '50', '100']) plt.ylabel(metric) plt.xlabel('Number of Sites') plt.legend() plt.title(title) for format in formats: plt.savefig(f'../../results/plots/{name}_{metric}_sites.{format}', format=format, bbox_inches='tight')
[ "json.loads", "numpy.median", "matplotlib.pyplot.savefig", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.figure", "numpy.quantile", "matplotlib.pyplot.yticks", "matplotlib.pyplot.title", "csv.reader", "matplotlib.pyplot.xscale" ]
[((2763, 2791), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4.5)'}), '(figsize=(6, 4.5))\n', (2773, 2791), True, 'import matplotlib.pyplot as plt\n'), ((3977, 4019), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0.5, 0.6, 0.7, 0.8, 0.9, 1.0]'], {}), '([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])\n', (3987, 4019), True, 'import matplotlib.pyplot as plt\n'), ((4032, 4049), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (4042, 4049), True, 'import matplotlib.pyplot as plt\n'), ((4062, 4156), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[1, 2, 5, 10, 20, 50, 100]', "['Centralized', '2', '5', '10', '20', '50', '100']"], {}), "([1, 2, 5, 10, 20, 50, 100], ['Centralized', '2', '5', '10', '20',\n '50', '100'])\n", (4072, 4156), True, 'import matplotlib.pyplot as plt\n'), ((4165, 4183), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['metric'], {}), '(metric)\n', (4175, 4183), True, 'import matplotlib.pyplot as plt\n'), ((4196, 4225), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of Sites"""'], {}), "('Number of Sites')\n", (4206, 4225), True, 'import matplotlib.pyplot as plt\n'), ((4238, 4250), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4248, 4250), True, 'import matplotlib.pyplot as plt\n'), ((4263, 4279), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (4272, 4279), True, 'import matplotlib.pyplot as plt\n'), ((1126, 1160), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""";"""'}), "(csvfile, delimiter=';')\n", (1136, 1160), False, 'import csv\n'), ((2095, 2123), 'numpy.median', 'np.median', (['stats[x][gmetric]'], {}), '(stats[x][gmetric])\n', (2104, 2123), True, 'import numpy as np\n'), ((2163, 2199), 'numpy.quantile', 'np.quantile', (['stats[x][gmetric]', '(0.25)'], {}), '(stats[x][gmetric], 0.25)\n', (2174, 2199), True, 'import numpy as np\n'), ((2239, 2275), 'numpy.quantile', 'np.quantile', (['stats[x][gmetric]', '(0.75)'], {}), '(stats[x][gmetric], 0.75)\n', (2250, 2275), True, 'import numpy as np\n'), ((2319, 2347), 'numpy.median', 'np.median', (['stats[x][lmetric]'], {}), '(stats[x][lmetric])\n', (2328, 2347), True, 'import numpy as np\n'), ((2387, 2423), 'numpy.quantile', 'np.quantile', (['stats[x][lmetric]', '(0.25)'], {}), '(stats[x][lmetric], 0.25)\n', (2398, 2423), True, 'import numpy as np\n'), ((2463, 2499), 'numpy.quantile', 'np.quantile', (['stats[x][lmetric]', '(0.75)'], {}), '(stats[x][lmetric], 0.75)\n', (2474, 2499), True, 'import numpy as np\n'), ((4332, 4439), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""../../results/plots/{name}_{metric}_sites.{format}"""'], {'format': 'format', 'bbox_inches': '"""tight"""'}), "(f'../../results/plots/{name}_{metric}_sites.{format}', format=\n format, bbox_inches='tight')\n", (4343, 4439), True, 'import matplotlib.pyplot as plt\n'), ((1669, 1694), 'json.loads', 'json.loads', (['row[gauc_idx]'], {}), '(row[gauc_idx])\n', (1679, 1694), False, 'import json\n'), ((1723, 1748), 'json.loads', 'json.loads', (['row[lauc_idx]'], {}), '(row[lauc_idx])\n', (1733, 1748), False, 'import json\n')]
""" # !/usr/bin/env python # -*- coding: utf-8 -*- @Time : 2022/2/24 20:12 @Author : <EMAIL> @ProjectName : udacity-program_self_driving_car_engineer_v1.0_source.0 @File : full_pipeline.py """ import numpy as np import cv2 import os import matplotlib.image as mpimg import matplotlib.pyplot as plt import glob from moviepy.editor import VideoFileClip # Load in the chessboard calibration images to a list cal_image_loc = glob.glob('camera_cal/calibration*.jpg') # Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((6 * 9, 3), np.float32) objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2) # Arrays for later storing object points and image points obj_points = [] # 3d points in real world space img_points = [] # 2d points in image plane. # Make a list of calibration images calibration_images = [] for im in cal_image_loc: img = mpimg.imread(im) calibration_images.append(img) verbose = False # Iterate through images for their points for image in calibration_images: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find the chessboard corners pattern_found, corners = cv2.findChessboardCorners(gray, (9, 6), None) if pattern_found is True: obj_points.append(objp) img_points.append(corners) if verbose: # Draw and display the corners img = cv2.drawChessboardCorners(image, (9, 6), corners, pattern_found) cv2.imshow('img', img) cv2.waitKey(500) if verbose: cv2.destroyAllWindows() # Returns camera calibration ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, gray.shape[::-1], None, None) class Left_Line(): """ the left line """ def __init__(self): # was the line detected in the last iteration? self.detected = False # recent polynomial coefficients self.recent_fit = [] # polynomial coefficients averaged over the last n iterations self.best_fit = None # polynomial coefficients for the most recent fit self.current_fit = [np.array([False])] # difference in fit coefficients between last and new fits self.diffs = np.array([0, 0, 0], dtype='float') # x values for detected line pixels self.allx = None # y values for detected line pixels self.ally = None # counter to reset after 5 iterations if issues arise self.counter = 0 class Right_Line(): """ the right line """ def __init__(self): # was the line detected in the last iteration? self.detected = False # recent polynomial coefficients self.recent_fit = [] # polynomial coefficients averaged over the last n iterations self.best_fit = None # polynomial coefficients for the most recent fit self.current_fit = [np.array([False])] # difference in fit coefficients between last and new fits self.diffs = np.array([0, 0, 0], dtype='float') # x values for detected line pixels self.allx = None # y values for detected line pixels self.ally = None # counter to reset after 5 iterations if issues arise self.counter = 0 def pipeline(img, s_thresh=(125, 255), sx_thresh=(10, 100), R_thresh=(200, 255), sobel_kernel=3): """ Pipeline to create binary image. This version uses thresholds on the R & S color channels and Sobelx. Binary activation occurs where any two of the three are activated. """ distorted_img = np.copy(img) dst = cv2.undistort(distorted_img, mtx, dist, None, mtx) # Pull R R = dst[:, :, 0] # Convert to HLS colorspace hls = cv2.cvtColor(dst, cv2.COLOR_RGB2HLS).astype(np.float) h_channel = hls[:, :, 0] l_channel = hls[:, :, 1] s_channel = hls[:, :, 2] # Sobelx - takes the derivate in x, absolute value, then rescale sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0, ksize=sobel_kernel) abs_sobelx = np.absolute(sobelx) scaled_sobelx = np.uint8(255 * abs_sobelx / np.max(abs_sobelx)) # Threshold x gradient sxbinary = np.zeros_like(scaled_sobelx) sxbinary[(scaled_sobelx >= sx_thresh[0]) & (scaled_sobelx <= sx_thresh[1])] = 1 # Threshold R color channel R_binary = np.zeros_like(R) R_binary[(R >= R_thresh[0]) & (R <= R_thresh[1])] = 1 # Threshold color channel s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1 # If two of the three are activated, activate in the binary image combined_binary = np.zeros_like(sxbinary) combined_binary[((s_binary == 1) & (sxbinary == 1)) | ((sxbinary == 1) & (R_binary == 1)) | ((s_binary == 1) & (R_binary == 1))] = 1 return combined_binary def birds_eye(img, mtx, dist): """ Birds eye first undistorts the image, using the calibration from earlier. Next, using defined source image points and destination points, it will transform the image as if the road was viewed from above, like a bird would see. Returns the birds eye image and transform matrix. """ # Put the image through the pipeline to get the binary image binary_img = pipeline(img) # Undistort undist = cv2.undistort(binary_img, mtx, dist, None, mtx) # Grab the image shape img_size = (undist.shape[1], undist.shape[0]) # Source points - defined area of lane line edges src = np.float32([[690, 450], [1110, img_size[1]], [175, img_size[1]], [595, 450]]) # 4 destination points to transfer offset = 300 # offset for dst points dst = np.float32([[img_size[0] - offset, 0], [img_size[0] - offset, img_size[1]], [offset, img_size[1]], [offset, 0]]) # Use cv2.getPerspectiveTransform() to get M, the transform matrix M = cv2.getPerspectiveTransform(src, dst) # Use cv2.warpPerspective() to warp the image to a top-down view top_down = cv2.warpPerspective(undist, M, img_size) return top_down, M def count_check(line): """ Resets to using new sliding windows below if upon failing five times in a row. """ if line.counter >= 5: line.detected = False def first_lines(img, mtx, dist): """ First Lines uses the birds eye image from above, creates a histogram of where the binary activations occur, and uses sliding windows along the peak areas to estimate where the lane lines are. """ # Load the birds eye image and transform matrix from birds_eye binary_warped, perspective_M = birds_eye(img, mtx, dist) # Histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0] / 2:, :], axis=0) # Output image an to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0] / 2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # Choose the number of sliding windows nwindows = 9 # Set height of windows window_height = np.int(binary_warped.shape[0] / nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated for each window leftx_current = leftx_base rightx_current = rightx_base # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window + 1) * window_height win_y_high = binary_warped.shape[0] - window * window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2) cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2) # Identify the nonzero pixels in x and y within the window good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & ( nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & ( nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each # The challenge videos sometimes throw errors, so the below try first # Upon the error being thrown, set line.detected to False # Left line first try: n = 5 left_line.current_fit = np.polyfit(lefty, leftx, 2) left_line.all_x = leftx left_line.all_y = lefty left_line.recent_fit.append(left_line.current_fit) if len(left_line.recent_fit) > 1: left_line.diffs = (left_line.recent_fit[-2] - left_line.recent_fit[-1]) / left_line.recent_fit[-2] left_line.recent_fit = left_line.recent_fit[-n:] left_line.best_fit = np.mean(left_line.recent_fit, axis=0) left_fit = left_line.current_fit left_line.detected = True left_line.counter = 0 except TypeError: left_fit = left_line.best_fit left_line.detected = False except np.linalg.LinAlgError: left_fit = left_line.best_fit left_line.detected = False # Next, right line try: n = 5 right_line.current_fit = np.polyfit(righty, rightx, 2) right_line.all_x = rightx right_line.all_y = righty right_line.recent_fit.append(right_line.current_fit) if len(right_line.recent_fit) > 1: right_line.diffs = (right_line.recent_fit[-2] - right_line.recent_fit[-1]) / right_line.recent_fit[-2] right_line.recent_fit = right_line.recent_fit[-n:] right_line.best_fit = np.mean(right_line.recent_fit, axis=0) right_fit = right_line.current_fit right_line.detected = True right_line.counter = 0 except TypeError: right_fit = right_line.best_fit right_line.detected = False except np.linalg.LinAlgError: right_fit = right_line.best_fit right_line.detected = False def second_ord_poly(line, val): """ Simple function being used to help calculate distance from center. Only used within Draw Lines below. Finds the base of the line at the bottom of the image. """ a = line[0] b = line[1] c = line[2] formula = (a * val ** 2) + (b * val) + c return formula def draw_lines(img, mtx, dist): """ Draw Lines will first check whether the lines are detected. If not, go back up to First Lines. If they are, we do not have to search the whole image for the lines. We can then draw the lines, as well as detect where the car is in relation to the middle of the lane, and what type of curvature it is driving at. """ # Pull in the image binary_warped, perspective_M = birds_eye(img, mtx, dist) # Check if lines were last detected; if not, re-run first_lines if left_line.detected == False | right_line.detected == False: first_lines(img, mtx, dist) # Set the fit as the current fit for now left_fit = left_line.current_fit right_fit = right_line.current_fit # Again, find the lane indicators nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_lane_inds = ((nonzerox > (left_fit[0] * (nonzeroy ** 2) + left_fit[1] * nonzeroy + left_fit[2] - margin)) & ( nonzerox < (left_fit[0] * (nonzeroy ** 2) + left_fit[1] * nonzeroy + left_fit[2] + margin))) right_lane_inds = ( (nonzerox > (right_fit[0] * (nonzeroy ** 2) + right_fit[1] * nonzeroy + right_fit[2] - margin)) & ( nonzerox < (right_fit[0] * (nonzeroy ** 2) + right_fit[1] * nonzeroy + right_fit[2] + margin))) # Set the x and y values of points on each line leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each again. # Similar to first_lines, need to try in case of errors # Left line first try: n = 5 left_line.current_fit = np.polyfit(lefty, leftx, 2) left_line.all_x = leftx left_line.all_y = lefty left_line.recent_fit.append(left_line.current_fit) if len(left_line.recent_fit) > 1: left_line.diffs = (left_line.recent_fit[-2] - left_line.recent_fit[-1]) / left_line.recent_fit[-2] left_line.recent_fit = left_line.recent_fit[-n:] left_line.best_fit = np.mean(left_line.recent_fit, axis=0) left_fit = left_line.current_fit left_line.detected = True left_line.counter = 0 except TypeError: left_fit = left_line.best_fit count_check(left_line) except np.linalg.LinAlgError: left_fit = left_line.best_fit count_check(left_line) # Now right line try: n = 5 right_line.current_fit = np.polyfit(righty, rightx, 2) right_line.all_x = rightx right_line.all_y = righty right_line.recent_fit.append(right_line.current_fit) if len(right_line.recent_fit) > 1: right_line.diffs = (right_line.recent_fit[-2] - right_line.recent_fit[-1]) / right_line.recent_fit[-2] right_line.recent_fit = right_line.recent_fit[-n:] right_line.best_fit = np.mean(right_line.recent_fit, axis=0) right_fit = right_line.current_fit right_line.detected = True right_line.counter = 0 except TypeError: right_fit = right_line.best_fit count_check(right_line) except np.linalg.LinAlgError: right_fit = right_line.best_fit count_check(right_line) # Generate x and y values for plotting fity = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) fit_leftx = left_fit[0] * fity ** 2 + left_fit[1] * fity + left_fit[2] fit_rightx = right_fit[0] * fity ** 2 + right_fit[1] * fity + right_fit[2] # Create an image to draw on and an image to show the selection window out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 window_img = np.zeros_like(out_img) # Color in left and right line pixels out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0] out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255] # Generate a polygon to illustrate the search window area # And recast the x and y points into usable format for cv2.fillPoly() left_line_window1 = np.array([np.transpose(np.vstack([fit_leftx - margin, fity]))]) left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([fit_leftx + margin, fity])))]) left_line_pts = np.hstack((left_line_window1, left_line_window2)) right_line_window1 = np.array([np.transpose(np.vstack([fit_rightx - margin, fity]))]) right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([fit_rightx + margin, fity])))]) right_line_pts = np.hstack((right_line_window1, right_line_window2)) # Calculate the pixel curve radius y_eval = np.max(fity) left_curverad = ((1 + (2 * left_fit[0] * y_eval + left_fit[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit[0]) right_curverad = ((1 + (2 * right_fit[0] * y_eval + right_fit[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit[0]) # Define conversions in x and y from pixels space to meters ym_per_pix = 30 / 720 # meters per pixel in y dimension xm_per_pix = 3.7 / 700 # meters per pixel in x dimension # Fit new polynomials to x,y in world space left_fit_cr = np.polyfit(left_line.all_y * ym_per_pix, left_line.all_x * xm_per_pix, 2) right_fit_cr = np.polyfit(right_line.all_y * ym_per_pix, right_line.all_x * xm_per_pix, 2) # Calculate the new radii of curvature left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute( 2 * left_fit_cr[0]) right_curverad = ((1 + (2 * right_fit_cr[0] * y_eval * ym_per_pix + right_fit_cr[1]) ** 2) ** 1.5) / np.absolute( 2 * right_fit_cr[0]) avg_rad = round(np.mean([left_curverad, right_curverad]), 0) rad_text = "Radius of Curvature = {}(m)".format(avg_rad) # Calculating middle of the image, aka where the car camera is middle_of_image = img.shape[1] / 2 car_position = middle_of_image * xm_per_pix # Calculating middle of the lane left_line_base = second_ord_poly(left_fit_cr, img.shape[0] * ym_per_pix) right_line_base = second_ord_poly(right_fit_cr, img.shape[0] * ym_per_pix) lane_mid = (left_line_base + right_line_base) / 2 # Calculate distance from center and list differently based on left or right dist_from_center = lane_mid - car_position if dist_from_center >= 0: center_text = "{} meters left of center".format(round(dist_from_center, 2)) else: center_text = "{} meters right of center".format(round(-dist_from_center, 2)) # List car's position in relation to middle on the image and radius of curvature font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, center_text, (10, 50), font, 1, (255, 255, 255), 2) cv2.putText(img, rad_text, (10, 100), font, 1, (255, 255, 255), 2) # Invert the transform matrix from birds_eye (to later make the image back to normal below) Minv = np.linalg.inv(perspective_M) # Create an image to draw the lines on warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([fit_leftx, fity]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([fit_rightx, fity])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) # Combine the result with the original image result = cv2.addWeighted(img, 1, newwarp, 0.3, 0) return result def process_image(image): """ This processes through everything above. Will return the image with car position, lane curvature, and lane lines drawn. """ result = draw_lines(image, mtx, dist) return result # Set the class lines equal to the variables used above left_line = Left_Line() right_line = Right_Line() # Convert to video # vid_output is where the image will be saved to vid_output = 'project_video_detected.mp4' # The file referenced in clip1 is the original video before anything has been done to it # clip1 = VideoFileClip("project_video.mp4") # NOTE: this function expects color images # vid_clip = clip1.fl_image(process_image) # vid_clip.write_videofile(vid_output, audio=False) test_img_dir = 'test_images' for test_img in os.listdir(test_img_dir): frame = cv2.imread(os.path.join(test_img_dir, test_img)) blend = process_image(frame) cv2.imwrite('output_images/{}'.format(test_img), blend) plt.imshow(cv2.cvtColor(blend, code=cv2.COLOR_BGR2RGB)) plt.show()
[ "cv2.rectangle", "numpy.hstack", "numpy.polyfit", "matplotlib.image.imread", "cv2.imshow", "numpy.array", "cv2.warpPerspective", "cv2.destroyAllWindows", "cv2.calibrateCamera", "cv2.findChessboardCorners", "numpy.mean", "os.listdir", "cv2.undistort", "numpy.max", "cv2.addWeighted", "numpy.linspace", "numpy.vstack", "numpy.concatenate", "cv2.waitKey", "glob.glob", "cv2.getPerspectiveTransform", "numpy.argmax", "cv2.putText", "cv2.cvtColor", "numpy.int_", "numpy.int", "matplotlib.pyplot.show", "numpy.copy", "numpy.dstack", "numpy.absolute", "os.path.join", "numpy.sum", "numpy.zeros", "numpy.linalg.inv", "cv2.drawChessboardCorners", "numpy.zeros_like", "numpy.float32", "cv2.Sobel" ]
[((442, 482), 'glob.glob', 'glob.glob', (['"""camera_cal/calibration*.jpg"""'], {}), "('camera_cal/calibration*.jpg')\n", (451, 482), False, 'import glob\n'), ((560, 592), 'numpy.zeros', 'np.zeros', (['(6 * 9, 3)', 'np.float32'], {}), '((6 * 9, 3), np.float32)\n', (568, 592), True, 'import numpy as np\n'), ((1607, 1680), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['obj_points', 'img_points', 'gray.shape[::-1]', 'None', 'None'], {}), '(obj_points, img_points, gray.shape[::-1], None, None)\n', (1626, 1680), False, 'import cv2\n'), ((20630, 20654), 'os.listdir', 'os.listdir', (['test_img_dir'], {}), '(test_img_dir)\n', (20640, 20654), False, 'import os\n'), ((892, 908), 'matplotlib.image.imread', 'mpimg.imread', (['im'], {}), '(im)\n', (904, 908), True, 'import matplotlib.image as mpimg\n'), ((1048, 1087), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1060, 1087), False, 'import cv2\n'), ((1152, 1197), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['gray', '(9, 6)', 'None'], {}), '(gray, (9, 6), None)\n', (1177, 1197), False, 'import cv2\n'), ((1522, 1545), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1543, 1545), False, 'import cv2\n'), ((3568, 3580), 'numpy.copy', 'np.copy', (['img'], {}), '(img)\n', (3575, 3580), True, 'import numpy as np\n'), ((3591, 3641), 'cv2.undistort', 'cv2.undistort', (['distorted_img', 'mtx', 'dist', 'None', 'mtx'], {}), '(distorted_img, mtx, dist, None, mtx)\n', (3604, 3641), False, 'import cv2\n'), ((3943, 4001), 'cv2.Sobel', 'cv2.Sobel', (['l_channel', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': 'sobel_kernel'}), '(l_channel, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n', (3952, 4001), False, 'import cv2\n'), ((4019, 4038), 'numpy.absolute', 'np.absolute', (['sobelx'], {}), '(sobelx)\n', (4030, 4038), True, 'import numpy as np\n'), ((4150, 4178), 'numpy.zeros_like', 'np.zeros_like', (['scaled_sobelx'], {}), '(scaled_sobelx)\n', (4163, 4178), True, 'import numpy as np\n'), ((4311, 4327), 'numpy.zeros_like', 'np.zeros_like', (['R'], {}), '(R)\n', (4324, 4327), True, 'import numpy as np\n'), ((4432, 4456), 'numpy.zeros_like', 'np.zeros_like', (['s_channel'], {}), '(s_channel)\n', (4445, 4456), True, 'import numpy as np\n'), ((4624, 4647), 'numpy.zeros_like', 'np.zeros_like', (['sxbinary'], {}), '(sxbinary)\n', (4637, 4647), True, 'import numpy as np\n'), ((5297, 5344), 'cv2.undistort', 'cv2.undistort', (['binary_img', 'mtx', 'dist', 'None', 'mtx'], {}), '(binary_img, mtx, dist, None, mtx)\n', (5310, 5344), False, 'import cv2\n'), ((5488, 5565), 'numpy.float32', 'np.float32', (['[[690, 450], [1110, img_size[1]], [175, img_size[1]], [595, 450]]'], {}), '([[690, 450], [1110, img_size[1]], [175, img_size[1]], [595, 450]])\n', (5498, 5565), True, 'import numpy as np\n'), ((5658, 5774), 'numpy.float32', 'np.float32', (['[[img_size[0] - offset, 0], [img_size[0] - offset, img_size[1]], [offset,\n img_size[1]], [offset, 0]]'], {}), '([[img_size[0] - offset, 0], [img_size[0] - offset, img_size[1]],\n [offset, img_size[1]], [offset, 0]])\n', (5668, 5774), True, 'import numpy as np\n'), ((5873, 5910), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['src', 'dst'], {}), '(src, dst)\n', (5900, 5910), False, 'import cv2\n'), ((5996, 6036), 'cv2.warpPerspective', 'cv2.warpPerspective', (['undist', 'M', 'img_size'], {}), '(undist, M, img_size)\n', (6015, 6036), False, 'import cv2\n'), ((6688, 6749), 'numpy.sum', 'np.sum', (['binary_warped[binary_warped.shape[0] / 2:, :]'], {'axis': '(0)'}), '(binary_warped[binary_warped.shape[0] / 2:, :], axis=0)\n', (6694, 6749), True, 'import numpy as np\n'), ((7036, 7066), 'numpy.int', 'np.int', (['(histogram.shape[0] / 2)'], {}), '(histogram.shape[0] / 2)\n', (7042, 7066), True, 'import numpy as np\n'), ((7084, 7115), 'numpy.argmax', 'np.argmax', (['histogram[:midpoint]'], {}), '(histogram[:midpoint])\n', (7093, 7115), True, 'import numpy as np\n'), ((7287, 7328), 'numpy.int', 'np.int', (['(binary_warped.shape[0] / nwindows)'], {}), '(binary_warped.shape[0] / nwindows)\n', (7293, 7328), True, 'import numpy as np\n'), ((7455, 7475), 'numpy.array', 'np.array', (['nonzero[0]'], {}), '(nonzero[0])\n', (7463, 7475), True, 'import numpy as np\n'), ((7491, 7511), 'numpy.array', 'np.array', (['nonzero[1]'], {}), '(nonzero[1])\n', (7499, 7511), True, 'import numpy as np\n'), ((9563, 9593), 'numpy.concatenate', 'np.concatenate', (['left_lane_inds'], {}), '(left_lane_inds)\n', (9577, 9593), True, 'import numpy as np\n'), ((9616, 9647), 'numpy.concatenate', 'np.concatenate', (['right_lane_inds'], {}), '(right_lane_inds)\n', (9630, 9647), True, 'import numpy as np\n'), ((12861, 12881), 'numpy.array', 'np.array', (['nonzero[0]'], {}), '(nonzero[0])\n', (12869, 12881), True, 'import numpy as np\n'), ((12897, 12917), 'numpy.array', 'np.array', (['nonzero[1]'], {}), '(nonzero[1])\n', (12905, 12917), True, 'import numpy as np\n'), ((15427, 15493), 'numpy.linspace', 'np.linspace', (['(0)', '(binary_warped.shape[0] - 1)', 'binary_warped.shape[0]'], {}), '(0, binary_warped.shape[0] - 1, binary_warped.shape[0])\n', (15438, 15493), True, 'import numpy as np\n'), ((15818, 15840), 'numpy.zeros_like', 'np.zeros_like', (['out_img'], {}), '(out_img)\n', (15831, 15840), True, 'import numpy as np\n'), ((16386, 16435), 'numpy.hstack', 'np.hstack', (['(left_line_window1, left_line_window2)'], {}), '((left_line_window1, left_line_window2))\n', (16395, 16435), True, 'import numpy as np\n'), ((16648, 16699), 'numpy.hstack', 'np.hstack', (['(right_line_window1, right_line_window2)'], {}), '((right_line_window1, right_line_window2))\n', (16657, 16699), True, 'import numpy as np\n'), ((16753, 16765), 'numpy.max', 'np.max', (['fity'], {}), '(fity)\n', (16759, 16765), True, 'import numpy as np\n'), ((17249, 17322), 'numpy.polyfit', 'np.polyfit', (['(left_line.all_y * ym_per_pix)', '(left_line.all_x * xm_per_pix)', '(2)'], {}), '(left_line.all_y * ym_per_pix, left_line.all_x * xm_per_pix, 2)\n', (17259, 17322), True, 'import numpy as np\n'), ((17342, 17417), 'numpy.polyfit', 'np.polyfit', (['(right_line.all_y * ym_per_pix)', '(right_line.all_x * xm_per_pix)', '(2)'], {}), '(right_line.all_y * ym_per_pix, right_line.all_x * xm_per_pix, 2)\n', (17352, 17417), True, 'import numpy as np\n'), ((18746, 18814), 'cv2.putText', 'cv2.putText', (['img', 'center_text', '(10, 50)', 'font', '(1)', '(255, 255, 255)', '(2)'], {}), '(img, center_text, (10, 50), font, 1, (255, 255, 255), 2)\n', (18757, 18814), False, 'import cv2\n'), ((18819, 18885), 'cv2.putText', 'cv2.putText', (['img', 'rad_text', '(10, 100)', 'font', '(1)', '(255, 255, 255)', '(2)'], {}), '(img, rad_text, (10, 100), font, 1, (255, 255, 255), 2)\n', (18830, 18885), False, 'import cv2\n'), ((18994, 19022), 'numpy.linalg.inv', 'np.linalg.inv', (['perspective_M'], {}), '(perspective_M)\n', (19007, 19022), True, 'import numpy as np\n'), ((19146, 19190), 'numpy.dstack', 'np.dstack', (['(warp_zero, warp_zero, warp_zero)'], {}), '((warp_zero, warp_zero, warp_zero))\n', (19155, 19190), True, 'import numpy as np\n'), ((19425, 19457), 'numpy.hstack', 'np.hstack', (['(pts_left, pts_right)'], {}), '((pts_left, pts_right))\n', (19434, 19457), True, 'import numpy as np\n'), ((19670, 19737), 'cv2.warpPerspective', 'cv2.warpPerspective', (['color_warp', 'Minv', '(img.shape[1], img.shape[0])'], {}), '(color_warp, Minv, (img.shape[1], img.shape[0]))\n', (19689, 19737), False, 'import cv2\n'), ((19801, 19841), 'cv2.addWeighted', 'cv2.addWeighted', (['img', '(1)', 'newwarp', '(0.3)', '(0)'], {}), '(img, 1, newwarp, 0.3, 0)\n', (19816, 19841), False, 'import cv2\n'), ((20876, 20886), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20884, 20886), True, 'import matplotlib.pyplot as plt\n'), ((2207, 2241), 'numpy.array', 'np.array', (['[0, 0, 0]'], {'dtype': '"""float"""'}), "([0, 0, 0], dtype='float')\n", (2215, 2241), True, 'import numpy as np\n'), ((2995, 3029), 'numpy.array', 'np.array', (['[0, 0, 0]'], {'dtype': '"""float"""'}), "([0, 0, 0], dtype='float')\n", (3003, 3029), True, 'import numpy as np\n'), ((6823, 6879), 'numpy.dstack', 'np.dstack', (['(binary_warped, binary_warped, binary_warped)'], {}), '((binary_warped, binary_warped, binary_warped))\n', (6832, 6879), True, 'import numpy as np\n'), ((7134, 7165), 'numpy.argmax', 'np.argmax', (['histogram[midpoint:]'], {}), '(histogram[midpoint:])\n', (7143, 7165), True, 'import numpy as np\n'), ((8438, 8538), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_xleft_low, win_y_low)', '(win_xleft_high, win_y_high)', '(0, 255, 0)', '(2)'], {}), '(out_img, (win_xleft_low, win_y_low), (win_xleft_high,\n win_y_high), (0, 255, 0), 2)\n', (8451, 8538), False, 'import cv2\n'), ((8543, 8645), 'cv2.rectangle', 'cv2.rectangle', (['out_img', '(win_xright_low, win_y_low)', '(win_xright_high, win_y_high)', '(0, 255, 0)', '(2)'], {}), '(out_img, (win_xright_low, win_y_low), (win_xright_high,\n win_y_high), (0, 255, 0), 2)\n', (8556, 8645), False, 'import cv2\n'), ((10109, 10136), 'numpy.polyfit', 'np.polyfit', (['lefty', 'leftx', '(2)'], {}), '(lefty, leftx, 2)\n', (10119, 10136), True, 'import numpy as np\n'), ((10499, 10536), 'numpy.mean', 'np.mean', (['left_line.recent_fit'], {'axis': '(0)'}), '(left_line.recent_fit, axis=0)\n', (10506, 10536), True, 'import numpy as np\n'), ((10924, 10953), 'numpy.polyfit', 'np.polyfit', (['righty', 'rightx', '(2)'], {}), '(righty, rightx, 2)\n', (10934, 10953), True, 'import numpy as np\n'), ((11330, 11368), 'numpy.mean', 'np.mean', (['right_line.recent_fit'], {'axis': '(0)'}), '(right_line.recent_fit, axis=0)\n', (11337, 11368), True, 'import numpy as np\n'), ((13813, 13840), 'numpy.polyfit', 'np.polyfit', (['lefty', 'leftx', '(2)'], {}), '(lefty, leftx, 2)\n', (13823, 13840), True, 'import numpy as np\n'), ((14203, 14240), 'numpy.mean', 'np.mean', (['left_line.recent_fit'], {'axis': '(0)'}), '(left_line.recent_fit, axis=0)\n', (14210, 14240), True, 'import numpy as np\n'), ((14618, 14647), 'numpy.polyfit', 'np.polyfit', (['righty', 'rightx', '(2)'], {}), '(righty, rightx, 2)\n', (14628, 14647), True, 'import numpy as np\n'), ((15024, 15062), 'numpy.mean', 'np.mean', (['right_line.recent_fit'], {'axis': '(0)'}), '(right_line.recent_fit, axis=0)\n', (15031, 15062), True, 'import numpy as np\n'), ((15738, 15794), 'numpy.dstack', 'np.dstack', (['(binary_warped, binary_warped, binary_warped)'], {}), '((binary_warped, binary_warped, binary_warped))\n', (15747, 15794), True, 'import numpy as np\n'), ((16849, 16877), 'numpy.absolute', 'np.absolute', (['(2 * left_fit[0])'], {}), '(2 * left_fit[0])\n', (16860, 16877), True, 'import numpy as np\n'), ((16964, 16993), 'numpy.absolute', 'np.absolute', (['(2 * right_fit[0])'], {}), '(2 * right_fit[0])\n', (16975, 16993), True, 'import numpy as np\n'), ((17564, 17595), 'numpy.absolute', 'np.absolute', (['(2 * left_fit_cr[0])'], {}), '(2 * left_fit_cr[0])\n', (17575, 17595), True, 'import numpy as np\n'), ((17710, 17742), 'numpy.absolute', 'np.absolute', (['(2 * right_fit_cr[0])'], {}), '(2 * right_fit_cr[0])\n', (17721, 17742), True, 'import numpy as np\n'), ((17772, 17812), 'numpy.mean', 'np.mean', (['[left_curverad, right_curverad]'], {}), '([left_curverad, right_curverad])\n', (17779, 17812), True, 'import numpy as np\n'), ((19536, 19550), 'numpy.int_', 'np.int_', (['[pts]'], {}), '([pts])\n', (19543, 19550), True, 'import numpy as np\n'), ((20679, 20715), 'os.path.join', 'os.path.join', (['test_img_dir', 'test_img'], {}), '(test_img_dir, test_img)\n', (20691, 20715), False, 'import os\n'), ((20827, 20870), 'cv2.cvtColor', 'cv2.cvtColor', (['blend'], {'code': 'cv2.COLOR_BGR2RGB'}), '(blend, code=cv2.COLOR_BGR2RGB)\n', (20839, 20870), False, 'import cv2\n'), ((1376, 1440), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['image', '(9, 6)', 'corners', 'pattern_found'], {}), '(image, (9, 6), corners, pattern_found)\n', (1401, 1440), False, 'import cv2\n'), ((1453, 1475), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (1463, 1475), False, 'import cv2\n'), ((1488, 1504), 'cv2.waitKey', 'cv2.waitKey', (['(500)'], {}), '(500)\n', (1499, 1504), False, 'import cv2\n'), ((2100, 2117), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (2108, 2117), True, 'import numpy as np\n'), ((2888, 2905), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (2896, 2905), True, 'import numpy as np\n'), ((3719, 3755), 'cv2.cvtColor', 'cv2.cvtColor', (['dst', 'cv2.COLOR_RGB2HLS'], {}), '(dst, cv2.COLOR_RGB2HLS)\n', (3731, 3755), False, 'import cv2\n'), ((4087, 4105), 'numpy.max', 'np.max', (['abs_sobelx'], {}), '(abs_sobelx)\n', (4093, 4105), True, 'import numpy as np\n'), ((19083, 19111), 'numpy.zeros_like', 'np.zeros_like', (['binary_warped'], {}), '(binary_warped)\n', (19096, 19111), True, 'import numpy as np\n'), ((9352, 9385), 'numpy.mean', 'np.mean', (['nonzerox[good_left_inds]'], {}), '(nonzerox[good_left_inds])\n', (9359, 9385), True, 'import numpy as np\n'), ((9465, 9499), 'numpy.mean', 'np.mean', (['nonzerox[good_right_inds]'], {}), '(nonzerox[good_right_inds])\n', (9472, 9499), True, 'import numpy as np\n'), ((16226, 16263), 'numpy.vstack', 'np.vstack', (['[fit_leftx - margin, fity]'], {}), '([fit_leftx - margin, fity])\n', (16235, 16263), True, 'import numpy as np\n'), ((16484, 16522), 'numpy.vstack', 'np.vstack', (['[fit_rightx - margin, fity]'], {}), '([fit_rightx - margin, fity])\n', (16493, 16522), True, 'import numpy as np\n'), ((19300, 19328), 'numpy.vstack', 'np.vstack', (['[fit_leftx, fity]'], {}), '([fit_leftx, fity])\n', (19309, 19328), True, 'import numpy as np\n'), ((16324, 16361), 'numpy.vstack', 'np.vstack', (['[fit_leftx + margin, fity]'], {}), '([fit_leftx + margin, fity])\n', (16333, 16361), True, 'import numpy as np\n'), ((16584, 16622), 'numpy.vstack', 'np.vstack', (['[fit_rightx + margin, fity]'], {}), '([fit_rightx + margin, fity])\n', (16593, 16622), True, 'import numpy as np\n'), ((19381, 19410), 'numpy.vstack', 'np.vstack', (['[fit_rightx, fity]'], {}), '([fit_rightx, fity])\n', (19390, 19410), True, 'import numpy as np\n')]
# --------------------------------------------------------------------------------- # QKeithleySweep -> QVisaApplication # Copyright (C) 2019 <NAME> # github: https://github.com/mesoic # email: <EMAIL> # --------------------------------------------------------------------------------- # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # #!/usr/bin/env python import os import sys import time import threading # Import numpy import numpy as np # Import QVisaApplication from PyQtVisa import QVisaApplication # Import PyQtVisa widgets from PyQtVisa.widgets import QVisaUnitSelector from PyQtVisa.widgets import QVisaDynamicPlot # Import QT backends from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy from PyQt5.QtCore import Qt, QStateMachine, QState, QObject from PyQt5.QtCore import Qt, QStateMachine, QState, QObject from PyQt5.QtGui import QIcon # Container class to construct sweep measurement widget class QKeithleySweep(QVisaApplication.QVisaApplication): def __init__(self, _config): # Inherits QVisaApplication -> QWidget super(QKeithleySweep, self).__init__(_config) # Generate Main Layout self.gen_main_layout() ##################################### # APPLICATION HELPER METHODS # # Wrapper method to get keitley write handle # Returns the pyVisaDevice object def keithley(self, __widget__): return self.get_device_by_name( __widget__.currentText() ) # Method to refresh the widget def refresh(self): # If add insturments have been initialized if self.get_devices() is not None: # Reset the widget and add insturments self.sweep_inst.refresh( self ) self.step_inst.refresh( self ) # Plot control widgets self.plot_x_inst.refresh( self ) self.plot_y_inst.refresh( self ) # Update sweep parameters and enable output button self.meas_button.setEnabled(True) self.update_meas_params() else: # Disable output button self.meas_button.setEnabled(False) # Method to set sweep parameters def set_sweep_params(self, start, stop, npts): # No hysteresis if self.sweep_hist.currentText() == "None": sp = np.linspace(float(start), float(stop), int(npts) ) self._set_app_metadata("__sweep__", sp) # Prepare reverse sweep if self.sweep_hist.currentText() == "Reverse-sweep": # Sweep centered hysteresis sp = np.linspace(float(start), float(stop), int(npts) ) sp = np.concatenate( (sp, sp[-2::-1]) ) self._set_app_metadata("__sweep__", sp) # Prepare a zero centered hysteresis if self.sweep_hist.currentText() == "Zero-centered": # Create a linspace sp = np.linspace(float(start), float(stop), int(npts) ) # Extract positive slice pos = np.where(sp > 0, sp, np.nan) pos = pos[~np.isnan(pos)] # Extract negative slice neg = np.where(sp < 0, sp, np.nan) neg = neg[~np.isnan(neg)] # Create the zero centered hysteresis re-insert zeros # Forward sweep, zero crossing if (start < 0.) and (stop > 0.) and (start < stop): sp = np.concatenate( ([0.0], pos, pos[-2::-1], [0.0], neg[::-1], neg[1::], [0.0]) ) # Reverse sweep, zero crossing elif (start > 0.) and (stop < 0.) and (start > stop): sp = np.concatenate( ([0.0], neg, neg[-2::-1], [0.0], pos[::-1], pos[1::], [0.0]) ) print(sp) # If not zero crossing, default to "Reverse-sweep" case else: sp = np.concatenate( (sp, sp[-2::-1]) ) # Set meta field self._set_app_metadata( "__sweep__", sp) # Method to set step parameters def set_step_params(self, start, stop, npts): # No hysteresis sp = np.linspace(float(start), float(stop), int(npts) ) self._set_app_metadata("__step__", sp) ##################################### # MAIN LAYOUT # def gen_main_layout(self): # Create Icon for QMessageBox self._set_icon( QIcon(os.path.join(os.path.dirname(os.path.realpath(__file__)), "python.ico"))) # Create layout objects and set layout self.layout = QHBoxLayout() self.layout.addWidget(self.gen_main_ctrl(), 1) self.layout.addWidget(self.gen_main_plot(), 3) self.setLayout(self.layout) ##################################### # MAIN LAYOUT # # Main controls: # a) Measure button and state machine # b) V-Step mode on/off state machine # c) IV-sweep and V-step configure pages # d) Save button def gen_main_ctrl(self): # Main control widget self.meas_ctrl = QWidget() self.meas_ctrl_layout = QVBoxLayout() ##################################### # MEASURE STATE MACHINE AND BUTTON # # Measurement Button. This will be a state machine which # alternates between 'measure' and 'abort' states self.meas_state = QStateMachine() self.meas_button = QPushButton() self.meas_button.setStyleSheet( "background-color: #dddddd; border-style: solid; border-width: 1px; border-color: #aaaaaa; padding: 7px;" ) # Create measurement states self.meas_run = QState() self.meas_stop = QState() # Assign state properties and transitions self.meas_run.assignProperty(self.meas_button, 'text', 'Abort Sweep') self.meas_run.addTransition(self.meas_button.clicked, self.meas_stop) self.meas_run.entered.connect(self.exec_meas_run) self.meas_stop.assignProperty(self.meas_button, 'text', 'Measure Sweep') self.meas_stop.addTransition(self.meas_button.clicked, self.meas_run) self.meas_stop.entered.connect(self.exec_meas_stop) # Add states, set initial state, and state machine self.meas_state.addState(self.meas_run) self.meas_state.addState(self.meas_stop) self.meas_state.setInitialState(self.meas_stop) self.meas_state.start() # Meas pages self.meas_pages = QStackedWidget() self.meas_pages.addWidget(self.gen_sweep_ctrl()) self.meas_pages.addWidget(self.gen_step_ctrl()) self.meas_pages.addWidget(self.gen_plot_ctrl()) # Meta widget for trace description self.meta_widget_label = QLabel("<b>Trace Description</b>") self.meta_widget = self._gen_meta_widget() self.meta_widget.set_meta_subkey("__desc__") # Save widget self.save_widget = self._gen_save_widget() # Pack widgets into layout self.meas_ctrl_layout.addWidget(self.meas_button) self.meas_ctrl_layout.addWidget(self.gen_config_ctrl()) self.meas_ctrl_layout.addWidget(self.meas_pages) # Add save widget self.meas_ctrl_layout.addStretch(1) self.meas_ctrl_layout.addWidget(self.meta_widget_label) self.meas_ctrl_layout.addWidget(self.meta_widget) self.meas_ctrl_layout.addWidget(self.save_widget) # Set layout and return widget reference self.meas_ctrl.setLayout(self.meas_ctrl_layout) return self.meas_ctrl ##################################### # CONFIGURE WIDGET # def gen_config_ctrl(self): self.meas_config = QWidget() self.meas_config_layout = QVBoxLayout() # Current/Voltage Sweep Mode self.meas_config_page_label = QLabel("<b>Configure Parameters</b>") self.meas_config_page = QComboBox() self.meas_config_page.setFixedWidth(200) self.meas_config_page.addItems(["IV-sweep", "IV-step", "IV-plot"]) self.meas_config_page.currentTextChanged.connect(self.update_config_page) # Add some space for layout clarity self.meas_config_layout.setContentsMargins(0,10,0,10) self.meas_config_layout.addWidget(self._gen_vbox_widget([self.meas_config_page_label, self.meas_config_page])) # Pack config layout and return reference self.meas_config.setLayout(self.meas_config_layout) return self.meas_config # Sweep control layout def gen_sweep_ctrl(self): self.sweep_ctrl = QWidget() self.sweep_ctrl_layout = QVBoxLayout() # Main control label self.sweep_ctrl_label = QLabel("<b>IV-sweep Parameters</b>") ##################################### # SWEEP INST SELECT # # Insturement selector and save widget self.sweep_inst_label = QLabel("Select Device") self.sweep_inst = self._gen_device_select() self.sweep_inst.setFixedWidth(200) ##################################### # SWEEP MEASUREMENT CONFIGURATION # # Current/Voltage Sweep Mode self.sweep_src_label = QLabel("Sweep Type") self.sweep_src = QComboBox() self.sweep_src.setFixedWidth(200) self.sweep_src.addItems(["Voltage", "Current"]) self.sweep_src.currentTextChanged.connect(self.update_sweep_ctrl) # Generate voltage and current source widgets self.gen_voltage_sweep() # self.voltage_sweep self.gen_current_sweep() # self.current_sweep # Add to stacked widget self.sweep_pages = QStackedWidget() self.sweep_pages.addWidget(self.voltage_sweep) self.sweep_pages.addWidget(self.current_sweep) self.sweep_pages.setCurrentIndex(0) # Hysteresis mode self.sweep_hist_label = QLabel("Hysteresis Mode") self.sweep_hist = QComboBox() self.sweep_hist.setFixedWidth(200) self.sweep_hist.addItems(["None", "Reverse-sweep", "Zero-centered"]) ##################################### # ADD CONTROLS # # Sweep configuration controls self.sweep_ctrl_layout.addWidget(self.sweep_ctrl_label) self.sweep_ctrl_layout.addWidget(self._gen_hbox_widget([self.sweep_inst,self.sweep_inst_label])) self.sweep_ctrl_layout.addWidget(self._gen_hbox_widget([self.sweep_src, self.sweep_src_label])) self.sweep_ctrl_layout.addWidget(self._gen_hbox_widget([self.sweep_hist, self.sweep_hist_label])) self.sweep_ctrl_layout.addWidget(self.sweep_pages) # Positioning self.sweep_ctrl.setLayout(self.sweep_ctrl_layout) return self.sweep_ctrl # Step control layout def gen_step_ctrl(self): self.step_ctrl = QWidget() self.step_ctrl_layout = QVBoxLayout() # Step control label self.step_ctrl_label = QLabel("<b>V-step Parameters</b>") # Voltage step instruement selector self.step_inst_label = QLabel("Select Device") self.step_inst = self._gen_device_select() self.step_inst.setFixedWidth(200) # Step control mode selector self.step_src_label = QLabel("Step Type") self.step_src = QComboBox() self.step_src.setFixedWidth(200) self.step_src.addItems(["Voltage", "Current"]) self.step_src.currentTextChanged.connect(self.update_step_ctrl) # Generate voltage and current source widgets self.gen_voltage_step() # self.voltage_step self.gen_current_step() # self.current_step # Add step modes to step_pages widget self.step_pages = QStackedWidget() self.step_pages.addWidget(self.voltage_step) self.step_pages.addWidget(self.current_step) self.step_pages.setCurrentIndex(0) # Step control state machine self.step_state = QStateMachine() self.step_button = QPushButton() self.step_button.setStyleSheet( "background-color: #dddddd; border-style: solid; border-width: 1px; border-color: #aaaaaa; padding: 7px;" ) # Create measurement states self.step_on = QState() self.step_off = QState() # Assign state properties and transitions self.step_on.assignProperty(self.step_button, 'text', 'Step Bias ON') self.step_on.addTransition(self.step_button.clicked, self.step_off) self.step_on.entered.connect(self.exec_step_on) self.step_off.assignProperty(self.step_button, 'text', 'Step Bias OFF') self.step_off.addTransition(self.step_button.clicked, self.step_on) self.step_off.entered.connect(self.exec_step_off) # Add states, set initial state, and state machine self.step_state.addState(self.step_on) self.step_state.addState(self.step_off) self.step_state.setInitialState(self.step_off) self.step_state.start() # Pack widgets self.step_ctrl_layout.addWidget(self.step_ctrl_label) self.step_ctrl_layout.addWidget(self._gen_hbox_widget([self.step_inst,self.step_inst_label])) self.step_ctrl_layout.addWidget(self._gen_hbox_widget([self.step_src, self.step_src_label])) self.step_ctrl_layout.addWidget(self.step_pages) self.step_ctrl_layout.addWidget(self.step_button) self.step_ctrl_layout.addStretch(1) # Set layout and return reference self.step_ctrl.setLayout(self.step_ctrl_layout) return self.step_ctrl # Plot control layout def gen_plot_ctrl(self): self.plot_ctrl = QWidget() self.plot_ctrl_layout = QVBoxLayout() # Voltage step instruement selector self.plot_x_inst_label = QLabel("<b>Configure x-axis</b>") self.plot_x_inst = self._gen_device_select() self.plot_x_inst.setFixedWidth(200) self.plot_x_inst.set_callback("update_plot_ctrl") self.plot_x_data = QComboBox() self.plot_x_data.setFixedWidth(100) self.plot_x_data.addItems(["Voltage", "Current"]) self.plot_x_data.currentTextChanged.connect( self.update_plot_ctrl ) # Voltage step instruement selector self.plot_y_inst_label = QLabel("<b>Configure y-axis</b>") self.plot_y_inst = self._gen_device_select() self.plot_y_inst.setFixedWidth(200) self.plot_y_inst.set_callback("update_plot_ctrl") self.plot_y_data = QComboBox() self.plot_y_data.setFixedWidth(100) self.plot_y_data.addItems(["Voltage", "Current"]) self.plot_y_data.setCurrentIndex(1) self.plot_y_data.currentTextChanged.connect( self.update_plot_ctrl ) # Add widgets self.plot_ctrl_layout.addWidget( self.plot_x_inst_label ) self.plot_ctrl_layout.addWidget( self._gen_hbox_widget( [self.plot_x_inst,self.plot_x_data]) ) self.plot_ctrl_layout.addWidget( self.plot_y_inst_label ) self.plot_ctrl_layout.addWidget( self._gen_hbox_widget( [self.plot_y_inst,self.plot_y_data]) ) self.plot_ctrl_layout.addStretch(1) # Set layout and return reference self.plot_ctrl.setLayout(self.plot_ctrl_layout) return self.plot_ctrl # Generate voltage sweep widget def gen_voltage_sweep(self): # New QWidget self.voltage_sweep = QWidget() self.voltage_sweep_layout = QVBoxLayout() # Sweep Start self.voltage_sweep_start_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Sweep Start (V)", "signed" : True, "limit" : [20.0, ""], "default" : [0.00, ""] } self.voltage_sweep_start = QVisaUnitSelector.QVisaUnitSelector(self.voltage_sweep_start_config) # Sweep Stop self.voltage_sweep_stop_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Sweep Stop (V)", "signed" : True, "limit" : [20.0, ""], "default" : [1.00, ""] } self.voltage_sweep_stop = QVisaUnitSelector.QVisaUnitSelector(self.voltage_sweep_stop_config) # Compliance Spinbox self.voltage_sweep_cmpl_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Compliance (A)", "signed" : False, "limit" : [1.0, "" ], "default" : [150, "m"] } self.voltage_sweep_cmpl = QVisaUnitSelector.QVisaUnitSelector(self.voltage_sweep_cmpl_config) # Number of points self.voltage_sweep_npts_config={ "unit" : "__INT__", "label" : "Number of Points", "signed" : False, "limit" : [512], "default" : [51] } self.voltage_sweep_npts = QVisaUnitSelector.QVisaUnitSelector(self.voltage_sweep_npts_config) # Measurement Delay self.voltage_sweep_delay_config={ "unit" : "__DOUBLE__", "label" : "Measurement Interval (s)", "signed" : False, "limit" : [60.0], "default" : [0.10] } self.voltage_sweep_delay = QVisaUnitSelector.QVisaUnitSelector(self.voltage_sweep_delay_config) # Pack selectors into layout self.voltage_sweep_layout.addWidget(self.voltage_sweep_start) self.voltage_sweep_layout.addWidget(self.voltage_sweep_stop) self.voltage_sweep_layout.addWidget(self.voltage_sweep_cmpl) self.voltage_sweep_layout.addWidget(self.voltage_sweep_npts) self.voltage_sweep_layout.addWidget(self.voltage_sweep_delay) self.voltage_sweep_layout.setContentsMargins(0,0,0,0) # Set layout self.voltage_sweep.setLayout(self.voltage_sweep_layout) # Generate current sweep widget def gen_current_sweep(self): # New QWidget self.current_sweep = QWidget() self.current_sweep_layout = QVBoxLayout() # Sweep Start self.current_sweep_start_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Sweep Start (A)", "signed" : True, "limit" : [1.0, "" ], "default" : [0.0, "m"] } self.current_sweep_start = QVisaUnitSelector.QVisaUnitSelector(self.current_sweep_start_config) # Sweep Stop self.current_sweep_stop_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Sweep Stop (A)", "signed" : True, "limit" : [1.0, "" ], "default" : [100, "m"] } self.current_sweep_stop = QVisaUnitSelector.QVisaUnitSelector(self.current_sweep_stop_config) # Compliance Spinbox self.current_sweep_cmpl_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Compliance (V)", "signed" : False, "limit" : [20., ""], "default" : [1.0, ""] } self.current_sweep_cmpl = QVisaUnitSelector.QVisaUnitSelector(self.current_sweep_cmpl_config) # Number of points self.current_sweep_npts_config={ "unit" : "__INT__", "label" : "Number of Points", "signed" : False, "limit" : [256], "default" : [11] } self.current_sweep_npts = QVisaUnitSelector.QVisaUnitSelector(self.current_sweep_npts_config) # Measurement Delay self.current_sweep_delay_config={ "unit" : "__DOUBLE__", "label" : "Measurement Interval (s)", "signed" : False, "limit" : [60.0], "default" : [0.1] } self.current_sweep_delay = QVisaUnitSelector.QVisaUnitSelector(self.current_sweep_delay_config) # Pack selectors into layout self.current_sweep_layout.addWidget(self.current_sweep_start) self.current_sweep_layout.addWidget(self.current_sweep_stop) self.current_sweep_layout.addWidget(self.current_sweep_cmpl) self.current_sweep_layout.addWidget(self.current_sweep_npts) self.current_sweep_layout.addWidget(self.current_sweep_delay) self.current_sweep_layout.setContentsMargins(0,0,0,0) # Set layout self.current_sweep.setLayout(self.current_sweep_layout) # Generate voltage step widget def gen_voltage_step(self): # New QWidget self.voltage_step= QWidget() self.voltage_step_layout = QVBoxLayout() # Step Start self.voltage_step_start_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Step Start (V)", "signed" : True, "limit" : [20.0, ""], "default" : [0.00, ""] } self.voltage_step_start = QVisaUnitSelector.QVisaUnitSelector(self.voltage_step_start_config) # Step Stop self.voltage_step_stop_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Step Stop (V)", "signed" : True, "limit" : [20.0, ""], "default" : [1.00, ""] } self.voltage_step_stop = QVisaUnitSelector.QVisaUnitSelector(self.voltage_step_stop_config) # Step Compliance Spinbox self.voltage_step_cmpl_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Compliance (A)", "signed" : False, "limit" : [1.0, "" ], "default" : [150, "m"] } self.voltage_step_cmpl = QVisaUnitSelector.QVisaUnitSelector(self.voltage_step_cmpl_config) # Step Number of points self.voltage_step_npts_config={ "unit" : "__INT__", "label" : "Number of Points", "signed" : False, "limit" : [256], "default" : [5] } self.voltage_step_npts = QVisaUnitSelector.QVisaUnitSelector(self.voltage_step_npts_config) # Pack selectors into layout self.voltage_step_layout.addWidget(self.voltage_step_start) self.voltage_step_layout.addWidget(self.voltage_step_stop) self.voltage_step_layout.addWidget(self.voltage_step_cmpl) self.voltage_step_layout.addWidget(self.voltage_step_npts) self.voltage_step_layout.setContentsMargins(0,0,0,0) # Set layout self.voltage_step.setLayout(self.voltage_step_layout) # Generate current step widget def gen_current_step(self): # New QWidget self.current_step = QWidget() self.current_step_layout = QVBoxLayout() # Step Start self.current_step_start_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Step Start (A)", "signed" : True, "limit" : [1.0, "" ], "default" : [0.0, "m"] } self.current_step_start = QVisaUnitSelector.QVisaUnitSelector(self.current_step_start_config) # Step Stop self.current_step_stop_config={ "unit" : "A", "min" : "u", "max" : "", "label" : "Step Stop (A)", "signed" : True, "limit" : [1.0, "" ], "default" : [1.0, "m"] } self.current_step_stop = QVisaUnitSelector.QVisaUnitSelector(self.current_step_stop_config) # Step Compliance Spinbox self.current_step_cmpl_config={ "unit" : "V", "min" : "u", "max" : "", "label" : "Compliance (V)", "signed" : False, "limit" : [20.0, ""], "default" : [1.00, ""] } self.current_step_cmpl = QVisaUnitSelector.QVisaUnitSelector(self.current_step_cmpl_config) # Step Number of points self.current_step_npts_config={ "unit" : "__INT__", "label" : "Number of Points", "signed" : False, "limit" : [256], "default" : [5] } self.current_step_npts = QVisaUnitSelector.QVisaUnitSelector(self.current_step_npts_config) # Pack selectors into layout self.current_step_layout.addWidget(self.current_step_start) self.current_step_layout.addWidget(self.current_step_stop) self.current_step_layout.addWidget(self.current_step_cmpl) self.current_step_layout.addWidget(self.current_step_npts) self.current_step_layout.addStretch(1) self.current_step_layout.setContentsMargins(0,0,0,0) # Set layout self.current_step.setLayout(self.current_step_layout) # Ádd dynamic plot def gen_main_plot(self): # Create QVisaDynamicPlot object (inherits QWidget) self.plot = QVisaDynamicPlot.QVisaDynamicPlot(self) self.plot.add_subplot(111) self.plot.add_origin_lines("111", "both") self.plot.set_axes_labels("111", "Voltage (V)", "Current (A)") # Refresh canvas self.plot.refresh_canvas(supress_warning=True) # Sync plot clear data button with application data self.plot.sync_application_data(True) # Sync meta widget when clearing data self.plot.set_mpl_refresh_callback("_sync_meta_widget_to_data_object") # Return the plot return self.plot # Sync meta widget def _sync_meta_widget_to_data_object(self): # Application keys _data_keys = self._get_data_object().keys() _widget_keys = self.meta_widget.get_meta_keys() # Check if widget keys are not in data keys for _key in _widget_keys: # If not then delete the key from meta_widget if _key not in _data_keys: self.meta_widget.del_meta_key(_key) ##################################### # UPDATE CONFIG PAGE # def update_config_page(self): if self.meas_config_page.currentText() == "IV-sweep": self.meas_pages.setCurrentIndex(0) if self.meas_config_page.currentText() == "IV-step": self.meas_pages.setCurrentIndex(1) if self.meas_config_page.currentText() == "IV-plot": self.meas_pages.setCurrentIndex(2) ##################################### # SWEEP CONTROL UPDATE METHODS # # Sweep control dynamic update def update_sweep_ctrl(self): # Switch to voltage sweep page if self.sweep_src.currentText() == "Voltage": self.sweep_pages.setCurrentIndex(0) self.update_meas_params() # Switch to current sweep page if self.sweep_src.currentText() == "Current": self.sweep_pages.setCurrentIndex(1) self.update_meas_params() # Sweep control dynamic update def update_step_ctrl(self): # Switch to voltage sweep page if self.step_src.currentText() == "Voltage": self.step_pages.setCurrentIndex(0) self.update_meas_params() # Switch to current sweep page if self.step_src.currentText() == "Current": self.step_pages.setCurrentIndex(1) self.update_meas_params() # Update plot axes when we change configuration def update_plot_ctrl(self): # Extract correct unit labels x_unit = "(V)" if self.plot_x_data.currentText() == "Voltage" else "(A)" y_unit = "(V)" if self.plot_y_data.currentText() == "Voltage" else "(A)" # Update axes self.plot.set_axes_labels("111", "%s %s : %s"%(self.plot_x_data.currentText(), x_unit ,self.plot_x_inst.currentText()), "%s %s : %s"%(self.plot_y_data.currentText(), y_unit ,self.plot_y_inst.currentText()) ) self.plot.update_canvas() # Create Measurement def update_meas_params(self): # Set up v-source(i-compliance) on keithley if self.sweep_src.currentText() == "Voltage": # Set sweeep paramaters self.set_sweep_params( self.voltage_sweep_start.value(), self.voltage_sweep_stop.value(), self.voltage_sweep_npts.value()) # Set keithley as voltage source if self.keithley(self.sweep_inst) is not None: self.keithley(self.sweep_inst).voltage_src() self.keithley(self.sweep_inst).set_voltage(0.0) self.keithley(self.sweep_inst).current_cmp(self.voltage_sweep_cmpl.value()) # Set up i-source(v-compliance) on keithley if self.sweep_src.currentText() == "Current": # Set sweeep paramaters self.set_sweep_params( self.current_sweep_start.value(), self.current_sweep_stop.value(), self.current_sweep_npts.value()) # Set keithley as voltage source if self.keithley(self.sweep_inst) is not None: self.keithley(self.sweep_inst).current_src() self.keithley(self.sweep_inst).set_current(0.0) self.keithley(self.sweep_inst).voltage_cmp(self.current_sweep_cmpl.value()) # Set step keithley as voltage source. Also ensure that we are not initializing # the the sweep keithely with step params if doubly selected. if ( ( self.keithley(self.step_inst) is not None) and (self.keithley(self.step_inst) != self.keithley(self.sweep_inst) ) ): # Set up v-source(i-compliance) on keithley if self.step_src.currentText() == "Voltage": # Set sweeep paramaters self.set_step_params( self.voltage_step_start.value(), self.voltage_step_stop.value(), self.voltage_step_npts.value()) # Set keithley as voltage source if self.keithley(self.step_inst) is not None: self.keithley(self.step_inst).voltage_src() self.keithley(self.step_inst).set_voltage(0.0) self.keithley(self.step_inst).current_cmp(self.voltage_step_cmpl.value()) # Set up i-source(v-compliance) on keithley if self.step_src.currentText() == "Current": # Set sweeep paramaters self.set_step_params( self.current_step_start.value(), self.current_step_stop.value(), self.current_step_npts.value()) # Set keithley as voltage source if self.keithley(self.step_inst) is not None: self.keithley(self.step_inst).current_src() self.keithley(self.step_inst).set_current(0.0) self.keithley(self.step_inst).voltage_cmp(self.current_step_cmpl.value()) ##################################### # MEASUREMENT EXECUTION THREADS # # Function we run when we enter run state def exec_step_on(self): # Update UI button to abort self.step_button.setStyleSheet( "background-color: #cce6ff; border-style: solid; border-width: 1px; border-color: #1a75ff; padding: 7px;") # Check if no insturments are initialized if self.sweep_inst.currentText() == "" and self.step_inst.currentText() == "": # Message box to warn the user msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("No devices initialized") msg.setWindowTitle("QKeithleySweep") msg.setWindowIcon(self._icon) msg.setStandardButtons(QMessageBox.Ok) msg.exec_() # Set app meta and revert state self._set_app_metadata("__exec_step__", False) self.step_button.click() # Check if the same insturment is initialized elif self.sweep_inst.currentText() == self.step_inst.currentText(): # Message box to warn the user msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("Same device %s selected for sweep and step parameters. Proceed?"%self.step_inst.currentText()) msg.setWindowTitle("QKeithleySweep") msg.setWindowIcon(self._icon) msg.setStandardButtons(QMessageBox.Ok) msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) self.msg_clear = msg.exec_() # Expose this for testing if self.msg_clear == QMessageBox.Yes: self._set_app_metadata("__exec_step__", True) else: self._set_app_metadata("__exec_step__", False) self.step_button.click() else: self._set_app_metadata("__exec_step__", True) # Function we run when we enter run state def exec_step_off(self): # Update UI button to abort self.step_button.setStyleSheet( "background-color: #dddddd; border-style: solid; border-width: 1px; border-color: #aaaaaa; padding: 7px;" ) self._set_app_metadata("__exec_step__", False) # Execute Sweep-Step Measurement def exec_sweep_step_thread(self): # Generate function pointer for sweep voltage/current mode if self.sweep_src.currentText() == "Voltage": __sweep_func__ = self.keithley(self.sweep_inst).set_voltage __sweep_delay__ = self.voltage_sweep_delay.value() if self.sweep_src.currentText() == "Current": __sweep_func__ = self.keithley(self.sweep_inst).set_current __sweep_delay__ = self.current_sweep_delay.value() # Clear plot and zero arrays start = time.time() # Use generator function so all traces have same color _c = self.plot.gen_next_color() _handle_index = 0 # Get data object data = self._get_data_object() # Master key _root = data.add_hash_key("iv-sweep-v-step") # Set metatata for root if self.step_src.currentText() == "Voltage": data.set_metadata(_root, "__type__", "iv-sweep-v-step") if self.step_src.currentText() == "Current": data.set_metadata(_root, "__type__", "iv-sweep-v-step") # Add key to meta widget self.meta_widget.add_meta_key(_root) # Create internal data structure for buffers buffers = { "__sweep__" : {"inst" : self.sweep_inst, "data" : None}, "__step__" : {"inst" : self.step_inst , "data" : None}, "__plotx__" : None, "__ploty__" : None } # plot-axis insturments for plot_key, plot_inst in zip(["__plotx__", "__ploty__" ], [ self.plot_x_inst, self.plot_y_inst] ): if self.sweep_inst.currentText() == plot_inst.currentText(): buffers[ plot_key ] = {"inst" : "__sweep__", "data" : None } elif self.step_inst.currentText() == plot_inst.currentText(): buffers[ plot_key ] = {"inst" : "__step__", "data" : None } else: buffers[ plot_key ] = {"inst" : plot_inst, "data" : None} # Loop throgh all insurments and enable outputs for _key, _buffer in buffers.items(): if _buffer["inst"] not in ["__sweep__", "__step__"]: self.keithley( _buffer["inst"] ).output_on() # Loop through step variables and generate subkeys for _step in self._get_app_metadata("__step__"): # If thread is running if self.thread_running: # A hash is generated for each voltage/current step for ease of data processing # Generate function pointer for step voltage/current mode if self.step_src.currentText() == "Voltage": __step_func__ = self.keithley(self.step_inst).set_voltage # Generate data key and set metadata data = self._get_data_object() key = data.add_hash_key("iv-sweep-v-step%s"%_step) # Add keys and metadata to data object data.set_metadata(key, "__root__", _root) data.set_metadata(key, "__step__", _step) data.set_subkeys(key, ["t", "V0", "I0", "P0", "V1", "I1", "P1"]) # Current Mode if self.step_src.currentText() == "Current": __step_func__ = self.keithley(self.step_inst).set_current key = data.add_hash_key("iv-sweep-i-step%s"%_step) # Add keys and metadata to data object data.set_metadata(key, "__root__", _root) data.set_metadata(key, "__step__", _step) data.set_subkeys(key, ["t", "V0", "I0", "P0", "V1", "I1", "P1"]) # Set step voltage/current __step_func__(_step) # Add axes handle to root self.plot.add_axes_handle("111", _root, _color=_c) # Bias settle if __sweep_delay__ != 0: time.sleep(__sweep_delay__) # Loop through sweep variables for _bias in self._get_app_metadata("__sweep__"): # If thread is running if self.thread_running: # Set voltage/current bias __sweep_func__(_bias) # Get data from buffer # Populate buffers buffers["__sweep__"]["data"] = self.keithley( buffers["__sweep__"]["inst"] ).meas().split(",") buffers["__step__"]["data"] = self.keithley( buffers["__step__"]["inst"] ).meas().split(",") # Plot insturments will copy sweep data or meas() if needed for plot_buffer in ["__plotx__", "__ploty__"]: if buffers[plot_buffer]["inst"] == "__sweep__": buffers[plot_buffer]["data"] = buffers["__sweep__"]["data"] elif buffers[plot_buffer]["inst"] == "__step__": buffers[plot_buffer]["data"] = buffers["__step__"]["data"] else: buffers[plot_buffer]["data"] = self.keithley( buffers[plot_buffer]["inst"] ).meas().split(",") # Apply delay if __sweep_delay__ != 0: time.sleep(__sweep_delay__) # Extract data from buffer _now = float(time.time() - start) # Append measured values to data arrays data.append_subkey_data(key,"t", _now ) data.append_subkey_data(key,"V0", float( buffers["__sweep__"]["data"][0]) ) data.append_subkey_data(key,"I0", float( buffers["__sweep__"]["data"][1]) ) data.append_subkey_data(key,"P0", float( buffers["__sweep__"]["data"][0]) * float(buffers["__sweep__"]["data"][1]) ) data.append_subkey_data(key,"V1", float( buffers["__step__"]["data"][0]) ) data.append_subkey_data(key,"I1", float( buffers["__step__"]["data"][1]) ) data.append_subkey_data(key,"P1", float( buffers["__step__"]["data"][0]) * float(buffers["__step__"]["data"][1]) ) # Sync x-axis data if self.plot_x_data.currentText() == "Voltage": p0 = buffers["__plotx__"]["data"][0] if self.plot_x_data.currentText() == "Current": p0 = buffers["__plotx__"]["data"][1] # Sync y-axis data if self.plot_y_data.currentText() == "Voltage": p1 = buffers["__ploty__"]["data"][0] if self.plot_y_data.currentText() == "Current": p1 = buffers["__ploty__"]["data"][1] # Update the data self.plot.append_handle_data("111", _root, float(p0), float(p1), _handle_index) self.plot.update_canvas() else: break # Increment handle index _handle_index += 1 else: break # Reset active keithleys __sweep_func__(0.0) __step_func__(0.0) # Loop throgh all insurments and disable outputs for _key, _buffer in buffers.items(): if _buffer["inst"] not in ["__sweep__", "__step__"]: self.keithley( _buffer["inst"] ).output_off() # Reset sweep control and update measurement state to stop. # Post a button click event to the QStateMachine to trigger # a state transition if thread is still running (not aborted) if self.thread_running: self.meas_button.click() # Execute Sweep Measurement def exec_sweep_thread(self): # Generate data key data = self._get_data_object() key = data.add_hash_key("iv-sweep") # Add data fields to key data.set_subkeys(key, ["t", "V", "I", "P"]) data.set_metadata(key, "__type__", "iv-sweep") # Add key to meta widget self.meta_widget.add_meta_key(key) # Generate function pointer for voltage/current mode if self.sweep_src.currentText() == "Voltage": __sweep_func__ = self.keithley(self.sweep_inst).set_voltage __sweep_delay__ = self.voltage_sweep_delay.value() if self.sweep_src.currentText() == "Current": __sweep_func__ = self.keithley(self.sweep_inst).set_current __sweep_delay__ = self.current_sweep_delay.value() # Clear plot and zero arrays handle = self.plot.add_axes_handle("111", key) start = time.time() # Create internal data structure for buffers buffers = { "__sweep__" : {"inst" : self.sweep_inst, "data" : None}, "__plotx__" : None, "__ploty__" : None } # x-axis insturment for plot_key, plot_inst in zip( ["__plotx__", "__ploty__" ], [self.plot_x_inst, self.plot_y_inst] ): if self.sweep_inst.currentText() == plot_inst.currentText(): buffers[plot_key] = {"inst" : "__sweep__", "data" : None } else: buffers[plot_key] = {"inst" : plot_inst, "data" : None} # Loop throgh all insurments and enable outputs for _key, _buffer in buffers.items(): if _buffer["inst"] not in ["__sweep__"]: self.keithley( _buffer["inst"] ).output_on() # Loop through sweep variables for _bias in self._get_app_metadata("__sweep__"): # If thread is running if self.thread_running: # Set voltage/current bias __sweep_func__(_bias) # Populate buffers buffers["__sweep__"]["data"] = self.keithley( buffers["__sweep__"]["inst"] ).meas().split(",") # Plot insturments will copy sweep data or meas() if needed for plot_buffer in ["__plotx__", "__ploty__"]: if buffers[plot_buffer]["inst"] == "__sweep__": buffers[plot_buffer]["data"] = buffers["__sweep__"]["data"] else: buffers[plot_buffer]["data"] = self.keithley( buffers[plot_buffer]["inst"] ).meas().split(",") if __sweep_delay__ != 0: time.sleep(__sweep_delay__) # Extract data from buffer _now = float(time.time() - start) # Append measured values to data arrays data.append_subkey_data(key,"t", _now ) data.append_subkey_data(key,"V", float( buffers["__sweep__"]["data"][0]) ) data.append_subkey_data(key,"I", float( buffers["__sweep__"]["data"][1]) ) data.append_subkey_data(key,"P", float( buffers["__sweep__"]["data"][0]) * float(buffers["__sweep__"]["data"][1]) ) # Sync x-axis data if self.plot_x_data.currentText() == "Voltage": p0 = buffers["__plotx__"]["data"][0] if self.plot_x_data.currentText() == "Current": p0 = buffers["__plotx__"]["data"][1] # Sync y-axis data if self.plot_y_data.currentText() == "Voltage": p1 = buffers["__ploty__"]["data"][0] if self.plot_y_data.currentText() == "Current": p1 = buffers["__ploty__"]["data"][1] # Update the data self.plot.append_handle_data("111", key, float(p0), float(p1)) self.plot.update_canvas() # Reset Keithley __sweep_func__(0.0) # Loop throgh all insurments and enable outputs for _key, _buffer in buffers.items(): if _buffer["inst"] not in ["__sweep__"]: self.keithley( _buffer["inst"] ).output_off() # Reset sweep control and update measurement state to stop. # Post a button click event to the QStateMachine to trigger # a state transition if thread is still running (not aborted) if self.thread_running: self.meas_button.click() # Function we run when we enter run state def exec_meas_run(self): # Update sweep and step params self.update_meas_params() # For startup protection if self.keithley(self.sweep_inst) is not None: # Update UI button to abort self.meas_button.setStyleSheet( "background-color: #ffcccc; border-style: solid; border-width: 1px; border-color: #800000; padding: 7px;") # Disable controls (sweep) self.sweep_src.setEnabled(False) self.sweep_inst.setEnabled(False) # Disable controls (step) self.step_src.setEnabled(False) self.step_inst.setEnabled(False) self.step_button.setEnabled(False) # Disable controls (save) self.save_widget.setEnabled(False) # Plot contollers (plots) self.plot.mpl_refresh_setEnabled(False) self.plot_x_inst.setEnabled(False) self.plot_x_data.setEnabled(False) self.plot_y_inst.setEnabled(False) self.plot_y_data.setEnabled(False) # Check app meta and run sweep or sweep-step tread if self._get_app_metadata("__exec_step__") == True: self.thread = threading.Thread(target=self.exec_sweep_step_thread, args=()) else: self.thread = threading.Thread(target=self.exec_sweep_thread, args=()) self.thread.daemon = True # Daemonize thread self.thread.start() # Start the execution self.thread_running = True # Function we run when we enter abort state def exec_meas_stop(self): # For startup protection if self.keithley(self.sweep_inst) is not None: # Update UI button to start state self.meas_button.setStyleSheet( "background-color: #dddddd; border-style: solid; border-width: 1px; border-color: #aaaaaa; padding: 7px;" ) # Enable controls (sweep) self.sweep_src.setEnabled(True) self.sweep_inst.setEnabled(True) # Enable controls (step) self.step_src.setEnabled(True) self.step_inst.setEnabled(True) self.step_button.setEnabled(True) # Enable controls (save) self.save_widget.setEnabled(True) # Plot contollers self.plot.mpl_refresh_setEnabled(True) self.plot_x_inst.setEnabled(True) self.plot_x_data.setEnabled(True) self.plot_y_inst.setEnabled(True) self.plot_y_data.setEnabled(True) # Kill measurement thread self.thread_running = False self.thread.join() # Waits for thread to complete
[ "PyQt5.QtWidgets.QMessageBox", "time.sleep", "PyQt5.QtWidgets.QStackedWidget", "PyQt5.QtWidgets.QVBoxLayout", "PyQt5.QtWidgets.QComboBox", "numpy.where", "PyQt5.QtWidgets.QLabel", "PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector", "numpy.concatenate", "PyQt5.QtWidgets.QPushButton", "PyQt5.QtWidgets.QWidget", "PyQtVisa.widgets.QVisaDynamicPlot.QVisaDynamicPlot", "PyQt5.QtWidgets.QHBoxLayout", "PyQt5.QtCore.QStateMachine", "numpy.isnan", "time.time", "os.path.realpath", "PyQt5.QtCore.QState", "threading.Thread" ]
[((5102, 5115), 'PyQt5.QtWidgets.QHBoxLayout', 'QHBoxLayout', ([], {}), '()\n', (5113, 5115), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((5533, 5542), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (5540, 5542), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((5569, 5582), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (5580, 5582), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((5799, 5814), 'PyQt5.QtCore.QStateMachine', 'QStateMachine', ([], {}), '()\n', (5812, 5814), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((5836, 5849), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ([], {}), '()\n', (5847, 5849), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((6046, 6054), 'PyQt5.QtCore.QState', 'QState', ([], {}), '()\n', (6052, 6054), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((6074, 6082), 'PyQt5.QtCore.QState', 'QState', ([], {}), '()\n', (6080, 6082), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((6778, 6794), 'PyQt5.QtWidgets.QStackedWidget', 'QStackedWidget', ([], {}), '()\n', (6792, 6794), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((7012, 7046), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>Trace Description</b>"""'], {}), "('<b>Trace Description</b>')\n", (7018, 7046), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((7846, 7855), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (7853, 7855), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((7884, 7897), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (7895, 7897), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((7963, 8000), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>Configure Parameters</b>"""'], {}), "('<b>Configure Parameters</b>')\n", (7969, 8000), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((8027, 8038), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (8036, 8038), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((8636, 8645), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (8643, 8645), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((8673, 8686), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (8684, 8686), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((8739, 8775), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>IV-sweep Parameters</b>"""'], {}), "('<b>IV-sweep Parameters</b>')\n", (8745, 8775), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((8913, 8936), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""Select Device"""'], {}), "('Select Device')\n", (8919, 8936), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((9162, 9182), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""Sweep Type"""'], {}), "('Sweep Type')\n", (9168, 9182), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((9202, 9213), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (9211, 9213), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((9564, 9580), 'PyQt5.QtWidgets.QStackedWidget', 'QStackedWidget', ([], {}), '()\n', (9578, 9580), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((9765, 9790), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""Hysteresis Mode"""'], {}), "('Hysteresis Mode')\n", (9771, 9790), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((9811, 9822), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (9820, 9822), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((10605, 10614), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (10612, 10614), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((10641, 10654), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (10652, 10654), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((10704, 10738), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>V-step Parameters</b>"""'], {}), "('<b>V-step Parameters</b>')\n", (10710, 10738), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((10804, 10827), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""Select Device"""'], {}), "('Select Device')\n", (10810, 10827), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((10965, 10984), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""Step Type"""'], {}), "('Step Type')\n", (10971, 10984), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((11003, 11014), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (11012, 11014), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((11372, 11388), 'PyQt5.QtWidgets.QStackedWidget', 'QStackedWidget', ([], {}), '()\n', (11386, 11388), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((11573, 11588), 'PyQt5.QtCore.QStateMachine', 'QStateMachine', ([], {}), '()\n', (11586, 11588), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((11610, 11623), 'PyQt5.QtWidgets.QPushButton', 'QPushButton', ([], {}), '()\n', (11621, 11623), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((11818, 11826), 'PyQt5.QtCore.QState', 'QState', ([], {}), '()\n', (11824, 11826), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((11845, 11853), 'PyQt5.QtCore.QState', 'QState', ([], {}), '()\n', (11851, 11853), False, 'from PyQt5.QtCore import Qt, QStateMachine, QState, QObject\n'), ((13091, 13100), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (13098, 13100), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((13127, 13140), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (13138, 13140), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((13207, 13240), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>Configure x-axis</b>"""'], {}), "('<b>Configure x-axis</b>')\n", (13213, 13240), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((13400, 13411), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (13409, 13411), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((13640, 13673), 'PyQt5.QtWidgets.QLabel', 'QLabel', (['"""<b>Configure y-axis</b>"""'], {}), "('<b>Configure y-axis</b>')\n", (13646, 13673), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((13833, 13844), 'PyQt5.QtWidgets.QComboBox', 'QComboBox', ([], {}), '()\n', (13842, 13844), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((14632, 14641), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (14639, 14641), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((14672, 14685), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (14683, 14685), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((14931, 14999), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_sweep_start_config'], {}), '(self.voltage_sweep_start_config)\n', (14966, 14999), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((15240, 15307), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_sweep_stop_config'], {}), '(self.voltage_sweep_stop_config)\n', (15275, 15307), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((15559, 15626), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_sweep_cmpl_config'], {}), '(self.voltage_sweep_cmpl_config)\n', (15594, 15626), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((15839, 15906), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_sweep_npts_config'], {}), '(self.voltage_sweep_npts_config)\n', (15874, 15906), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((16136, 16204), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_sweep_delay_config'], {}), '(self.voltage_sweep_delay_config)\n', (16171, 16204), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((16793, 16802), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (16800, 16802), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((16833, 16846), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (16844, 16846), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((17092, 17160), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_sweep_start_config'], {}), '(self.current_sweep_start_config)\n', (17127, 17160), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((17401, 17468), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_sweep_stop_config'], {}), '(self.current_sweep_stop_config)\n', (17436, 17468), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((17717, 17784), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_sweep_cmpl_config'], {}), '(self.current_sweep_cmpl_config)\n', (17752, 17784), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((17996, 18063), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_sweep_npts_config'], {}), '(self.current_sweep_npts_config)\n', (18031, 18063), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((18291, 18359), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_sweep_delay_config'], {}), '(self.current_sweep_delay_config)\n', (18326, 18359), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((18946, 18955), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (18953, 18955), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((18985, 18998), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (18996, 18998), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((19239, 19306), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_step_start_config'], {}), '(self.voltage_step_start_config)\n', (19274, 19306), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((19543, 19609), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_step_stop_config'], {}), '(self.voltage_step_stop_config)\n', (19578, 19609), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((19864, 19930), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_step_cmpl_config'], {}), '(self.voltage_step_cmpl_config)\n', (19899, 19930), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((20146, 20212), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.voltage_step_npts_config'], {}), '(self.voltage_step_npts_config)\n', (20181, 20212), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((20721, 20730), 'PyQt5.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (20728, 20730), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((20760, 20773), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (20771, 20773), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((21014, 21081), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_step_start_config'], {}), '(self.current_step_start_config)\n', (21049, 21081), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((21318, 21384), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_step_stop_config'], {}), '(self.current_step_stop_config)\n', (21353, 21384), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((21638, 21704), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_step_cmpl_config'], {}), '(self.current_step_cmpl_config)\n', (21673, 21704), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((21919, 21985), 'PyQtVisa.widgets.QVisaUnitSelector.QVisaUnitSelector', 'QVisaUnitSelector.QVisaUnitSelector', (['self.current_step_npts_config'], {}), '(self.current_step_npts_config)\n', (21954, 21985), False, 'from PyQtVisa.widgets import QVisaUnitSelector\n'), ((22554, 22593), 'PyQtVisa.widgets.QVisaDynamicPlot.QVisaDynamicPlot', 'QVisaDynamicPlot.QVisaDynamicPlot', (['self'], {}), '(self)\n', (22587, 22593), False, 'from PyQtVisa.widgets import QVisaDynamicPlot\n'), ((30091, 30102), 'time.time', 'time.time', ([], {}), '()\n', (30100, 30102), False, 'import time\n'), ((36810, 36821), 'time.time', 'time.time', ([], {}), '()\n', (36819, 36821), False, 'import time\n'), ((3549, 3581), 'numpy.concatenate', 'np.concatenate', (['(sp, sp[-2::-1])'], {}), '((sp, sp[-2::-1]))\n', (3563, 3581), True, 'import numpy as np\n'), ((3846, 3874), 'numpy.where', 'np.where', (['(sp > 0)', 'sp', 'np.nan'], {}), '(sp > 0, sp, np.nan)\n', (3854, 3874), True, 'import numpy as np\n'), ((3944, 3972), 'numpy.where', 'np.where', (['(sp < 0)', 'sp', 'np.nan'], {}), '(sp < 0, sp, np.nan)\n', (3952, 3972), True, 'import numpy as np\n'), ((28147, 28160), 'PyQt5.QtWidgets.QMessageBox', 'QMessageBox', ([], {}), '()\n', (28158, 28160), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((4159, 4234), 'numpy.concatenate', 'np.concatenate', (['([0.0], pos, pos[-2::-1], [0.0], neg[::-1], neg[1:], [0.0])'], {}), '(([0.0], pos, pos[-2::-1], [0.0], neg[::-1], neg[1:], [0.0]))\n', (4173, 4234), True, 'import numpy as np\n'), ((28645, 28658), 'PyQt5.QtWidgets.QMessageBox', 'QMessageBox', ([], {}), '()\n', (28656, 28658), False, 'from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QComboBox, QSpinBox, QDoubleSpinBox, QPushButton, QCheckBox, QLabel, QLineEdit, QStackedWidget, QSizePolicy\n'), ((40793, 40854), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.exec_sweep_step_thread', 'args': '()'}), '(target=self.exec_sweep_step_thread, args=())\n', (40809, 40854), False, 'import threading\n'), ((40884, 40940), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.exec_sweep_thread', 'args': '()'}), '(target=self.exec_sweep_thread, args=())\n', (40900, 40940), False, 'import threading\n'), ((3891, 3904), 'numpy.isnan', 'np.isnan', (['pos'], {}), '(pos)\n', (3899, 3904), True, 'import numpy as np\n'), ((3988, 4001), 'numpy.isnan', 'np.isnan', (['neg'], {}), '(neg)\n', (3996, 4001), True, 'import numpy as np\n'), ((4342, 4417), 'numpy.concatenate', 'np.concatenate', (['([0.0], neg, neg[-2::-1], [0.0], pos[::-1], pos[1:], [0.0])'], {}), '(([0.0], neg, neg[-2::-1], [0.0], pos[::-1], pos[1:], [0.0]))\n', (4356, 4417), True, 'import numpy as np\n'), ((4519, 4551), 'numpy.concatenate', 'np.concatenate', (['(sp, sp[-2::-1])'], {}), '((sp, sp[-2::-1]))\n', (4533, 4551), True, 'import numpy as np\n'), ((32926, 32953), 'time.sleep', 'time.sleep', (['__sweep_delay__'], {}), '(__sweep_delay__)\n', (32936, 32953), False, 'import time\n'), ((38230, 38257), 'time.sleep', 'time.sleep', (['__sweep_delay__'], {}), '(__sweep_delay__)\n', (38240, 38257), False, 'import time\n'), ((4996, 5022), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (5012, 5022), False, 'import os\n'), ((38307, 38318), 'time.time', 'time.time', ([], {}), '()\n', (38316, 38318), False, 'import time\n'), ((33985, 34012), 'time.sleep', 'time.sleep', (['__sweep_delay__'], {}), '(__sweep_delay__)\n', (33995, 34012), False, 'import time\n'), ((34066, 34077), 'time.time', 'time.time', ([], {}), '()\n', (34075, 34077), False, 'import time\n')]
#!/usr/bin/python3 # RS-274X per standard Revision 2021.02 import re import copy import numpy as np import vertices # TODO replace all vertices with outline class # Meant for extracting substrings only # Cast to int or float will catch invalid strings RE_INT = r'[+-]?[0-9]+' RE_DEC = r'[+-]?[0-9\.]+?' EXPOSURE_ON = 1 EXPOSURE_OFF = 0 class Gerber(): def __init__(self): self.format_num_int = None self.format_num_dec = None self.unit = None self.current_point = None self.current_aperture = None # Interpolation should be None, but not all files have G01 self.interpolation = 'linear' self.region = None self.transform = ApertureTransform() self.apertures = {} self.templates = { 'C': Circle(1.0), 'R': Rectangle(1.0, 1.0), 'O': Obround(1.0, 1.0), 'P': Polygon(1.0, 3, 0.0) } self.objects = [] self.objects_list_stack = [self.objects] self.reached_eof = False def add_object(self, new_obj): self.objects_list_stack[-1].append(new_obj) def comment(self, statement: str): pass def ignore(self, statement: str): pass def not_implemented(self, statement: str): raise NotImplementedError('Command not implemented: ' + statement) def begin_region(self, statement: str): # TODO is self.region required? self.region = Region(self.transform) self.objects_list_stack.append(self.region) def end_region(self, statement: str): self.region.end_contour() self.objects_list_stack.pop() self.add_object(self.region) self.region = None def get_command_function(self, statement: str): commands = { 'G04': self.comment, 'MO': self.set_mode, 'FS': self.set_format, 'AD': self.aperture_define, 'AM': self.aperture_macro, 'Dnn': self.set_current_aperture, 'D01': self.interpolate_operation, 'D02': self.move_operation, 'D03': self.flash_operation, 'G01': self.set_interpolation, 'G02': self.set_interpolation, 'G03': self.set_interpolation, 'G74': self.not_implemented, 'G75': self.ignore, 'LP': self.load_polarity, 'LM': self.load_mirroring, 'LR': self.load_rotation, 'LS': self.load_scaling, 'G36': self.begin_region, 'G37': self.end_region, 'AB': self.aperture_block, 'SR': self.step_and_repeat, 'TF': self.ignore, 'TA': self.ignore, 'TO': self.ignore, 'TD': self.ignore, 'M02': self.set_eof } # Extended commands # e.g. # %MOMM*% # %AMDonut* # 1,1,$1,$2,$3* # $4=$1x0.75* # 1,0,$4,$2,$3* # % # %ADD11Donut,0.30X0X0*% code = None if statement.startswith('%'): code = statement[1:3] else: # Word commands # e.g. # G04 comment * # D10* # X0Y0D02* match = re.search(r'[GDM](\d\d)', statement) if match: code = match.group() if code[0] == 'D' and int(match.group(1)) >= 10: code = 'Dnn' try: return commands[code] except KeyError: raise KeyError(f'Unrecognized statement: {statement}') def set_eof(self, statement: str): if statement != 'M02*': raise ValueError('Invalid EOF statement') self.reached_eof = True def parse(self, filename: str): with open(filename, 'r') as f: delimiter = False for line_num, line in enumerate(f): if line.isspace(): continue if line.startswith('%'): delimiter = True statement = '' if delimiter: statement += line else: statement = line if line.endswith('%\n'): delimiter = False if not delimiter: statement = statement.strip() try: command = self.get_command_function(statement) command(statement) except (ValueError, KeyError) as ex: raise ValueError(f'Error line {line_num + 1}: {ex}') if not self.reached_eof: raise ValueError('File did not contain EOF marker') def set_mode(self, statement: str): # Set unit of measurement to metric or imperial if statement == '%MOMM*%': self.unit = 'mm' elif statement == '%MOIN*%': self.unit = 'in' else: raise ValueError(f'Unrecognized mode statement: {statement}') def set_format(self, statement: str): # Set coordinates and distances in operations # %FSLAX36Y36*% sets 3 integer digits, 6 decimal digits # 6 decimal digits implies 10^-6 is increment if self.format_num_dec is not None or self.format_num_int is not None: raise ValueError('Format must be set exactly once') match = re.search(r'%FSLAX([1-6])([3-6])Y([1-6])([3-6])\*%', statement) if match is None: raise ValueError(f'Unrecognized format statement: {statement}') if match.group(1) != match.group(3): raise ValueError(f'Mismatched format X, Y integer digits: {statement}') if match.group(2) != match.group(4): raise ValueError(f'Mismatched format X, Y decimal digits: {statement}') self.format_num_int = int(match.group(1)) self.format_num_dec = int(match.group(2)) self.format_scale = 10**(-self.format_num_dec) def set_interpolation(self, statement: str): # Set interpolation state to linear or circular if statement == 'G01*': self.interpolation = 'linear' elif statement == 'G02*': self.interpolation = 'cw_circular' elif statement == 'G03*': self.interpolation = 'ccw_circular' else: raise ValueError(f'Unrecognized interpolation statement: {statement}') def create_aperture(self): if self.current_aperture is not None: return self.apertures[self.current_aperture].clone() else: return None def get_new_point(self, x: str, y: str): # Parse strings, e.g. X2152000 and Y1215000 if x and y: return (int(x[1:]), int(y[1:])) elif x: return (int(x[1:]), self.current_point[1]) elif y: return (self.current_point[0], int(y[1:])) else: raise ValueError('Invalid x and y') def interpolate_operation(self, statement: str): # D01 linear/circular line segment match = re.search(rf'(X{RE_INT})?(Y{RE_INT})?(I{RE_INT})?(J{RE_INT})?D01\*', statement) if match is not None: x = match.group(1) y = match.group(2) i = match.group(3) j = match.group(4) new_point = self.get_new_point(x, y) if self.interpolation == 'linear': self.add_object(Draw(self.create_aperture(), self.transform, self.current_point, new_point)) elif self.interpolation in ('cw_circular', 'ccw_circular'): if i and j: offset = (int(i[1:]), int(j[1:])) else: raise ValueError(f'Missing offset: I {i}, J {j}') is_cw = (self.interpolation == 'cw_circular') self.add_object(Arc(self.create_aperture(), self.transform, self.current_point, new_point, offset, is_cw)) else: raise ValueError(f'Invalid interpolation: {self.interpolation}') self.current_point = new_point else: raise ValueError(f'Unrecognized interpolate operation: {statement}') def move_operation(self, statement: str): # D02 move operation match = re.search(rf'(X{RE_INT})?(Y{RE_INT})?D02\*', statement) if match is not None: x = match.group(1) y = match.group(2) self.current_point = self.get_new_point(x, y) else: raise ValueError(f'Unrecognized move operation: {statement}') def flash_operation(self, statement: str): # D03 create flash object match = re.search(rf'(X{RE_INT})?(Y{RE_INT})?D03\*', statement) if match is not None: x = match.group(1) y = match.group(2) new_point = self.get_new_point(x, y) aperture = self.create_aperture() self.add_object(Flash(aperture, self.transform, new_point)) self.current_point = new_point else: raise ValueError(f'Unrecognized flash operation: {statement}') def load_polarity(self, statement: str): # Polarity is either clear or dark if statement == '%LPC*%': self.transform.polarity = 'clear' elif statement == '%LPD*%': self.transform.polarity = 'dark' else: raise ValueError(f'Unrecognized polarity statement: {statement}') def load_mirroring(self, statement: str): # Mirror either N, X, Y or XY match = re.search(r'%LM(N|X|Y|XY)\*%', statement) if match is not None: self.transform.mirroring = match.group(1) else: raise ValueError(f'Unrecognized mirroring statement: {statement}') def load_rotation(self, statement: str): # Rotation in degrees counterclockwise match = re.search(r'%LR(\S+)\*%', statement) if match is not None: self.transform.rotation = float(match.group(1)) else: raise ValueError(f'Unrecognized rotation statement: {statement}') def load_scaling(self, statement: str): # Scaling where 1.0 is no scaling match = re.search(r'%LS(\S+)\*%', statement) if match is not None: self.transform.scaling = float(match.group(1)) else: raise ValueError(f'Unrecognized scaling statement: {statement}') def aperture_define(self, statement: str): # Parse e.g. %ADD100C,1.5*% # AD, D100, C, 1.5 # cmd, ident, template match = re.search(r'%AD(D[0-9]{2,})([\w\.\$]+)(,\S*)?\*%', statement) if match is not None: ident = match.group(1) template_name = match.group(2) parameters = match.group(3) if parameters: parameters = parameters.lstrip(',') if ident in self.apertures: raise ValueError(f'Aperture {ident} already defined') if template_name in self.templates: self.apertures[ident] = self.templates[template_name].derive_from(parameters) else: raise KeyError(f'Aperture template {template_name} not defined') else: raise ValueError(f'Unrecognized aperture define statement: {statement}') def aperture_macro(self, statement: str): # %AMCIRC*\n1,1,1.5,0,0,0*% match = re.search(r'%AM([\w\.\$]+)', statement) if match is not None: ident = match.group(1) if ident in self.templates: raise ValueError(f'Aperture {ident} template already defined') self.templates[ident] = Macro.parse(statement) else: raise ValueError(f'Unrecognized aperture macro statement: {statement}') def aperture_block(self, statement: str): # %ABD12*% # %ADD11C,0.5*% # D10* # G01* # X-2500000Y-1000000D03* # Y1000000D03* # %LPC*% # ... # G01* # %AB*% match = re.search(r'%AB(D[0-9]{2,})?\*%', statement) if match is not None: ident = match.group(1) if ident is None: # Close Block self.objects_list_stack.pop() else: # Open new Block if ident in self.apertures: raise ValueError(f'Aperture {ident} already defined') self.apertures[ident] = BlockAperture() self.objects_list_stack.append(self.apertures[ident]) else: raise ValueError(f'Unrecognized aperture block statement: {statement}') def set_current_aperture(self, statement: str): # D10* # select aperture D10 match = re.search(r'(D[0-9]{2,})\*', statement) if match is not None: ident = match.group(1) if ident in self.apertures: self.current_aperture = ident else: raise KeyError(f'Aperture {ident} is not defined') else: raise ValueError(f'Unrecognized set current aperture statement: {statement}') def step_and_repeat(self, statement: str): # %SRX3Y2I5.0J4.0*% # ... # %SR*% # Step and repeat all enclosed statements if statement == '%SR*%': self.objects_list_stack.pop() else: match = re.search(rf'%SRX(\d+)Y(\d+)I({RE_DEC})J({RE_DEC})\*%', statement) if match is not None: x = int(match.group(1)) y = int(match.group(2)) i = float(match.group(3)) j = float(match.group(4)) sr = StepAndRepeat(x, y, i, j) self.add_object(sr) self.objects_list_stack.append(sr) else: raise ValueError(f'Unrecognized step and repeat statement: {statement}') class ApertureTransform(): def __init__(self, polarity: str = 'dark', mirroring: str = 'N', rotation: float = 0.0, scaling: float = 1.0): self.polarity = polarity self.mirroring = mirroring self.rotation = rotation self.scaling = scaling class Aperture(): def __init__(self): pass def derive_from(self, statement: str): if statement is None: raise ValueError('Missing parameters statement') tokens = statement.split('X') return type(self)(*[float(token) for token in tokens]) def clone(self): new = copy.copy(self) return new def get_hole_vertices(self, dest: list = None): hole_pts = None if self.hole_diameter: hole_pts = vertices.circle(self.hole_diameter) hole_pts = np.flip(hole_pts, 0) if dest is not None: dest.append(hole_pts) return hole_pts def get_outline(self, dest: list = None): raise NotImplementedError('get_outline not implemented') class Circle(Aperture): def __init__(self, diameter: float, hole_diameter: float = None): super().__init__() self.diameter = diameter self.hole_diameter = hole_diameter def get_outline(self, dest: list = None): pts = vertices.circle(self.diameter) holes = [] self.get_hole_vertices(holes) outline = vertices.OutlineVertices(pts, holes) if dest is not None: dest.append(outline) return outline class Rectangle(Aperture): def __init__(self, x_size: float, y_size: float, hole_diameter: float = None): super().__init__() self.x_size = x_size self.y_size = y_size self.hole_diameter = hole_diameter def get_outline(self, dest: list = None): pts = vertices.rectangle(self.x_size, self.y_size) holes = [] self.get_hole_vertices(holes) outline = vertices.OutlineVertices(pts, holes) if dest is not None: dest.append(outline) return outline class Obround(Aperture): def __init__(self, x_size: float, y_size: float, hole_diameter: float = None): super().__init__() self.x_size = x_size self.y_size = y_size self.hole_diameter = hole_diameter def get_outline(self, dest: list = None): w = min(self.x_size, self.y_size) z = 0.5 * (max(self.x_size, self.y_size) - w) if self.x_size > self.y_size: x1, x2 = -z, z y1, y2 = 0, 0 else: x1, x2 = 0, 0 y1, y2 = -z, z pts = vertices.rounded_line(w, x1, y1, x2, y2) holes = [] self.get_hole_vertices(holes) outline = vertices.OutlineVertices(pts, holes) if dest is not None: dest.append(outline) return outline class Polygon(Aperture): def __init__(self, outer_diameter: float, vertices: int, rotation: float = 0.0, hole_diameter: float = None): super().__init__() self.outer_diameter = outer_diameter self.vertices = int(vertices) self.rotation = rotation self.hole_diameter = hole_diameter if self.vertices not in range(3, 13): raise ValueError('Polygon vertices must be from 3 to 12') def get_outline(self, dest: list = None): pts = vertices.regular_poly(self.outer_diameter, self.vertices) vertices.rotate(pts, self.rotation) holes = [] self.get_hole_vertices(holes) outline = vertices.OutlineVertices(pts, holes) if dest is not None: dest.append(outline) return outline class Macro(Aperture): def __init__(self, template_str: str, primitives: list): super().__init__() self.template_str = template_str self.primitives = primitives def get_outline(self, dest: list = None): outlines = [] for prim in self.primitives: outlines.append(prim.get_outline(dest)) return outlines def derive_from(self, statement: str): # Collect parameter values from creation statement params = {} if statement is not None: for i, token in enumerate(statement.split('X')): params[i + 1] = float(token) # Create primitives by parsing template string primitives = [] blocks = self.template_str.replace('\n', '').split('*') for block in blocks: # Ignore open/close block or comment if block.startswith('%') or block.startswith('0'): continue # Resolve new variables if block.startswith('$'): expr = re.search(r'\$(\d+)\s*=([^*]+)*', block) expr_p = expr.group(1) expr_e = expr.group(2) for p, v in params.items(): expr_e = expr_e.replace(f'${p}', str(v)) params[expr_p] = Macro.eval_expression(expr_e) # Attempt to create a primitive else: code = block.split(',')[0] for p, v in params.items(): block = block.replace(f'${p}', str(v)) missing = re.search(r'\$\d+', block) if missing: raise KeyError('Unfulfilled macro parameter ' + missing.group()) try: primitives.append(Macro.primtypes(code).parse(block)) except KeyError: raise KeyError('Unrecognized macro code ' + str(code)) return type(self)(self.template_str, primitives) @staticmethod def primtypes(code): prims = { '1': MacroCircle, '20': MacroVectorLine, '21': MacroCenterLine, '4': MacroOutline, '5': MacroPolygon, '6': MacroMoire, '7': MacroThermal } return prims[code] @classmethod def parse(cls, statement: str): if not statement.startswith('%AM'): raise ValueError('Invalid define macro statement') # TODO validate template return cls(statement, []) @staticmethod def eval_expression(expr: str): legal = set('0123456789()-+/x.') chars = set(expr) illegal = chars.difference(legal) if len(illegal) > 0: raise ValueError('Illegal characters in expression: ' + expr) expr = expr.replace('x', '*') # Multiplication return eval(expr) class MacroPrimitive(): def __init__(self, exposure, x, y, rotation): if exposure not in (EXPOSURE_OFF, EXPOSURE_ON): raise ValueError('Invalid exposure value') self.exposure = exposure self.x = x self.y = y self.rotation = rotation def get_outline(self, dest: list = None): raise NotImplementedError('get_vertices not implemented') @classmethod def parse(cls, statement: str): if statement is None: raise ValueError('Missing parameters statement') tokens = statement.split(',')[1:] # Discard first token (shape code) return cls(*[Macro.eval_expression(token) for token in tokens]) class MacroCircle(MacroPrimitive): def __init__(self, exposure, diameter, x, y, rotation=0.0): super().__init__(exposure, x, y, rotation) self.diameter = diameter def get_outline(self, dest: list = None): pts = vertices.circle(self.diameter) outline = vertices.OutlineVertices(pts) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroVectorLine(MacroPrimitive): def __init__(self, exposure, width, x1, y1, x2, y2, rotation=0.0): super().__init__(exposure, 0, 0, rotation) self.width = width self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def get_outline(self, dest: list = None): pts = vertices.thick_line(self.width, self.x1, self.y1, self.x2, self.y2) outline = vertices.OutlineVertices(pts) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroCenterLine(MacroPrimitive): def __init__(self, exposure, width, height, x, y, rotation=0.0): super().__init__(exposure, x, y, rotation) self.width = width self.height = height def get_outline(self, dest: list = None): pts = vertices.rectangle(self.width, self.height) outline = vertices.OutlineVertices(pts) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroPolygon(MacroPrimitive): def __init__(self, exposure, vertices, x, y, diameter, rotation=0.0): super().__init__(exposure, x, y, rotation) self.vertices = vertices self.diameter = diameter def get_outline(self, dest: list = None): pts = vertices.regular_poly(self.diameter, self.vertices) outline = vertices.OutlineVertices(pts) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroThermal(MacroPrimitive): def __init__(self, x, y, outer_diameter, inner_diameter, gap, rotation=0.0): super().__init__(EXPOSURE_ON, x, y, rotation) self.outer_diameter = outer_diameter self.inner_diameter = inner_diameter self.gap = gap def get_outline(self, dest: list = None): pts = vertices.circle(self.outer_diameter) hole_pts = vertices.circle(self.inner_diameter) holes = [np.flip(hole_pts, 0)] # TODO add gaps outline = vertices.OutlineVertices(pts, holes) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroMoire(MacroPrimitive): def __init__(self, x, y, outer_diameter, ring_thickness, gap, num_rings, crosshair_thickness, crosshair_length, rotation=0.0): super().__init__(EXPOSURE_ON, x, y, rotation) self.outer_diameter = outer_diameter self.ring_thickness = ring_thickness self.gap = gap self.num_rings = num_rings self.crosshair_thickness = crosshair_thickness self.crosshair_length = crosshair_length def get_outline(self, dest: list = None): pts = vertices.circle(self.outer_diameter) holes = [vertices.circle(self.inner_diameter)] # TODO implement properly outline = vertices.OutlineVertices(pts, holes) outline.positive = self.exposure == 1 outline.translate(self.x, self.y) outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class MacroOutline(MacroPrimitive): def __init__(self, exposure, vertices, x, y, *args): N = 2 * vertices + 1 if len(args) == N: super().__init__(exposure, x, y, rotation=float(args[-1])) self.vertices = vertices self.coordinates = [*args[:-1]] else: raise ValueError(f'Expected {N} parameters but received {len(args)}') def get_outline(self, dest: list = None): N = int(len(self.coordinates) / 2) pts = np.array(self.coordinates) pts.resize((N, 2)) outline = vertices.OutlineVertices(pts) outline.positive = self.exposure == 1 outline.rotate(self.rotation) if dest is not None: dest.append(outline) return outline class BlockAperture(Aperture): def __init__(self): super().__init__() self.objects = [] def append(self, object): self.objects.append(object) class GraphicalObject(): def __init__(self, aperture, transform, origin: tuple): self.aperture = aperture self.transform = copy.copy(transform) self.origin = origin def translate(self, translation): dx, dy = translation x0, y0 = self.origin self.origin = (x0 + dx, y0 + dy) def get_outline(self, dest: list = None, scale: float = 1e-6): raise NotImplementedError('get_outline not implemented') class Draw(GraphicalObject): def __init__(self, aperture, transform, origin: tuple, endpoint: tuple): super().__init__(aperture, transform, origin) self.endpoint = endpoint def translate(self, translation): dx, dy = translation x0, y0 = self.origin x1, y1 = self.endpoint self.origin = (x0 + dx, y0 + dy) self.endpoint = (x1 + dx, y1 + dy) def get_outline(self, dest: list = None, scale: float = 1e-6): x0, y0 = scale * np.array(self.origin) x1, y1 = scale * np.array(self.endpoint) pts = vertices.rounded_line(self.aperture.diameter, x0, y0, x1, y1) outline = vertices.OutlineVertices(pts) # TODO apply transform if dest is not None: dest.append(outline) return outline # TODO Arc needs quadrant mode class Arc(GraphicalObject): def __init__(self, aperture, transform, origin: tuple, endpoint: tuple, offset: tuple, is_cw: bool = True): super().__init__(aperture, transform, origin) self.endpoint = endpoint self.offset = offset self.is_cw = is_cw def translate(self, translation): dx, dy = translation x0, y0 = self.origin x1, y1 = self.endpoint self.origin = (x0 + dx, y0 + dy) self.endpoint = (x1 + dx, y1 + dy) def get_outline(self, dest: list = None, scale: float = 1e-6): dx, dy = scale * np.array(self.offset) x1, y1 = scale * np.array(self.origin) x2, y2 = scale * np.array(self.endpoint) x0, y0 = x1 + dx, y1 + dy pts = vertices.rounded_arc(self.aperture.diameter, x0, y0, x1, y1, x2, y2) vertices.translate(pts, x0, y0) outline = vertices.OutlineVertices(pts) # TODO apply transform if dest is not None: dest.append(outline) return outline class Flash(GraphicalObject): def __init__(self, aperture, transform, origin: tuple): super().__init__(aperture, transform, origin) def get_outline(self, dest: list = None, scale: float = 1e-6): outlines = self.aperture.get_outline(dest) if type(outlines) != list: outlines = [outlines] x0, y0 = scale * np.array(self.origin) # TODO replace with apply transform function for outline in outlines: outline.positive = self.transform.polarity == 'dark' outline.rotate(self.transform.rotation) outline.translate(x0, y0) return outlines class Region(GraphicalObject): def __init__(self, transform): super().__init__(None, transform, None) self.objects = [] self.contours = [] def end_contour(self): if len(self.contours) > 0: prev_start, prev_len = self.contours[-1] new_start = prev_start + prev_len self.contours.append((new_start, len(self.objects) - new_start)) else: self.contours.append((0, len(self.objects))) def append(self, object): if not isinstance(object, (Draw, Arc)): raise TypeError('Region only supports Draw and Arc objects') if len(self.objects) > 0 and object.origin != self.objects[-1].endpoint: self.end_contour() self.objects.append(object) class StepAndRepeat(): def __init__(self, nx: int, ny: int, step_x: float, step_y: float): if nx < 1 or ny < 1: raise ValueError('Repeat must be 1 or greater') if step_x < 0.0 or step_y < 0.0: raise ValueError('Step size must be positive') self.nx = nx self.ny = ny self.step_x = step_x self.step_y = step_y self.objects = [] def append(self, object): self.objects.append(object)
[ "vertices.rotate", "numpy.flip", "vertices.rounded_arc", "vertices.thick_line", "vertices.translate", "vertices.regular_poly", "vertices.rounded_line", "vertices.OutlineVertices", "vertices.circle", "numpy.array", "vertices.rectangle", "copy.copy", "re.search" ]
[((5454, 5517), 're.search', 're.search', (['"""%FSLAX([1-6])([3-6])Y([1-6])([3-6])\\\\*%"""', 'statement'], {}), "('%FSLAX([1-6])([3-6])Y([1-6])([3-6])\\\\*%', statement)\n", (5463, 5517), False, 'import re\n'), ((7133, 7212), 're.search', 're.search', (['f"""(X{RE_INT})?(Y{RE_INT})?(I{RE_INT})?(J{RE_INT})?D01\\\\*"""', 'statement'], {}), "(f'(X{RE_INT})?(Y{RE_INT})?(I{RE_INT})?(J{RE_INT})?D01\\\\*', statement)\n", (7142, 7212), False, 'import re\n'), ((8441, 8496), 're.search', 're.search', (['f"""(X{RE_INT})?(Y{RE_INT})?D02\\\\*"""', 'statement'], {}), "(f'(X{RE_INT})?(Y{RE_INT})?D02\\\\*', statement)\n", (8450, 8496), False, 'import re\n'), ((8833, 8888), 're.search', 're.search', (['f"""(X{RE_INT})?(Y{RE_INT})?D03\\\\*"""', 'statement'], {}), "(f'(X{RE_INT})?(Y{RE_INT})?D03\\\\*', statement)\n", (8842, 8888), False, 'import re\n'), ((9723, 9764), 're.search', 're.search', (['"""%LM(N|X|Y|XY)\\\\*%"""', 'statement'], {}), "('%LM(N|X|Y|XY)\\\\*%', statement)\n", (9732, 9764), False, 'import re\n'), ((10051, 10088), 're.search', 're.search', (['"""%LR(\\\\S+)\\\\*%"""', 'statement'], {}), "('%LR(\\\\S+)\\\\*%', statement)\n", (10060, 10088), False, 'import re\n'), ((10373, 10410), 're.search', 're.search', (['"""%LS(\\\\S+)\\\\*%"""', 'statement'], {}), "('%LS(\\\\S+)\\\\*%', statement)\n", (10382, 10410), False, 'import re\n'), ((10748, 10813), 're.search', 're.search', (['"""%AD(D[0-9]{2,})([\\\\w\\\\.\\\\$]+)(,\\\\S*)?\\\\*%"""', 'statement'], {}), "('%AD(D[0-9]{2,})([\\\\w\\\\.\\\\$]+)(,\\\\S*)?\\\\*%', statement)\n", (10757, 10813), False, 'import re\n'), ((11588, 11629), 're.search', 're.search', (['"""%AM([\\\\w\\\\.\\\\$]+)"""', 'statement'], {}), "('%AM([\\\\w\\\\.\\\\$]+)', statement)\n", (11597, 11629), False, 'import re\n'), ((12223, 12267), 're.search', 're.search', (['"""%AB(D[0-9]{2,})?\\\\*%"""', 'statement'], {}), "('%AB(D[0-9]{2,})?\\\\*%', statement)\n", (12232, 12267), False, 'import re\n'), ((12916, 12955), 're.search', 're.search', (['"""(D[0-9]{2,})\\\\*"""', 'statement'], {}), "('(D[0-9]{2,})\\\\*', statement)\n", (12925, 12955), False, 'import re\n'), ((14706, 14721), 'copy.copy', 'copy.copy', (['self'], {}), '(self)\n', (14715, 14721), False, 'import copy\n'), ((15419, 15449), 'vertices.circle', 'vertices.circle', (['self.diameter'], {}), '(self.diameter)\n', (15434, 15449), False, 'import vertices\n'), ((15525, 15561), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (15549, 15561), False, 'import vertices\n'), ((15965, 16009), 'vertices.rectangle', 'vertices.rectangle', (['self.x_size', 'self.y_size'], {}), '(self.x_size, self.y_size)\n', (15983, 16009), False, 'import vertices\n'), ((16085, 16121), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (16109, 16121), False, 'import vertices\n'), ((16777, 16817), 'vertices.rounded_line', 'vertices.rounded_line', (['w', 'x1', 'y1', 'x2', 'y2'], {}), '(w, x1, y1, x2, y2)\n', (16798, 16817), False, 'import vertices\n'), ((16893, 16929), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (16917, 16929), False, 'import vertices\n'), ((17536, 17593), 'vertices.regular_poly', 'vertices.regular_poly', (['self.outer_diameter', 'self.vertices'], {}), '(self.outer_diameter, self.vertices)\n', (17557, 17593), False, 'import vertices\n'), ((17602, 17637), 'vertices.rotate', 'vertices.rotate', (['pts', 'self.rotation'], {}), '(pts, self.rotation)\n', (17617, 17637), False, 'import vertices\n'), ((17713, 17749), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (17737, 17749), False, 'import vertices\n'), ((21675, 21705), 'vertices.circle', 'vertices.circle', (['self.diameter'], {}), '(self.diameter)\n', (21690, 21705), False, 'import vertices\n'), ((21724, 21753), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (21748, 21753), False, 'import vertices\n'), ((22300, 22367), 'vertices.thick_line', 'vertices.thick_line', (['self.width', 'self.x1', 'self.y1', 'self.x2', 'self.y2'], {}), '(self.width, self.x1, self.y1, self.x2, self.y2)\n', (22319, 22367), False, 'import vertices\n'), ((22454, 22483), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (22478, 22483), False, 'import vertices\n'), ((22973, 23016), 'vertices.rectangle', 'vertices.rectangle', (['self.width', 'self.height'], {}), '(self.width, self.height)\n', (22991, 23016), False, 'import vertices\n'), ((23035, 23064), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (23059, 23064), False, 'import vertices\n'), ((23566, 23617), 'vertices.regular_poly', 'vertices.regular_poly', (['self.diameter', 'self.vertices'], {}), '(self.diameter, self.vertices)\n', (23587, 23617), False, 'import vertices\n'), ((23636, 23665), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (23660, 23665), False, 'import vertices\n'), ((24241, 24277), 'vertices.circle', 'vertices.circle', (['self.outer_diameter'], {}), '(self.outer_diameter)\n', (24256, 24277), False, 'import vertices\n'), ((24297, 24333), 'vertices.circle', 'vertices.circle', (['self.inner_diameter'], {}), '(self.inner_diameter)\n', (24312, 24333), False, 'import vertices\n'), ((24415, 24451), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (24439, 24451), False, 'import vertices\n'), ((25231, 25267), 'vertices.circle', 'vertices.circle', (['self.outer_diameter'], {}), '(self.outer_diameter)\n', (25246, 25267), False, 'import vertices\n'), ((25375, 25411), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts', 'holes'], {}), '(pts, holes)\n', (25399, 25411), False, 'import vertices\n'), ((26126, 26152), 'numpy.array', 'np.array', (['self.coordinates'], {}), '(self.coordinates)\n', (26134, 26152), True, 'import numpy as np\n'), ((26198, 26227), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (26222, 26227), False, 'import vertices\n'), ((26719, 26739), 'copy.copy', 'copy.copy', (['transform'], {}), '(transform)\n', (26728, 26739), False, 'import copy\n'), ((27625, 27686), 'vertices.rounded_line', 'vertices.rounded_line', (['self.aperture.diameter', 'x0', 'y0', 'x1', 'y1'], {}), '(self.aperture.diameter, x0, y0, x1, y1)\n', (27646, 27686), False, 'import vertices\n'), ((27705, 27734), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (27729, 27734), False, 'import vertices\n'), ((28655, 28723), 'vertices.rounded_arc', 'vertices.rounded_arc', (['self.aperture.diameter', 'x0', 'y0', 'x1', 'y1', 'x2', 'y2'], {}), '(self.aperture.diameter, x0, y0, x1, y1, x2, y2)\n', (28675, 28723), False, 'import vertices\n'), ((28732, 28763), 'vertices.translate', 'vertices.translate', (['pts', 'x0', 'y0'], {}), '(pts, x0, y0)\n', (28750, 28763), False, 'import vertices\n'), ((28782, 28811), 'vertices.OutlineVertices', 'vertices.OutlineVertices', (['pts'], {}), '(pts)\n', (28806, 28811), False, 'import vertices\n'), ((3279, 3316), 're.search', 're.search', (['"""[GDM](\\\\d\\\\d)"""', 'statement'], {}), "('[GDM](\\\\d\\\\d)', statement)\n", (3288, 3316), False, 'import re\n'), ((13561, 13629), 're.search', 're.search', (['f"""%SRX(\\\\d+)Y(\\\\d+)I({RE_DEC})J({RE_DEC})\\\\*%"""', 'statement'], {}), "(f'%SRX(\\\\d+)Y(\\\\d+)I({RE_DEC})J({RE_DEC})\\\\*%', statement)\n", (13570, 13629), False, 'import re\n'), ((14872, 14907), 'vertices.circle', 'vertices.circle', (['self.hole_diameter'], {}), '(self.hole_diameter)\n', (14887, 14907), False, 'import vertices\n'), ((14931, 14951), 'numpy.flip', 'np.flip', (['hole_pts', '(0)'], {}), '(hole_pts, 0)\n', (14938, 14951), True, 'import numpy as np\n'), ((24351, 24371), 'numpy.flip', 'np.flip', (['hole_pts', '(0)'], {}), '(hole_pts, 0)\n', (24358, 24371), True, 'import numpy as np\n'), ((25285, 25321), 'vertices.circle', 'vertices.circle', (['self.inner_diameter'], {}), '(self.inner_diameter)\n', (25300, 25321), False, 'import vertices\n'), ((27540, 27561), 'numpy.array', 'np.array', (['self.origin'], {}), '(self.origin)\n', (27548, 27561), True, 'import numpy as np\n'), ((27587, 27610), 'numpy.array', 'np.array', (['self.endpoint'], {}), '(self.endpoint)\n', (27595, 27610), True, 'import numpy as np\n'), ((28489, 28510), 'numpy.array', 'np.array', (['self.offset'], {}), '(self.offset)\n', (28497, 28510), True, 'import numpy as np\n'), ((28536, 28557), 'numpy.array', 'np.array', (['self.origin'], {}), '(self.origin)\n', (28544, 28557), True, 'import numpy as np\n'), ((28583, 28606), 'numpy.array', 'np.array', (['self.endpoint'], {}), '(self.endpoint)\n', (28591, 28606), True, 'import numpy as np\n'), ((29287, 29308), 'numpy.array', 'np.array', (['self.origin'], {}), '(self.origin)\n', (29295, 29308), True, 'import numpy as np\n'), ((18877, 18919), 're.search', 're.search', (['"""\\\\$(\\\\d+)\\\\s*=([^*]+)*"""', 'block'], {}), "('\\\\$(\\\\d+)\\\\s*=([^*]+)*', block)\n", (18886, 18919), False, 'import re\n'), ((19398, 19425), 're.search', 're.search', (['"""\\\\$\\\\d+"""', 'block'], {}), "('\\\\$\\\\d+', block)\n", (19407, 19425), False, 'import re\n')]
"""A wrapper env that handles multiple tasks from different envs. Useful while training multi-task reinforcement learning algorithms. It provides observations augmented with one-hot representation of tasks. """ import random import akro import gym import numpy as np def round_robin_strategy(num_tasks, last_task=None): """A function for sampling tasks in round robin fashion. Args: num_tasks (int): Total number of tasks. last_task (int): Previously sampled task. Returns: int: task id. """ if last_task is None: return 0 return (last_task + 1) % num_tasks def uniform_random_strategy(num_tasks, _): """A function for sampling tasks uniformly at random. Args: num_tasks (int): Total number of tasks. _ (object): Ignored by this sampling strategy. Returns: int: task id. """ return random.randint(0, num_tasks - 1) class MultiEnvWrapper(gym.Wrapper): """A wrapper class to handle multiple gym environments. Args: envs (list(gym.Env)): A list of objects implementing gym.Env. sample_strategy (function(int, int)): Sample strategy to be used when sampling a new task. """ def __init__(self, envs, task_name=None, sample_strategy=uniform_random_strategy): self._sample_strategy = sample_strategy self._num_tasks = len(envs) self._active_task_index = None self._observation_space = None self._envs_names_list = task_name or dict() max_flat_dim = np.prod(envs[0].observation_space.shape) for i, env in enumerate(envs): assert len(env.observation_space.shape) == 1 if np.prod(env.observation_space.shape) >= max_flat_dim: self.max_observation_space_index = i max_flat_dim = np.prod(env.observation_space.shape) self._max_plain_dim = max_flat_dim super().__init__(envs[self.max_observation_space_index]) self._task_envs = [] for env in envs: if env.action_space.shape != self.env.action_space.shape: raise ValueError('Action space of all envs should be same.') self._task_envs.append(env) self.spec.observation_space = self.observation_space @property def num_tasks(self): """Total number of tasks. Returns: int: number of tasks. """ return len(self._task_envs) @property def task_space(self): """Task Space. Returns: akro.Box: Task space. """ one_hot_ub = np.ones(self.num_tasks) one_hot_lb = np.zeros(self.num_tasks) return akro.Box(one_hot_lb, one_hot_ub) @property def active_task_index(self): """Index of active task env. Returns: int: Index of active task. """ return self._active_task_index @property def observation_space(self): """Observation space. Returns: akro.Box: Observation space. """ task_lb, task_ub = self.task_space.bounds env_lb, env_ub = self._observation_space.bounds return akro.Box(np.concatenate([task_lb, env_lb]), np.concatenate([task_ub, env_ub])) @observation_space.setter def observation_space(self, observation_space): """Observation space setter. Args: observation_space (akro.Box): Observation space. """ self._observation_space = observation_space @property def active_task_one_hot(self): """One-hot representation of active task. Returns: numpy.ndarray: one-hot representation of active task """ one_hot = np.zeros(self.task_space.shape) index = self.active_task_index or 0 one_hot[index] = self.task_space.high[index] return one_hot def reset(self, **kwargs): """Sample new task and call reset on new task env. Args: kwargs (dict): Keyword arguments to be passed to gym.Env.reset Returns: numpy.ndarray: active task one-hot representation + observation """ self._active_task_index = self._sample_strategy( self._num_tasks, self._active_task_index) self.env = self._task_envs[self._active_task_index] obs = self.env.reset(**kwargs) obs = self._augment_observation(obs) oh_obs = self._obs_with_one_hot(obs) return oh_obs def _augment_observation(self, obs): # optionally zero-pad observation if np.prod(obs.shape) < self._max_plain_dim: zeros = np.zeros( shape=(self._max_plain_dim - np.prod(obs.shape),) ) obs = np.concatenate([obs, zeros]) return obs def step(self, action): """gym.Env step for the active task env. Args: action (object): object to be passed in gym.Env.reset(action) Returns: object: agent's observation of the current environment float: amount of reward returned after previous action bool: whether the episode has ended dict: contains auxiliary diagnostic information """ obs, reward, done, info = self.env.step(action) obs = self._augment_observation(obs) oh_obs = self._obs_with_one_hot(obs) info['task_id'] = self._active_task_index info['task_name'] = self._envs_names_list[self._active_task_index] return oh_obs, reward, done, info def close(self): """Close all task envs.""" for env in self._task_envs: env.close() def _obs_with_one_hot(self, obs): """Concatenate active task one-hot representation with observation. Args: obs (numpy.ndarray): observation Returns: numpy.ndarray: active task one-hot + observation """ oh_obs = np.concatenate([self.active_task_one_hot, obs]) return oh_obs # """A wrapper env that handles multiple tasks from different envs. # Useful while training multi-task reinforcement learning algorithms. # It provides observations augmented with one-hot representation of tasks. # """ # import random # import akro # import gym # import numpy as np # def round_robin_strategy(num_tasks, last_task=None): # """A function for sampling tasks in round robin fashion. # Args: # num_tasks (int): Total number of tasks. # last_task (int): Previously sampled task. # Returns: # int: task id. # """ # if last_task is None: # return 0 # return (last_task + 1) % num_tasks # def uniform_random_strategy(num_tasks, _): # """A function for sampling tasks uniformly at random. # Args: # num_tasks (int): Total number of tasks. # _ (object): Ignored by this sampling strategy. # Returns: # int: task id. # """ # return random.randint(0, num_tasks - 1) # class MultiEnvWrapper(gym.Wrapper): # """A wrapper class to handle multiple gym environments. # Args: # envs (list(gym.Env)): # A list of objects implementing gym.Env. # sample_strategy (function(int, int)): # Sample strategy to be used when sampling a new task. # """ # def __init__(self, envs, sample_strategy=uniform_random_strategy): # self._sample_strategy = sample_strategy # self._num_tasks = len(envs) # self._active_task_index = None # self._observation_space = None # max_flat_dim = np.prod(envs[0].observation_space.shape) # max_observation_space_index = 0 # for i, env in enumerate(envs): # assert len(env.observation_space.shape) == 1 # if np.prod(env.observation_space.shape) >= max_flat_dim: # self.max_observation_space_index = i # max_flat_dim = np.prod(env.observation_space.shape) # self._max_plain_dim = max_flat_dim # super().__init__(envs[self.max_observation_space_index]) # self._task_envs = [] # for i, env in enumerate(envs): # if env.action_space.shape != self.env.action_space.shape: # raise ValueError('Action space of all envs should be same.') # self._task_envs.append(env) # self.env.spec.observation_space = self._task_envs[self.max_observation_space_index].observation_space # @property # def num_tasks(self): # """Total number of tasks. # Returns: # int: number of tasks. # """ # return len(self._task_envs) # @property # def task_space(self): # """Task Space. # Returns: # akro.Box: Task space. # """ # one_hot_ub = np.ones(self.num_tasks) # one_hot_lb = np.zeros(self.num_tasks) # return akro.Box(one_hot_lb, one_hot_ub) # @property # def active_task_index(self): # """Index of active task env. # Returns: # int: Index of active task. # """ # return self._active_task_index # @property # def observation_space(self): # """Observation space. # Returns: # akro.Box: Observation space. # """ # task_lb, task_ub = self.task_space.bounds # env_lb, env_ub = self._observation_space.bounds # return akro.Box(np.concatenate([task_lb, env_lb]), # np.concatenate([task_ub, env_ub])) # @observation_space.setter # def observation_space(self, observation_space): # """Observation space setter. # Args: # observation_space (akro.Box): Observation space. # """ # self._observation_space = observation_space # @property # def active_task_one_hot(self): # """One-hot representation of active task. # Returns: # numpy.ndarray: one-hot representation of active task # """ # one_hot = np.zeros(self.task_space.shape) # index = self.active_task_index or 0 # one_hot[index] = self.task_space.high[index] # return one_hot # def reset(self, **kwargs): # """Sample new task and call reset on new task env. # Args: # kwargs (dict): Keyword arguments to be passed to gym.Env.reset # Returns: # numpy.ndarray: active task one-hot representation + observation # """ # self._active_task_index = self._sample_strategy( # self._num_tasks, self._active_task_index) # self.env = self._task_envs[self._active_task_index] # obs = self.env.reset(**kwargs) # obs = self._augment_observation(obs) # oh_obs = self._obs_with_one_hot(obs) # return oh_obs # def step(self, action): # """gym.Env step for the active task env. # Args: # action (object): object to be passed in gym.Env.reset(action) # Returns: # object: agent's observation of the current environment # float: amount of reward returned after previous action # bool: whether the episode has ended # dict: contains auxiliary diagnostic information # """ # obs, reward, done, info = self.env.step(action) # obs = self._augment_observation(obs) # oh_obs = self._obs_with_one_hot(obs) # info['task_id'] = self._active_task_index # return oh_obs, reward, done, info # def _augment_observation(self, obs): # # optionally zero-pad observation # if np.prod(obs.shape) < self._max_plain_dim: # zeros = np.zeros( # shape=(self._max_plain_dim - np.prod(obs.shape),) # ) # obs = np.concatenate([obs, zeros]) # return obs # def close(self): # """Close all task envs.""" # for env in self._task_envs: # env.close() # def _obs_with_one_hot(self, obs): # """Concatenate active task one-hot representation with observation. # Args: # obs (numpy.ndarray): observation # Returns: # numpy.ndarray: active task one-hot + observation # """ # oh_obs = np.concatenate([self.active_task_one_hot, obs]) # return oh_obs
[ "numpy.prod", "numpy.ones", "numpy.zeros", "numpy.concatenate", "akro.Box", "random.randint" ]
[((896, 928), 'random.randint', 'random.randint', (['(0)', '(num_tasks - 1)'], {}), '(0, num_tasks - 1)\n', (910, 928), False, 'import random\n'), ((1566, 1606), 'numpy.prod', 'np.prod', (['envs[0].observation_space.shape'], {}), '(envs[0].observation_space.shape)\n', (1573, 1606), True, 'import numpy as np\n'), ((2630, 2653), 'numpy.ones', 'np.ones', (['self.num_tasks'], {}), '(self.num_tasks)\n', (2637, 2653), True, 'import numpy as np\n'), ((2675, 2699), 'numpy.zeros', 'np.zeros', (['self.num_tasks'], {}), '(self.num_tasks)\n', (2683, 2699), True, 'import numpy as np\n'), ((2715, 2747), 'akro.Box', 'akro.Box', (['one_hot_lb', 'one_hot_ub'], {}), '(one_hot_lb, one_hot_ub)\n', (2723, 2747), False, 'import akro\n'), ((3791, 3822), 'numpy.zeros', 'np.zeros', (['self.task_space.shape'], {}), '(self.task_space.shape)\n', (3799, 3822), True, 'import numpy as np\n'), ((6021, 6068), 'numpy.concatenate', 'np.concatenate', (['[self.active_task_one_hot, obs]'], {}), '([self.active_task_one_hot, obs])\n', (6035, 6068), True, 'import numpy as np\n'), ((3222, 3255), 'numpy.concatenate', 'np.concatenate', (['[task_lb, env_lb]'], {}), '([task_lb, env_lb])\n', (3236, 3255), True, 'import numpy as np\n'), ((3281, 3314), 'numpy.concatenate', 'np.concatenate', (['[task_ub, env_ub]'], {}), '([task_ub, env_ub])\n', (3295, 3314), True, 'import numpy as np\n'), ((4649, 4667), 'numpy.prod', 'np.prod', (['obs.shape'], {}), '(obs.shape)\n', (4656, 4667), True, 'import numpy as np\n'), ((4819, 4847), 'numpy.concatenate', 'np.concatenate', (['[obs, zeros]'], {}), '([obs, zeros])\n', (4833, 4847), True, 'import numpy as np\n'), ((1718, 1754), 'numpy.prod', 'np.prod', (['env.observation_space.shape'], {}), '(env.observation_space.shape)\n', (1725, 1754), True, 'import numpy as np\n'), ((1856, 1892), 'numpy.prod', 'np.prod', (['env.observation_space.shape'], {}), '(env.observation_space.shape)\n', (1863, 1892), True, 'import numpy as np\n'), ((4766, 4784), 'numpy.prod', 'np.prod', (['obs.shape'], {}), '(obs.shape)\n', (4773, 4784), True, 'import numpy as np\n')]
import numpy as np np.random.seed(10) import matplotlib.pyplot as plt from mpi4py import MPI # For shared memory deployment: `export OPENBLAS_NUM_THREADS=1` # Method of snapshots def generate_right_vectors(A): ''' A - Snapshot matrix - shape: NxS returns V - truncated right singular vectors ''' new_mat = np.matmul(np.transpose(A),A) w, v = np.linalg.eig(new_mat) svals = np.sqrt(np.abs(w)) rval = np.argmax(svals<0.0001) # eps0 return v[:,:rval], np.sqrt(np.abs(w[:rval])) # Covariance eigenvectors, singular values # Randomized SVD to accelerate def low_rank_svd(A,K): M = A.shape[0] N = A.shape[1] omega = np.random.normal(size=(N,2*K)) omega_pm = np.matmul(A,np.transpose(A)) Y = np.matmul(omega_pm,np.matmul(A,omega)) Qred, Rred = np.linalg.qr(Y) B = np.matmul(np.transpose(Qred),A) ustar, snew, _ = np.linalg.svd(B) unew = np.matmul(Qred,ustar) unew = unew[:,:K] snew = snew[:K] return unew, snew # Check orthogonality def check_ortho(modes,num_modes): for m1 in range(num_modes): for m2 in range(num_modes): if m1 == m2: s_ = np.sum(modes[:,m1]*modes[:,m2]) if not np.isclose(s_,1.0): print('Orthogonality check failed') break else: s_ = np.sum(modes[:,m1]*modes[:,m2]) if not np.isclose(s_,0.0): print('Orthogonality check failed') break print('Orthogonality check passed successfully') class online_svd_calculator(object): """ docstring for online_svd_calculator: K : Number of modes to truncate ff : Forget factor """ def __init__(self, K, ff, low_rank=False): super(online_svd_calculator, self).__init__() self.K = K self.ff = ff # Initialize MPI self.comm = MPI.COMM_WORLD self.rank = self.comm.Get_rank() self.nprocs = self.comm.Get_size() self.iteration = 0 self.low_rank = low_rank # Initialize def initialize(self, A): self.ulocal, self.svalue = self.parallel_svd(A) def parallel_qr(self,A): # Perform the local QR q, r = np.linalg.qr(A) rlocal_shape_0 = r.shape[0] rlocal_shape_1 = r.shape[1] # Gather data at rank 0: r_global = self.comm.gather(r,root=0) # perform SVD at rank 0: if self.rank == 0: temp = r_global[0] for i in range(self.nprocs-1): temp = np.concatenate((temp,r_global[i+1]),axis=0) r_global = temp qglobal, rfinal = np.linalg.qr(r_global) qglobal = -qglobal # Trick for consistency rfinal = -rfinal # For this rank qlocal = np.matmul(q,qglobal[:rlocal_shape_0]) # send to other ranks for rank in range(1,self.nprocs): self.comm.send(qglobal[rank*rlocal_shape_0:(rank+1)*rlocal_shape_0], dest=rank, tag=rank+10) # Step b of Levy-Lindenbaum - small operation if self.low_rank: # Low rank SVD unew, snew = low_rank_svd(rfinal,self.K) else: unew, snew, _ = np.linalg.svd(rfinal) else: # Receive qglobal slices from other ranks qglobal = self.comm.recv(source=0, tag=self.rank+10) # For this rank qlocal = np.matmul(q,qglobal) # To receive new singular vectors unew = None snew = None unew = self.comm.bcast(unew,root=0) snew = self.comm.bcast(snew,root=0) return qlocal, unew, snew def parallel_svd(self,A): vlocal, slocal = generate_right_vectors(A) # Find Wr wlocal = np.matmul(vlocal,np.diag(slocal).T) # Gather data at rank 0: wglobal = self.comm.gather(wlocal,root=0) # perform SVD at rank 0: if self.rank == 0: temp = wglobal[0] for i in range(self.nprocs-1): temp = np.concatenate((temp,wglobal[i+1]),axis=-1) wglobal = temp if self.low_rank: x, s = low_rank_svd(wglobal,self.K) else: x, s, y = np.linalg.svd(wglobal) else: x = None s = None x = self.comm.bcast(x,root=0) s = self.comm.bcast(s,root=0) # # Find truncation threshold # s_ratio = np.cumsum(s)/np.sum(s) # rval = np.argmax(1.0-s_ratio<0.0001) # eps1 # perform APMOS at each local rank phi_local = [] for mode in range(self.K): phi_temp = 1.0/s[mode]*np.matmul(A,x[:,mode:mode+1]) phi_local.append(phi_temp) temp = phi_local[0] for i in range(self.K-1): temp = np.concatenate((temp,phi_local[i+1]),axis=-1) return temp, s[:self.K] # def incorporate_data(self,A): self.iteration+=1 ll = self.ff*np.matmul(self.ulocal,np.diag(self.svalue)) ll = np.concatenate((ll,A),axis=-1) qlocal, utemp, self.svalue = self.parallel_qr(ll) self.ulocal = np.matmul(qlocal,utemp) def gather_modes(self): # Gather modes at rank 0 # This is automatically in order phi_global = self.comm.gather(self.ulocal,root=0) if self.rank == 0: phi = phi_global[0] for i in range(self.nprocs-1): phi = np.concatenate((phi,phi_global[i+1]),axis=0) np.save('Online_Parallel_POD.npy',phi) np.save('Online_Parallel_SingularValues.npy',self.svalue) # Validate serial = np.load('Serial_Modes_MOS.npy') parallel_online = np.load('Online_Parallel_POD.npy') serial_online = np.load('Online_Serial_POD.npy') plt.figure() plt.plot(serial[:,0],label='serial one-shot') plt.plot(parallel_online[:,0],label='parallel_online') plt.plot(serial_online[:,0],label='serial_online') plt.title('U comparison - column 0') plt.xlabel('Domain') plt.ylabel('U magnitude') plt.legend() plt.figure() plt.plot(serial[:,2],label='serial one-shot') plt.plot(parallel_online[:,2],label='parallel_online') plt.plot(serial_online[:,2],label='serial_online') plt.title('U comparison - column 2') plt.xlabel('Domain') plt.ylabel('U magnitude') plt.legend() serial_svs = np.load('Serial_SingularValues.npy') serial_online_svs = np.load('Online_Serial_SingularValues.npy') parallel_online_svs = np.load('Online_Parallel_SingularValues.npy') plt.figure() plt.plot(serial_svs[:self.K],label='serial one-shot') plt.plot(parallel_online_svs[:self.K],label='parallel_online') plt.plot(serial_online_svs[:self.K],label='serial_online') plt.title('Singular values') plt.xlabel('Index') plt.ylabel('Magnitude') plt.legend() plt.show() # Check orthogonality - should all be successful check_ortho(serial,self.K) check_ortho(serial_online,self.K) check_ortho(parallel_online,self.K) if __name__ == '__main__': from time import time # Initialize timer start_time = time() test_class = online_svd_calculator(10,1.0,low_rank=True) iteration = 0 data = np.load('points_rank_'+str(test_class.rank)+'_batch_'+str(iteration)+'.npy') test_class.initialize(data) for iteration in range(1,4): data = np.load('points_rank_'+str(test_class.rank)+'_batch_'+str(iteration)+'.npy') test_class.incorporate_data(data) end_time = time() print('Time required for parallel streaming SVD (each rank):', end_time-start_time) test_class.gather_modes()
[ "matplotlib.pyplot.ylabel", "numpy.save", "numpy.linalg.qr", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.matmul", "numpy.random.seed", "numpy.concatenate", "numpy.random.normal", "numpy.abs", "numpy.linalg.eig", "numpy.argmax", "numpy.linalg.svd", "matplotlib.pyplot.title", "numpy.transpose", "time.time", "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "numpy.isclose", "numpy.diag", "numpy.sum", "matplotlib.pyplot.figure", "numpy.load" ]
[((19, 37), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (33, 37), True, 'import numpy as np\n'), ((368, 390), 'numpy.linalg.eig', 'np.linalg.eig', (['new_mat'], {}), '(new_mat)\n', (381, 390), True, 'import numpy as np\n'), ((434, 459), 'numpy.argmax', 'np.argmax', (['(svals < 0.0001)'], {}), '(svals < 0.0001)\n', (443, 459), True, 'import numpy as np\n'), ((664, 697), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(N, 2 * K)'}), '(size=(N, 2 * K))\n', (680, 697), True, 'import numpy as np\n'), ((805, 820), 'numpy.linalg.qr', 'np.linalg.qr', (['Y'], {}), '(Y)\n', (817, 820), True, 'import numpy as np\n'), ((883, 899), 'numpy.linalg.svd', 'np.linalg.svd', (['B'], {}), '(B)\n', (896, 899), True, 'import numpy as np\n'), ((916, 938), 'numpy.matmul', 'np.matmul', (['Qred', 'ustar'], {}), '(Qred, ustar)\n', (925, 938), True, 'import numpy as np\n'), ((7592, 7598), 'time.time', 'time', ([], {}), '()\n', (7596, 7598), False, 'from time import time\n'), ((7984, 7990), 'time.time', 'time', ([], {}), '()\n', (7988, 7990), False, 'from time import time\n'), ((338, 353), 'numpy.transpose', 'np.transpose', (['A'], {}), '(A)\n', (350, 353), True, 'import numpy as np\n'), ((412, 421), 'numpy.abs', 'np.abs', (['w'], {}), '(w)\n', (418, 421), True, 'import numpy as np\n'), ((723, 738), 'numpy.transpose', 'np.transpose', (['A'], {}), '(A)\n', (735, 738), True, 'import numpy as np\n'), ((767, 786), 'numpy.matmul', 'np.matmul', (['A', 'omega'], {}), '(A, omega)\n', (776, 786), True, 'import numpy as np\n'), ((840, 858), 'numpy.transpose', 'np.transpose', (['Qred'], {}), '(Qred)\n', (852, 858), True, 'import numpy as np\n'), ((2280, 2295), 'numpy.linalg.qr', 'np.linalg.qr', (['A'], {}), '(A)\n', (2292, 2295), True, 'import numpy as np\n'), ((5170, 5202), 'numpy.concatenate', 'np.concatenate', (['(ll, A)'], {'axis': '(-1)'}), '((ll, A), axis=-1)\n', (5184, 5202), True, 'import numpy as np\n'), ((5283, 5307), 'numpy.matmul', 'np.matmul', (['qlocal', 'utemp'], {}), '(qlocal, utemp)\n', (5292, 5307), True, 'import numpy as np\n'), ((497, 513), 'numpy.abs', 'np.abs', (['w[:rval]'], {}), '(w[:rval])\n', (503, 513), True, 'import numpy as np\n'), ((2709, 2731), 'numpy.linalg.qr', 'np.linalg.qr', (['r_global'], {}), '(r_global)\n', (2721, 2731), True, 'import numpy as np\n'), ((2866, 2904), 'numpy.matmul', 'np.matmul', (['q', 'qglobal[:rlocal_shape_0]'], {}), '(q, qglobal[:rlocal_shape_0])\n', (2875, 2904), True, 'import numpy as np\n'), ((3527, 3548), 'numpy.matmul', 'np.matmul', (['q', 'qglobal'], {}), '(q, qglobal)\n', (3536, 3548), True, 'import numpy as np\n'), ((4949, 4998), 'numpy.concatenate', 'np.concatenate', (['(temp, phi_local[i + 1])'], {'axis': '(-1)'}), '((temp, phi_local[i + 1]), axis=-1)\n', (4963, 4998), True, 'import numpy as np\n'), ((5651, 5690), 'numpy.save', 'np.save', (['"""Online_Parallel_POD.npy"""', 'phi'], {}), "('Online_Parallel_POD.npy', phi)\n", (5658, 5690), True, 'import numpy as np\n'), ((5702, 5760), 'numpy.save', 'np.save', (['"""Online_Parallel_SingularValues.npy"""', 'self.svalue'], {}), "('Online_Parallel_SingularValues.npy', self.svalue)\n", (5709, 5760), True, 'import numpy as np\n'), ((5805, 5836), 'numpy.load', 'np.load', (['"""Serial_Modes_MOS.npy"""'], {}), "('Serial_Modes_MOS.npy')\n", (5812, 5836), True, 'import numpy as np\n'), ((5867, 5901), 'numpy.load', 'np.load', (['"""Online_Parallel_POD.npy"""'], {}), "('Online_Parallel_POD.npy')\n", (5874, 5901), True, 'import numpy as np\n'), ((5930, 5962), 'numpy.load', 'np.load', (['"""Online_Serial_POD.npy"""'], {}), "('Online_Serial_POD.npy')\n", (5937, 5962), True, 'import numpy as np\n'), ((5976, 5988), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5986, 5988), True, 'import matplotlib.pyplot as plt\n'), ((6001, 6048), 'matplotlib.pyplot.plot', 'plt.plot', (['serial[:, 0]'], {'label': '"""serial one-shot"""'}), "(serial[:, 0], label='serial one-shot')\n", (6009, 6048), True, 'import matplotlib.pyplot as plt\n'), ((6059, 6115), 'matplotlib.pyplot.plot', 'plt.plot', (['parallel_online[:, 0]'], {'label': '"""parallel_online"""'}), "(parallel_online[:, 0], label='parallel_online')\n", (6067, 6115), True, 'import matplotlib.pyplot as plt\n'), ((6126, 6178), 'matplotlib.pyplot.plot', 'plt.plot', (['serial_online[:, 0]'], {'label': '"""serial_online"""'}), "(serial_online[:, 0], label='serial_online')\n", (6134, 6178), True, 'import matplotlib.pyplot as plt\n'), ((6189, 6225), 'matplotlib.pyplot.title', 'plt.title', (['"""U comparison - column 0"""'], {}), "('U comparison - column 0')\n", (6198, 6225), True, 'import matplotlib.pyplot as plt\n'), ((6238, 6258), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Domain"""'], {}), "('Domain')\n", (6248, 6258), True, 'import matplotlib.pyplot as plt\n'), ((6271, 6296), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""U magnitude"""'], {}), "('U magnitude')\n", (6281, 6296), True, 'import matplotlib.pyplot as plt\n'), ((6309, 6321), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6319, 6321), True, 'import matplotlib.pyplot as plt\n'), ((6335, 6347), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6345, 6347), True, 'import matplotlib.pyplot as plt\n'), ((6360, 6407), 'matplotlib.pyplot.plot', 'plt.plot', (['serial[:, 2]'], {'label': '"""serial one-shot"""'}), "(serial[:, 2], label='serial one-shot')\n", (6368, 6407), True, 'import matplotlib.pyplot as plt\n'), ((6418, 6474), 'matplotlib.pyplot.plot', 'plt.plot', (['parallel_online[:, 2]'], {'label': '"""parallel_online"""'}), "(parallel_online[:, 2], label='parallel_online')\n", (6426, 6474), True, 'import matplotlib.pyplot as plt\n'), ((6485, 6537), 'matplotlib.pyplot.plot', 'plt.plot', (['serial_online[:, 2]'], {'label': '"""serial_online"""'}), "(serial_online[:, 2], label='serial_online')\n", (6493, 6537), True, 'import matplotlib.pyplot as plt\n'), ((6548, 6584), 'matplotlib.pyplot.title', 'plt.title', (['"""U comparison - column 2"""'], {}), "('U comparison - column 2')\n", (6557, 6584), True, 'import matplotlib.pyplot as plt\n'), ((6597, 6617), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Domain"""'], {}), "('Domain')\n", (6607, 6617), True, 'import matplotlib.pyplot as plt\n'), ((6630, 6655), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""U magnitude"""'], {}), "('U magnitude')\n", (6640, 6655), True, 'import matplotlib.pyplot as plt\n'), ((6668, 6680), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6678, 6680), True, 'import matplotlib.pyplot as plt\n'), ((6707, 6743), 'numpy.load', 'np.load', (['"""Serial_SingularValues.npy"""'], {}), "('Serial_SingularValues.npy')\n", (6714, 6743), True, 'import numpy as np\n'), ((6776, 6819), 'numpy.load', 'np.load', (['"""Online_Serial_SingularValues.npy"""'], {}), "('Online_Serial_SingularValues.npy')\n", (6783, 6819), True, 'import numpy as np\n'), ((6854, 6899), 'numpy.load', 'np.load', (['"""Online_Parallel_SingularValues.npy"""'], {}), "('Online_Parallel_SingularValues.npy')\n", (6861, 6899), True, 'import numpy as np\n'), ((6913, 6925), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6923, 6925), True, 'import matplotlib.pyplot as plt\n'), ((6938, 6992), 'matplotlib.pyplot.plot', 'plt.plot', (['serial_svs[:self.K]'], {'label': '"""serial one-shot"""'}), "(serial_svs[:self.K], label='serial one-shot')\n", (6946, 6992), True, 'import matplotlib.pyplot as plt\n'), ((7004, 7067), 'matplotlib.pyplot.plot', 'plt.plot', (['parallel_online_svs[:self.K]'], {'label': '"""parallel_online"""'}), "(parallel_online_svs[:self.K], label='parallel_online')\n", (7012, 7067), True, 'import matplotlib.pyplot as plt\n'), ((7079, 7138), 'matplotlib.pyplot.plot', 'plt.plot', (['serial_online_svs[:self.K]'], {'label': '"""serial_online"""'}), "(serial_online_svs[:self.K], label='serial_online')\n", (7087, 7138), True, 'import matplotlib.pyplot as plt\n'), ((7150, 7178), 'matplotlib.pyplot.title', 'plt.title', (['"""Singular values"""'], {}), "('Singular values')\n", (7159, 7178), True, 'import matplotlib.pyplot as plt\n'), ((7191, 7210), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Index"""'], {}), "('Index')\n", (7201, 7210), True, 'import matplotlib.pyplot as plt\n'), ((7223, 7246), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude"""'], {}), "('Magnitude')\n", (7233, 7246), True, 'import matplotlib.pyplot as plt\n'), ((7259, 7271), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7269, 7271), True, 'import matplotlib.pyplot as plt\n'), ((7284, 7294), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7292, 7294), True, 'import matplotlib.pyplot as plt\n'), ((1175, 1210), 'numpy.sum', 'np.sum', (['(modes[:, m1] * modes[:, m2])'], {}), '(modes[:, m1] * modes[:, m2])\n', (1181, 1210), True, 'import numpy as np\n'), ((1372, 1407), 'numpy.sum', 'np.sum', (['(modes[:, m1] * modes[:, m2])'], {}), '(modes[:, m1] * modes[:, m2])\n', (1378, 1407), True, 'import numpy as np\n'), ((2606, 2653), 'numpy.concatenate', 'np.concatenate', (['(temp, r_global[i + 1])'], {'axis': '(0)'}), '((temp, r_global[i + 1]), axis=0)\n', (2620, 2653), True, 'import numpy as np\n'), ((3321, 3342), 'numpy.linalg.svd', 'np.linalg.svd', (['rfinal'], {}), '(rfinal)\n', (3334, 3342), True, 'import numpy as np\n'), ((3903, 3918), 'numpy.diag', 'np.diag', (['slocal'], {}), '(slocal)\n', (3910, 3918), True, 'import numpy as np\n'), ((4163, 4210), 'numpy.concatenate', 'np.concatenate', (['(temp, wglobal[i + 1])'], {'axis': '(-1)'}), '((temp, wglobal[i + 1]), axis=-1)\n', (4177, 4210), True, 'import numpy as np\n'), ((4361, 4383), 'numpy.linalg.svd', 'np.linalg.svd', (['wglobal'], {}), '(wglobal)\n', (4374, 4383), True, 'import numpy as np\n'), ((4798, 4831), 'numpy.matmul', 'np.matmul', (['A', 'x[:, mode:mode + 1]'], {}), '(A, x[:, mode:mode + 1])\n', (4807, 4831), True, 'import numpy as np\n'), ((5135, 5155), 'numpy.diag', 'np.diag', (['self.svalue'], {}), '(self.svalue)\n', (5142, 5155), True, 'import numpy as np\n'), ((5593, 5641), 'numpy.concatenate', 'np.concatenate', (['(phi, phi_global[i + 1])'], {'axis': '(0)'}), '((phi, phi_global[i + 1]), axis=0)\n', (5607, 5641), True, 'import numpy as np\n'), ((1231, 1250), 'numpy.isclose', 'np.isclose', (['s_', '(1.0)'], {}), '(s_, 1.0)\n', (1241, 1250), True, 'import numpy as np\n'), ((1428, 1447), 'numpy.isclose', 'np.isclose', (['s_', '(0.0)'], {}), '(s_, 0.0)\n', (1438, 1447), True, 'import numpy as np\n')]
''' THis is the main training code. ''' import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" # set GPU id at the very begining import argparse import random import math import numpy as np import torch import torch.nn.parallel import torch.optim as optim import torch.utils.data import torch.nn.functional as F from torch.multiprocessing import freeze_support import json import sys import time import pdb # internal package from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom from models.pan import PAN from loss.loss import loss from utils.helper import adjust_learning_rate, upsample from utils.average_meter import AverageMeter torch.set_num_threads(2) # main function: if __name__ == '__main__': freeze_support() parser = argparse.ArgumentParser() parser.add_argument( '--batch', type=int, default=16, help='input batch size') parser.add_argument( '--worker', type=int, default=4, help='number of data loading workers') parser.add_argument( '--epoch', type=int, default=601, help='number of epochs') parser.add_argument('--output', type=str, default='outputs', help='output folder name') parser.add_argument('--model', type=str, default='', help='model path') parser.add_argument('--dataset_type', type=str, default='ctw', help="dataset type - ctw | tt | synthtext | msra | ic15 | custom") parser.add_argument('--gpu', type=bool, default=False, help="GPU being used or not") opt = parser.parse_args() print(opt) opt.manualSeed = random.randint(1, 10000) # fix seed print("Random Seed:", opt.manualSeed) random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) torch.cuda.manual_seed(opt.manualSeed) np.random.seed(opt.manualSeed) # turn on GPU for models: if opt.gpu == False: device = torch.device("cpu") print("CPU being used!") else: if torch.cuda.is_available() == True and opt.gpu == True: device = torch.device("cuda") print("GPU being used!") else: device = torch.device("cpu") print("CPU being used!") # set training parameters batch_size = opt.batch neck_channel = (64, 128, 256, 512) pa_in_channels = 512 hidden_dim = 128 num_classes = 6 loss_text_weight = 1.0 loss_kernel_weight = 0.5 loss_emb_weight = 0.25 opt.optimizer = 'Adam' opt.lr = 1e-3 opt.schedule = 'polylr' epochs = opt.epoch worker = opt.worker dataset_type = opt.dataset_type output_path = opt.output trained_model_path = opt.model # create dataset print("Create dataset......") if dataset_type == 'ctw': # ctw dataset train_dataset = ctw1500.PAN_CTW(split='train', is_transform=True, img_size=640, short_size=640, kernel_scale=0.7, report_speed=False) elif dataset_type == 'tt': # totaltext dataset train_dataset = totaltext.PAN_TT(split='train', is_transform=True, img_size=640, short_size=640, kernel_scale=0.7, with_rec=False, report_speed=False) elif dataset_type == 'synthtext': # synthtext dataset train_dataset = synthtext.PAN_Synth(is_transform=True, img_size=640, short_size=640, kernel_scale=0.5, with_rec=False) elif dataset_type == 'msra': # msra dataset train_dataset = msra.PAN_MSRA(split='train', is_transform=True, img_size=736, short_size=736, kernel_scale=0.7, report_speed=False) elif dataset_type == 'ic15': # msra dataset train_dataset = ic15.PAN_IC15(split='train', is_transform=True, img_size=736, short_size=736, kernel_scale=0.5, with_rec=False) elif dataset_type == 'custom': # msra dataset train_dataset = custom.PAN_CTW(split='train', is_transform=True, img_size=640, short_size=640, kernel_scale=0.7, report_speed=False) else: print("Not supported yet!") exit(1) # make dataloader train_dataloader = torch.utils.data.DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=int(worker), drop_last=True, pin_memory=True) print("Length of train dataset is:", len(train_dataset)) # make model output folder try: os.makedirs(output_path) except OSError: pass # create model print("Create model......") model = PAN(pretrained=False, neck_channel=neck_channel, pa_in_channels=pa_in_channels, hidden_dim=hidden_dim, num_classes=num_classes) if trained_model_path != '': if torch.cuda.is_available() == True and opt.gpu == True: model.load_state_dict(torch.load(trained_model_path, map_location=lambda storage, loc: storage), strict=False) model = torch.nn.DataParallel(model).to(device) else: model.load_state_dict(torch.load(trained_model_path, map_location=lambda storage, loc: storage), strict=False) else: if torch.cuda.is_available() == True and opt.gpu == True: model = torch.nn.DataParallel(model).to(device) else: model = model.to(device) if opt.optimizer == 'SGD': optimizer = optim.SGD(model.parameters(), lr=opt.lr, momentum=0.99, weight_decay=5e-4) elif opt.optimizer == 'Adam': optimizer = optim.Adam(model.parameters(), lr=opt.lr) else: print("Error: Please specify correct optimizer!") exit(1) # train, evaluate, and save model print("Training starts......") start_epoch = 0 for epoch in range(start_epoch, epochs): print('Epoch: [%d | %d]' % (epoch + 1, epochs)) model.train() # meters losses = AverageMeter() losses_text = AverageMeter() losses_kernels = AverageMeter() losses_emb = AverageMeter() losses_rec = AverageMeter() ious_text = AverageMeter() ious_kernel = AverageMeter() for iter, data in enumerate(train_dataloader): # adjust learning rate adjust_learning_rate(optimizer, train_dataloader, epoch, iter, opt.schedule, opt.lr, epochs) outputs = dict() # forward for detection output det_out = model(data['imgs'].to(device)) det_out = upsample(det_out, data['imgs'].size()) # retreive ground truth labels gt_texts = data['gt_texts'].to(device) gt_kernels = data['gt_kernels'].to(device) training_masks = data['training_masks'].to(device) gt_instances = data['gt_instances'].to(device) gt_bboxes = data['gt_bboxes'].to(device) # calculate total loss det_loss = loss(det_out, gt_texts, gt_kernels, training_masks, gt_instances, gt_bboxes, loss_text_weight, loss_kernel_weight, loss_emb_weight) outputs.update(det_loss) # detection loss loss_text = torch.mean(outputs['loss_text']) losses_text.update(loss_text.item()) loss_kernels = torch.mean(outputs['loss_kernels']) losses_kernels.update(loss_kernels.item()) loss_emb = torch.mean(outputs['loss_emb']) losses_emb.update(loss_emb.item()) loss_total = loss_text + loss_kernels + loss_emb iou_text = torch.mean(outputs['iou_text']) ious_text.update(iou_text.item()) iou_kernel = torch.mean(outputs['iou_kernel']) ious_kernel.update(iou_kernel.item()) losses.update(loss_total.item()) # backward optimizer.zero_grad() loss_total.backward() optimizer.step() # print log #print("batch: {} / total batch: {}".format(iter+1, len(train_dataloader))) if iter % 20 == 0: output_log = '({batch}/{size}) LR: {lr:.6f} | ' \ 'Loss: {loss:.3f} | ' \ 'Loss (text/kernel/emb): {loss_text:.3f}/{loss_kernel:.3f}/{loss_emb:.3f} ' \ '| IoU (text/kernel): {iou_text:.3f}/{iou_kernel:.3f}'.format( batch=iter + 1, size=len(train_dataloader), lr=optimizer.param_groups[0]['lr'], loss_text=losses_text.avg, loss_kernel=losses_kernels.avg, loss_emb=losses_emb.avg, loss=losses.avg, iou_text=ious_text.avg, iou_kernel=ious_kernel.avg, ) print(output_log) sys.stdout.flush() with open(os.path.join(output_path,'statistics.txt'), 'a') as f: f.write("{} {} {} {} {} {}\n".format(losses_text.avg, losses_kernels.avg, losses_emb.avg, losses.avg, ious_text.avg, ious_kernel.avg)) if epoch % 20 == 0: print("Save model......") if torch.cuda.is_available() == True and opt.gpu == True: torch.save(model.module.state_dict(), '%s/model_epoch_%s.pth' % (output_path, str(epoch))) else: torch.save(model.state_dict(), '%s/model_epoch_%s.pth' % (output_path, str(epoch)))
[ "dataset.synthtext.PAN_Synth", "torch.cuda.is_available", "torch.multiprocessing.freeze_support", "loss.loss.loss", "argparse.ArgumentParser", "models.pan.PAN", "torch.mean", "dataset.custom.PAN_CTW", "torch.set_num_threads", "numpy.random.seed", "sys.stdout.flush", "dataset.ic15.PAN_IC15", "random.randint", "utils.average_meter.AverageMeter", "dataset.ctw1500.PAN_CTW", "utils.helper.adjust_learning_rate", "dataset.totaltext.PAN_TT", "torch.device", "dataset.msra.PAN_MSRA", "torch.manual_seed", "os.makedirs", "torch.load", "os.path.join", "torch.nn.DataParallel", "random.seed", "torch.cuda.manual_seed" ]
[((647, 671), 'torch.set_num_threads', 'torch.set_num_threads', (['(2)'], {}), '(2)\n', (668, 671), False, 'import torch\n'), ((720, 736), 'torch.multiprocessing.freeze_support', 'freeze_support', ([], {}), '()\n', (734, 736), False, 'from torch.multiprocessing import freeze_support\n'), ((750, 775), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (773, 775), False, 'import argparse\n'), ((1523, 1547), 'random.randint', 'random.randint', (['(1)', '(10000)'], {}), '(1, 10000)\n', (1537, 1547), False, 'import random\n'), ((1606, 1633), 'random.seed', 'random.seed', (['opt.manualSeed'], {}), '(opt.manualSeed)\n', (1617, 1633), False, 'import random\n'), ((1638, 1671), 'torch.manual_seed', 'torch.manual_seed', (['opt.manualSeed'], {}), '(opt.manualSeed)\n', (1655, 1671), False, 'import torch\n'), ((1676, 1714), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['opt.manualSeed'], {}), '(opt.manualSeed)\n', (1698, 1714), False, 'import torch\n'), ((1719, 1749), 'numpy.random.seed', 'np.random.seed', (['opt.manualSeed'], {}), '(opt.manualSeed)\n', (1733, 1749), True, 'import numpy as np\n'), ((5596, 5728), 'models.pan.PAN', 'PAN', ([], {'pretrained': '(False)', 'neck_channel': 'neck_channel', 'pa_in_channels': 'pa_in_channels', 'hidden_dim': 'hidden_dim', 'num_classes': 'num_classes'}), '(pretrained=False, neck_channel=neck_channel, pa_in_channels=\n pa_in_channels, hidden_dim=hidden_dim, num_classes=num_classes)\n', (5599, 5728), False, 'from models.pan import PAN\n'), ((1827, 1846), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1839, 1846), False, 'import torch\n'), ((2718, 2840), 'dataset.ctw1500.PAN_CTW', 'ctw1500.PAN_CTW', ([], {'split': '"""train"""', 'is_transform': '(True)', 'img_size': '(640)', 'short_size': '(640)', 'kernel_scale': '(0.7)', 'report_speed': '(False)'}), "(split='train', is_transform=True, img_size=640, short_size=\n 640, kernel_scale=0.7, report_speed=False)\n", (2733, 2840), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n'), ((5474, 5498), 'os.makedirs', 'os.makedirs', (['output_path'], {}), '(output_path)\n', (5485, 5498), False, 'import os\n'), ((6892, 6906), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6904, 6906), False, 'from utils.average_meter import AverageMeter\n'), ((6929, 6943), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6941, 6943), False, 'from utils.average_meter import AverageMeter\n'), ((6969, 6983), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6981, 6983), False, 'from utils.average_meter import AverageMeter\n'), ((7005, 7019), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7017, 7019), False, 'from utils.average_meter import AverageMeter\n'), ((7041, 7055), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7053, 7055), False, 'from utils.average_meter import AverageMeter\n'), ((7076, 7090), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7088, 7090), False, 'from utils.average_meter import AverageMeter\n'), ((7113, 7127), 'utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (7125, 7127), False, 'from utils.average_meter import AverageMeter\n'), ((1977, 1997), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1989, 1997), False, 'import torch\n'), ((2070, 2089), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2082, 2089), False, 'import torch\n'), ((3111, 3250), 'dataset.totaltext.PAN_TT', 'totaltext.PAN_TT', ([], {'split': '"""train"""', 'is_transform': '(True)', 'img_size': '(640)', 'short_size': '(640)', 'kernel_scale': '(0.7)', 'with_rec': '(False)', 'report_speed': '(False)'}), "(split='train', is_transform=True, img_size=640, short_size\n =640, kernel_scale=0.7, with_rec=False, report_speed=False)\n", (3127, 3250), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n'), ((7244, 7340), 'utils.helper.adjust_learning_rate', 'adjust_learning_rate', (['optimizer', 'train_dataloader', 'epoch', 'iter', 'opt.schedule', 'opt.lr', 'epochs'], {}), '(optimizer, train_dataloader, epoch, iter, opt.schedule,\n opt.lr, epochs)\n', (7264, 7340), False, 'from utils.helper import adjust_learning_rate, upsample\n'), ((7918, 8053), 'loss.loss.loss', 'loss', (['det_out', 'gt_texts', 'gt_kernels', 'training_masks', 'gt_instances', 'gt_bboxes', 'loss_text_weight', 'loss_kernel_weight', 'loss_emb_weight'], {}), '(det_out, gt_texts, gt_kernels, training_masks, gt_instances, gt_bboxes,\n loss_text_weight, loss_kernel_weight, loss_emb_weight)\n', (7922, 8053), False, 'from loss.loss import loss\n'), ((8153, 8185), 'torch.mean', 'torch.mean', (["outputs['loss_text']"], {}), "(outputs['loss_text'])\n", (8163, 8185), False, 'import torch\n'), ((8263, 8298), 'torch.mean', 'torch.mean', (["outputs['loss_kernels']"], {}), "(outputs['loss_kernels'])\n", (8273, 8298), False, 'import torch\n'), ((8378, 8409), 'torch.mean', 'torch.mean', (["outputs['loss_emb']"], {}), "(outputs['loss_emb'])\n", (8388, 8409), False, 'import torch\n'), ((8543, 8574), 'torch.mean', 'torch.mean', (["outputs['iou_text']"], {}), "(outputs['iou_text'])\n", (8553, 8574), False, 'import torch\n'), ((8646, 8679), 'torch.mean', 'torch.mean', (["outputs['iou_kernel']"], {}), "(outputs['iou_kernel'])\n", (8656, 8679), False, 'import torch\n'), ((1901, 1926), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1924, 1926), False, 'import torch\n'), ((3574, 3680), 'dataset.synthtext.PAN_Synth', 'synthtext.PAN_Synth', ([], {'is_transform': '(True)', 'img_size': '(640)', 'short_size': '(640)', 'kernel_scale': '(0.5)', 'with_rec': '(False)'}), '(is_transform=True, img_size=640, short_size=640,\n kernel_scale=0.5, with_rec=False)\n', (3593, 3680), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n'), ((5769, 5794), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5792, 5794), False, 'import torch\n'), ((5858, 5931), 'torch.load', 'torch.load', (['trained_model_path'], {'map_location': '(lambda storage, loc: storage)'}), '(trained_model_path, map_location=lambda storage, loc: storage)\n', (5868, 5931), False, 'import torch\n'), ((6055, 6128), 'torch.load', 'torch.load', (['trained_model_path'], {'map_location': '(lambda storage, loc: storage)'}), '(trained_model_path, map_location=lambda storage, loc: storage)\n', (6065, 6128), False, 'import torch\n'), ((6165, 6190), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6188, 6190), False, 'import torch\n'), ((9852, 9870), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (9868, 9870), False, 'import sys\n'), ((3925, 4045), 'dataset.msra.PAN_MSRA', 'msra.PAN_MSRA', ([], {'split': '"""train"""', 'is_transform': '(True)', 'img_size': '(736)', 'short_size': '(736)', 'kernel_scale': '(0.7)', 'report_speed': '(False)'}), "(split='train', is_transform=True, img_size=736, short_size=\n 736, kernel_scale=0.7, report_speed=False)\n", (3938, 4045), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n'), ((5967, 5995), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (5988, 5995), False, 'import torch\n'), ((6240, 6268), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (6261, 6268), False, 'import torch\n'), ((10189, 10214), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10212, 10214), False, 'import torch\n'), ((4303, 4419), 'dataset.ic15.PAN_IC15', 'ic15.PAN_IC15', ([], {'split': '"""train"""', 'is_transform': '(True)', 'img_size': '(736)', 'short_size': '(736)', 'kernel_scale': '(0.5)', 'with_rec': '(False)'}), "(split='train', is_transform=True, img_size=736, short_size=\n 736, kernel_scale=0.5, with_rec=False)\n", (4316, 4419), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n'), ((9897, 9940), 'os.path.join', 'os.path.join', (['output_path', '"""statistics.txt"""'], {}), "(output_path, 'statistics.txt')\n", (9909, 9940), False, 'import os\n'), ((4679, 4800), 'dataset.custom.PAN_CTW', 'custom.PAN_CTW', ([], {'split': '"""train"""', 'is_transform': '(True)', 'img_size': '(640)', 'short_size': '(640)', 'kernel_scale': '(0.7)', 'report_speed': '(False)'}), "(split='train', is_transform=True, img_size=640, short_size=\n 640, kernel_scale=0.7, report_speed=False)\n", (4693, 4800), False, 'from dataset import ctw1500, totaltext, synthtext, msra, ic15, custom\n')]
import os, sys sys.path.append(os.getcwd()) import time import numpy as np import tensorflow as tf import tflib as lib import tflib.ops.linear import tflib.ops.conv2d import tflib.ops.batchnorm import tflib.ops.deconv2d import tflib.save_images import tflib.plot import tflib.flow_handler as fh import tflib.SINTELdata as sintel MODE = 'wgan-gp' # Valid options are dcgan, wgan, or wgan-gp DIM = 64 # This overfits substantially; you're probably better off with 64 # or 128? LAMBDA = 10 # Gradient penalty lambda hyperparameter CRITIC_ITERS = 5 # How many critic iterations per generator iteration BATCH_SIZE = 64 # Batch size ITERS = 100000 # How many generator iterations to train for # 200000 takes too long IM_DIM = 32 # number of pixels along x and y (square assumed) SQUARE_IM_DIM = IM_DIM*IM_DIM # 32*32 = 1024 OUTPUT_DIM = IM_DIM*IM_DIM*3 # Number of pixels (3*32*32) - rgb color OUTPUT_DIM_FLOW = IM_DIM*IM_DIM*2 # Number of pixels (2*32*32) - uv direction CONTINUE = False # Default False, set True if restoring from checkpoint START_ITER = 0 # Default 0, set accordingly if restoring from checkpoint (100, 200, ...) CURRENT_PATH = "sintel/flowcganuv5" restore_path = "/home/linkermann/opticalFlow/opticalFlowGAN/results/" + CURRENT_PATH + "/model.ckpt" lib.print_model_settings(locals().copy()) if(CONTINUE): tf.reset_default_graph() def LeakyReLU(x, alpha=0.2): return tf.maximum(alpha*x, x) def ReLULayer(name, n_in, n_out, inputs): output = lib.ops.linear.Linear(name+'.Linear', n_in, n_out, inputs) return tf.nn.relu(output) def LeakyReLULayer(name, n_in, n_out, inputs): output = lib.ops.linear.Linear(name+'.Linear', n_in, n_out, inputs) return LeakyReLU(output) def Generator(n_samples, conditions, noise=None): # input conds additional to noise if noise is None: noise = tf.random_normal([n_samples, SQUARE_IM_DIM]) noise = tf.reshape(noise, [n_samples, 1, IM_DIM, IM_DIM]) # new conditional input: last frames conds = tf.reshape(conditions, [n_samples, 6, IM_DIM, IM_DIM]) # conditions: (64,2*3072) TO conds: (64,6,32,32) # for now just concat the inputs: noise as seventh dim of cond image output = tf.concat([noise, conds], 1) # to: (BATCH_SIZE,7,32,32) output = tf.reshape(output, [n_samples, SQUARE_IM_DIM*7]) # 32x32x4 = 4096; to: (BATCH_SIZE, 4096) output = lib.ops.linear.Linear('Generator.Input', SQUARE_IM_DIM*7, 4*4*4*DIM, output) # 4*4*4*DIM = 64*64 = 4096 output = lib.ops.batchnorm.Batchnorm('Generator.BN1', [0], output) output = tf.nn.relu(output) output = tf.reshape(output, [-1, 4*DIM, 4, 4]) output = lib.ops.deconv2d.Deconv2D('Generator.2', 4*DIM, 2*DIM, 5, output) output = lib.ops.batchnorm.Batchnorm('Generator.BN2', [0,2,3], output) output = tf.nn.relu(output) output = lib.ops.deconv2d.Deconv2D('Generator.3', 2*DIM, DIM, 5, output) output = lib.ops.batchnorm.Batchnorm('Generator.BN3', [0,2,3], output) output = tf.nn.relu(output) output = lib.ops.deconv2d.Deconv2D('Generator.5', DIM, 2, 5, output) # output flow in color --> dim is 2 output = tf.tanh(output) return tf.reshape(output, [-1, OUTPUT_DIM_FLOW]) # output flow --> dim is 2 def Discriminator(inputs, conditions): # input conds as well inputs = tf.reshape(inputs, [-1, 2, IM_DIM, IM_DIM]) # input flow --> dim is 2 conds = tf.reshape(conditions, [-1, 6, IM_DIM, IM_DIM]) # new conditional input: last frames # for now just concat the inputs ins = tf.concat([inputs, conds], 1) #to: (BATCH_SIZE, 8, 32, 32) output = lib.ops.conv2d.Conv2D('Discriminator.1', 8, DIM, 5, ins, stride=2) # first dim is different: 8 now output = LeakyReLU(output) output = lib.ops.conv2d.Conv2D('Discriminator.2', DIM, 2*DIM, 5, output, stride=2) if MODE != 'wgan-gp': output = lib.ops.batchnorm.Batchnorm('Discriminator.BN2', [0,2,3], output) output = LeakyReLU(output) output = lib.ops.conv2d.Conv2D('Discriminator.3', 2*DIM, 4*DIM, 5, output, stride=2) if MODE != 'wgan-gp': output = lib.ops.batchnorm.Batchnorm('Discriminator.BN3', [0,2,3], output) output = LeakyReLU(output) #output = lib.ops.conv2d.Conv2D('Discriminator.4', 4*DIM, 8*DIM, 5, output, stride=2) # if MODE != 'wgan-gp': # output = lib.ops.batchnorm.Batchnorm('Discriminator.BN4', [0,2,3], output) # output = LeakyReLU(output) output = tf.reshape(output, [-1, 4*4*8*DIM]) # adjusted outcome output = lib.ops.linear.Linear('Discriminator.Output', 4*4*8*DIM, 1, output) return tf.reshape(output, [-1]) cond_data_int = tf.placeholder(tf.int32, shape=[BATCH_SIZE, 2*OUTPUT_DIM]) # cond input for G and D, 2 frames! cond_data = 2*((tf.cast(cond_data_int, tf.float32)/255.)-.5) #normalized [-1,1]! #real_data_int = tf.placeholder(tf.int32, shape=[BATCH_SIZE, OUTPUT_DIM_FLOW]) # real data is flow, dim 2! real_data = tf.placeholder(tf.float32, shape=[BATCH_SIZE, OUTPUT_DIM_FLOW]) #already float, normalized [-1,1]! fake_data = Generator(BATCH_SIZE, cond_data) disc_real = Discriminator(real_data, cond_data) disc_fake = Discriminator(fake_data, cond_data) gen_params = lib.params_with_name('Generator') disc_params = lib.params_with_name('Discriminator') if MODE == 'wgan': gen_cost = -tf.reduce_mean(disc_fake) disc_cost = tf.reduce_mean(disc_fake) - tf.reduce_mean(disc_real) gen_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-5).minimize(gen_cost, var_list=gen_params) disc_train_op = tf.train.RMSPropOptimizer(learning_rate=5e-5).minimize(disc_cost, var_list=disc_params) clip_ops = [] for var in disc_params: clip_bounds = [-.01, .01] clip_ops.append( tf.assign( var, tf.clip_by_value(var, clip_bounds[0], clip_bounds[1]) ) ) clip_disc_weights = tf.group(*clip_ops) elif MODE == 'wgan-gp': # Standard WGAN loss gen_cost = -tf.reduce_mean(disc_fake) disc_cost = tf.reduce_mean(disc_fake) - tf.reduce_mean(disc_real) # Gradient penalty alpha = tf.random_uniform( shape=[BATCH_SIZE,1], minval=0., maxval=1. ) differences = fake_data - real_data interpolates = real_data + (alpha*differences) gradients = tf.gradients(Discriminator(interpolates, cond_data), [interpolates])[0] #added cond here slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1])) gradient_penalty = tf.reduce_mean((slopes-1.)**2) disc_cost += LAMBDA*gradient_penalty gen_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(gen_cost, var_list=gen_params) disc_train_op = tf.train.AdamOptimizer(learning_rate=1e-4, beta1=0.5, beta2=0.9).minimize(disc_cost, var_list=disc_params) elif MODE == 'dcgan': gen_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.ones_like(disc_fake))) disc_cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_fake, tf.zeros_like(disc_fake))) disc_cost += tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(disc_real, tf.ones_like(disc_real))) disc_cost /= 2. gen_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(gen_cost, var_list=lib.params_with_name('Generator')) disc_train_op = tf.train.AdamOptimizer(learning_rate=2e-4, beta1=0.5).minimize(disc_cost, var_list=lib.params_with_name('Discriminator.')) # Dataset iterators gen = sintel.load_train_gen(BATCH_SIZE, (IM_DIM,IM_DIM,3), (IM_DIM,IM_DIM,2)) # batch size, im size, im size flow dev_gen = sintel.load_test_gen(BATCH_SIZE, (IM_DIM,IM_DIM,3), (IM_DIM,IM_DIM,2)) # For generating samples: define fixed noise and conditional input fixed_cond_samples, fixed_flow_samples = next(gen) # shape: (batchsize, 3072) fixed_cond_data_int = fixed_cond_samples[:,0:2*OUTPUT_DIM] # earlier frames as condition, cond samples shape (64,3*3072) fixed_real_data = fixed_flow_samples[:,OUTPUT_DIM_FLOW:] # later flow for discr, flow samples shape (64,2048) fixed_real_data_norm01 = tf.cast(fixed_real_data+1.0, tf.float32)/2.0 # [0,1] fixed_cond_data_normalized = 2*((tf.cast(fixed_cond_data_int, tf.float32)/255.)-.5) #normalized [-1,1]! fixed_viz_data_int = fixed_cond_samples[:,OUTPUT_DIM:2*OUTPUT_DIM] # each later frame for viz if(CONTINUE): fixed_noise = tf.get_variable("noise", shape=[BATCH_SIZE, SQUARE_IM_DIM]) # take same noise like saved model else: fixed_noise = tf.Variable(tf.random_normal(shape=[BATCH_SIZE, SQUARE_IM_DIM], dtype=tf.float32), name='noise') #variable: saved, for additional channel fixed_noise_samples = Generator(BATCH_SIZE, fixed_cond_data_normalized, noise=fixed_noise) # Generator(n_samples,conds, noise): def generate_image(frame, true_dist): # generates 64 (batch-size) samples next to each other in one image! print("Iteration %d : \n" % frame) samples = session.run(fixed_noise_samples, feed_dict={real_data: fixed_real_data, cond_data_int: fixed_cond_data_int}) # output range (-1.0,1.0), size=(BATCH_SIZE, OUT_DIM) #samples_255 = ((samples+1.)*(255./2)).astype('int32') #(-1,1) to [0,255] for displaying samples_01 = ((samples+1.)/2.).astype('float32') # [0,1] is a np.ndarray shape (64, 2048) # print(fixed_real_data_norm01.eval()) # shape (64, 2048) # bigger areas with (almost) same flow images2show = fixed_viz_data_int.reshape(BATCH_SIZE,3,IM_DIM,IM_DIM) sample_flowimages, real_flowimages = [], [] for i in range(0, BATCH_SIZE): real_flowimg, flowimg = [],[] # reset to be sure flowimg = fh.computeFlowImg(samples[i,:].reshape((IM_DIM,IM_DIM,2))) # (32, 32, 3) # now color img!! :) flowimg_T = np.transpose(flowimg, [2,0,1]) # (3, 32, 32) # flowimage = flowimage_T.reshape((OUTPUT_DIM,)) # instead of flatten? sample_flowimages.append(flowimg_T) real_uvflow = fixed_real_data[i,:] real_uvflow = real_uvflow.reshape((IM_DIM,IM_DIM,2)) real_flowimg = fh.computeFlowImg(real_uvflow) # (32, 32, 3) color img! real_flowimg = real_flowimg.reshape(IM_DIM,IM_DIM,3).astype('int32') # (32, 32, 3) real_flowimg_T = np.transpose(real_flowimg, [2,0,1]) # (3, 32, 32) real_flowimages.append(real_flowimg_T) # or which one? # also save as .flo? images2show = np.insert(images2show, i*2+1, flowimg_T, axis=0) #samples_255[2*i+1,:] = flowimage # sample flow color image # images2show.shape: (128, 3, 32, 32) = (2*BATCH_SIZE, 3, IM_DIM, IM_DIM) # images.reshape((2*BATCH_SIZE, 3, IM_DIM, IM_DIM)) lib.save_images.save_images(images2show, 'samples_{}.jpg'.format(frame)) sample_flowims_np = np.asarray(sample_flowimages, np.int32) real_flowims_np = np.asarray(real_flowimages, np.int32) sample_flowims = tf.convert_to_tensor(sample_flowims_np, np.int32) real_flowims = tf.convert_to_tensor(real_flowims_np, np.int32) # turn into tensor to reshape later # tensor = tf.constant(np_array) # another way to create a tensor # compare generated flow to real one # float..? # u-v-component wise real = tf.reshape(fixed_real_data_norm01, [BATCH_SIZE,IM_DIM,IM_DIM,2]) # use tf.reshape! Tensor! batch! real_u = tf.slice(real, [0,0,0,0], [real.get_shape()[0],real.get_shape()[1],real.get_shape()[2], 1]) real_v = tf.slice(real, [0,0,0,1], [real.get_shape()[0],real.get_shape()[1],real.get_shape()[2], 1]) pred = tf.reshape(samples_01,[BATCH_SIZE,IM_DIM,IM_DIM,2]) # use tf reshape! pred_u = tf.slice(pred, [0,0,0,0], [pred.get_shape()[0],pred.get_shape()[1],pred.get_shape()[2], 1]) pred_v = tf.slice(pred, [0,0,0,1], [pred.get_shape()[0],pred.get_shape()[1],pred.get_shape()[2], 1]) # shape (64, 32, 32) all of them # mse & ssim on components mseval_per_entry_u = tf.keras.metrics.mse(real_u, pred_u) # on gray, on [0,1], (64,32,32), small vals (^-1,-2,-3) mseval_u = tf.reduce_mean(mseval_per_entry_u, [1,2]) # shape (64,) # diff numbers mseval_per_entry_v = tf.keras.metrics.mse(real_v, pred_v) # on gray, on [0,1], (64,32,32), small vals (^-1,-2,-3) mseval_v = tf.reduce_mean(mseval_per_entry_v, [1,2]) # shape (64,) # diff than per u entry #ssimval_u = tf.image.ssim(real_u, pred_u, max_val=1.0) # in: tensor 64-batch, out: tensor ssimvals (64,) #ssimval_v = tf.image.ssim(real_v, pred_v, max_val=1.0) # in: tensor 64-batch, out: tensor ssimvals (64,) # also minus vals, around 0, u and v differ # avg: add and divide by 2 mseval_uv = tf.add(mseval_u, mseval_v) # tf.cast neccessary? tensor2 = tf.constant(2.0, shape=[64]) #ssimval_uv = tf.add(ssimval_u, ssimval_v) # (64,) mseval_uv = tf.div(mseval_uv, tensor2) #ssimval_uv = tf.div(ssimval_uv, tensor2) # (64,), small around 0, up to 0.3 after first 100 iter #ssimval_list_uv = ssimval_uv.eval() # to numpy array # (64,) mseval_list_uv = mseval_uv.eval() # (64,) print("mseval uv") print(mseval_list_uv) #print("ssimval uv") #print(ssimval_list_uv) # flow color ims to gray real_flowims = tf.cast(real_flowims, tf.float32)/255. # to [0,1] real_color = tf.reshape(real_flowims, [BATCH_SIZE,IM_DIM,IM_DIM,3]) real_gray = tf.image.rgb_to_grayscale(real_color) # tensor batch to gray; returns original dtype = float [0,1] # print("real gray") # (64, 32, 32, 1) sample_flowims = tf.cast(sample_flowims, tf.float32)/255. # to [0,1] pred_color = tf.reshape(sample_flowims, [BATCH_SIZE,IM_DIM,IM_DIM,3]) # use tf.reshape! Tensor! batch! pred_gray = tf.image.rgb_to_grayscale(pred_color) # (64, 32, 32, 1) # mse & ssim on grayscale mseval_per_entry_rgb = tf.keras.metrics.mse(real_gray, pred_gray) # on grayscale, on [0,1].. mseval_rgb = tf.reduce_mean(mseval_per_entry_rgb, [1,2]) #ssimval_rgb = tf.image.ssim(real_gray, pred_gray, max_val=1.0) # in: tensor 64-batch, out: tensor ssimvals (64,) #ssimval_list_rgb = ssimval_rgb.eval() # to numpy array # (64,) mseval_list_rgb = mseval_rgb.eval() # (64,) print("mseval rgb") print(mseval_list_rgb) #print("ssimval rgb") #print(ssimval_list_rgb) # print(ssimval_list) # print(mseval_list) for i in range (0,3): #lib.plot.plot('SSIM uv for sample %d' % (i+1), ssimval_list_uv[i]) #lib.plot.plot('SSIM rgb for sample %d' % (i+1), ssimval_list_rgb[i]) lib.plot.plot('MSE uv for sample %d' % (i+1), mseval_list_uv[i]) lib.plot.plot('MSE rgb for sample %d' % (i+1), mseval_list_rgb[i]) print("sample %d \t MSE: %.5f \t %.5f\r\n" % (i, mseval_list_uv[i], mseval_list_rgb[i])) #SSIM: %.5f \t %.5f\r\n" % (i, mseval_list_uv[i], mseval_list_rgb[i], ssimval_list_uv[i], ssimval_list_rgb[i])) init_op = tf.global_variables_initializer() # op to initialize the variables. saver = tf.train.Saver() # ops to save and restore all the variables. # Train loop with tf.Session() as session: if(CONTINUE): # Restore variables from disk. saver.restore(session, restore_path) print("Model restored.") lib.plot.restore(START_ITER) # does not fully work, but makes plots start from newly started iteration else: session.run(init_op) for iteration in range(START_ITER, ITERS): # START_ITER: 0 or from last checkpoint start_time = time.time() # Train generator if iteration > 0: _data, _ = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument not needed _cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier frames as conditional data, # flow for disc not needed here _ = session.run(gen_train_op, feed_dict={cond_data_int: _cond_data}) # Train critic if MODE == 'dcgan': disc_iters = 1 else: disc_iters = CRITIC_ITERS for i in range(disc_iters): _data, _flow = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument _cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier 2 frames as conditional data, _real_data = _flow[:,OUTPUT_DIM_FLOW:] # later flow as real data for discriminator _disc_cost, _ = session.run([disc_cost, disc_train_op], feed_dict={real_data: _real_data, cond_data_int: _cond_data}) if MODE == 'wgan': _ = session.run(clip_disc_weights) lib.plot.plot('train disc cost', _disc_cost) lib.plot.plot('time', time.time() - start_time) # Calculate dev loss and generate samples every 100 iters if iteration % 100 == 99: dev_disc_costs = [] _data, _flow = next(gen) # shape: (batchsize, 6144), double output_dim now # flow as second argument _cond_data = _data[:, 0:2*OUTPUT_DIM] # earlier 2 frames as conditional data _real_data = _flow[:,OUTPUT_DIM_FLOW:] # later flow as real data for discriminator _dev_disc_cost = session.run(disc_cost, feed_dict={real_data: _real_data, cond_data_int: _cond_data}) dev_disc_costs.append(_dev_disc_cost) lib.plot.plot('dev disc cost', np.mean(dev_disc_costs)) generate_image(iteration, _data) # Save the variables to disk. save_path = saver.save(session, restore_path) print("Model saved in path: %s" % save_path) # chkp.print_tensors_in_checkpoint_file("model.ckpt", tensor_name='', all_tensors=True) # Save logs every 100 iters if (iteration < 5) or (iteration % 100 == 99): lib.plot.flush() lib.plot.tick()
[ "tensorflow.div", "tflib.plot.plot", "tensorflow.get_variable", "tensorflow.tanh", "tensorflow.group", "tflib.ops.linear.Linear", "tflib.ops.deconv2d.Deconv2D", "tensorflow.reduce_mean", "tensorflow.ones_like", "tensorflow.cast", "numpy.mean", "tensorflow.random_normal", "tflib.ops.conv2d.Conv2D", "tensorflow.placeholder", "tensorflow.Session", "numpy.asarray", "tflib.flow_handler.computeFlowImg", "tensorflow.concat", "tensorflow.clip_by_value", "tensorflow.maximum", "tensorflow.convert_to_tensor", "tensorflow.square", "tensorflow.train.AdamOptimizer", "tensorflow.zeros_like", "tflib.plot.flush", "tflib.params_with_name", "tensorflow.image.rgb_to_grayscale", "tflib.plot.restore", "tensorflow.add", "tflib.SINTELdata.load_train_gen", "tensorflow.reshape", "numpy.transpose", "tflib.SINTELdata.load_test_gen", "time.time", "numpy.insert", "tflib.ops.batchnorm.Batchnorm", "tensorflow.reset_default_graph", "tensorflow.keras.metrics.mse", "tensorflow.nn.relu", "tensorflow.train.RMSPropOptimizer", "tensorflow.train.Saver", "os.getcwd", "tensorflow.global_variables_initializer", "tensorflow.random_uniform", "tflib.plot.tick", "tensorflow.constant" ]
[((4611, 4671), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[BATCH_SIZE, 2 * OUTPUT_DIM]'}), '(tf.int32, shape=[BATCH_SIZE, 2 * OUTPUT_DIM])\n', (4625, 4671), True, 'import tensorflow as tf\n'), ((4908, 4971), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[BATCH_SIZE, OUTPUT_DIM_FLOW]'}), '(tf.float32, shape=[BATCH_SIZE, OUTPUT_DIM_FLOW])\n', (4922, 4971), True, 'import tensorflow as tf\n'), ((5163, 5196), 'tflib.params_with_name', 'lib.params_with_name', (['"""Generator"""'], {}), "('Generator')\n", (5183, 5196), True, 'import tflib as lib\n'), ((5211, 5248), 'tflib.params_with_name', 'lib.params_with_name', (['"""Discriminator"""'], {}), "('Discriminator')\n", (5231, 5248), True, 'import tflib as lib\n'), ((7640, 7715), 'tflib.SINTELdata.load_train_gen', 'sintel.load_train_gen', (['BATCH_SIZE', '(IM_DIM, IM_DIM, 3)', '(IM_DIM, IM_DIM, 2)'], {}), '(BATCH_SIZE, (IM_DIM, IM_DIM, 3), (IM_DIM, IM_DIM, 2))\n', (7661, 7715), True, 'import tflib.SINTELdata as sintel\n'), ((7758, 7832), 'tflib.SINTELdata.load_test_gen', 'sintel.load_test_gen', (['BATCH_SIZE', '(IM_DIM, IM_DIM, 3)', '(IM_DIM, IM_DIM, 2)'], {}), '(BATCH_SIZE, (IM_DIM, IM_DIM, 3), (IM_DIM, IM_DIM, 2))\n', (7778, 7832), True, 'import tflib.SINTELdata as sintel\n'), ((14938, 14971), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (14969, 14971), True, 'import tensorflow as tf\n'), ((15016, 15032), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (15030, 15032), True, 'import tensorflow as tf\n'), ((31, 42), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (40, 42), False, 'import os, sys\n'), ((1332, 1356), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (1354, 1356), True, 'import tensorflow as tf\n'), ((1398, 1422), 'tensorflow.maximum', 'tf.maximum', (['(alpha * x)', 'x'], {}), '(alpha * x, x)\n', (1408, 1422), True, 'import tensorflow as tf\n'), ((1477, 1537), 'tflib.ops.linear.Linear', 'lib.ops.linear.Linear', (["(name + '.Linear')", 'n_in', 'n_out', 'inputs'], {}), "(name + '.Linear', n_in, n_out, inputs)\n", (1498, 1537), True, 'import tflib as lib\n'), ((1547, 1565), 'tensorflow.nn.relu', 'tf.nn.relu', (['output'], {}), '(output)\n', (1557, 1565), True, 'import tensorflow as tf\n'), ((1627, 1687), 'tflib.ops.linear.Linear', 'lib.ops.linear.Linear', (["(name + '.Linear')", 'n_in', 'n_out', 'inputs'], {}), "(name + '.Linear', n_in, n_out, inputs)\n", (1648, 1687), True, 'import tflib as lib\n'), ((1897, 1946), 'tensorflow.reshape', 'tf.reshape', (['noise', '[n_samples, 1, IM_DIM, IM_DIM]'], {}), '(noise, [n_samples, 1, IM_DIM, IM_DIM])\n', (1907, 1946), True, 'import tensorflow as tf\n'), ((2000, 2054), 'tensorflow.reshape', 'tf.reshape', (['conditions', '[n_samples, 6, IM_DIM, IM_DIM]'], {}), '(conditions, [n_samples, 6, IM_DIM, IM_DIM])\n', (2010, 2054), True, 'import tensorflow as tf\n'), ((2193, 2221), 'tensorflow.concat', 'tf.concat', (['[noise, conds]', '(1)'], {}), '([noise, conds], 1)\n', (2202, 2221), True, 'import tensorflow as tf\n'), ((2263, 2313), 'tensorflow.reshape', 'tf.reshape', (['output', '[n_samples, SQUARE_IM_DIM * 7]'], {}), '(output, [n_samples, SQUARE_IM_DIM * 7])\n', (2273, 2313), True, 'import tensorflow as tf\n'), ((2367, 2455), 'tflib.ops.linear.Linear', 'lib.ops.linear.Linear', (['"""Generator.Input"""', '(SQUARE_IM_DIM * 7)', '(4 * 4 * 4 * DIM)', 'output'], {}), "('Generator.Input', SQUARE_IM_DIM * 7, 4 * 4 * 4 * DIM,\n output)\n", (2388, 2455), True, 'import tflib as lib\n'), ((2484, 2541), 'tflib.ops.batchnorm.Batchnorm', 'lib.ops.batchnorm.Batchnorm', (['"""Generator.BN1"""', '[0]', 'output'], {}), "('Generator.BN1', [0], output)\n", (2511, 2541), True, 'import tflib as lib\n'), ((2555, 2573), 'tensorflow.nn.relu', 'tf.nn.relu', (['output'], {}), '(output)\n', (2565, 2573), True, 'import tensorflow as tf\n'), ((2587, 2626), 'tensorflow.reshape', 'tf.reshape', (['output', '[-1, 4 * DIM, 4, 4]'], {}), '(output, [-1, 4 * DIM, 4, 4])\n', (2597, 2626), True, 'import tensorflow as tf\n'), ((2639, 2708), 'tflib.ops.deconv2d.Deconv2D', 'lib.ops.deconv2d.Deconv2D', (['"""Generator.2"""', '(4 * DIM)', '(2 * DIM)', '(5)', 'output'], {}), "('Generator.2', 4 * DIM, 2 * DIM, 5, output)\n", (2664, 2708), True, 'import tflib as lib\n'), ((2718, 2781), 'tflib.ops.batchnorm.Batchnorm', 'lib.ops.batchnorm.Batchnorm', (['"""Generator.BN2"""', '[0, 2, 3]', 'output'], {}), "('Generator.BN2', [0, 2, 3], output)\n", (2745, 2781), True, 'import tflib as lib\n'), ((2793, 2811), 'tensorflow.nn.relu', 'tf.nn.relu', (['output'], {}), '(output)\n', (2803, 2811), True, 'import tensorflow as tf\n'), ((2826, 2891), 'tflib.ops.deconv2d.Deconv2D', 'lib.ops.deconv2d.Deconv2D', (['"""Generator.3"""', '(2 * DIM)', 'DIM', '(5)', 'output'], {}), "('Generator.3', 2 * DIM, DIM, 5, output)\n", (2851, 2891), True, 'import tflib as lib\n'), ((2903, 2966), 'tflib.ops.batchnorm.Batchnorm', 'lib.ops.batchnorm.Batchnorm', (['"""Generator.BN3"""', '[0, 2, 3]', 'output'], {}), "('Generator.BN3', [0, 2, 3], output)\n", (2930, 2966), True, 'import tflib as lib\n'), ((2978, 2996), 'tensorflow.nn.relu', 'tf.nn.relu', (['output'], {}), '(output)\n', (2988, 2996), True, 'import tensorflow as tf\n'), ((3011, 3070), 'tflib.ops.deconv2d.Deconv2D', 'lib.ops.deconv2d.Deconv2D', (['"""Generator.5"""', 'DIM', '(2)', '(5)', 'output'], {}), "('Generator.5', DIM, 2, 5, output)\n", (3036, 3070), True, 'import tflib as lib\n'), ((3122, 3137), 'tensorflow.tanh', 'tf.tanh', (['output'], {}), '(output)\n', (3129, 3137), True, 'import tensorflow as tf\n'), ((3150, 3191), 'tensorflow.reshape', 'tf.reshape', (['output', '[-1, OUTPUT_DIM_FLOW]'], {}), '(output, [-1, OUTPUT_DIM_FLOW])\n', (3160, 3191), True, 'import tensorflow as tf\n'), ((3295, 3338), 'tensorflow.reshape', 'tf.reshape', (['inputs', '[-1, 2, IM_DIM, IM_DIM]'], {}), '(inputs, [-1, 2, IM_DIM, IM_DIM])\n', (3305, 3338), True, 'import tensorflow as tf\n'), ((3379, 3426), 'tensorflow.reshape', 'tf.reshape', (['conditions', '[-1, 6, IM_DIM, IM_DIM]'], {}), '(conditions, [-1, 6, IM_DIM, IM_DIM])\n', (3389, 3426), True, 'import tensorflow as tf\n'), ((3512, 3541), 'tensorflow.concat', 'tf.concat', (['[inputs, conds]', '(1)'], {}), '([inputs, conds], 1)\n', (3521, 3541), True, 'import tensorflow as tf\n'), ((3585, 3651), 'tflib.ops.conv2d.Conv2D', 'lib.ops.conv2d.Conv2D', (['"""Discriminator.1"""', '(8)', 'DIM', '(5)', 'ins'], {'stride': '(2)'}), "('Discriminator.1', 8, DIM, 5, ins, stride=2)\n", (3606, 3651), True, 'import tflib as lib\n'), ((3730, 3805), 'tflib.ops.conv2d.Conv2D', 'lib.ops.conv2d.Conv2D', (['"""Discriminator.2"""', 'DIM', '(2 * DIM)', '(5)', 'output'], {'stride': '(2)'}), "('Discriminator.2', DIM, 2 * DIM, 5, output, stride=2)\n", (3751, 3805), True, 'import tflib as lib\n'), ((3958, 4037), 'tflib.ops.conv2d.Conv2D', 'lib.ops.conv2d.Conv2D', (['"""Discriminator.3"""', '(2 * DIM)', '(4 * DIM)', '(5)', 'output'], {'stride': '(2)'}), "('Discriminator.3', 2 * DIM, 4 * DIM, 5, output, stride=2)\n", (3979, 4037), True, 'import tflib as lib\n'), ((4421, 4462), 'tensorflow.reshape', 'tf.reshape', (['output', '[-1, 4 * 4 * 8 * DIM]'], {}), '(output, [-1, 4 * 4 * 8 * DIM])\n', (4431, 4462), True, 'import tensorflow as tf\n'), ((4489, 4562), 'tflib.ops.linear.Linear', 'lib.ops.linear.Linear', (['"""Discriminator.Output"""', '(4 * 4 * 8 * DIM)', '(1)', 'output'], {}), "('Discriminator.Output', 4 * 4 * 8 * DIM, 1, output)\n", (4510, 4562), True, 'import tflib as lib\n'), ((4569, 4593), 'tensorflow.reshape', 'tf.reshape', (['output', '[-1]'], {}), '(output, [-1])\n', (4579, 4593), True, 'import tensorflow as tf\n'), ((5864, 5883), 'tensorflow.group', 'tf.group', (['*clip_ops'], {}), '(*clip_ops)\n', (5872, 5883), True, 'import tensorflow as tf\n'), ((8234, 8276), 'tensorflow.cast', 'tf.cast', (['(fixed_real_data + 1.0)', 'tf.float32'], {}), '(fixed_real_data + 1.0, tf.float32)\n', (8241, 8276), True, 'import tensorflow as tf\n'), ((8518, 8577), 'tensorflow.get_variable', 'tf.get_variable', (['"""noise"""'], {'shape': '[BATCH_SIZE, SQUARE_IM_DIM]'}), "('noise', shape=[BATCH_SIZE, SQUARE_IM_DIM])\n", (8533, 8577), True, 'import tensorflow as tf\n'), ((10863, 10902), 'numpy.asarray', 'np.asarray', (['sample_flowimages', 'np.int32'], {}), '(sample_flowimages, np.int32)\n', (10873, 10902), True, 'import numpy as np\n'), ((10925, 10962), 'numpy.asarray', 'np.asarray', (['real_flowimages', 'np.int32'], {}), '(real_flowimages, np.int32)\n', (10935, 10962), True, 'import numpy as np\n'), ((10984, 11033), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['sample_flowims_np', 'np.int32'], {}), '(sample_flowims_np, np.int32)\n', (11004, 11033), True, 'import tensorflow as tf\n'), ((11053, 11100), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['real_flowims_np', 'np.int32'], {}), '(real_flowims_np, np.int32)\n', (11073, 11100), True, 'import tensorflow as tf\n'), ((11297, 11364), 'tensorflow.reshape', 'tf.reshape', (['fixed_real_data_norm01', '[BATCH_SIZE, IM_DIM, IM_DIM, 2]'], {}), '(fixed_real_data_norm01, [BATCH_SIZE, IM_DIM, IM_DIM, 2])\n', (11307, 11364), True, 'import tensorflow as tf\n'), ((11617, 11672), 'tensorflow.reshape', 'tf.reshape', (['samples_01', '[BATCH_SIZE, IM_DIM, IM_DIM, 2]'], {}), '(samples_01, [BATCH_SIZE, IM_DIM, IM_DIM, 2])\n', (11627, 11672), True, 'import tensorflow as tf\n'), ((11988, 12024), 'tensorflow.keras.metrics.mse', 'tf.keras.metrics.mse', (['real_u', 'pred_u'], {}), '(real_u, pred_u)\n', (12008, 12024), True, 'import tensorflow as tf\n'), ((12098, 12140), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['mseval_per_entry_u', '[1, 2]'], {}), '(mseval_per_entry_u, [1, 2])\n', (12112, 12140), True, 'import tensorflow as tf\n'), ((12194, 12230), 'tensorflow.keras.metrics.mse', 'tf.keras.metrics.mse', (['real_v', 'pred_v'], {}), '(real_v, pred_v)\n', (12214, 12230), True, 'import tensorflow as tf\n'), ((12304, 12346), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['mseval_per_entry_v', '[1, 2]'], {}), '(mseval_per_entry_v, [1, 2])\n', (12318, 12346), True, 'import tensorflow as tf\n'), ((12703, 12729), 'tensorflow.add', 'tf.add', (['mseval_u', 'mseval_v'], {}), '(mseval_u, mseval_v)\n', (12709, 12729), True, 'import tensorflow as tf\n'), ((12767, 12795), 'tensorflow.constant', 'tf.constant', (['(2.0)'], {'shape': '[64]'}), '(2.0, shape=[64])\n', (12778, 12795), True, 'import tensorflow as tf\n'), ((12867, 12893), 'tensorflow.div', 'tf.div', (['mseval_uv', 'tensor2'], {}), '(mseval_uv, tensor2)\n', (12873, 12893), True, 'import tensorflow as tf\n'), ((13327, 13384), 'tensorflow.reshape', 'tf.reshape', (['real_flowims', '[BATCH_SIZE, IM_DIM, IM_DIM, 3]'], {}), '(real_flowims, [BATCH_SIZE, IM_DIM, IM_DIM, 3])\n', (13337, 13384), True, 'import tensorflow as tf\n'), ((13399, 13436), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['real_color'], {}), '(real_color)\n', (13424, 13436), True, 'import tensorflow as tf\n'), ((13631, 13690), 'tensorflow.reshape', 'tf.reshape', (['sample_flowims', '[BATCH_SIZE, IM_DIM, IM_DIM, 3]'], {}), '(sample_flowims, [BATCH_SIZE, IM_DIM, IM_DIM, 3])\n', (13641, 13690), True, 'import tensorflow as tf\n'), ((13738, 13775), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['pred_color'], {}), '(pred_color)\n', (13763, 13775), True, 'import tensorflow as tf\n'), ((13853, 13895), 'tensorflow.keras.metrics.mse', 'tf.keras.metrics.mse', (['real_gray', 'pred_gray'], {}), '(real_gray, pred_gray)\n', (13873, 13895), True, 'import tensorflow as tf\n'), ((13942, 13986), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['mseval_per_entry_rgb', '[1, 2]'], {}), '(mseval_per_entry_rgb, [1, 2])\n', (13956, 13986), True, 'import tensorflow as tf\n'), ((15099, 15111), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (15109, 15111), True, 'import tensorflow as tf\n'), ((1838, 1882), 'tensorflow.random_normal', 'tf.random_normal', (['[n_samples, SQUARE_IM_DIM]'], {}), '([n_samples, SQUARE_IM_DIM])\n', (1854, 1882), True, 'import tensorflow as tf\n'), ((3847, 3914), 'tflib.ops.batchnorm.Batchnorm', 'lib.ops.batchnorm.Batchnorm', (['"""Discriminator.BN2"""', '[0, 2, 3]', 'output'], {}), "('Discriminator.BN2', [0, 2, 3], output)\n", (3874, 3914), True, 'import tflib as lib\n'), ((4077, 4144), 'tflib.ops.batchnorm.Batchnorm', 'lib.ops.batchnorm.Batchnorm', (['"""Discriminator.BN3"""', '[0, 2, 3]', 'output'], {}), "('Discriminator.BN3', [0, 2, 3], output)\n", (4104, 4144), True, 'import tflib as lib\n'), ((5285, 5310), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_fake'], {}), '(disc_fake)\n', (5299, 5310), True, 'import tensorflow as tf\n'), ((5327, 5352), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_fake'], {}), '(disc_fake)\n', (5341, 5352), True, 'import tensorflow as tf\n'), ((5355, 5380), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_real'], {}), '(disc_real)\n', (5369, 5380), True, 'import tensorflow as tf\n'), ((6082, 6146), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '[BATCH_SIZE, 1]', 'minval': '(0.0)', 'maxval': '(1.0)'}), '(shape=[BATCH_SIZE, 1], minval=0.0, maxval=1.0)\n', (6099, 6146), True, 'import tensorflow as tf\n'), ((6475, 6510), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((slopes - 1.0) ** 2)'], {}), '((slopes - 1.0) ** 2)\n', (6489, 6510), True, 'import tensorflow as tf\n'), ((8649, 8718), 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[BATCH_SIZE, SQUARE_IM_DIM]', 'dtype': 'tf.float32'}), '(shape=[BATCH_SIZE, SQUARE_IM_DIM], dtype=tf.float32)\n', (8665, 8718), True, 'import tensorflow as tf\n'), ((9866, 9898), 'numpy.transpose', 'np.transpose', (['flowimg', '[2, 0, 1]'], {}), '(flowimg, [2, 0, 1])\n', (9878, 9898), True, 'import numpy as np\n'), ((10173, 10203), 'tflib.flow_handler.computeFlowImg', 'fh.computeFlowImg', (['real_uvflow'], {}), '(real_uvflow)\n', (10190, 10203), True, 'import tflib.flow_handler as fh\n'), ((10347, 10384), 'numpy.transpose', 'np.transpose', (['real_flowimg', '[2, 0, 1]'], {}), '(real_flowimg, [2, 0, 1])\n', (10359, 10384), True, 'import numpy as np\n'), ((10506, 10558), 'numpy.insert', 'np.insert', (['images2show', '(i * 2 + 1)', 'flowimg_T'], {'axis': '(0)'}), '(images2show, i * 2 + 1, flowimg_T, axis=0)\n', (10515, 10558), True, 'import numpy as np\n'), ((13260, 13293), 'tensorflow.cast', 'tf.cast', (['real_flowims', 'tf.float32'], {}), '(real_flowims, tf.float32)\n', (13267, 13293), True, 'import tensorflow as tf\n'), ((13562, 13597), 'tensorflow.cast', 'tf.cast', (['sample_flowims', 'tf.float32'], {}), '(sample_flowims, tf.float32)\n', (13569, 13597), True, 'import tensorflow as tf\n'), ((14568, 14634), 'tflib.plot.plot', 'lib.plot.plot', (["('MSE uv for sample %d' % (i + 1))", 'mseval_list_uv[i]'], {}), "('MSE uv for sample %d' % (i + 1), mseval_list_uv[i])\n", (14581, 14634), True, 'import tflib as lib\n'), ((14641, 14709), 'tflib.plot.plot', 'lib.plot.plot', (["('MSE rgb for sample %d' % (i + 1))", 'mseval_list_rgb[i]'], {}), "('MSE rgb for sample %d' % (i + 1), mseval_list_rgb[i])\n", (14654, 14709), True, 'import tflib as lib\n'), ((15271, 15299), 'tflib.plot.restore', 'lib.plot.restore', (['START_ITER'], {}), '(START_ITER)\n', (15287, 15299), True, 'import tflib as lib\n'), ((15527, 15538), 'time.time', 'time.time', ([], {}), '()\n', (15536, 15538), False, 'import time\n'), ((16605, 16649), 'tflib.plot.plot', 'lib.plot.plot', (['"""train disc cost"""', '_disc_cost'], {}), "('train disc cost', _disc_cost)\n", (16618, 16649), True, 'import tflib as lib\n'), ((17809, 17824), 'tflib.plot.tick', 'lib.plot.tick', ([], {}), '()\n', (17822, 17824), True, 'import tflib as lib\n'), ((4722, 4756), 'tensorflow.cast', 'tf.cast', (['cond_data_int', 'tf.float32'], {}), '(cond_data_int, tf.float32)\n', (4729, 4756), True, 'import tensorflow as tf\n'), ((5401, 5447), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': '(5e-05)'}), '(learning_rate=5e-05)\n', (5426, 5447), True, 'import tensorflow as tf\n'), ((5507, 5553), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': '(5e-05)'}), '(learning_rate=5e-05)\n', (5532, 5553), True, 'import tensorflow as tf\n'), ((5950, 5975), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_fake'], {}), '(disc_fake)\n', (5964, 5975), True, 'import tensorflow as tf\n'), ((5992, 6017), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_fake'], {}), '(disc_fake)\n', (6006, 6017), True, 'import tensorflow as tf\n'), ((6020, 6045), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['disc_real'], {}), '(disc_real)\n', (6034, 6045), True, 'import tensorflow as tf\n'), ((8320, 8360), 'tensorflow.cast', 'tf.cast', (['fixed_cond_data_int', 'tf.float32'], {}), '(fixed_cond_data_int, tf.float32)\n', (8327, 8360), True, 'import tensorflow as tf\n'), ((17783, 17799), 'tflib.plot.flush', 'lib.plot.flush', ([], {}), '()\n', (17797, 17799), True, 'import tflib as lib\n'), ((5762, 5815), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['var', 'clip_bounds[0]', 'clip_bounds[1]'], {}), '(var, clip_bounds[0], clip_bounds[1])\n', (5778, 5815), True, 'import tensorflow as tf\n'), ((6406, 6426), 'tensorflow.square', 'tf.square', (['gradients'], {}), '(gradients)\n', (6415, 6426), True, 'import tensorflow as tf\n'), ((6567, 6633), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.0001)', 'beta1': '(0.5)', 'beta2': '(0.9)'}), '(learning_rate=0.0001, beta1=0.5, beta2=0.9)\n', (6589, 6633), True, 'import tensorflow as tf\n'), ((6692, 6758), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.0001)', 'beta1': '(0.5)', 'beta2': '(0.9)'}), '(learning_rate=0.0001, beta1=0.5, beta2=0.9)\n', (6714, 6758), True, 'import tensorflow as tf\n'), ((16680, 16691), 'time.time', 'time.time', ([], {}), '()\n', (16689, 16691), False, 'import time\n'), ((17351, 17374), 'numpy.mean', 'np.mean', (['dev_disc_costs'], {}), '(dev_disc_costs)\n', (17358, 17374), True, 'import numpy as np\n'), ((6903, 6926), 'tensorflow.ones_like', 'tf.ones_like', (['disc_fake'], {}), '(disc_fake)\n', (6915, 6926), True, 'import tensorflow as tf\n'), ((7012, 7036), 'tensorflow.zeros_like', 'tf.zeros_like', (['disc_fake'], {}), '(disc_fake)\n', (7025, 7036), True, 'import tensorflow as tf\n'), ((7122, 7145), 'tensorflow.ones_like', 'tf.ones_like', (['disc_real'], {}), '(disc_real)\n', (7134, 7145), True, 'import tensorflow as tf\n'), ((7188, 7243), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.0002)', 'beta1': '(0.5)'}), '(learning_rate=0.0002, beta1=0.5)\n', (7210, 7243), True, 'import tensorflow as tf\n'), ((7352, 7385), 'tflib.params_with_name', 'lib.params_with_name', (['"""Generator"""'], {}), "('Generator')\n", (7372, 7385), True, 'import tflib as lib\n'), ((7407, 7462), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.0002)', 'beta1': '(0.5)'}), '(learning_rate=0.0002, beta1=0.5)\n', (7429, 7462), True, 'import tensorflow as tf\n'), ((7573, 7611), 'tflib.params_with_name', 'lib.params_with_name', (['"""Discriminator."""'], {}), "('Discriminator.')\n", (7593, 7611), True, 'import tflib as lib\n')]
""" This file contains tests for plotter_utils.py. @author: <NAME> """ import matplotlib.pyplot as plt import numpy as np import pytest from matplotlib.figure import Figure from gdef_reporter.plotter_styles import get_plotter_style_histogram from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, \ _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot from tests.conftest import AUTO_SHOW ORIGINAL_FIGURE_SIZE = (4, 3.5) ORIGINAL_DPI = 300 def auto_show(fig): if AUTO_SHOW: fig.show() # tests for functions to plot a 2D area map class TestAreaPlots: def test_plot_to_ax(self, data_test_cases): fig1, ax1 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE) plot_to_ax(ax1, data_test_cases, pixel_width=1.0) auto_show(fig1) assert type(fig1) is Figure assert fig1.axes[1].get_title() == "nm" # default unit for z-values should be nm fig2, ax2 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE) pixel_width = 5.0 title = f"{type(data_test_cases).__name__}\npixel_width={pixel_width}" plot_to_ax(ax2, data_test_cases, pixel_width=pixel_width, title=title) auto_show(fig2) assert ax2.get_title() == title fig3, ax3 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE) z_factor = 1.0 title = f"{type(data_test_cases).__name__}\nz_unit: [m] - z_factor={z_factor}" plot_to_ax(ax3, data_test_cases, pixel_width=5.0, z_unit="µm", title=title) auto_show(fig3) assert fig3.axes[1].get_title() == "\u03BCm" def test_create_plot(self, data_test_cases): fig1 = create_plot(data_test_cases, 1e-6, "default value for cropped (True)", ORIGINAL_FIGURE_SIZE, ORIGINAL_DPI) auto_show(fig1) assert np.any(comparison := (fig1.get_size_inches() < ORIGINAL_FIGURE_SIZE)) and not np.all(comparison) assert fig1.dpi == ORIGINAL_DPI fig2 = create_plot(data_test_cases, 1e-6, "cropped=False", max_figure_size=ORIGINAL_FIGURE_SIZE, cropped=False) assert np.all(fig2.get_size_inches() == ORIGINAL_FIGURE_SIZE) auto_show(fig2) class Test1DPlotZHistogram: def test_plot_z_histogram_to_ax__defaults(self, data_test_cases): # first, check default behaviour of parameters title, , n_bins, units and add_norm fig1, ax1 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE, constrained_layout=True) plot_z_histogram_to_ax(ax1, data_test_cases, title="") auto_show(fig1) assert len(ax1.lines) == 0 # no Gauss fit (expected default behaviour) assert ax1.get_title().startswith("\u03BC=") # default title starts with mu=... assert ax1.get_xlabel() == "z [\u03BCm]" # default units should be µm; note: µ == \u03BC is False! assert len(ax1.containers[0]) == 200 # default n_bins should be 200 def test_plot_z_histogram_to_ax__defaults_multiple(self, multiple_data_test_cases): # first, check default behaviour of parameters title, , n_bins, units and add_norm fig1, ax1 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE, constrained_layout=True) if isinstance(multiple_data_test_cases, dict): if (_list := len([data for data in multiple_data_test_cases.values() if isinstance(data, np.ndarray)]) > 0)\ and _list < len(multiple_data_test_cases): with pytest.raises(AssertionError): plot_z_histogram_to_ax(ax1, multiple_data_test_cases) return plot_z_histogram_to_ax(ax1, multiple_data_test_cases, title="") auto_show(fig1) assert len(ax1.lines) == 0 # no Gauss fit (expected default behaviour) if len(multiple_data_test_cases) == 1: assert ax1.get_title().startswith("\u03BC=") # default title for one data set shows mu=... else: assert ax1.get_title() == "" # no default title if no data or more than one dataset assert ax1.get_xlabel() == "z [\u03BCm]" # default units should be µm; note: µ == \u03BC is False! for container in ax1.containers: assert len(container.patches) == 200 # default n_bins should be 200 def test_plot_z_histogram_to_ax__set_parameters(self, data_test_cases): # first, check setting a title, selecting units µm, set n_bins and draw normal distribution fit fig1, ax1 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE, constrained_layout=True) title = "Use [µm] and Gauss fit" n_bins = 20 plot_z_histogram_to_ax(ax1, data_test_cases, n_bins=n_bins, units="nm", title=title, add_norm=True) auto_show(fig1) assert len(ax1.lines) == 1 # Gauss fit (add_norm=True) assert ax1.get_title() == title assert str(ax1.get_xlabel()) == str(f"z [nm]") # note: comparison between µ and \u03BC is False! assert len(ax1.containers[0]) == n_bins # default n_bins should be 200 # second, check no title via title=None fig2, ax2 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE, constrained_layout=True) title = None plot_z_histogram_to_ax(ax2, data_test_cases, n_bins=20, units="µm", title=title) auto_show(fig2) assert ax2.get_title() == "" # expected for title=None def test_plot_z_histogram_to_ax__multiple(self, multiple_data_test_cases): fig1, ax1 = plt.subplots(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE, constrained_layout=True) pixel_width = None if isinstance(multiple_data_test_cases, dict): pixel_width = 0.5e-6 plot_z_histogram_to_ax(ax1, multiple_data_test_cases, pixel_width=pixel_width, title="", add_norm=True) auto_show(fig1) assert isinstance(fig1, Figure) assert len(fig1.axes[0].containers) == len(multiple_data_test_cases) assert len(fig1.axes[0].lines) == len(multiple_data_test_cases) # Gauss fits (add_norm=True) def test_create_z_histogram_plot__defaults(self, data_test_cases): # check setting figure_size and dpi and also default of parameters title, n_bins, units and add_norm fig1 = create_z_histogram_plot(data_test_cases) auto_show(fig1) assert type(fig1) is Figure assert len(fig1.axes[0].lines) == 0 # no Gauss fit (expected default behaviour) assert fig1.axes[0].get_title().startswith("\u03BC=") # default title starts with mu=... assert fig1.axes[0].get_xlabel() == "z [\u03BCm]" # default units should be µm; note: µ == \u03BC is False! assert len(fig1.axes[0].containers[0]) == 200 # default n_bins should be 200 def test_create_z_histogram_plot__set_paramaters(self, data_test_cases): # first, check setting label, a title, selecting units µm, set n_bins and draw normal distribution fit labels = type(data_test_cases).__name__ title = "Use [nm] and Gauss fit" n_bins = 20 plotter_style = get_plotter_style_histogram(ORIGINAL_DPI, ORIGINAL_FIGURE_SIZE) fig1 = create_z_histogram_plot(data_test_cases, labels, n_bins=n_bins, title=title, units="nm", add_norm=True, plotter_style=plotter_style) auto_show(fig1) assert len(fig1.axes[0].lines) == 1 # Gauss fit (add_norm=True) assert np.any(fig1.get_size_inches() == ORIGINAL_FIGURE_SIZE) assert fig1.dpi == ORIGINAL_DPI assert fig1._suptitle.get_text() == title assert fig1.axes[0].get_title() == "" assert str(fig1.axes[0].get_xlabel()) == str(f"z [nm]") # note: comparison between µ and \u03BC is False! assert len(fig1.axes[0].containers[0]) == n_bins # default n_bins should be 200 # second, check no title via title=None fig2 = create_z_histogram_plot(data_test_cases, title=None) auto_show(fig2) assert fig2._suptitle is None assert fig2.axes[0].get_title() == "" def test_create_z_histogram_plot__multiple(self, multiple_data_test_cases): labels = None pixel_width = 0.5e-6 if isinstance(multiple_data_test_cases, list): labels = [] for i, data in enumerate(multiple_data_test_cases): labels.append(f"{i} - {type(data).__name__}") fig1 = create_z_histogram_plot(multiple_data_test_cases, pixel_width=pixel_width, labels=labels, title="", add_norm=True) auto_show(fig1) assert len(fig1.axes[0].containers) == len(multiple_data_test_cases) assert len(fig1.axes[0].lines) == len(multiple_data_test_cases) # Gauss fits (add_norm=True) class Test1DPlotRMS: def test_plot_rms_to_ax(self): pass def test_create_rms_plot__default(self, data_test_cases): fig = create_rms_plot(data_test_cases) assert isinstance(fig, Figure) if isinstance(data_test_cases, np.ndarray): assert fig.axes[0].get_xlabel() == "x [px]" else: assert fig.axes[0].get_xlabel() == "x [\u03BCm]" assert fig.axes[0].legend_ is None auto_show(fig) def test_create_rms_plot__set_parameters(self, data_test_cases): pixel_width = 0.5e-9 # define a length scale for np.ndarray labels = f"{type(data_test_cases).__name__}" fig = create_rms_plot(data_test_cases, label_list=labels, pixel_width=pixel_width, moving_average_n=1, subtract_average=True, x_units="nm") assert isinstance(fig, Figure) assert fig.axes[0].get_xlabel() == "x [nm]" assert fig.axes[0].legend_ is not None auto_show(fig) def test_create_rms_plot__multiple_default(self, multiple_data_test_cases): if isinstance(multiple_data_test_cases, dict): if (_list := len([data for data in multiple_data_test_cases.values() if isinstance(data, np.ndarray)]) > 0)\ and _list < len(multiple_data_test_cases): with pytest.raises(AssertionError): create_rms_plot(multiple_data_test_cases) return fig = create_rms_plot(multiple_data_test_cases) assert len(multiple_data_test_cases) == len(fig.axes[0].lines) auto_show(fig) def test_create_rms_plot__multiple_set_parameter(self, multiple_data_test_cases): labels = None pixel_width = 0.5e-6 title = type(multiple_data_test_cases).__name__ if isinstance(multiple_data_test_cases, list): labels = [f"{type(data).__name__}" for data in multiple_data_test_cases] fig = create_rms_plot(multiple_data_test_cases, label_list=labels, pixel_width=pixel_width, moving_average_n=1, subtract_average=False, x_units="nm", title=title) assert fig.axes[0].legend_ is not None or len(multiple_data_test_cases) == 0 assert len(multiple_data_test_cases) == len(fig.axes[0].lines) assert fig.axes[0].get_xlabel() == "x [nm]" auto_show(fig) class Test1DPlotRMSWithError: def test_create_rms_with_error_plot(self, data_test_cases): fig = create_rms_with_error_plot(data_test_cases) if isinstance(data_test_cases, np.ndarray): assert fig.axes[0].get_xlabel() == "x [px]" else: assert fig.axes[0].get_xlabel() == "x [\u03BCm]" auto_show(fig) def test_create_rms_with_error_plot__multiple(self, multiple_data_test_cases): pixel_width = None if isinstance(multiple_data_test_cases, dict): if (_list := len([data for data in multiple_data_test_cases.values() if isinstance(data, np.ndarray)]) > 0)\ and _list < len(multiple_data_test_cases): with pytest.raises(AssertionError): create_rms_with_error_plot(multiple_data_test_cases) pixel_width = 0.5e-6 # setting a pixel_width, np.ndarray has a length scale -> no AssertionError fig = create_rms_with_error_plot(multiple_data_test_cases, pixel_width=pixel_width) assert fig.axes[0].get_xlabel() == "x [\u03BCm]" auto_show(fig) class TestSummaryPlot: def test_create_summary_plot(self, multiple_data_test_cases): pixel_width = 0.5e-6 title = f"{type(multiple_data_test_cases).__name__}" fig = create_summary_plot(multiple_data_test_cases, pixel_width=pixel_width, title=title) assert isinstance(fig, Figure) auto_show(fig) class TestSpecialFunctions: def test_extract_ndarray_and_pixel_width(self, data_test_cases): pixel_width = 1 ndarray2d, px_width = _extract_ndarray_and_pixel_width(data_test_cases, pixel_width=pixel_width) assert type(ndarray2d) is np.ndarray if isinstance(data_test_cases, np.ndarray): assert np.all(data_test_cases == ndarray2d) assert px_width == pixel_width else: assert np.all(data_test_cases.values == ndarray2d) assert data_test_cases.pixel_width == px_width def test_save_figure(self, tmp_path): fig, _ = plt.subplots(1, 1, dpi=72, figsize=(1, 1), constrained_layout=True) # first try saving in existing folder with default settings assert tmp_path.exists() filename = "default" save_figure(fig, tmp_path, filename) png_file = tmp_path / f"{filename}.png" # should be saved by default pdf_file = tmp_path / f"{filename}.pdf" # should not be saved by default assert png_file.exists() assert not pdf_file.exists() # second, save nothing: filename = "save_nothing" save_figure(fig, tmp_path, filename, png=False, pdf=False) png_file = tmp_path / f"{filename}.png" # should be saved by default pdf_file = tmp_path / f"{filename}.pdf" # should not be saved by default assert not png_file.exists() assert not pdf_file.exists() # third, only save pdf filename = "save_pdf" save_figure(fig, tmp_path, filename, png=False, pdf=True) png_file = tmp_path / f"{filename}.png" # should be saved by default pdf_file = tmp_path / f"{filename}.pdf" # should not be saved by default assert not png_file.exists() assert pdf_file.exists() # fourth, use folder that does not exist jet and save both png and pdf new_tmp_path = tmp_path / "new/" assert not new_tmp_path.exists() filename = "save_pdf_and_png" save_figure(fig, new_tmp_path, filename, png=True, pdf=True) png_file = new_tmp_path / f"{filename}.png" # should be saved by default pdf_file = new_tmp_path / f"{filename}.pdf" # should not be saved by default assert png_file.exists() assert pdf_file.exists()
[ "gdef_reporter.plotter_utils.save_figure", "gdef_reporter.plotter_utils.create_summary_plot", "gdef_reporter.plotter_styles.get_plotter_style_histogram", "gdef_reporter.plotter_utils.create_z_histogram_plot", "gdef_reporter.plotter_utils.create_rms_plot", "gdef_reporter.plotter_utils.plot_to_ax", "gdef_reporter.plotter_utils._extract_ndarray_and_pixel_width", "pytest.raises", "gdef_reporter.plotter_utils.create_plot", "gdef_reporter.plotter_utils.plot_z_histogram_to_ax", "numpy.all", "gdef_reporter.plotter_utils.create_rms_with_error_plot", "matplotlib.pyplot.subplots" ]
[((759, 825), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE)\n', (771, 825), True, 'import matplotlib.pyplot as plt\n'), ((834, 883), 'gdef_reporter.plotter_utils.plot_to_ax', 'plot_to_ax', (['ax1', 'data_test_cases'], {'pixel_width': '(1.0)'}), '(ax1, data_test_cases, pixel_width=1.0)\n', (844, 883), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((1055, 1121), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE)\n', (1067, 1121), True, 'import matplotlib.pyplot as plt\n'), ((1235, 1305), 'gdef_reporter.plotter_utils.plot_to_ax', 'plot_to_ax', (['ax2', 'data_test_cases'], {'pixel_width': 'pixel_width', 'title': 'title'}), '(ax2, data_test_cases, pixel_width=pixel_width, title=title)\n', (1245, 1305), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((1391, 1457), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE)\n', (1403, 1457), True, 'import matplotlib.pyplot as plt\n'), ((1576, 1651), 'gdef_reporter.plotter_utils.plot_to_ax', 'plot_to_ax', (['ax3', 'data_test_cases'], {'pixel_width': '(5.0)', 'z_unit': '"""µm"""', 'title': 'title'}), "(ax3, data_test_cases, pixel_width=5.0, z_unit='µm', title=title)\n", (1586, 1651), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((1794, 1905), 'gdef_reporter.plotter_utils.create_plot', 'create_plot', (['data_test_cases', '(1e-06)', '"""default value for cropped (True)"""', 'ORIGINAL_FIGURE_SIZE', 'ORIGINAL_DPI'], {}), "(data_test_cases, 1e-06, 'default value for cropped (True)',\n ORIGINAL_FIGURE_SIZE, ORIGINAL_DPI)\n", (1805, 1905), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((2120, 2230), 'gdef_reporter.plotter_utils.create_plot', 'create_plot', (['data_test_cases', '(1e-06)', '"""cropped=False"""'], {'max_figure_size': 'ORIGINAL_FIGURE_SIZE', 'cropped': '(False)'}), "(data_test_cases, 1e-06, 'cropped=False', max_figure_size=\n ORIGINAL_FIGURE_SIZE, cropped=False)\n", (2131, 2230), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((2530, 2625), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE', 'constrained_layout': '(True)'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE,\n constrained_layout=True)\n', (2542, 2625), True, 'import matplotlib.pyplot as plt\n'), ((2630, 2684), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax1', 'data_test_cases'], {'title': '""""""'}), "(ax1, data_test_cases, title='')\n", (2652, 2684), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((3264, 3359), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE', 'constrained_layout': '(True)'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE,\n constrained_layout=True)\n', (3276, 3359), True, 'import matplotlib.pyplot as plt\n'), ((3754, 3817), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax1', 'multiple_data_test_cases'], {'title': '""""""'}), "(ax1, multiple_data_test_cases, title='')\n", (3776, 3817), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((4618, 4713), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE', 'constrained_layout': '(True)'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE,\n constrained_layout=True)\n', (4630, 4713), True, 'import matplotlib.pyplot as plt\n'), ((4779, 4882), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax1', 'data_test_cases'], {'n_bins': 'n_bins', 'units': '"""nm"""', 'title': 'title', 'add_norm': '(True)'}), "(ax1, data_test_cases, n_bins=n_bins, units='nm',\n title=title, add_norm=True)\n", (4801, 4882), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((5262, 5357), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE', 'constrained_layout': '(True)'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE,\n constrained_layout=True)\n', (5274, 5357), True, 'import matplotlib.pyplot as plt\n'), ((5383, 5468), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax2', 'data_test_cases'], {'n_bins': '(20)', 'units': '"""µm"""', 'title': 'title'}), "(ax2, data_test_cases, n_bins=20, units='µm', title=title\n )\n", (5405, 5468), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((5652, 5747), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': 'ORIGINAL_DPI', 'figsize': 'ORIGINAL_FIGURE_SIZE', 'constrained_layout': '(True)'}), '(1, 1, dpi=ORIGINAL_DPI, figsize=ORIGINAL_FIGURE_SIZE,\n constrained_layout=True)\n', (5664, 5747), True, 'import matplotlib.pyplot as plt\n'), ((5868, 5976), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax1', 'multiple_data_test_cases'], {'pixel_width': 'pixel_width', 'title': '""""""', 'add_norm': '(True)'}), "(ax1, multiple_data_test_cases, pixel_width=\n pixel_width, title='', add_norm=True)\n", (5890, 5976), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((6412, 6452), 'gdef_reporter.plotter_utils.create_z_histogram_plot', 'create_z_histogram_plot', (['data_test_cases'], {}), '(data_test_cases)\n', (6435, 6452), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((7226, 7289), 'gdef_reporter.plotter_styles.get_plotter_style_histogram', 'get_plotter_style_histogram', (['ORIGINAL_DPI', 'ORIGINAL_FIGURE_SIZE'], {}), '(ORIGINAL_DPI, ORIGINAL_FIGURE_SIZE)\n', (7253, 7289), False, 'from gdef_reporter.plotter_styles import get_plotter_style_histogram\n'), ((7305, 7441), 'gdef_reporter.plotter_utils.create_z_histogram_plot', 'create_z_histogram_plot', (['data_test_cases', 'labels'], {'n_bins': 'n_bins', 'title': 'title', 'units': '"""nm"""', 'add_norm': '(True)', 'plotter_style': 'plotter_style'}), "(data_test_cases, labels, n_bins=n_bins, title=title,\n units='nm', add_norm=True, plotter_style=plotter_style)\n", (7328, 7441), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((8048, 8100), 'gdef_reporter.plotter_utils.create_z_histogram_plot', 'create_z_histogram_plot', (['data_test_cases'], {'title': 'None'}), '(data_test_cases, title=None)\n', (8071, 8100), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((8562, 8680), 'gdef_reporter.plotter_utils.create_z_histogram_plot', 'create_z_histogram_plot', (['multiple_data_test_cases'], {'pixel_width': 'pixel_width', 'labels': 'labels', 'title': '""""""', 'add_norm': '(True)'}), "(multiple_data_test_cases, pixel_width=pixel_width,\n labels=labels, title='', add_norm=True)\n", (8585, 8680), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((9067, 9099), 'gdef_reporter.plotter_utils.create_rms_plot', 'create_rms_plot', (['data_test_cases'], {}), '(data_test_cases)\n', (9082, 9099), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((9594, 9731), 'gdef_reporter.plotter_utils.create_rms_plot', 'create_rms_plot', (['data_test_cases'], {'label_list': 'labels', 'pixel_width': 'pixel_width', 'moving_average_n': '(1)', 'subtract_average': '(True)', 'x_units': '"""nm"""'}), "(data_test_cases, label_list=labels, pixel_width=pixel_width,\n moving_average_n=1, subtract_average=True, x_units='nm')\n", (9609, 9731), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((10391, 10432), 'gdef_reporter.plotter_utils.create_rms_plot', 'create_rms_plot', (['multiple_data_test_cases'], {}), '(multiple_data_test_cases)\n', (10406, 10432), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((10875, 11040), 'gdef_reporter.plotter_utils.create_rms_plot', 'create_rms_plot', (['multiple_data_test_cases'], {'label_list': 'labels', 'pixel_width': 'pixel_width', 'moving_average_n': '(1)', 'subtract_average': '(False)', 'x_units': '"""nm"""', 'title': 'title'}), "(multiple_data_test_cases, label_list=labels, pixel_width=\n pixel_width, moving_average_n=1, subtract_average=False, x_units='nm',\n title=title)\n", (10890, 11040), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((11403, 11446), 'gdef_reporter.plotter_utils.create_rms_with_error_plot', 'create_rms_with_error_plot', (['data_test_cases'], {}), '(data_test_cases)\n', (11429, 11446), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((12257, 12334), 'gdef_reporter.plotter_utils.create_rms_with_error_plot', 'create_rms_with_error_plot', (['multiple_data_test_cases'], {'pixel_width': 'pixel_width'}), '(multiple_data_test_cases, pixel_width=pixel_width)\n', (12283, 12334), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((12610, 12697), 'gdef_reporter.plotter_utils.create_summary_plot', 'create_summary_plot', (['multiple_data_test_cases'], {'pixel_width': 'pixel_width', 'title': 'title'}), '(multiple_data_test_cases, pixel_width=pixel_width,\n title=title)\n', (12629, 12697), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((12909, 12983), 'gdef_reporter.plotter_utils._extract_ndarray_and_pixel_width', '_extract_ndarray_and_pixel_width', (['data_test_cases'], {'pixel_width': 'pixel_width'}), '(data_test_cases, pixel_width=pixel_width)\n', (12941, 12983), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((13376, 13443), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'dpi': '(72)', 'figsize': '(1, 1)', 'constrained_layout': '(True)'}), '(1, 1, dpi=72, figsize=(1, 1), constrained_layout=True)\n', (13388, 13443), True, 'import matplotlib.pyplot as plt\n'), ((13583, 13619), 'gdef_reporter.plotter_utils.save_figure', 'save_figure', (['fig', 'tmp_path', 'filename'], {}), '(fig, tmp_path, filename)\n', (13594, 13619), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((13925, 13983), 'gdef_reporter.plotter_utils.save_figure', 'save_figure', (['fig', 'tmp_path', 'filename'], {'png': '(False)', 'pdf': '(False)'}), '(fig, tmp_path, filename, png=False, pdf=False)\n', (13936, 13983), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((14288, 14345), 'gdef_reporter.plotter_utils.save_figure', 'save_figure', (['fig', 'tmp_path', 'filename'], {'png': '(False)', 'pdf': '(True)'}), '(fig, tmp_path, filename, png=False, pdf=True)\n', (14299, 14345), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((14784, 14844), 'gdef_reporter.plotter_utils.save_figure', 'save_figure', (['fig', 'new_tmp_path', 'filename'], {'png': '(True)', 'pdf': '(True)'}), '(fig, new_tmp_path, filename, png=True, pdf=True)\n', (14795, 14844), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((13100, 13136), 'numpy.all', 'np.all', (['(data_test_cases == ndarray2d)'], {}), '(data_test_cases == ndarray2d)\n', (13106, 13136), True, 'import numpy as np\n'), ((13213, 13256), 'numpy.all', 'np.all', (['(data_test_cases.values == ndarray2d)'], {}), '(data_test_cases.values == ndarray2d)\n', (13219, 13256), True, 'import numpy as np\n'), ((2045, 2063), 'numpy.all', 'np.all', (['comparison'], {}), '(comparison)\n', (2051, 2063), True, 'import numpy as np\n'), ((3617, 3646), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (3630, 3646), False, 'import pytest\n'), ((3668, 3721), 'gdef_reporter.plotter_utils.plot_z_histogram_to_ax', 'plot_z_histogram_to_ax', (['ax1', 'multiple_data_test_cases'], {}), '(ax1, multiple_data_test_cases)\n', (3690, 3721), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((10260, 10289), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (10273, 10289), False, 'import pytest\n'), ((10311, 10352), 'gdef_reporter.plotter_utils.create_rms_plot', 'create_rms_plot', (['multiple_data_test_cases'], {}), '(multiple_data_test_cases)\n', (10326, 10352), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n'), ((12024, 12053), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (12037, 12053), False, 'import pytest\n'), ((12075, 12127), 'gdef_reporter.plotter_utils.create_rms_with_error_plot', 'create_rms_with_error_plot', (['multiple_data_test_cases'], {}), '(multiple_data_test_cases)\n', (12101, 12127), False, 'from gdef_reporter.plotter_utils import plot_to_ax, create_plot, plot_z_histogram_to_ax, create_z_histogram_plot, _extract_ndarray_and_pixel_width, save_figure, create_rms_plot, create_rms_with_error_plot, create_summary_plot\n')]
import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import minmax_scale import matplotlib.pyplot as plt from model.loss import CategoricalCrossEntropy from model.layers.dense import Dense from model.layers.relu import LeakyReLU from model.layers.softmax import Softmax from model.neural_network import NeuralNetwork def spiral_data(points, classes): X = np.zeros((points * classes, 2)) y = np.zeros(points * classes, dtype='uint8') for class_number in range(classes): ix = range(points * class_number, points * (class_number + 1)) r = np.linspace(0.0, 1, points) # radius t = np.linspace(class_number * 4, (class_number + 1) * 4, points) + np.random.randn(points) * 0.2 X[ix] = np.c_[r * np.sin(t * 2.5), r * np.cos(t * 2.5)] y[ix] = class_number return X, y # ------------------------------------ DATASET N = 200 # number of points per class D = 2 # dimensionality K = 3 # number of classes X, y = spiral_data(points=N, classes=K) print("Scale values") print('Min: %.3f, Max: %.3f' % (X.min(), X.max())) X = minmax_scale(X, feature_range=(0, 1)) print('Min: %.3f, Max: %.3f' % (X.min(), X.max())) # plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral) # plt.show() # ------------------------------------ SPLIT DATA """X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=65)""" # ------------------------------------ HYPER PARAMETERS STEP_SIZE = 1e-1 N_EPOCHS = 2000 BATCH_SIZE = 32 # ------------------------------------ BUILD THE MODEL nn = NeuralNetwork([ Dense(200), LeakyReLU(), Dense(100), LeakyReLU(), Dense(50), LeakyReLU(), Dense(K), Softmax() ], CategoricalCrossEntropy()) # ------------------------------------ FIT THE MODEL nn.train(dataset=X, labels=y, epochs=N_EPOCHS, batch_size=BATCH_SIZE, step_size=STEP_SIZE) # ------------------------------------ EVALUATE THE MODEL train_loss = nn.metrics.history['train_loss'] val_loss = nn.metrics.history['val_loss'] epochs = range(0, N_EPOCHS) plt.plot(epochs, train_loss, 'g', label='Training loss') plt.plot(epochs, val_loss, 'b', label='validation loss') plt.title('Training and Validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() print(f"train loss: {train_loss}") print(f"val loss: {val_loss}") train_acc = nn.metrics.history['train_acc'] val_acc = nn.metrics.history['val_acc'] epochs = range(0, N_EPOCHS) plt.plot(epochs, train_acc, 'g', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='validation accuracy') plt.title('Training and Validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() print(f"train acc: {train_acc}") print(f"val acc: {val_acc}")
[ "model.loss.CategoricalCrossEntropy", "model.layers.relu.LeakyReLU", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "model.layers.dense.Dense", "numpy.zeros", "numpy.linspace", "sklearn.preprocessing.minmax_scale", "model.layers.softmax.Softmax", "numpy.cos", "numpy.sin", "matplotlib.pyplot.title", "numpy.random.randn", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((1123, 1160), 'sklearn.preprocessing.minmax_scale', 'minmax_scale', (['X'], {'feature_range': '(0, 1)'}), '(X, feature_range=(0, 1))\n', (1135, 1160), False, 'from sklearn.preprocessing import minmax_scale\n'), ((2273, 2329), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'train_loss', '"""g"""'], {'label': '"""Training loss"""'}), "(epochs, train_loss, 'g', label='Training loss')\n", (2281, 2329), True, 'import matplotlib.pyplot as plt\n'), ((2330, 2386), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'val_loss', '"""b"""'], {'label': '"""validation loss"""'}), "(epochs, val_loss, 'b', label='validation loss')\n", (2338, 2386), True, 'import matplotlib.pyplot as plt\n'), ((2387, 2428), 'matplotlib.pyplot.title', 'plt.title', (['"""Training and Validation loss"""'], {}), "('Training and Validation loss')\n", (2396, 2428), True, 'import matplotlib.pyplot as plt\n'), ((2429, 2449), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (2439, 2449), True, 'import matplotlib.pyplot as plt\n'), ((2450, 2468), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (2460, 2468), True, 'import matplotlib.pyplot as plt\n'), ((2469, 2481), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2479, 2481), True, 'import matplotlib.pyplot as plt\n'), ((2482, 2492), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2490, 2492), True, 'import matplotlib.pyplot as plt\n'), ((2673, 2732), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'train_acc', '"""g"""'], {'label': '"""Training accuracy"""'}), "(epochs, train_acc, 'g', label='Training accuracy')\n", (2681, 2732), True, 'import matplotlib.pyplot as plt\n'), ((2733, 2792), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'val_acc', '"""b"""'], {'label': '"""validation accuracy"""'}), "(epochs, val_acc, 'b', label='validation accuracy')\n", (2741, 2792), True, 'import matplotlib.pyplot as plt\n'), ((2793, 2838), 'matplotlib.pyplot.title', 'plt.title', (['"""Training and Validation accuracy"""'], {}), "('Training and Validation accuracy')\n", (2802, 2838), True, 'import matplotlib.pyplot as plt\n'), ((2839, 2859), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (2849, 2859), True, 'import matplotlib.pyplot as plt\n'), ((2860, 2882), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (2870, 2882), True, 'import matplotlib.pyplot as plt\n'), ((2883, 2895), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2893, 2895), True, 'import matplotlib.pyplot as plt\n'), ((2896, 2906), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2904, 2906), True, 'import matplotlib.pyplot as plt\n'), ((408, 439), 'numpy.zeros', 'np.zeros', (['(points * classes, 2)'], {}), '((points * classes, 2))\n', (416, 439), True, 'import numpy as np\n'), ((448, 489), 'numpy.zeros', 'np.zeros', (['(points * classes)'], {'dtype': '"""uint8"""'}), "(points * classes, dtype='uint8')\n", (456, 489), True, 'import numpy as np\n'), ((1890, 1915), 'model.loss.CategoricalCrossEntropy', 'CategoricalCrossEntropy', ([], {}), '()\n', (1913, 1915), False, 'from model.loss import CategoricalCrossEntropy\n'), ((613, 640), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1)', 'points'], {}), '(0.0, 1, points)\n', (624, 640), True, 'import numpy as np\n'), ((1781, 1791), 'model.layers.dense.Dense', 'Dense', (['(200)'], {}), '(200)\n', (1786, 1791), False, 'from model.layers.dense import Dense\n'), ((1793, 1804), 'model.layers.relu.LeakyReLU', 'LeakyReLU', ([], {}), '()\n', (1802, 1804), False, 'from model.layers.relu import LeakyReLU\n'), ((1810, 1820), 'model.layers.dense.Dense', 'Dense', (['(100)'], {}), '(100)\n', (1815, 1820), False, 'from model.layers.dense import Dense\n'), ((1822, 1833), 'model.layers.relu.LeakyReLU', 'LeakyReLU', ([], {}), '()\n', (1831, 1833), False, 'from model.layers.relu import LeakyReLU\n'), ((1839, 1848), 'model.layers.dense.Dense', 'Dense', (['(50)'], {}), '(50)\n', (1844, 1848), False, 'from model.layers.dense import Dense\n'), ((1850, 1861), 'model.layers.relu.LeakyReLU', 'LeakyReLU', ([], {}), '()\n', (1859, 1861), False, 'from model.layers.relu import LeakyReLU\n'), ((1867, 1875), 'model.layers.dense.Dense', 'Dense', (['K'], {}), '(K)\n', (1872, 1875), False, 'from model.layers.dense import Dense\n'), ((1877, 1886), 'model.layers.softmax.Softmax', 'Softmax', ([], {}), '()\n', (1884, 1886), False, 'from model.layers.softmax import Softmax\n'), ((663, 724), 'numpy.linspace', 'np.linspace', (['(class_number * 4)', '((class_number + 1) * 4)', 'points'], {}), '(class_number * 4, (class_number + 1) * 4, points)\n', (674, 724), True, 'import numpy as np\n'), ((727, 750), 'numpy.random.randn', 'np.random.randn', (['points'], {}), '(points)\n', (742, 750), True, 'import numpy as np\n'), ((783, 798), 'numpy.sin', 'np.sin', (['(t * 2.5)'], {}), '(t * 2.5)\n', (789, 798), True, 'import numpy as np\n'), ((804, 819), 'numpy.cos', 'np.cos', (['(t * 2.5)'], {}), '(t * 2.5)\n', (810, 819), True, 'import numpy as np\n')]
import json import numpy as np import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from model import NeuralNetwork from nltk_utils import stem, tokenize, bag_of_words with open('./data/data.json', 'r') as f: data = json.load(f) all_words = [] tags = [] xy = [] for intents in data['intents']: tag = intents['tag'] tags.append(tag) for pattern in intents['patterns']: w = tokenize(pattern) all_words.extend(w) xy.append((w, tag)) ignore_words = ['?', '!', '.', ','] all_words = [stem(w) for w in all_words if w not in ignore_words] all_words = sorted(set(all_words)) tags = sorted(set(tags)) print(tags) x_train = [] y_train = [] for (pattern_sentence, tag) in xy: bag = bag_of_words(pattern_sentence, all_words) x_train.append(bag) label = tags.index(tag) y_train.append(label) x_train = np.array(x_train) y_train = np.array(y_train) class ChatDataset(Dataset): def __init__(self) -> None: self.n_samples = len(x_train) self.x_data = x_train self.y_data = y_train #dataset[index] def __getitem__(self, index: int) -> None: return self.x_data[index], self.y_data[index] def __len__(self) -> int: return self.n_samples # Hyperparams batch_size = 8 hidden_size = 8 output_size = len(tags) input_size = len(x_train[0]) learning_rate = 0.001 num_epochs = 1000 dataset = ChatDataset() train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, num_workers=2) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = NeuralNetwork(input_size, hidden_size, output_size).to(device) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) for epoch in range(num_epochs): for (words, labels) in train_loader: words = words.to(device) labels = labels.to(device) outputs = model(words) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() if (epoch+1) % 100 == 0: print(f'epoch [{epoch+1}/{num_epochs}], loss: {loss.item():.4f}') print(f'final loss: {loss.item():.4f}') data = { "model_state": model.state_dict(), "input_size": input_size, "output_size": output_size, "hidden_size": hidden_size, "all_words": all_words, "tags": tags } FILE = './data/data.pth' torch.save(data, FILE) print(f'training complete. file saved to {FILE}') print(x_train)
[ "torch.nn.CrossEntropyLoss", "numpy.array", "nltk_utils.bag_of_words", "nltk_utils.tokenize", "torch.cuda.is_available", "torch.save", "torch.utils.data.DataLoader", "json.load", "model.NeuralNetwork", "nltk_utils.stem" ]
[((896, 913), 'numpy.array', 'np.array', (['x_train'], {}), '(x_train)\n', (904, 913), True, 'import numpy as np\n'), ((924, 941), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (932, 941), True, 'import numpy as np\n'), ((1468, 1547), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'dataset', 'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': '(2)'}), '(dataset=dataset, batch_size=batch_size, shuffle=True, num_workers=2)\n', (1478, 1547), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((1703, 1724), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1722, 1724), True, 'import torch.nn as nn\n'), ((2456, 2478), 'torch.save', 'torch.save', (['data', 'FILE'], {}), '(data, FILE)\n', (2466, 2478), False, 'import torch\n'), ((255, 267), 'json.load', 'json.load', (['f'], {}), '(f)\n', (264, 267), False, 'import json\n'), ((564, 571), 'nltk_utils.stem', 'stem', (['w'], {}), '(w)\n', (568, 571), False, 'from nltk_utils import stem, tokenize, bag_of_words\n'), ((763, 804), 'nltk_utils.bag_of_words', 'bag_of_words', (['pattern_sentence', 'all_words'], {}), '(pattern_sentence, all_words)\n', (775, 804), False, 'from nltk_utils import stem, tokenize, bag_of_words\n'), ((440, 457), 'nltk_utils.tokenize', 'tokenize', (['pattern'], {}), '(pattern)\n', (448, 457), False, 'from nltk_utils import stem, tokenize, bag_of_words\n'), ((1581, 1606), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1604, 1606), False, 'import torch\n'), ((1627, 1678), 'model.NeuralNetwork', 'NeuralNetwork', (['input_size', 'hidden_size', 'output_size'], {}), '(input_size, hidden_size, output_size)\n', (1640, 1678), False, 'from model import NeuralNetwork\n')]
import os import sys import syglass as sy from syglass import pyglass import numpy as np import tifffile import subprocess def extract(projectPath): project = sy.get_project(projectPath) head, tail = os.path.split(projectPath) # Get a dictionary showing the number of blocks in each level #codebreak() resolution_map = project.get_resolution_map() # Calculate the index of the highest resolution level max_resolution_level = len(resolution_map) - 1 # Determine the number of blocks in this level block_count = resolution_map[max_resolution_level] # get size of project total_size = project.get_size(max_resolution_level) xsize = total_size[1] ysize = total_size[2] zslices = total_size[0] dimensions = np.asarray([1,xsize, ysize]) offset = np.asarray([0,0,0]) os.chdir(os.path.dirname(projectPath)) for slice in range(zslices): s = str(slice).zfill(5) offset[0] = slice block = project.get_custom_block(0, max_resolution_level, offset, dimensions) data = block.data print(s + ".tiff") tifffile.imwrite(tail + "_" + s + ".tiff", data) subprocess.run(['explorer', head]) def main(): print("Image Extractor, by <NAME>") print("Attempts to extract the original data volume from a syGlass project") print("and write it to a series of TIFF files") print("---------------------------------------") print("Usage: Highlight a project and use the Script Launcher in syGlass.") print("---------------------------------------") print(sys.argv) for syGlassProjectPath in sys.argv: print("Extracting project from: " + syGlassProjectPath) extract(syGlassProjectPath) if __name__== "__main__": main()
[ "subprocess.run", "numpy.asarray", "os.path.split", "os.path.dirname", "syglass.get_project", "tifffile.imwrite" ]
[((162, 189), 'syglass.get_project', 'sy.get_project', (['projectPath'], {}), '(projectPath)\n', (176, 189), True, 'import syglass as sy\n'), ((204, 230), 'os.path.split', 'os.path.split', (['projectPath'], {}), '(projectPath)\n', (217, 230), False, 'import os\n'), ((736, 765), 'numpy.asarray', 'np.asarray', (['[1, xsize, ysize]'], {}), '([1, xsize, ysize])\n', (746, 765), True, 'import numpy as np\n'), ((775, 796), 'numpy.asarray', 'np.asarray', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (785, 796), True, 'import numpy as np\n'), ((1084, 1118), 'subprocess.run', 'subprocess.run', (["['explorer', head]"], {}), "(['explorer', head])\n", (1098, 1118), False, 'import subprocess\n'), ((805, 833), 'os.path.dirname', 'os.path.dirname', (['projectPath'], {}), '(projectPath)\n', (820, 833), False, 'import os\n'), ((1034, 1082), 'tifffile.imwrite', 'tifffile.imwrite', (["(tail + '_' + s + '.tiff')", 'data'], {}), "(tail + '_' + s + '.tiff', data)\n", (1050, 1082), False, 'import tifffile\n')]
import os import sys from dataclasses import dataclass import click import numpy as np import xgboost as xgb from rich import print, traceback WD = os.path.dirname(__file__) @click.command() @click.option('-i', '--input', required=True, type=str, help='Path to data file to predict.') @click.option('-m', '--model', type=str, help='Path to an already trained XGBoost model. If not passed a default model will be loaded.') @click.option('-c/-nc', '--cuda/--no-cuda', type=bool, default=False, help='Whether to enable cuda or not') @click.option('-o', '--output', type=str, help='Path to write the output to') def main(input: str, model: str, cuda: bool, output: str): """Command-line interface for {{ cookiecutter.project_name }}""" print(r"""[bold blue] {{ cookiecutter.project_name }} """) print('[bold blue]Run [green]{{ cookiecutter.project_name }} --help [blue]for an overview of all commands\n') if not model: model = get_xgboost_model(f'{WD}/models/xgboost_test_model.xgb') else: model = get_xgboost_model(model) if cuda: model.set_param({'predictor': 'gpu_predictor'}) print('[bold blue] Parsing data') data_to_predict = parse_data_to_predict(input) print('[bold blue] Performing predictions') predictions = np.round(model.predict(data_to_predict.DM)) print(predictions) if output: print(f'[bold blue]Writing predictions to {output}') write_results(predictions, output) @dataclass class Dataset: X: np.ndarray y: list DM: xgb.DMatrix gene_names: list sample_names: list def parse_data_to_predict(path_to_data_to_predict: str) -> Dataset: """ Parses the data to predict and returns a full Dataset include the DMatrix :param path_to_data_to_predict: Path to the data on which predictions should be performed on """ X = [] y = [] gene_names = [] sample_names = [] with open(path_to_data_to_predict, "r") as file: all_runs_info = next(file).split("\n")[0].split("\t")[2:] for run_info in all_runs_info: split_info = run_info.split("_") y.append(int(split_info[0])) sample_names.append(split_info[1]) for line in file: split = line.split("\n")[0].split("\t") X.append([float(x) for x in split[2:]]) gene_names.append(split[:2]) X = [list(i) for i in zip(*X)] X_np = np.array(X) DM = xgb.DMatrix(X_np, label=y) return Dataset(X_np, y, DM, gene_names, sample_names) def write_results(predictions: np.ndarray, path_to_write_to) -> None: """ Writes the predictions into a human readable file. :param predictions: Predictions as a numpy array :param path_to_write_to: Path to write the predictions to """ np.savetxt(path_to_write_to, predictions, delimiter=',') def get_xgboost_model(path_to_xgboost_model: str): """ Fetches the model of choice and creates a booster from it. :param path_to_xgboost_model: Path to the xgboost model1 """ model = xgb.Booster() model.load_model(os.path.abspath(path_to_xgboost_model)) return model if __name__ == "__main__": traceback.install() sys.exit(main()) # pragma: no cover
[ "rich.traceback.install", "click.option", "os.path.dirname", "rich.print", "numpy.array", "xgboost.Booster", "numpy.savetxt", "os.path.abspath", "xgboost.DMatrix", "click.command" ]
[((150, 175), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (165, 175), False, 'import os\n'), ((179, 194), 'click.command', 'click.command', ([], {}), '()\n', (192, 194), False, 'import click\n'), ((196, 293), 'click.option', 'click.option', (['"""-i"""', '"""--input"""'], {'required': '(True)', 'type': 'str', 'help': '"""Path to data file to predict."""'}), "('-i', '--input', required=True, type=str, help=\n 'Path to data file to predict.')\n", (208, 293), False, 'import click\n'), ((290, 435), 'click.option', 'click.option', (['"""-m"""', '"""--model"""'], {'type': 'str', 'help': '"""Path to an already trained XGBoost model. If not passed a default model will be loaded."""'}), "('-m', '--model', type=str, help=\n 'Path to an already trained XGBoost model. If not passed a default model will be loaded.'\n )\n", (302, 435), False, 'import click\n'), ((427, 538), 'click.option', 'click.option', (['"""-c/-nc"""', '"""--cuda/--no-cuda"""'], {'type': 'bool', 'default': '(False)', 'help': '"""Whether to enable cuda or not"""'}), "('-c/-nc', '--cuda/--no-cuda', type=bool, default=False, help=\n 'Whether to enable cuda or not')\n", (439, 538), False, 'import click\n'), ((535, 611), 'click.option', 'click.option', (['"""-o"""', '"""--output"""'], {'type': 'str', 'help': '"""Path to write the output to"""'}), "('-o', '--output', type=str, help='Path to write the output to')\n", (547, 611), False, 'import click\n'), ((745, 818), 'rich.print', 'print', (['"""[bold blue]\n {{ cookiecutter.project_name }}\n """'], {}), '("""[bold blue]\n {{ cookiecutter.project_name }}\n """)\n', (750, 818), False, 'from rich import print, traceback\n'), ((825, 947), 'rich.print', 'print', (['"""[bold blue]Run [green]{{ cookiecutter.project_name }} --help [blue]for an overview of all commands\n"""'], {}), '(\n """[bold blue]Run [green]{{ cookiecutter.project_name }} --help [blue]for an overview of all commands\n"""\n )\n', (830, 947), False, 'from rich import print, traceback\n'), ((1150, 1183), 'rich.print', 'print', (['"""[bold blue] Parsing data"""'], {}), "('[bold blue] Parsing data')\n", (1155, 1183), False, 'from rich import print, traceback\n'), ((1239, 1282), 'rich.print', 'print', (['"""[bold blue] Performing predictions"""'], {}), "('[bold blue] Performing predictions')\n", (1244, 1282), False, 'from rich import print, traceback\n'), ((1349, 1367), 'rich.print', 'print', (['predictions'], {}), '(predictions)\n', (1354, 1367), False, 'from rich import print, traceback\n'), ((2444, 2455), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (2452, 2455), True, 'import numpy as np\n'), ((2465, 2491), 'xgboost.DMatrix', 'xgb.DMatrix', (['X_np'], {'label': 'y'}), '(X_np, label=y)\n', (2476, 2491), True, 'import xgboost as xgb\n'), ((2813, 2869), 'numpy.savetxt', 'np.savetxt', (['path_to_write_to', 'predictions'], {'delimiter': '""","""'}), "(path_to_write_to, predictions, delimiter=',')\n", (2823, 2869), True, 'import numpy as np\n'), ((3075, 3088), 'xgboost.Booster', 'xgb.Booster', ([], {}), '()\n', (3086, 3088), True, 'import xgboost as xgb\n'), ((3201, 3220), 'rich.traceback.install', 'traceback.install', ([], {}), '()\n', (3218, 3220), False, 'from rich import print, traceback\n'), ((1391, 1443), 'rich.print', 'print', (['f"""[bold blue]Writing predictions to {output}"""'], {}), "(f'[bold blue]Writing predictions to {output}')\n", (1396, 1443), False, 'from rich import print, traceback\n'), ((3110, 3148), 'os.path.abspath', 'os.path.abspath', (['path_to_xgboost_model'], {}), '(path_to_xgboost_model)\n', (3125, 3148), False, 'import os\n')]
from __future__ import division, absolute_import, print_function from past.builtins import xrange import unittest import numpy.testing as testing import numpy as np import fitsio import os from numpy import random from redmapper import Cluster from redmapper import Configuration from redmapper import CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatellite from redmapper import GalaxyCatalog from redmapper import RedSequenceColorPar from redmapper import Background from redmapper import ZredBackground from redmapper import ZlambdaCorrectionPar class CenteringTestCase(unittest.TestCase): """ Test application of the centering models (CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatelliate). """ def test_wcenzred(self): """ Test running of CenteringWcenZred. """ file_path = 'data_for_tests' cluster = self._setup_cluster() tempcat = fitsio.read(os.path.join(file_path, 'test_wcen_zred_data.fit')) corr_filename = 'test_dr8_zlambdacorr.fit' zlambda_corr = ZlambdaCorrectionPar(os.path.join(file_path, 'test_dr8_zlambdacorr.fit'), zlambda_pivot=30.0) zlambda_corr = ZlambdaCorrectionPar(file_path + '/' + corr_filename, zlambda_pivot=30.0) # And the meat of it... cent = CenteringWcenZred(cluster, zlambda_corr=zlambda_corr) cent.find_center() testing.assert_almost_equal(cent.p_cen, tempcat[0]['PCEN'][tempcat[0]['GOOD']], 5) testing.assert_almost_equal(cent.q_cen, tempcat[0]['QCEN'][tempcat[0]['GOOD']], 4) testing.assert_almost_equal(cent.p_sat, tempcat[0]['PSAT'], 4) testing.assert_almost_equal(cent.p_fg, tempcat[0]['PFG'], 4) testing.assert_array_equal(cent.index, tempcat[0]['USE'][tempcat[0]['GOOD']]) def test_bcg(self): """ Test running of CenteringBcg. """ cluster = self._setup_cluster() cent = CenteringBCG(cluster) cent.find_center() self.assertEqual(cent.maxind, 72) self.assertEqual(cent.ngood, 1) testing.assert_almost_equal(cent.ra, 150.55890608) testing.assert_almost_equal(cent.dec, 20.53794937) testing.assert_almost_equal(cent.p_cen[0], 1.0) testing.assert_almost_equal(cent.q_cen[0], 1.0) testing.assert_almost_equal(cent.p_sat[0], 0.0) def test_random(self): """ Test running of CenteringRandom. """ random.seed(seed=12345) cluster = self._setup_cluster() cent = CenteringRandom(cluster) cent.find_center() self.assertEqual(cent.maxind, -1) self.assertEqual(cent.ngood, 1) testing.assert_almost_equal(cent.ra[0], 150.57049502423266) testing.assert_almost_equal(cent.dec[0], 20.604521924053167) testing.assert_almost_equal(cent.p_cen[0], 1.0) testing.assert_almost_equal(cent.q_cen[0], 1.0) testing.assert_almost_equal(cent.p_sat[0], 0.0) def test_randsat(self): """ Test running of CenteringRandomSatellite. """ random.seed(seed=12345) cluster = self._setup_cluster() cent = CenteringRandomSatellite(cluster) cent.find_center() # Confirmed that the distribution is correct, this just checks for regression self.assertEqual(cent.maxind, 721) self.assertEqual(cent.ngood, 1) testing.assert_almost_equal(cent.ra[0], 150.67510227) testing.assert_almost_equal(cent.dec[0], 20.48011092) testing.assert_almost_equal(cent.p_cen[0], 1.0) testing.assert_almost_equal(cent.q_cen[0], 1.0) testing.assert_almost_equal(cent.p_sat[0], 0.0) def _setup_cluster(self): """ Set up the cluster to run through the centering code. """ file_path = 'data_for_tests' cluster = Cluster() cluster.config = Configuration(os.path.join(file_path, 'testconfig.yaml')) tempcat = fitsio.read(os.path.join(file_path, 'test_wcen_zred_data.fit')) temp_neighbors = np.zeros(tempcat[0]['RAS'].size, dtype = [('RA', 'f8'), ('DEC', 'f8'), ('DIST', 'f4'), ('R', 'f4'), ('P', 'f4'), ('PFREE', 'f4'), ('PMEM', 'f4'), ('MAG', 'f4', 5), ('MAG_ERR', 'f4', 5), ('REFMAG', 'f4'), ('REFMAG_ERR', 'f4'), ('CHISQ', 'f4'), ('ZRED', 'f4'), ('ZRED_E', 'f4'), ('ZRED_CHISQ', 'f4')]) temp_neighbors['RA'] = tempcat[0]['RAS'] temp_neighbors['DEC'] = tempcat[0]['DECS'] temp_neighbors['R'] = tempcat[0]['R'] temp_neighbors['P'] = tempcat[0]['PVALS'] temp_neighbors['PFREE'] = tempcat[0]['WVALS'] temp_neighbors['PMEM'] = tempcat[0]['WTVALS'] temp_neighbors['REFMAG'] = tempcat[0]['REFMAG_TOTAL'] temp_neighbors['ZRED'] = tempcat[0]['GZREDS'] temp_neighbors['ZRED_E'] = tempcat[0]['GZREDE'] temp_neighbors['ZRED_CHISQ'] = tempcat[0]['GCHISQ'] temp_neighbors['DIST'] = tempcat[0]['R'] / (np.radians(1.) * cluster.config.cosmo.Da(0, tempcat[0]['ZCLUSTER'])) neighbors = GalaxyCatalog(temp_neighbors) cluster.set_neighbors(neighbors) zred_filename = 'test_dr8_pars.fit' cluster.zredstr = RedSequenceColorPar(os.path.join(file_path, 'test_dr8_pars.fit'), fine=True, zrange=[0.25, 0.35]) cluster.bkg = Background(os.path.join(file_path, 'test_bkg.fit')) cluster.zredbkg = ZredBackground(os.path.join(file_path, 'test_bkg.fit')) cluster.redshift = tempcat[0]['ZCLUSTER'] cluster.ra = tempcat[0]['RAC'] cluster.dec = tempcat[0]['DECC'] cluster.r_lambda = 1.0 * (tempcat[0]['LAMBDA'] / 100.0)**0.2 cluster.Lambda = tempcat[0]['LAMBDA'] cluster.scaleval = tempcat[0]['SCALEVAL'] return cluster if __name__=='__main__': unittest.main()
[ "numpy.radians", "redmapper.Cluster", "redmapper.CenteringWcenZred", "os.path.join", "numpy.testing.assert_almost_equal", "numpy.zeros", "redmapper.ZlambdaCorrectionPar", "redmapper.CenteringRandom", "redmapper.CenteringBCG", "numpy.random.seed", "unittest.main", "redmapper.GalaxyCatalog", "numpy.testing.assert_array_equal", "redmapper.CenteringRandomSatellite" ]
[((6462, 6477), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6475, 6477), False, 'import unittest\n'), ((1209, 1282), 'redmapper.ZlambdaCorrectionPar', 'ZlambdaCorrectionPar', (["(file_path + '/' + corr_filename)"], {'zlambda_pivot': '(30.0)'}), "(file_path + '/' + corr_filename, zlambda_pivot=30.0)\n", (1229, 1282), False, 'from redmapper import ZlambdaCorrectionPar\n'), ((1332, 1385), 'redmapper.CenteringWcenZred', 'CenteringWcenZred', (['cluster'], {'zlambda_corr': 'zlambda_corr'}), '(cluster, zlambda_corr=zlambda_corr)\n', (1349, 1385), False, 'from redmapper import CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatellite\n'), ((1422, 1509), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_cen', "tempcat[0]['PCEN'][tempcat[0]['GOOD']]", '(5)'], {}), "(cent.p_cen, tempcat[0]['PCEN'][tempcat[0][\n 'GOOD']], 5)\n", (1449, 1509), True, 'import numpy.testing as testing\n'), ((1513, 1600), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.q_cen', "tempcat[0]['QCEN'][tempcat[0]['GOOD']]", '(4)'], {}), "(cent.q_cen, tempcat[0]['QCEN'][tempcat[0][\n 'GOOD']], 4)\n", (1540, 1600), True, 'import numpy.testing as testing\n'), ((1604, 1666), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_sat', "tempcat[0]['PSAT']", '(4)'], {}), "(cent.p_sat, tempcat[0]['PSAT'], 4)\n", (1631, 1666), True, 'import numpy.testing as testing\n'), ((1675, 1735), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_fg', "tempcat[0]['PFG']", '(4)'], {}), "(cent.p_fg, tempcat[0]['PFG'], 4)\n", (1702, 1735), True, 'import numpy.testing as testing\n'), ((1744, 1821), 'numpy.testing.assert_array_equal', 'testing.assert_array_equal', (['cent.index', "tempcat[0]['USE'][tempcat[0]['GOOD']]"], {}), "(cent.index, tempcat[0]['USE'][tempcat[0]['GOOD']])\n", (1770, 1821), True, 'import numpy.testing as testing\n'), ((1965, 1986), 'redmapper.CenteringBCG', 'CenteringBCG', (['cluster'], {}), '(cluster)\n', (1977, 1986), False, 'from redmapper import CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatellite\n'), ((2105, 2155), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.ra', '(150.55890608)'], {}), '(cent.ra, 150.55890608)\n', (2132, 2155), True, 'import numpy.testing as testing\n'), ((2164, 2214), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.dec', '(20.53794937)'], {}), '(cent.dec, 20.53794937)\n', (2191, 2214), True, 'import numpy.testing as testing\n'), ((2223, 2270), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_cen[0]', '(1.0)'], {}), '(cent.p_cen[0], 1.0)\n', (2250, 2270), True, 'import numpy.testing as testing\n'), ((2279, 2326), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.q_cen[0]', '(1.0)'], {}), '(cent.q_cen[0], 1.0)\n', (2306, 2326), True, 'import numpy.testing as testing\n'), ((2335, 2382), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_sat[0]', '(0.0)'], {}), '(cent.p_sat[0], 0.0)\n', (2362, 2382), True, 'import numpy.testing as testing\n'), ((2485, 2508), 'numpy.random.seed', 'random.seed', ([], {'seed': '(12345)'}), '(seed=12345)\n', (2496, 2508), False, 'from numpy import random\n'), ((2566, 2590), 'redmapper.CenteringRandom', 'CenteringRandom', (['cluster'], {}), '(cluster)\n', (2581, 2590), False, 'from redmapper import CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatellite\n'), ((2709, 2768), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.ra[0]', '(150.57049502423266)'], {}), '(cent.ra[0], 150.57049502423266)\n', (2736, 2768), True, 'import numpy.testing as testing\n'), ((2777, 2837), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.dec[0]', '(20.604521924053167)'], {}), '(cent.dec[0], 20.604521924053167)\n', (2804, 2837), True, 'import numpy.testing as testing\n'), ((2846, 2893), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_cen[0]', '(1.0)'], {}), '(cent.p_cen[0], 1.0)\n', (2873, 2893), True, 'import numpy.testing as testing\n'), ((2902, 2949), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.q_cen[0]', '(1.0)'], {}), '(cent.q_cen[0], 1.0)\n', (2929, 2949), True, 'import numpy.testing as testing\n'), ((2958, 3005), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_sat[0]', '(0.0)'], {}), '(cent.p_sat[0], 0.0)\n', (2985, 3005), True, 'import numpy.testing as testing\n'), ((3118, 3141), 'numpy.random.seed', 'random.seed', ([], {'seed': '(12345)'}), '(seed=12345)\n', (3129, 3141), False, 'from numpy import random\n'), ((3199, 3232), 'redmapper.CenteringRandomSatellite', 'CenteringRandomSatellite', (['cluster'], {}), '(cluster)\n', (3223, 3232), False, 'from redmapper import CenteringWcenZred, CenteringBCG, CenteringRandom, CenteringRandomSatellite\n'), ((3439, 3492), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.ra[0]', '(150.67510227)'], {}), '(cent.ra[0], 150.67510227)\n', (3466, 3492), True, 'import numpy.testing as testing\n'), ((3501, 3554), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.dec[0]', '(20.48011092)'], {}), '(cent.dec[0], 20.48011092)\n', (3528, 3554), True, 'import numpy.testing as testing\n'), ((3563, 3610), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_cen[0]', '(1.0)'], {}), '(cent.p_cen[0], 1.0)\n', (3590, 3610), True, 'import numpy.testing as testing\n'), ((3619, 3666), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.q_cen[0]', '(1.0)'], {}), '(cent.q_cen[0], 1.0)\n', (3646, 3666), True, 'import numpy.testing as testing\n'), ((3675, 3722), 'numpy.testing.assert_almost_equal', 'testing.assert_almost_equal', (['cent.p_sat[0]', '(0.0)'], {}), '(cent.p_sat[0], 0.0)\n', (3702, 3722), True, 'import numpy.testing as testing\n'), ((3896, 3905), 'redmapper.Cluster', 'Cluster', ([], {}), '()\n', (3903, 3905), False, 'from redmapper import Cluster\n'), ((4099, 4415), 'numpy.zeros', 'np.zeros', (["tempcat[0]['RAS'].size"], {'dtype': "[('RA', 'f8'), ('DEC', 'f8'), ('DIST', 'f4'), ('R', 'f4'), ('P', 'f4'), (\n 'PFREE', 'f4'), ('PMEM', 'f4'), ('MAG', 'f4', 5), ('MAG_ERR', 'f4', 5),\n ('REFMAG', 'f4'), ('REFMAG_ERR', 'f4'), ('CHISQ', 'f4'), ('ZRED', 'f4'),\n ('ZRED_E', 'f4'), ('ZRED_CHISQ', 'f4')]"}), "(tempcat[0]['RAS'].size, dtype=[('RA', 'f8'), ('DEC', 'f8'), (\n 'DIST', 'f4'), ('R', 'f4'), ('P', 'f4'), ('PFREE', 'f4'), ('PMEM', 'f4'\n ), ('MAG', 'f4', 5), ('MAG_ERR', 'f4', 5), ('REFMAG', 'f4'), (\n 'REFMAG_ERR', 'f4'), ('CHISQ', 'f4'), ('ZRED', 'f4'), ('ZRED_E', 'f4'),\n ('ZRED_CHISQ', 'f4')])\n", (4107, 4415), True, 'import numpy as np\n'), ((5714, 5743), 'redmapper.GalaxyCatalog', 'GalaxyCatalog', (['temp_neighbors'], {}), '(temp_neighbors)\n', (5727, 5743), False, 'from redmapper import GalaxyCatalog\n'), ((965, 1015), 'os.path.join', 'os.path.join', (['file_path', '"""test_wcen_zred_data.fit"""'], {}), "(file_path, 'test_wcen_zred_data.fit')\n", (977, 1015), False, 'import os\n'), ((1113, 1164), 'os.path.join', 'os.path.join', (['file_path', '"""test_dr8_zlambdacorr.fit"""'], {}), "(file_path, 'test_dr8_zlambdacorr.fit')\n", (1125, 1164), False, 'import os\n'), ((3946, 3988), 'os.path.join', 'os.path.join', (['file_path', '"""testconfig.yaml"""'], {}), "(file_path, 'testconfig.yaml')\n", (3958, 3988), False, 'import os\n'), ((4021, 4071), 'os.path.join', 'os.path.join', (['file_path', '"""test_wcen_zred_data.fit"""'], {}), "(file_path, 'test_wcen_zred_data.fit')\n", (4033, 4071), False, 'import os\n'), ((5876, 5920), 'os.path.join', 'os.path.join', (['file_path', '"""test_dr8_pars.fit"""'], {}), "(file_path, 'test_dr8_pars.fit')\n", (5888, 5920), False, 'import os\n'), ((5988, 6027), 'os.path.join', 'os.path.join', (['file_path', '"""test_bkg.fit"""'], {}), "(file_path, 'test_bkg.fit')\n", (6000, 6027), False, 'import os\n'), ((6070, 6109), 'os.path.join', 'os.path.join', (['file_path', '"""test_bkg.fit"""'], {}), "(file_path, 'test_bkg.fit')\n", (6082, 6109), False, 'import os\n'), ((5624, 5639), 'numpy.radians', 'np.radians', (['(1.0)'], {}), '(1.0)\n', (5634, 5639), True, 'import numpy as np\n')]
"""Classes for use with Yambo Representation of a spectrum. Main functionality is to read from Yambo output, o.qp files and also netcdf databases. """ import re import copy as cp import numpy as np import asetk.atomistic.fundamental as fu import asetk.atomistic.constants as atc from . import cube class Dispersion: """A Dispersion holds the k-points belonging to one spin""" def __init__(self, energylevels=None, kvectors=None, weights=None): """Set up spectrum from a list of EnergyLevels.""" self.__energylevels = energylevels self.__kvectors = kvectors self.__weights = weights @property def energylevels(self): """Returns energylevelsi of all k-points.""" return self.__energylevels @property def kvectors(self): return self.__kvectors @property def weights(self): return self.__weights @property def energies(self): """Returns list of energy levels of all k-points.""" list = [el.energies for el in self.__energylevels] return np.concatenate(list) @property def occupations(self): """Returns list of level occupations of all k-points.""" os = [] for el in self.__energylevels: os = os + list(el.occupations) return os def copy(self, dispersion): """Performs deep copy of dispersion.""" self.__energylevels = [ el.copy() for el in dispersion.__energylevels ] self.__kvectors = cp.copy(spectrum.__kvectors) self.__weights = cp.copy(spectrum.__weights) def shift(self, de): for levels in self.__energylevels: levels.shift(de) def __str__(self): text = "Dispersion containing {} k-points\n".format(len(self.__energylevels)) for i in range(len(self.__energylevels)): e = self.__energylevels[i] k = self.__kvectors[i] text += 'k = ({:6.3f}, {:6.3f}, {:6.3f})'.format(k[0], k[1], k[2]) if self.__weights: w = self.__weights[i] text += ', w = {}'.format(w) text += ' : {}\n'.format(e.__str__()) return text def __getitem__(self, index): return self.__energylevels[index] @property def nk(self): return len(self.energylevels) class Spectrum(object): """A Spectrum holds the data belonging to all spins""" def __init__(self, energylevels=None): """Set up spectrum from a list of EnergyLevels.""" self.dispersions = [ Dispersion(energylevels) ] @classmethod def from_output(cls, fname, mode='QP'): """Creates Spectrum from Yambo output file""" tmp = Spectrum() tmp.read_from_output(fname, mode) return tmp @classmethod def from_qp(cls, fname=None, mode='QP'): """Creates Spectrum from Yambo o.qp file""" tmp = Spectrum() tmp.read_from_qp(fname, mode) return tmp @classmethod def from_netcdf_db(cls, fname=None, mode='QP'): """Creates Spectrum from Yambo netcdf database""" tmp = Spectrum() tmp.read_from_netcdf_db(fname, mode=mode) return tmp @property def energies(self): """Returns list of energies e[ispin][ibnd].""" list = [disp.energies for disp in self.dispersions] return list @property def energylevels(self): """Returns list of Energylevels l[ispin][ibnd].""" list = [] for d in self.dispersions: sum = fu.Energylevels() for el in d.energylevels: sum += el list.append(sum) return list @property def occupations(self): """Returns list of level occupations of all spins.""" os = [] for disp in self.dispersions: os = os + disp.occupations return os @property def nspin(self): return len(self.dispersions) def copy(self, spectrum): """Performs deep copy of spectrum.""" self.dispersions = [ el.copy() for el in spectrum.dispersions ] self.spins = cp.copy(spectrum.spins) def shift(self, de): for disp in self.dispersions: disp.shift(de) def __str__(self): text = "Spectrum containing {} spins\n".format(len(self.dispersions)) for i in range(len(self.dispersions)): d = self.dispersions[i] s = self.spins[i] text += 'spin {} : {}\n'.format(s+1, d.__str__()) return text def __getitem__(self, index): return self.levels[index] def read_from_output(self, fname, mode=None): s = open(fname, 'r').read() floatregex = '-?\d+\.\d+' lineregex='[^\r\n]*\r?\n' #blanklineregex='(?:^\s*$)' if mode == 'DFT' or mode == None: kptregex = 'X\* K.*?: ({f})\s*({f})\s*({f}).*?weight\s*({f}){l}(.*?)[\*\[]'\ .format(f=floatregex,l=lineregex) fermiregex='Fermi Level.*?:(\s*[\-\d\.]+)' elif mode == 'QP': kptregex = 'Q?P \[eV\].*?:\s*({f})\s+({f})\s+({f})(.*?)[Q\[]'\ .format(f=floatregex) self.spins=[] self.dispersions=[] # No spin for the moment, but shouldn't be too difficult to extend for spin in [0]: disp = Dispersion() matches=re.findall(kptregex, s, re.DOTALL) if mode == 'DFT' or mode == None: fermi = float(re.search(fermiregex, s).group(1)) energylevels = [] kvectors = [] weights = [] for match in matches: kx, ky, kz, weight, ldata = match kvectors.append( np.array([kx, ky, kz], dtype=float) ) weights.append( float(weight) ) energies = re.findall('({f})'.format(f=floatregex), ldata, re.DOTALL) energies = np.array(energies, dtype=float) levels = fu.EnergyLevels(energies=energies,occupations=None, fermi=fermi) energylevels.append(levels) disp = Dispersion(energylevels=energylevels, kvectors=kvectors, weights=weights) elif mode == 'QP': energylevels = [] kvectors = [] for match in matches: kx, ky, kz, ldata = match kvectors.append( np.array([kx, ky, kz], dtype=float) ) energies = re.findall('E=\s*({f})'.format(f=floatregex), ldata, re.DOTALL) energies = np.array(energies, dtype=float) levels = fu.EnergyLevels(energies=energies) energylevels.append(levels) disp = Dispersion(energylevels=energylevels, kvectors=kvectors) self.dispersions.append(disp) self.spins.append(spin) def read_from_qp(self, fname="o.qp", ihomo=None): """Read from o.qp output (has more digits than in report. Anyhow, the proper way would be to read the database""" s = open(fname, 'r').read() data = np.genfromtxt(fname, dtype=float) energies = data[:,2] + data[:,3] # setting HOMO to zero if ihomo: energies -= energies[ihomo] self.spins=[] self.dispersions=[] # No spin for the moment, but shouldn't be too difficult to extend for spin in [0]: levels = fu.EnergyLevels(energies=energies,occupations=None) disp = Dispersion(energylevels=[levels], kvectors = [ (0,0,0) ] ) self.dispersions.append(disp) self.spins.append(spin) def read_from_netcdf_db(self, fname="ndb.QP", mode="QP"): """Read from netCDF database requires netCDF4 python module""" from netCDF4 import Dataset f = Dataset(fname, 'r') SPIN_VARS = f.variables['SPIN_VARS'][:] QP_kpts = f.variables['QP_kpts'][:] QP_table = f.variables['QP_table'][:] QP_E_Eo_Z = f.variables['QP_E_Eo_Z'][:] f.close() nspin = len(SPIN_VARS) nk = QP_kpts.shape[1] kpts = [ QP_kpts[:,ik] for ik in range(nk) ] ibnds, dum, iks, ispins = QP_table nbnd = len(ibnds) / (nspin * nk) if mode == "QP": iener = 0 elif mode == "DFT": iener = 1 else: print("Error: Did not recognize mode '{}'.".format(mode)) self.spins=[] self.dispersions=[] for ispin in range(nspin): is_spin = np.where(ispins == SPIN_VARS[ispin])[0] energylevels = [] kvectors = [] for ik in range(nk): k = kpts[ik] is_k = np.where(iks == ik+1)[0] # still need to figure out the first index # is it real vs. complex? e = QP_E_Eo_Z[0, np.intersect1d(is_spin,is_k), iener] * atc.Ha / atc.eV levels = fu.EnergyLevels(energies=e,occupations=None) kvectors.append(k) energylevels.append(levels) disp = Dispersion(energylevels=energylevels, kvectors = kvectors) self.dispersions.append(disp) self.spins.append(ispin) ## setting HOMO to zero #if ihomo: # energies -= energies[ihomo]
[ "numpy.intersect1d", "numpy.where", "netCDF4.Dataset", "asetk.atomistic.fundamental.Energylevels", "re.findall", "numpy.array", "numpy.concatenate", "copy.copy", "numpy.genfromtxt", "asetk.atomistic.fundamental.EnergyLevels", "re.search" ]
[((1070, 1090), 'numpy.concatenate', 'np.concatenate', (['list'], {}), '(list)\n', (1084, 1090), True, 'import numpy as np\n'), ((1501, 1529), 'copy.copy', 'cp.copy', (['spectrum.__kvectors'], {}), '(spectrum.__kvectors)\n', (1508, 1529), True, 'import copy as cp\n'), ((1555, 1582), 'copy.copy', 'cp.copy', (['spectrum.__weights'], {}), '(spectrum.__weights)\n', (1562, 1582), True, 'import copy as cp\n'), ((4129, 4152), 'copy.copy', 'cp.copy', (['spectrum.spins'], {}), '(spectrum.spins)\n', (4136, 4152), True, 'import copy as cp\n'), ((7232, 7265), 'numpy.genfromtxt', 'np.genfromtxt', (['fname'], {'dtype': 'float'}), '(fname, dtype=float)\n', (7245, 7265), True, 'import numpy as np\n'), ((7987, 8006), 'netCDF4.Dataset', 'Dataset', (['fname', '"""r"""'], {}), "(fname, 'r')\n", (7994, 8006), False, 'from netCDF4 import Dataset\n'), ((3540, 3557), 'asetk.atomistic.fundamental.Energylevels', 'fu.Energylevels', ([], {}), '()\n', (3555, 3557), True, 'import asetk.atomistic.fundamental as fu\n'), ((5402, 5436), 're.findall', 're.findall', (['kptregex', 's', 're.DOTALL'], {}), '(kptregex, s, re.DOTALL)\n', (5412, 5436), False, 'import re\n'), ((7585, 7637), 'asetk.atomistic.fundamental.EnergyLevels', 'fu.EnergyLevels', ([], {'energies': 'energies', 'occupations': 'None'}), '(energies=energies, occupations=None)\n', (7600, 7637), True, 'import asetk.atomistic.fundamental as fu\n'), ((8712, 8748), 'numpy.where', 'np.where', (['(ispins == SPIN_VARS[ispin])'], {}), '(ispins == SPIN_VARS[ispin])\n', (8720, 8748), True, 'import numpy as np\n'), ((9134, 9179), 'asetk.atomistic.fundamental.EnergyLevels', 'fu.EnergyLevels', ([], {'energies': 'e', 'occupations': 'None'}), '(energies=e, occupations=None)\n', (9149, 9179), True, 'import asetk.atomistic.fundamental as fu\n'), ((5987, 6018), 'numpy.array', 'np.array', (['energies'], {'dtype': 'float'}), '(energies, dtype=float)\n', (5995, 6018), True, 'import numpy as np\n'), ((6048, 6113), 'asetk.atomistic.fundamental.EnergyLevels', 'fu.EnergyLevels', ([], {'energies': 'energies', 'occupations': 'None', 'fermi': 'fermi'}), '(energies=energies, occupations=None, fermi=fermi)\n', (6063, 6113), True, 'import asetk.atomistic.fundamental as fu\n'), ((8895, 8918), 'numpy.where', 'np.where', (['(iks == ik + 1)'], {}), '(iks == ik + 1)\n', (8903, 8918), True, 'import numpy as np\n'), ((5774, 5809), 'numpy.array', 'np.array', (['[kx, ky, kz]'], {'dtype': 'float'}), '([kx, ky, kz], dtype=float)\n', (5782, 5809), True, 'import numpy as np\n'), ((6661, 6692), 'numpy.array', 'np.array', (['energies'], {'dtype': 'float'}), '(energies, dtype=float)\n', (6669, 6692), True, 'import numpy as np\n'), ((6722, 6756), 'asetk.atomistic.fundamental.EnergyLevels', 'fu.EnergyLevels', ([], {'energies': 'energies'}), '(energies=energies)\n', (6737, 6756), True, 'import asetk.atomistic.fundamental as fu\n'), ((5515, 5539), 're.search', 're.search', (['fermiregex', 's'], {}), '(fermiregex, s)\n', (5524, 5539), False, 'import re\n'), ((6496, 6531), 'numpy.array', 'np.array', (['[kx, ky, kz]'], {'dtype': 'float'}), '([kx, ky, kz], dtype=float)\n', (6504, 6531), True, 'import numpy as np\n'), ((9054, 9083), 'numpy.intersect1d', 'np.intersect1d', (['is_spin', 'is_k'], {}), '(is_spin, is_k)\n', (9068, 9083), True, 'import numpy as np\n')]
import itertools import numpy as np from jspp_imageutils.image.types import GenImgArray, GenImgBatch from typing import Tuple, Iterable, Iterator # TODO: fix everywhere the x and y axis nomenclature """ chunk_image_on_position -> returns images chunk_image_generator -> returns images chunk_data_image_generator -> returns batches of data """ def chunk_image_on_position(arr_img: GenImgArray, x_pos: Iterable[int], y_pos: Iterable[int], dimensions: Tuple[int, int] = (50, 50), warn_leftovers=True) -> \ Iterator[Tuple[int, int, GenImgArray]]: # TODO decide if this should handle centering the points ... x_ends = [x + dimensions[0] for x in x_pos] y_ends = [y + dimensions[1] for y in y_pos] i = 0 # TODO find a better way to indent this ... for y_start, y_end, x_start, x_end in \ zip(y_pos, y_ends, x_pos, x_ends): temp_arr_img = arr_img[x_start:x_end, y_start:y_end, ] if temp_arr_img.shape[0:2] == dimensions: yield x_start, y_start, temp_arr_img i += 1 else: if warn_leftovers: print("skipping chunk due to weird size", str(temp_arr_img.shape)) print("Image generator yielded ", str(i), " images") def chunk_image_generator(img, chunk_size: Tuple[int, int] = (500, 500), displacement: Tuple[int, int] = (250, 250), warn_leftovers=True) -> \ Iterator[Tuple[int, int, GenImgArray]]: """ Gets an image read with tensorflow.keras.preprocessing.image.load_img and returns a generator that iterates over rectangular areas of it. chunks are of dims (chunk_size, colors) """ # TODO unify the input for this guy ... arr_img = np.asarray(img) dims = arr_img.shape x_starts = [ displacement[0] * x for x in range(dims[0] // displacement[0]) ] x_starts = [x for x in x_starts if x >= 0 & (x + chunk_size[0]) < dims[0]] y_starts = [ displacement[1] * y for y in range(dims[1] // displacement[1]) ] y_starts = [y for y in y_starts if y >= 0 & (y + chunk_size[1]) < dims[1]] coord_pairs = itertools.product(x_starts, y_starts) coord_pairs = np.array(list(coord_pairs)) my_gen = chunk_image_on_position( arr_img, coord_pairs[:, 0], coord_pairs[:, 1], dimensions=chunk_size, warn_leftovers=warn_leftovers) for chunk in my_gen: yield(chunk) def chunk_data_image_generator(img: GenImgArray, chunk_size: Tuple[int, int] = (500, 500), displacement: Tuple[int, int] = (250, 250), batch: int = 16) -> GenImgBatch: """ chunk_data_image_generator [summary] Gets an image read with tensorflow.keras.preprocessing.image.load_img and returns a generator that iterates over BATCHES of rectangular areas of it dimensions are (batch, chunk_size, colors) :param img: [description] :type img: GenImgArray :param chunk_size: [description], defaults to (500, 500) :type chunk_size: Tuple[int, int], optional :param displacement: [description], defaults to (250, 250) :type displacement: Tuple[int, int], optional :param batch: [description], defaults to 16 :type batch: int, optional :return: [description] :rtype: GenImgBatch """ # np.concatenate((a1, a2)) img_generator = chunk_image_generator( img=img, chunk_size=chunk_size, displacement=displacement) counter = 0 img_buffer = [] for _, _, temp_arr_img in img_generator: tmp_arr_dims = temp_arr_img.shape temp_arr_img = temp_arr_img.reshape(1, *tmp_arr_dims) img_buffer.append(temp_arr_img) counter += 1 if counter == batch: yield(np.concatenate(img_buffer)) counter = 0 img_buffer = [] yield(np.concatenate(img_buffer))
[ "itertools.product", "numpy.asarray", "numpy.concatenate" ]
[((1915, 1930), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (1925, 1930), True, 'import numpy as np\n'), ((2354, 2391), 'itertools.product', 'itertools.product', (['x_starts', 'y_starts'], {}), '(x_starts, y_starts)\n', (2371, 2391), False, 'import itertools\n'), ((4118, 4144), 'numpy.concatenate', 'np.concatenate', (['img_buffer'], {}), '(img_buffer)\n', (4132, 4144), True, 'import numpy as np\n'), ((4026, 4052), 'numpy.concatenate', 'np.concatenate', (['img_buffer'], {}), '(img_buffer)\n', (4040, 4052), True, 'import numpy as np\n')]
"""Compute ordinary Voronoi diagrams in Shapely geometries.""" import operator import numpy import scipy.spatial import shapely.geometry import shapely.geometry.base import shapely.prepared def pointset_bounds(coords): return ( min(coords, key=operator.itemgetter(0))[0], min(coords, key=operator.itemgetter(1))[1], max(coords, key=operator.itemgetter(0))[0], max(coords, key=operator.itemgetter(1))[1], ) def bounds_to_limiting_generators(minx, miny, maxx, maxy): addx = maxx - minx addy = maxy - miny return [ (minx - addx, miny - addy), (maxx + addx, miny - addy), (minx - addx, maxy + addy), (maxx + addx, maxy + addy), ] def cells(points, extent=None): if extent is None: bbox = pointset_bounds(points) extent_prep = None else: if not isinstance(extent, shapely.geometry.base.BaseGeometry): extent = shapely.geometry.box(*extent) bbox = extent.bounds extent_prep = shapely.prepared.prep(extent) boundgens = bounds_to_limiting_generators(*bbox) diagram = scipy.spatial.Voronoi(numpy.concatenate((points, boundgens))) for reg_i in diagram.point_region[:-len(boundgens)]: coords = diagram.vertices[diagram.regions[reg_i]] poly = shapely.geometry.Polygon(coords) if extent_prep is None or extent_prep.contains(poly): yield poly else: yield extent.intersection(poly) def cells_shapely(points, extent=None): return cells(numpy.array([pt.coords[0] for pt in points]), extent=extent)
[ "numpy.array", "operator.itemgetter", "numpy.concatenate" ]
[((1145, 1183), 'numpy.concatenate', 'numpy.concatenate', (['(points, boundgens)'], {}), '((points, boundgens))\n', (1162, 1183), False, 'import numpy\n'), ((1550, 1594), 'numpy.array', 'numpy.array', (['[pt.coords[0] for pt in points]'], {}), '([pt.coords[0] for pt in points])\n', (1561, 1594), False, 'import numpy\n'), ((260, 282), 'operator.itemgetter', 'operator.itemgetter', (['(0)'], {}), '(0)\n', (279, 282), False, 'import operator\n'), ((312, 334), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (331, 334), False, 'import operator\n'), ((364, 386), 'operator.itemgetter', 'operator.itemgetter', (['(0)'], {}), '(0)\n', (383, 386), False, 'import operator\n'), ((416, 438), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (435, 438), False, 'import operator\n')]
"""Plots composite saliency map.""" import argparse import numpy import matplotlib matplotlib.use('agg') from matplotlib import pyplot from gewittergefahr.gg_utils import general_utils as gg_general_utils from gewittergefahr.gg_utils import file_system_utils from gewittergefahr.plotting import imagemagick_utils from ml4tc.utils import normalization from ml4tc.machine_learning import saliency from ml4tc.machine_learning import neural_net from ml4tc.plotting import plotting_utils from ml4tc.plotting import satellite_plotting from ml4tc.plotting import predictor_plotting MAX_COLOUR_PERCENTILE = 99. SHIPS_BUILTIN_LAG_TIMES_HOURS = numpy.array([numpy.nan, 0, 1.5, 3]) COLOUR_BAR_FONT_SIZE = 12 SCALAR_SATELLITE_FONT_SIZE = 20 LAGGED_SHIPS_FONT_SIZE = 20 FORECAST_SHIPS_FONT_SIZE = 10 FIGURE_RESOLUTION_DPI = 300 PANEL_SIZE_PX = int(2.5e6) SALIENCY_FILE_ARG_NAME = 'input_saliency_file_name' NORMALIZATION_FILE_ARG_NAME = 'input_normalization_file_name' PLOT_INPUT_GRAD_ARG_NAME = 'plot_input_times_grad' SPATIAL_COLOUR_MAP_ARG_NAME = 'spatial_colour_map_name' NONSPATIAL_COLOUR_MAP_ARG_NAME = 'nonspatial_colour_map_name' SMOOTHING_RADIUS_ARG_NAME = 'smoothing_radius_px' OUTPUT_DIR_ARG_NAME = 'output_dir_name' SALIENCY_FILE_HELP_STRING = ( 'Path to saliency file. Will be read by `saliency.read_composite_file`.' ) NORMALIZATION_FILE_HELP_STRING = ( 'Path to file with normalization params (will be used to denormalize ' 'brightness-temperature maps before plotting). Will be read by ' '`normalization.read_file`.' ) PLOT_INPUT_GRAD_HELP_STRING = ( 'Boolean flag. If 1 (0), will plot input * gradient (saliency).' ) SPATIAL_COLOUR_MAP_HELP_STRING = ( 'Name of colour scheme for spatial saliency maps. Must be accepted by ' '`matplotlib.pyplot.get_cmap`.' ) NONSPATIAL_COLOUR_MAP_HELP_STRING = ( 'Name of colour scheme for non-spatial saliency maps. Must be accepted by ' '`matplotlib.pyplot.get_cmap`.' ) SMOOTHING_RADIUS_HELP_STRING = ( 'Smoothing radius (number of pixels) for saliency maps. If you do not want' ' to smooth, make this 0 or negative.' ) OUTPUT_DIR_HELP_STRING = 'Name of output directory. Images will be saved here.' INPUT_ARG_PARSER = argparse.ArgumentParser() INPUT_ARG_PARSER.add_argument( '--' + SALIENCY_FILE_ARG_NAME, type=str, required=True, help=SALIENCY_FILE_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + NORMALIZATION_FILE_ARG_NAME, type=str, required=True, help=NORMALIZATION_FILE_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + PLOT_INPUT_GRAD_ARG_NAME, type=int, required=True, help=PLOT_INPUT_GRAD_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + SPATIAL_COLOUR_MAP_ARG_NAME, type=str, required=False, default='BuGn', help=SPATIAL_COLOUR_MAP_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + NONSPATIAL_COLOUR_MAP_ARG_NAME, type=str, required=False, default='binary', help=NONSPATIAL_COLOUR_MAP_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + SMOOTHING_RADIUS_ARG_NAME, type=float, required=False, default=-1, help=SMOOTHING_RADIUS_HELP_STRING ) INPUT_ARG_PARSER.add_argument( '--' + OUTPUT_DIR_ARG_NAME, type=str, required=True, help=OUTPUT_DIR_HELP_STRING ) def _plot_brightness_temp_saliency( saliency_dict, model_metadata_dict, normalization_table_xarray, colour_map_object, plot_input_times_grad, output_dir_name): """Plots saliency for brightness temp for each lag time at one init time. :param saliency_dict: See doc for `_plot_scalar_satellite_saliency`. :param model_metadata_dict: Same. :param normalization_table_xarray: xarray table returned by `normalization.read_file`. :param colour_map_object: See doc for `_plot_scalar_satellite_saliency`. :param plot_input_times_grad: Same. :param output_dir_name: Same. """ predictor_matrices = [ None if p is None else numpy.expand_dims(p, axis=0) for p in saliency_dict[saliency.THREE_PREDICTORS_KEY] ] if plot_input_times_grad: this_key = saliency.THREE_INPUT_GRAD_KEY else: this_key = saliency.THREE_SALIENCY_KEY saliency_matrices = [ None if p is None else numpy.expand_dims(p, axis=0) for p in saliency_dict[this_key] ] num_lag_times = predictor_matrices[0].shape[3] grid_latitudes_deg_n = numpy.linspace( -10, 10, num=predictor_matrices[0].shape[1], dtype=float ) grid_latitude_matrix_deg_n = numpy.expand_dims(grid_latitudes_deg_n, axis=1) grid_latitude_matrix_deg_n = numpy.repeat( grid_latitude_matrix_deg_n, axis=1, repeats=num_lag_times ) grid_longitudes_deg_e = numpy.linspace( 300, 320, num=predictor_matrices[0].shape[2], dtype=float ) grid_longitude_matrix_deg_e = numpy.expand_dims( grid_longitudes_deg_e, axis=1 ) grid_longitude_matrix_deg_e = numpy.repeat( grid_longitude_matrix_deg_e, axis=1, repeats=num_lag_times ) figure_objects, axes_objects, pathless_output_file_names = ( predictor_plotting.plot_brightness_temp_one_example( predictor_matrices_one_example=predictor_matrices, model_metadata_dict=model_metadata_dict, cyclone_id_string='2005AL12', init_time_unix_sec=0, grid_latitude_matrix_deg_n=grid_latitude_matrix_deg_n, grid_longitude_matrix_deg_e=grid_longitude_matrix_deg_e, normalization_table_xarray=normalization_table_xarray, border_latitudes_deg_n=numpy.array([20.]), border_longitudes_deg_e=numpy.array([330.]) ) ) validation_option_dict = ( model_metadata_dict[neural_net.VALIDATION_OPTIONS_KEY] ) num_model_lag_times = len( validation_option_dict[neural_net.SATELLITE_LAG_TIMES_KEY] ) all_saliency_values = numpy.concatenate([ numpy.ravel(s) for s in saliency_matrices if s is not None ]) min_abs_contour_value = numpy.percentile( numpy.absolute(all_saliency_values), 100. - MAX_COLOUR_PERCENTILE ) max_abs_contour_value = numpy.percentile( numpy.absolute(all_saliency_values), MAX_COLOUR_PERCENTILE ) panel_file_names = [''] * num_model_lag_times for k in range(num_model_lag_times): min_abs_contour_value, max_abs_contour_value = ( satellite_plotting.plot_saliency( saliency_matrix=saliency_matrices[0][0, ..., k, 0], axes_object=axes_objects[k], latitude_array_deg_n=grid_latitude_matrix_deg_n[:, k], longitude_array_deg_e=grid_longitude_matrix_deg_e[:, k], min_abs_contour_value=min_abs_contour_value, max_abs_contour_value=max_abs_contour_value, half_num_contours=10, colour_map_object=colour_map_object ) ) panel_file_names[k] = '{0:s}/{1:s}'.format( output_dir_name, pathless_output_file_names[k] ) print('Saving figure to file: "{0:s}"...'.format( panel_file_names[k] )) figure_objects[k].savefig( panel_file_names[k], dpi=FIGURE_RESOLUTION_DPI, pad_inches=0, bbox_inches='tight' ) pyplot.close(figure_objects[k]) imagemagick_utils.resize_image( input_file_name=panel_file_names[k], output_file_name=panel_file_names[k], output_size_pixels=PANEL_SIZE_PX ) concat_figure_file_name = '{0:s}/brightness_temp_concat.jpg'.format( output_dir_name ) plotting_utils.concat_panels( panel_file_names=panel_file_names, concat_figure_file_name=concat_figure_file_name ) this_cmap_object, this_cnorm_object = ( satellite_plotting.get_colour_scheme() ) plotting_utils.add_colour_bar( figure_file_name=concat_figure_file_name, colour_map_object=this_cmap_object, colour_norm_object=this_cnorm_object, orientation_string='vertical', font_size=COLOUR_BAR_FONT_SIZE, cbar_label_string='Brightness temp (K)', tick_label_format_string='{0:d}' ) colour_norm_object = pyplot.Normalize( vmin=min_abs_contour_value, vmax=max_abs_contour_value ) label_string = 'Absolute {0:s}'.format( 'input times gradient' if plot_input_times_grad else 'saliency' ) plotting_utils.add_colour_bar( figure_file_name=concat_figure_file_name, colour_map_object=colour_map_object, colour_norm_object=colour_norm_object, orientation_string='vertical', font_size=COLOUR_BAR_FONT_SIZE, cbar_label_string=label_string, tick_label_format_string='{0:.2g}' ) def _run(saliency_file_name, normalization_file_name, plot_input_times_grad, spatial_colour_map_name, nonspatial_colour_map_name, smoothing_radius_px, output_dir_name): """Plots composite saliency map. This is effectively the main method. :param saliency_file_name: See documentation at top of file. :param normalization_file_name: Same. :param plot_input_times_grad: Same. :param spatial_colour_map_name: Same. :param nonspatial_colour_map_name: Same. :param smoothing_radius_px: Same. :param output_dir_name: Same. """ spatial_colour_map_object = pyplot.get_cmap(spatial_colour_map_name) nonspatial_colour_map_object = pyplot.get_cmap(nonspatial_colour_map_name) file_system_utils.mkdir_recursive_if_necessary( directory_name=output_dir_name ) # Read files. print('Reading data from: "{0:s}"...'.format(saliency_file_name)) saliency_dict = saliency.read_composite_file(saliency_file_name) if plot_input_times_grad: this_key = saliency.THREE_INPUT_GRAD_KEY else: this_key = saliency.THREE_SALIENCY_KEY if smoothing_radius_px > 0 and saliency_dict[this_key][0] is not None: print(( 'Smoothing maps with Gaussian filter (e-folding radius of {0:.1f} ' 'pixels)...' ).format(smoothing_radius_px)) num_lag_times = saliency_dict[this_key][0].shape[-2] for k in range(num_lag_times): saliency_dict[this_key][0][..., k, 0] = ( gg_general_utils.apply_gaussian_filter( input_matrix=saliency_dict[this_key][0][..., k, 0], e_folding_radius_grid_cells=smoothing_radius_px ) ) model_file_name = saliency_dict[saliency.MODEL_FILE_KEY] model_metafile_name = neural_net.find_metafile( model_file_name=model_file_name, raise_error_if_missing=True ) print('Reading metadata from: "{0:s}"...'.format(model_metafile_name)) model_metadata_dict = neural_net.read_metafile(model_metafile_name) print('Reading data from: "{0:s}"...'.format(normalization_file_name)) normalization_table_xarray = normalization.read_file( normalization_file_name ) # Plot saliency map. _plot_brightness_temp_saliency( saliency_dict=saliency_dict, model_metadata_dict=model_metadata_dict, normalization_table_xarray=normalization_table_xarray, colour_map_object=spatial_colour_map_object, plot_input_times_grad=plot_input_times_grad, output_dir_name=output_dir_name ) if __name__ == '__main__': INPUT_ARG_OBJECT = INPUT_ARG_PARSER.parse_args() _run( saliency_file_name=getattr(INPUT_ARG_OBJECT, SALIENCY_FILE_ARG_NAME), normalization_file_name=getattr( INPUT_ARG_OBJECT, NORMALIZATION_FILE_ARG_NAME ), plot_input_times_grad=bool(getattr( INPUT_ARG_OBJECT, PLOT_INPUT_GRAD_ARG_NAME )), spatial_colour_map_name=getattr( INPUT_ARG_OBJECT, SPATIAL_COLOUR_MAP_ARG_NAME ), nonspatial_colour_map_name=getattr( INPUT_ARG_OBJECT, NONSPATIAL_COLOUR_MAP_ARG_NAME ), smoothing_radius_px=getattr( INPUT_ARG_OBJECT, SMOOTHING_RADIUS_ARG_NAME ), output_dir_name=getattr(INPUT_ARG_OBJECT, OUTPUT_DIR_ARG_NAME) )
[ "ml4tc.plotting.plotting_utils.concat_panels", "numpy.array", "numpy.ravel", "gewittergefahr.gg_utils.general_utils.apply_gaussian_filter", "numpy.repeat", "argparse.ArgumentParser", "matplotlib.pyplot.Normalize", "matplotlib.pyplot.close", "numpy.linspace", "ml4tc.machine_learning.neural_net.find_metafile", "ml4tc.plotting.satellite_plotting.plot_saliency", "ml4tc.plotting.satellite_plotting.get_colour_scheme", "ml4tc.machine_learning.neural_net.read_metafile", "ml4tc.utils.normalization.read_file", "matplotlib.use", "ml4tc.machine_learning.saliency.read_composite_file", "matplotlib.pyplot.get_cmap", "ml4tc.plotting.plotting_utils.add_colour_bar", "numpy.absolute", "gewittergefahr.gg_utils.file_system_utils.mkdir_recursive_if_necessary", "numpy.expand_dims", "gewittergefahr.plotting.imagemagick_utils.resize_image" ]
[((84, 105), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (98, 105), False, 'import matplotlib\n'), ((637, 672), 'numpy.array', 'numpy.array', (['[numpy.nan, 0, 1.5, 3]'], {}), '([numpy.nan, 0, 1.5, 3])\n', (648, 672), False, 'import numpy\n'), ((2217, 2242), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2240, 2242), False, 'import argparse\n'), ((4362, 4434), 'numpy.linspace', 'numpy.linspace', (['(-10)', '(10)'], {'num': 'predictor_matrices[0].shape[1]', 'dtype': 'float'}), '(-10, 10, num=predictor_matrices[0].shape[1], dtype=float)\n', (4376, 4434), False, 'import numpy\n'), ((4482, 4529), 'numpy.expand_dims', 'numpy.expand_dims', (['grid_latitudes_deg_n'], {'axis': '(1)'}), '(grid_latitudes_deg_n, axis=1)\n', (4499, 4529), False, 'import numpy\n'), ((4563, 4634), 'numpy.repeat', 'numpy.repeat', (['grid_latitude_matrix_deg_n'], {'axis': '(1)', 'repeats': 'num_lag_times'}), '(grid_latitude_matrix_deg_n, axis=1, repeats=num_lag_times)\n', (4575, 4634), False, 'import numpy\n'), ((4678, 4751), 'numpy.linspace', 'numpy.linspace', (['(300)', '(320)'], {'num': 'predictor_matrices[0].shape[2]', 'dtype': 'float'}), '(300, 320, num=predictor_matrices[0].shape[2], dtype=float)\n', (4692, 4751), False, 'import numpy\n'), ((4800, 4848), 'numpy.expand_dims', 'numpy.expand_dims', (['grid_longitudes_deg_e'], {'axis': '(1)'}), '(grid_longitudes_deg_e, axis=1)\n', (4817, 4848), False, 'import numpy\n'), ((4897, 4969), 'numpy.repeat', 'numpy.repeat', (['grid_longitude_matrix_deg_e'], {'axis': '(1)', 'repeats': 'num_lag_times'}), '(grid_longitude_matrix_deg_e, axis=1, repeats=num_lag_times)\n', (4909, 4969), False, 'import numpy\n'), ((7598, 7714), 'ml4tc.plotting.plotting_utils.concat_panels', 'plotting_utils.concat_panels', ([], {'panel_file_names': 'panel_file_names', 'concat_figure_file_name': 'concat_figure_file_name'}), '(panel_file_names=panel_file_names,\n concat_figure_file_name=concat_figure_file_name)\n', (7626, 7714), False, 'from ml4tc.plotting import plotting_utils\n'), ((7786, 7824), 'ml4tc.plotting.satellite_plotting.get_colour_scheme', 'satellite_plotting.get_colour_scheme', ([], {}), '()\n', (7822, 7824), False, 'from ml4tc.plotting import satellite_plotting\n'), ((7835, 8136), 'ml4tc.plotting.plotting_utils.add_colour_bar', 'plotting_utils.add_colour_bar', ([], {'figure_file_name': 'concat_figure_file_name', 'colour_map_object': 'this_cmap_object', 'colour_norm_object': 'this_cnorm_object', 'orientation_string': '"""vertical"""', 'font_size': 'COLOUR_BAR_FONT_SIZE', 'cbar_label_string': '"""Brightness temp (K)"""', 'tick_label_format_string': '"""{0:d}"""'}), "(figure_file_name=concat_figure_file_name,\n colour_map_object=this_cmap_object, colour_norm_object=\n this_cnorm_object, orientation_string='vertical', font_size=\n COLOUR_BAR_FONT_SIZE, cbar_label_string='Brightness temp (K)',\n tick_label_format_string='{0:d}')\n", (7864, 8136), False, 'from ml4tc.plotting import plotting_utils\n'), ((8199, 8271), 'matplotlib.pyplot.Normalize', 'pyplot.Normalize', ([], {'vmin': 'min_abs_contour_value', 'vmax': 'max_abs_contour_value'}), '(vmin=min_abs_contour_value, vmax=max_abs_contour_value)\n', (8215, 8271), False, 'from matplotlib import pyplot\n'), ((8412, 8708), 'ml4tc.plotting.plotting_utils.add_colour_bar', 'plotting_utils.add_colour_bar', ([], {'figure_file_name': 'concat_figure_file_name', 'colour_map_object': 'colour_map_object', 'colour_norm_object': 'colour_norm_object', 'orientation_string': '"""vertical"""', 'font_size': 'COLOUR_BAR_FONT_SIZE', 'cbar_label_string': 'label_string', 'tick_label_format_string': '"""{0:.2g}"""'}), "(figure_file_name=concat_figure_file_name,\n colour_map_object=colour_map_object, colour_norm_object=\n colour_norm_object, orientation_string='vertical', font_size=\n COLOUR_BAR_FONT_SIZE, cbar_label_string=label_string,\n tick_label_format_string='{0:.2g}')\n", (8441, 8708), False, 'from ml4tc.plotting import plotting_utils\n'), ((9353, 9393), 'matplotlib.pyplot.get_cmap', 'pyplot.get_cmap', (['spatial_colour_map_name'], {}), '(spatial_colour_map_name)\n', (9368, 9393), False, 'from matplotlib import pyplot\n'), ((9429, 9472), 'matplotlib.pyplot.get_cmap', 'pyplot.get_cmap', (['nonspatial_colour_map_name'], {}), '(nonspatial_colour_map_name)\n', (9444, 9472), False, 'from matplotlib import pyplot\n'), ((9477, 9555), 'gewittergefahr.gg_utils.file_system_utils.mkdir_recursive_if_necessary', 'file_system_utils.mkdir_recursive_if_necessary', ([], {'directory_name': 'output_dir_name'}), '(directory_name=output_dir_name)\n', (9523, 9555), False, 'from gewittergefahr.gg_utils import file_system_utils\n'), ((9679, 9727), 'ml4tc.machine_learning.saliency.read_composite_file', 'saliency.read_composite_file', (['saliency_file_name'], {}), '(saliency_file_name)\n', (9707, 9727), False, 'from ml4tc.machine_learning import saliency\n'), ((10573, 10663), 'ml4tc.machine_learning.neural_net.find_metafile', 'neural_net.find_metafile', ([], {'model_file_name': 'model_file_name', 'raise_error_if_missing': '(True)'}), '(model_file_name=model_file_name,\n raise_error_if_missing=True)\n', (10597, 10663), False, 'from ml4tc.machine_learning import neural_net\n'), ((10775, 10820), 'ml4tc.machine_learning.neural_net.read_metafile', 'neural_net.read_metafile', (['model_metafile_name'], {}), '(model_metafile_name)\n', (10799, 10820), False, 'from ml4tc.machine_learning import neural_net\n'), ((10930, 10978), 'ml4tc.utils.normalization.read_file', 'normalization.read_file', (['normalization_file_name'], {}), '(normalization_file_name)\n', (10953, 10978), False, 'from ml4tc.utils import normalization\n'), ((6001, 6036), 'numpy.absolute', 'numpy.absolute', (['all_saliency_values'], {}), '(all_saliency_values)\n', (6015, 6036), False, 'import numpy\n'), ((6127, 6162), 'numpy.absolute', 'numpy.absolute', (['all_saliency_values'], {}), '(all_saliency_values)\n', (6141, 6162), False, 'import numpy\n'), ((6354, 6751), 'ml4tc.plotting.satellite_plotting.plot_saliency', 'satellite_plotting.plot_saliency', ([], {'saliency_matrix': 'saliency_matrices[0][0, ..., k, 0]', 'axes_object': 'axes_objects[k]', 'latitude_array_deg_n': 'grid_latitude_matrix_deg_n[:, k]', 'longitude_array_deg_e': 'grid_longitude_matrix_deg_e[:, k]', 'min_abs_contour_value': 'min_abs_contour_value', 'max_abs_contour_value': 'max_abs_contour_value', 'half_num_contours': '(10)', 'colour_map_object': 'colour_map_object'}), '(saliency_matrix=saliency_matrices[0][0,\n ..., k, 0], axes_object=axes_objects[k], latitude_array_deg_n=\n grid_latitude_matrix_deg_n[:, k], longitude_array_deg_e=\n grid_longitude_matrix_deg_e[:, k], min_abs_contour_value=\n min_abs_contour_value, max_abs_contour_value=max_abs_contour_value,\n half_num_contours=10, colour_map_object=colour_map_object)\n', (6386, 6751), False, 'from ml4tc.plotting import satellite_plotting\n'), ((7263, 7294), 'matplotlib.pyplot.close', 'pyplot.close', (['figure_objects[k]'], {}), '(figure_objects[k])\n', (7275, 7294), False, 'from matplotlib import pyplot\n'), ((7304, 7447), 'gewittergefahr.plotting.imagemagick_utils.resize_image', 'imagemagick_utils.resize_image', ([], {'input_file_name': 'panel_file_names[k]', 'output_file_name': 'panel_file_names[k]', 'output_size_pixels': 'PANEL_SIZE_PX'}), '(input_file_name=panel_file_names[k],\n output_file_name=panel_file_names[k], output_size_pixels=PANEL_SIZE_PX)\n', (7334, 7447), False, 'from gewittergefahr.plotting import imagemagick_utils\n'), ((3915, 3943), 'numpy.expand_dims', 'numpy.expand_dims', (['p'], {'axis': '(0)'}), '(p, axis=0)\n', (3932, 3943), False, 'import numpy\n'), ((4207, 4235), 'numpy.expand_dims', 'numpy.expand_dims', (['p'], {'axis': '(0)'}), '(p, axis=0)\n', (4224, 4235), False, 'import numpy\n'), ((5529, 5548), 'numpy.array', 'numpy.array', (['[20.0]'], {}), '([20.0])\n', (5540, 5548), False, 'import numpy\n'), ((5585, 5605), 'numpy.array', 'numpy.array', (['[330.0]'], {}), '([330.0])\n', (5596, 5605), False, 'import numpy\n'), ((5881, 5895), 'numpy.ravel', 'numpy.ravel', (['s'], {}), '(s)\n', (5892, 5895), False, 'import numpy\n'), ((10273, 10417), 'gewittergefahr.gg_utils.general_utils.apply_gaussian_filter', 'gg_general_utils.apply_gaussian_filter', ([], {'input_matrix': 'saliency_dict[this_key][0][..., k, 0]', 'e_folding_radius_grid_cells': 'smoothing_radius_px'}), '(input_matrix=saliency_dict[this_key]\n [0][..., k, 0], e_folding_radius_grid_cells=smoothing_radius_px)\n', (10311, 10417), True, 'from gewittergefahr.gg_utils import general_utils as gg_general_utils\n')]
import numpy as np def import_accuracy(y_test, predictions): errors = abs(predictions - y_test) mape = 100 * (errors / y_test) accuracy = 100 - np.mean(mape) return accuracy
[ "numpy.mean" ]
[((148, 161), 'numpy.mean', 'np.mean', (['mape'], {}), '(mape)\n', (155, 161), True, 'import numpy as np\n')]
import numpy as np import os import torch import torch.utils.data as data import pdb import pickle from pathlib import Path from scipy import signal import librosa import scipy from itertools import permutations from numpy.linalg import solve import numpy as np import soundfile as sf from convolutive_prediction import Apply_ConvolutivePrediction class AudioDataset(data.Dataset): def __init__(self,trainMode, functionMode, num_spks, num_ch, pickle_dir, ref_ch, model,device,cudaUse,check_audio,dereverb_Info,**STFT_args): super(AudioDataset, self).__init__() self.trainMode = trainMode self.functionMode = functionMode self.model = model self.fs = STFT_args['fs'] self.window = STFT_args['window'] self.nperseg = STFT_args['length'] self.noverlap = STFT_args['overlap'] self.num_spks = num_spks self.num_ch = num_ch self.device = device self.cudaUse = cudaUse self.pickle_dir = list(Path(pickle_dir).glob('**/**/**/**/*.pickle')) hann_win = scipy.signal.get_window('hann', self.nperseg) self.scale = np.sqrt(1.0 / hann_win.sum()**2) self.check_audio = check_audio self.ref_ch = ref_ch self.dereverb_flag = dereverb_Info[0] self.predictionType = dereverb_Info[1] self.tapDelay = dereverb_Info[2] self.nTap = dereverb_Info[3] self.reverb_variance_flowValue = dereverb_Info[4] # self.pickle_dir = self.pickle_dir[0:10] # # check chunked audio signal # MAX_INT16 = np.iinfo(np.int16).max # test= ref2 * MAX_INT16 # test = test.astype(np.int16) # wf.write('sample_ref2.wav',16000,test) def STFT(self,time_sig): ''' input : [T,Nch] output : [Nch,F,T] ''' assert time_sig.shape[0] > time_sig.shape[1], "Please check the STFT input dimension, input = [T,Nch] " num_ch = time_sig.shape[1] for num_ch in range(num_ch): # scipy.signal.stft : output : [F range, T range, FxT components] _,_,stft_ch = signal.stft(time_sig[:,num_ch],fs=self.fs,window=self.window,nperseg=self.nperseg,noverlap=self.noverlap) # output : [FxT] stft_ch = np.expand_dims(stft_ch,axis=0) if num_ch == 0: stft_chcat = stft_ch else: stft_chcat = np.append(stft_chcat,stft_ch,axis=0) return stft_chcat def __getitem__(self,index): with open(self.pickle_dir[index], 'rb') as f: data_infos = pickle.load(f) f.close() mix = data_infos['mix'] mix_stft = self.STFT(mix) mix_stft = mix_stft/self.scale # scale equality between scipy stft and matlab stft ##################### Todo ######################################################################################################### ###################### reference ch로 하도록 mix stft, ref_stft등 circular shift 해야됨. ############################################################################################################################## assert self.num_spks+1 == len(data_infos), "[ERROR] Check the number of speakers" ref_stft = [[] for spk_idx in range(self.num_spks)] for spk_idx in range(self.num_spks): ref_sig = data_infos['ref'+str(spk_idx+1)] if len(ref_sig.shape) == 1: ref_sig = np.expand_dims(ref_sig,axis=1) ref_stft[spk_idx] = torch.permute(torch.from_numpy(self.STFT(ref_sig)),[0,2,1]) ref_stft[spk_idx] = ref_stft[spk_idx]/self.scale # scale equality between scipy stft and matlab stft # numpy to torch & reshpae [C,F,T] ->[C,T,F] mix_stft = torch.permute( torch.from_numpy(mix_stft),[0,2,1]) if self.functionMode == 'Separate': """ Output : mix_stft : [Mic,T,F] ref_stft : [Mic,T,F] """ return torch.roll(mix_stft,-self.ref_ch,dims=0), torch.roll(ref_stft,-self.ref_ch,dims=0) elif self.functionMode == 'Beamforming': """ Output : mix_stft : [Mic,T,F] ref_stft : [Mic,T,F] """ BeamOutSaveDir = str(self.pickle_dir[index]).replace('CleanMix','Beamforming') MISO1OutSaveDir = str(self.pickle_dir[index]).replace('CleanMix','MISO1') return mix_stft, ref_stft, BeamOutSaveDir, MISO1OutSaveDir elif 'Enhance' in self.functionMode: """ Output : mix_stft : [Mic,T,F] ref_stft_1ch, list, [Mic,T,F] MISO1_stft, list, [Mic,T,F] Beamform_stft, list, [Mic,T,F] """ if len(mix_stft.shape)==3: mix_stft = torch.unsqueeze(mix_stft,dim=0) if self.cudaUse: mix_stft = mix_stft.cuda(self.device) ref_stft_1ch = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): if len(ref_stft[spk_idx].shape) == 3: ref_stft[spk_idx] = torch.unsqueeze(ref_stft[spk_idx], dim=0) ref_stft_1ch[spk_idx] = ref_stft[spk_idx][:,self.ref_ch,:,:] # select reference mic channel ref_stft_1ch[spk_idx] = torch.unsqueeze(ref_stft_1ch[spk_idx], dim=1) B, Mic, T, F = mix_stft.size() """ Apply Source Separation """ if self.functionMode == 'Enhance_Load_MISO1_Output' or self.functionMode == 'Enhance_Load_MISO1_MVDR_Output': MISO1OutSaveDir = str(self.pickle_dir[index]).replace('CleanMix','MISO1') MISO1_stft = [[] for _ in range(self.num_spks)] # Load MISO1 Output for spk_idx in range(self.num_spks): spk_name = '_s{}.wav'.format(spk_idx+1) MISO1_sig, fs = librosa.load(MISO1OutSaveDir.replace('.pickle',spk_name), mono= False, sr= 8000) if MISO1_sig.shape[1] != self.num_ch: MISO1_sig = MISO1_sig.T assert fs == self.fs, 'Check sampling rate' if len(MISO1_sig.shape) == 1: MISO1_sig = np.expand_dims(MISO1_sig, axis=1) MISO1_stft[spk_idx] = torch.permute(torch.from_numpy(self.STFT(MISO1_sig)),[0,2,1]) MISO1_stft[spk_idx] = MISO1_stft[spk_idx]/self.scale # MISO1_spk1 = torch.unsqueeze(MISO1_stft[0],dim=0) # MISO1_spk2 = torch.unsqueeze(MISO1_stft[1],dim=0) else: MISO1_stft = self.MISO1_Inference(mix_stft, ref_ch = self.ref_ch) if self.cudaUse: mix_stft = mix_stft.detach().cpu() for spk_idx in range(self.num_spks): MISO1_stft[spk_idx] = MISO1_stft[spk_idx].detach().cpu() """ Source Alignment between Clean reference signal and MISO1 signal calculate magnitude distance between ref mic(ch0) and target signal(reference mic : ch0) """ for spk_idx in range(self.num_spks): if spk_idx == 0 : ref_ = ref_stft_1ch[spk_idx] s_MISO1 = MISO1_stft[spk_idx][:,0,:,:] # [B,T,F] else: ref_ = torch.cat((ref_,ref_stft_1ch[spk_idx]), dim=1) s_MISO1 = torch.stack((s_MISO1, MISO1_stft[spk_idx][:,0,:,:]), dim=1) s_MISO1_ = torch.unsqueeze(s_MISO1,dim=2) #[B,Spks,1,T,F] magnitude_MISO1 = torch.abs(torch.sqrt(s_MISO1_.real**2 + s_MISO1_.imag**2)) #[B,Spks,1,T,F] s_ref = torch.unsqueeze(ref_, dim=1) magnitude_distance = torch.sum(torch.abs(magnitude_MISO1 - abs(s_ref)),[3,4]) perms = ref_.new_tensor(list(permutations(range(self.num_spks))), dtype=torch.long) #[[0,1],[1,0]] index_ = torch.unsqueeze(perms, dim=2) perms_one_hot = ref_.new_zeros((*perms.size(), self.num_spks), dtype=torch.float).scatter_(2,index_,1) batchwise_distance = torch.einsum('bij,pij->bp',[magnitude_distance, perms_one_hot]) min_distance_idx = torch.argmin(batchwise_distance, dim=1) for batch_idx in range(B): align_index = torch.argmax(perms_one_hot[min_distance_idx[batch_idx]], dim=1) for spk_idx in range(self.num_spks): target_index = align_index[spk_idx] ref_stft_1ch[spk_idx] = torch.unsqueeze(ref_[batch_idx,target_index,...],dim=0) """ Apply Dereverberation Method 1. WPE : weighted prediction error 2. ICP : inverse convolutive prediction 3. FCP : forward convolutive prediction 4. cFCP : combine forward convolutive prediction """ if self.dereverb_flag : dereverb_stft = [[] for _ in range(self.num_spks)] observe = torch.permute(mix_stft,[0,3,1,2]).detach().cpu().numpy() if self.predictionType == 'cFCP': source = [torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() for spk_idx in range(self.num_spks)] dereverb_stft = Apply_ConvolutivePrediction(observe,source,self.num_spks,self.predictionType,self.tapDelay,self.nTap,self.reverb_variance_flowValue) elif self.predictionType == 'test': source = [torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() for spk_idx in range(self.num_spks)] dereverb_stft = Apply_ConvolutivePrediction(observe,source,self.num_spks,self.predictionType,self.tapDelay,self.nTap,self.reverb_variance_flowValue) else: for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(mix_stft,[0,3,1,2]).detach().cpu().numpy() dereverb_stft[spk_idx] = Apply_ConvolutivePrediction(observe,source,self.num_spks,self.predictionType,self.tapDelay,self.nTap,self.reverb_variance_flowValue) ################################# ########### Testcode ########### ################################# # WPE DNN_WPE_dereverb_stft = [[] for _ in range(self.num_spks)] FCP_dereverb_stft = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(mix_stft,[0,3,1,2]).detach().cpu().numpy() DNN_WPE_dereverb_stft[spk_idx] = Apply_ConvolutivePrediction(observe,source,self.num_spks,'DNN_WPE',self.tapDelay,self.nTap,self.reverb_variance_flowValue) # FCP source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(mix_stft,[0,3,1,2]).detach().cpu().numpy() FCP_dereverb_stft[spk_idx] = Apply_ConvolutivePrediction(observe,source,self.num_spks,'FCP',self.tapDelay,self.nTap,self.reverb_variance_flowValue) ################################# ########### Testcode ########### ################################# """ Apply MVDR Beamforming """ if self.functionMode == 'Enhance_Load_MVDR_Output' or self.functionMode == 'Enhance_Load_MISO1_MVDR_Output': BeamformSaveDir = str(self.pickle_dir[index]).replace('CleanMix','Beamforming') Beamform_stft = [[] for _ in range(self.num_spks)] # Load MISO1 Output for spk_idx in range(self.num_spks): spk_name = '_s{}.wav'.format(spk_idx+1) Beamform_sig, fs = librosa.load(BeamformSaveDir.replace('.pickle',spk_name), mono= False, sr= 8000) if len(Beamform_sig.shape) == 1: Beamform_sig = np.expand_dims(Beamform_sig, axis=1) assert fs == self.fs, 'Check sampling rate' Beamform_stft[spk_idx] = torch.permute(torch.from_numpy(self.STFT(Beamform_sig)),[0,2,1]) Beamform_stft[spk_idx] = Beamform_stft[spk_idx]/self.scale else: Beamform_stft = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() if self.dereverb_flag : observe = torch.permute(dereverb_stft[spk_idx],[0,3,1,2]) else: observe = torch.permute(mix_stft,[0,3,1,2]).detach().cpu() Beamform_stft[spk_idx] = self.Apply_Beamforming(source, observe) ################################# ########### Testcode ########### ################################# DNN_WPE_Beamform_stft = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(DNN_WPE_dereverb_stft[spk_idx],[0,3,1,2]) DNN_WPE_Beamform_stft[spk_idx] = self.Apply_Beamforming(source, observe) FCP_Beamform_stft = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(FCP_dereverb_stft[spk_idx],[0,3,1,2]) FCP_Beamform_stft[spk_idx] = self.Apply_Beamforming(source, observe) Origin_Beamform_stft = [[] for _ in range(self.num_spks)] for spk_idx in range(self.num_spks): source = torch.permute(MISO1_stft[spk_idx],[0,3,1,2]).numpy() observe = torch.permute(mix_stft,[0,3,1,2]) Origin_Beamform_stft[spk_idx] = self.Apply_Beamforming(source, observe) ################################# ########### Testcode ########### ################################# if len(mix_stft.shape)== 4: mix_stft = torch.squeeze(mix_stft) for spk_idx in range(self.num_spks): if len(MISO1_stft[spk_idx].shape)== 4: MISO1_stft[spk_idx] = torch.squeeze(MISO1_stft[spk_idx]) if len(dereverb_stft[spk_idx].shape)==4: dereverb_stft[spk_idx] = torch.squeeze(dereverb_stft[spk_idx]) if self.check_audio: ''' Check the result of MISO1 ''' self.save_audio(np.transpose(mix_stft, [0,2,1]), 'mix') for spk_idx in range(self.num_spks): self.save_audio(np.transpose(ref_stft_1ch[spk_idx], [0,2,1]), 'ref_s{}'.format(spk_idx)) self.save_audio(np.transpose(MISO1_stft[spk_idx], [0,2,1]), 'MISO1_s{}'.format(spk_idx)) if self.dereverb_flag: self.save_audio(np.transpose(dereverb_stft[spk_idx], [0,2,1]), self.predictionType+'_s{}'.format(spk_idx)) self.save_audio(np.transpose(Beamform_stft[spk_idx], [0,2,1]), self.predictionType+'_Beamform_s{}'.format(spk_idx)) else: self.save_audio(np.transpose(Beamform_stft[spk_idx], [0,2,1]), 'Beamform_s{}'.format(spk_idx)) ################################# ########### Testcode ########### ################################# #WPE self.save_audio(np.transpose(np.squeeze(DNN_WPE_dereverb_stft[spk_idx],axis=0), [0,2,1]), 'DNN_WPE_s{}'.format(spk_idx)) self.save_audio(np.transpose(DNN_WPE_Beamform_stft[spk_idx], [0,2,1]), 'DNN_WPE_Beamform_s{}'.format(spk_idx)) #FCP self.save_audio(np.transpose(np.squeeze(FCP_dereverb_stft[spk_idx],axis=0), [0,2,1]), 'FCP_s{}'.format(spk_idx)) self.save_audio(np.transpose(FCP_Beamform_stft[spk_idx], [0,2,1]), 'FCP_Beamform_s{}'.format(spk_idx)) #Origin Beamforming self.save_audio(np.transpose(Origin_Beamform_stft[spk_idx], [0,2,1]), 'Origin_Beamform_s{}'.format(spk_idx)) ################################# ########### Testcode ########### ################################# pdb.set_trace() return mix_stft, ref_stft_1ch, MISO1_stft, Beamform_stft else: assert -1, '[Error] Choose correct train mode' def save_audio(self,signal, wavname): ''' Input: signal : [Ch,F,T] wavename : str, wav name to save ''' hann_win = scipy.signal.get_window(self.window, self.nperseg) scale = np.sqrt(1.0 / hann_win.sum()**2) MAX_INT16 = np.iinfo(np.int16).max signal = signal * scale t_sig = self.ISTFT(signal) t_sig= t_sig * MAX_INT16 t_sig = t_sig.astype(np.int16) sf.write('{}.wav'.format(wavname),t_sig.T, self.fs,'PCM_24') def ISTFT(self,FT_sig): ''' input : [F,T] output : [T,C] ''' # if FT_sig.shape[1] != self.config['ISTFT']['length']+1: # FT_sig = np.transpose(FT_sig,(0,1)) # [C,T,F] -> [C,F,T] _, t_sig = signal.istft(FT_sig,fs=self.fs, window=self.window, nperseg=self.nperseg, noverlap=self.noverlap) #[C,F,T] -> [T,C] return t_sig def MISO1_Inference(self,mix_stft,ref_ch=0): """ Input: mix_stft : observe STFT, size - [B, Mic, T, F] Output: MISO1_stft : list of separated source, - [B, reference Mic, T, F] 1. circular shift the microphone array at run time for the prediction of each microphone signal If the microphones are arranged uniformly on a circle, Select the reference microphone by circular shifting the microphone. e.g reference mic q -> [Yq, Yq+1, ..., Yp, Y1, ..., Yq-1] 2. Using Permutation Invariance Alignmnet method to match between clean target signal and estimated signal """ B, M, T, F = mix_stft.size() MISO1_stft = [torch.empty(B,M,T,F, dtype=torch.complex64) for _ in range(self.num_spks)] Mic_array = [x for x in range(M)] Mic_array = np.roll(Mic_array, -ref_ch) # [ref_ch, ref_ch+1, ..., 0, 1, ..., ref_ch-1] # print('Mic_array : ', Mic_array) with torch.no_grad(): mix_stft_refCh = torch.roll(mix_stft,-ref_ch, dims=1) MISO1_refCh = self.model(mix_stft_refCh) for spk_idx in range(self.num_spks): MISO1_stft[spk_idx][:,ref_ch,...] = MISO1_refCh[:,spk_idx,...] # MISO1_spk1[:,ref_ch,...] = MISO1_refCh[:,0,...] # MISO1_spk2[:,ref_ch,...] = MISO1_refCh[:,1,...] s_MISO1_refCh = torch.unsqueeze(MISO1_refCh, dim=2) s_Magnitude_refCh = torch.abs(torch.sqrt(s_MISO1_refCh.real**2 + s_MISO1_refCh.imag**2)) # [B,Spks,1,T,F] with torch.no_grad(): for shiftIdx in Mic_array[1:]: # print('shift Micnumber', shiftIdx) mix_stft_shift = torch.roll(mix_stft,-shiftIdx, dims=1) MISO1_chShift = self.model(mix_stft_shift) s_MISO1_chShift = torch.unsqueeze(MISO1_chShift, dim=1) #[B,1,Spks,T,F] s_magnitude_chShift = torch.sum(torch.abs(s_Magnitude_refCh - abs(s_MISO1_chShift)),[3,4]) #[B,Spks,Spks,T,F] perms = MISO1_chShift.new_tensor(list(permutations(range(self.num_spks))), dtype=torch.long) index_ = torch.unsqueeze(perms, dim=2) perms_one_hot = MISO1_chShift.new_zeros((*perms.size(), self.num_spks), dtype=torch.float).scatter_(2,index_,1) batchwise_distance = torch.einsum('bij,pij->bp', [s_magnitude_chShift, perms_one_hot]) min_distance_idx = torch.argmin(batchwise_distance,dim=1) for batch_idx in range(B): align_index = torch.argmax(perms_one_hot[min_distance_idx[batch_idx]],dim=1) for spk_idx in range(self.num_spks): target_index = align_index[spk_idx] MISO1_stft[spk_idx][:,shiftIdx,...] = MISO1_chShift[batch_idx,target_index,...] return MISO1_stft def Apply_Beamforming(self, source_stft, mix_stft, epsi=1e-6): """ Input : mix_stft : observe STFT, size - [B, F, Ch, T], np.ndarray source_stft : estimated source STFT, size - [B, F, Ch, T], np.ndarray Output : Beamform_stft : MVDR Beamforming output, size - [B, 1, T, F], np.ndarray 1. estimate target steering using EigenValue decomposition 2. get source, noise Spatial Covariance Matrix, S = 1/T * xx_h 3. MVDR Beamformer """ B, F, M, T = source_stft.shape # Apply small Diagonal matrix to prevent matrix inversion error eye = np.eye(M) eye = eye.reshape(1,1,M,M) delta = epsi * np.tile(eye,[B,F,1,1]) ''' Source ''' source_SCM = self.get_spatial_covariance_matrix(source_stft,normalize=True) # target covariance matrix, size : [B,F,C,C] source_SCM = 0.5 * (source_SCM + np.conj(source_SCM.swapaxes(-1,-2))) # verify hermitian symmetric ''' Noise Spatial Covariance ''' noise_signal = mix_stft - source_stft # s1_noise_signal = mix_stft #MPDR noise_SCM = self.get_spatial_covariance_matrix(noise_signal,normalize = True) # noise covariance matrix, size : [B,F,C,C] # s1_SCMn = self.condition_covariance(s1_SCMn, 1e-6) # s1_SCMn /= np.trace(s1_SCMn, axis1=-2, axis2= -1)[...,None, None] noise_SCM = 0.5 * (noise_SCM + np.conj(noise_SCM.swapaxes(-1,-2))) # verify hermitian symmetric ''' Get Steering vector : Eigen-decomposition ''' shape = source_SCM.shape source_steering = np.empty(shape[:-1], dtype=np.complex) # s1_SCMs += delta source_SCM = np.reshape(source_SCM, (-1,) + shape[-2:]) eigenvals, eigenvecs = np.linalg.eigh(source_SCM) # Find max eigenvals vals = np.argmax(eigenvals, axis=-1) # Select eigenvec for max eigenval source_steering = np.array([eigenvecs[i,:,vals[i]] for i in range(eigenvals.shape[0])]) # s1_steering = np.array([eigenvecs[i,:,vals[i]] * np.sqrt(Mic/np.linalg.norm(eigenvecs[i,:,vals[i]])) for i in range(eigenvals.shape[0])]) # [B*F,Ch,Ch] source_steering = np.reshape(source_steering, shape[:-1]) # [B,F,Ch] source_SCM = np.reshape(source_SCM, shape) ''' steering normalize with respect to the reference microphone ''' # ver 1 source_steering = source_steering / np.expand_dims(source_steering[:,:,0], axis=2) for b_idx in range(0,B): for f_idx in range(0,F): # s1_steering[b_idx,f_idx,:] = s1_steering[b_idx,f_idx,:] / s1_steering[b_idx,f_idx,0] source_steering[b_idx,f_idx,:] = source_steering[b_idx,f_idx,:] * np.sqrt(M/(np.linalg.norm(source_steering[b_idx,f_idx,:]))) # ver 2 # s1_steering = self.normalize(s1_steering) source_steering = self.PhaseCorrection(source_steering) beamformer = self.get_mvdr_beamformer(source_steering, noise_SCM, delta) # s1_beamformer = self.blind_analytic_normalization(s1_beamformer,s1_SCMn) source_bf = self.apply_beamformer(beamformer,mix_stft) source_bf = torch.permute(torch.from_numpy(source_bf), [0,2,1]) return source_bf def get_spatial_covariance_matrix(self,observation,normalize): ''' Input : observation : complex size : [B,F,C,T] Return : R : double size : [B,F,C,C] ''' B,F,C,T = observation.shape R = np.einsum('...dt,...et-> ...de', observation, observation.conj()) if normalize: normalization = np.sum(np.ones((B,F,1,T)),axis=-1, keepdims=True) R /= normalization return R def PhaseCorrection(self,W): #Matlab과 동일 """ Phase correction to reduce distortions due to phase inconsistencies. Input: W : steering vector size : [B,F,Ch] """ w = W.copy() B, F, Ch = w.shape for b_idx in range(0,B): for f in range(1, F): w[b_idx,f, :] *= np.exp(-1j*np.angle( np.sum(w[b_idx,f, :] * w[b_idx,f-1, :].conj(), axis=-1, keepdims=True))) return w def condition_covariance(self,x,gamma): """see https://stt.msu.edu/users/mauryaas/Ashwini_JPEN.pdf (2.3)""" B,F,_,_ = x.shape for b_idx in range(0,B): scale = gamma * np.trace(x[b_idx,...]) / x[b_idx,...].shape[-1] scaled_eye = np.eye(x.shape[-1]) * scale x[b_idx,...] = (x[b_idx,...]+scaled_eye) / (1+gamma) return x def normalize(self,vector): B,F,Ch = vector.shape for b_idx in range(0,B): for ii in range(0,F): weight = np.matmul(np.conjugate(vector[b_idx,ii,:]).reshape(1,-1), vector[b_idx,ii,:]) vector[b_idx,ii,:] = (vector[b_idx,ii,:] / weight) return vector def blind_analytic_normalization(self,vector, noise_psd_matrix, eps=0): """Reduces distortions in beamformed ouptput. :param vector: Beamforming vector with shape (..., sensors) :param noise_psd_matrix: with shape (..., sensors, sensors) :return: Scaled Deamforming vector with shape (..., sensors) """ nominator = np.einsum( '...a,...ab,...bc,...c->...', vector.conj(), noise_psd_matrix, noise_psd_matrix, vector ) nominator = np.abs(np.sqrt(nominator)) denominator = np.einsum( '...a,...ab,...b->...', vector.conj(), noise_psd_matrix, vector ) denominator = np.abs(denominator) normalization = nominator / (denominator + eps) return vector * normalization[..., np.newaxis] def get_mvdr_beamformer(self, steering_vector, R_noise, delta): """ Returns the MVDR beamformers vector Input : steering_vector : Acoustic transfer function vector shape : [B, F, Ch] R_noise : Noise spatial covariance matrix shape : [B, F, Ch, Ch] """ R_noise += delta numer = solve(R_noise, steering_vector) denom = np.einsum('...d,...d->...', steering_vector.conj(), numer) beamformer = numer / np.expand_dims(denom, axis=-1) return beamformer def apply_beamformer(self, beamformer, mixture): return np.einsum('...a,...at->...t',beamformer.conj(), mixture) def __len__(self): return len(self.pickle_dir)
[ "numpy.trace", "numpy.sqrt", "torch.sqrt", "numpy.iinfo", "torch.from_numpy", "convolutive_prediction.Apply_ConvolutivePrediction", "torch.squeeze", "numpy.linalg.norm", "scipy.signal.get_window", "numpy.reshape", "pathlib.Path", "torch.unsqueeze", "numpy.conjugate", "numpy.empty", "torch.permute", "numpy.linalg.eigh", "torch.roll", "torch.argmax", "numpy.abs", "numpy.eye", "numpy.tile", "numpy.ones", "pickle.load", "numpy.argmax", "numpy.squeeze", "torch.einsum", "torch.argmin", "numpy.transpose", "torch.empty", "torch.cat", "numpy.linalg.solve", "numpy.roll", "scipy.signal.istft", "scipy.signal.stft", "torch.stack", "numpy.append", "numpy.expand_dims", "pdb.set_trace", "torch.no_grad" ]
[((1067, 1112), 'scipy.signal.get_window', 'scipy.signal.get_window', (['"""hann"""', 'self.nperseg'], {}), "('hann', self.nperseg)\n", (1090, 1112), False, 'import scipy\n'), ((17637, 17687), 'scipy.signal.get_window', 'scipy.signal.get_window', (['self.window', 'self.nperseg'], {}), '(self.window, self.nperseg)\n', (17660, 17687), False, 'import scipy\n'), ((18248, 18350), 'scipy.signal.istft', 'signal.istft', (['FT_sig'], {'fs': 'self.fs', 'window': 'self.window', 'nperseg': 'self.nperseg', 'noverlap': 'self.noverlap'}), '(FT_sig, fs=self.fs, window=self.window, nperseg=self.nperseg,\n noverlap=self.noverlap)\n', (18260, 18350), False, 'from scipy import signal\n'), ((19264, 19291), 'numpy.roll', 'np.roll', (['Mic_array', '(-ref_ch)'], {}), '(Mic_array, -ref_ch)\n', (19271, 19291), True, 'import numpy as np\n'), ((19808, 19843), 'torch.unsqueeze', 'torch.unsqueeze', (['MISO1_refCh'], {'dim': '(2)'}), '(MISO1_refCh, dim=2)\n', (19823, 19843), False, 'import torch\n'), ((22043, 22052), 'numpy.eye', 'np.eye', (['M'], {}), '(M)\n', (22049, 22052), True, 'import numpy as np\n'), ((23026, 23064), 'numpy.empty', 'np.empty', (['shape[:-1]'], {'dtype': 'np.complex'}), '(shape[:-1], dtype=np.complex)\n', (23034, 23064), True, 'import numpy as np\n'), ((23114, 23156), 'numpy.reshape', 'np.reshape', (['source_SCM', '((-1,) + shape[-2:])'], {}), '(source_SCM, (-1,) + shape[-2:])\n', (23124, 23156), True, 'import numpy as np\n'), ((23189, 23215), 'numpy.linalg.eigh', 'np.linalg.eigh', (['source_SCM'], {}), '(source_SCM)\n', (23203, 23215), True, 'import numpy as np\n'), ((23260, 23289), 'numpy.argmax', 'np.argmax', (['eigenvals'], {'axis': '(-1)'}), '(eigenvals, axis=-1)\n', (23269, 23289), True, 'import numpy as np\n'), ((23617, 23656), 'numpy.reshape', 'np.reshape', (['source_steering', 'shape[:-1]'], {}), '(source_steering, shape[:-1])\n', (23627, 23656), True, 'import numpy as np\n'), ((23689, 23718), 'numpy.reshape', 'np.reshape', (['source_SCM', 'shape'], {}), '(source_SCM, shape)\n', (23699, 23718), True, 'import numpy as np\n'), ((27234, 27253), 'numpy.abs', 'np.abs', (['denominator'], {}), '(denominator)\n', (27240, 27253), True, 'import numpy as np\n'), ((27794, 27825), 'numpy.linalg.solve', 'solve', (['R_noise', 'steering_vector'], {}), '(R_noise, steering_vector)\n', (27799, 27825), False, 'from numpy.linalg import solve\n'), ((2118, 2233), 'scipy.signal.stft', 'signal.stft', (['time_sig[:, num_ch]'], {'fs': 'self.fs', 'window': 'self.window', 'nperseg': 'self.nperseg', 'noverlap': 'self.noverlap'}), '(time_sig[:, num_ch], fs=self.fs, window=self.window, nperseg=\n self.nperseg, noverlap=self.noverlap)\n', (2129, 2233), False, 'from scipy import signal\n'), ((2275, 2306), 'numpy.expand_dims', 'np.expand_dims', (['stft_ch'], {'axis': '(0)'}), '(stft_ch, axis=0)\n', (2289, 2306), True, 'import numpy as np\n'), ((2617, 2631), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2628, 2631), False, 'import pickle\n'), ((3824, 3850), 'torch.from_numpy', 'torch.from_numpy', (['mix_stft'], {}), '(mix_stft)\n', (3840, 3850), False, 'import torch\n'), ((17757, 17775), 'numpy.iinfo', 'np.iinfo', (['np.int16'], {}), '(np.int16)\n', (17765, 17775), True, 'import numpy as np\n'), ((19118, 19164), 'torch.empty', 'torch.empty', (['B', 'M', 'T', 'F'], {'dtype': 'torch.complex64'}), '(B, M, T, F, dtype=torch.complex64)\n', (19129, 19164), False, 'import torch\n'), ((19397, 19412), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (19410, 19412), False, 'import torch\n'), ((19443, 19480), 'torch.roll', 'torch.roll', (['mix_stft', '(-ref_ch)'], {'dims': '(1)'}), '(mix_stft, -ref_ch, dims=1)\n', (19453, 19480), False, 'import torch\n'), ((19882, 19943), 'torch.sqrt', 'torch.sqrt', (['(s_MISO1_refCh.real ** 2 + s_MISO1_refCh.imag ** 2)'], {}), '(s_MISO1_refCh.real ** 2 + s_MISO1_refCh.imag ** 2)\n', (19892, 19943), False, 'import torch\n'), ((19980, 19995), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (19993, 19995), False, 'import torch\n'), ((22111, 22137), 'numpy.tile', 'np.tile', (['eye', '[B, F, 1, 1]'], {}), '(eye, [B, F, 1, 1])\n', (22118, 22137), True, 'import numpy as np\n'), ((23865, 23913), 'numpy.expand_dims', 'np.expand_dims', (['source_steering[:, :, 0]'], {'axis': '(2)'}), '(source_steering[:, :, 0], axis=2)\n', (23879, 23913), True, 'import numpy as np\n'), ((24630, 24657), 'torch.from_numpy', 'torch.from_numpy', (['source_bf'], {}), '(source_bf)\n', (24646, 24657), False, 'import torch\n'), ((27072, 27090), 'numpy.sqrt', 'np.sqrt', (['nominator'], {}), '(nominator)\n', (27079, 27090), True, 'import numpy as np\n'), ((27930, 27960), 'numpy.expand_dims', 'np.expand_dims', (['denom'], {'axis': '(-1)'}), '(denom, axis=-1)\n', (27944, 27960), True, 'import numpy as np\n'), ((2418, 2456), 'numpy.append', 'np.append', (['stft_chcat', 'stft_ch'], {'axis': '(0)'}), '(stft_chcat, stft_ch, axis=0)\n', (2427, 2456), True, 'import numpy as np\n'), ((3492, 3523), 'numpy.expand_dims', 'np.expand_dims', (['ref_sig'], {'axis': '(1)'}), '(ref_sig, axis=1)\n', (3506, 3523), True, 'import numpy as np\n'), ((4092, 4134), 'torch.roll', 'torch.roll', (['mix_stft', '(-self.ref_ch)'], {'dims': '(0)'}), '(mix_stft, -self.ref_ch, dims=0)\n', (4102, 4134), False, 'import torch\n'), ((4134, 4176), 'torch.roll', 'torch.roll', (['ref_stft', '(-self.ref_ch)'], {'dims': '(0)'}), '(ref_stft, -self.ref_ch, dims=0)\n', (4144, 4176), False, 'import torch\n'), ((20143, 20182), 'torch.roll', 'torch.roll', (['mix_stft', '(-shiftIdx)'], {'dims': '(1)'}), '(mix_stft, -shiftIdx, dims=1)\n', (20153, 20182), False, 'import torch\n'), ((20276, 20313), 'torch.unsqueeze', 'torch.unsqueeze', (['MISO1_chShift'], {'dim': '(1)'}), '(MISO1_chShift, dim=1)\n', (20291, 20313), False, 'import torch\n'), ((20590, 20619), 'torch.unsqueeze', 'torch.unsqueeze', (['perms'], {'dim': '(2)'}), '(perms, dim=2)\n', (20605, 20619), False, 'import torch\n'), ((20785, 20850), 'torch.einsum', 'torch.einsum', (['"""bij,pij->bp"""', '[s_magnitude_chShift, perms_one_hot]'], {}), "('bij,pij->bp', [s_magnitude_chShift, perms_one_hot])\n", (20797, 20850), False, 'import torch\n'), ((20886, 20925), 'torch.argmin', 'torch.argmin', (['batchwise_distance'], {'dim': '(1)'}), '(batchwise_distance, dim=1)\n', (20898, 20925), False, 'import torch\n'), ((25157, 25178), 'numpy.ones', 'np.ones', (['(B, F, 1, T)'], {}), '((B, F, 1, T))\n', (25164, 25178), True, 'import numpy as np\n'), ((26050, 26069), 'numpy.eye', 'np.eye', (['x.shape[-1]'], {}), '(x.shape[-1])\n', (26056, 26069), True, 'import numpy as np\n'), ((1001, 1017), 'pathlib.Path', 'Path', (['pickle_dir'], {}), '(pickle_dir)\n', (1005, 1017), False, 'from pathlib import Path\n'), ((7817, 7848), 'torch.unsqueeze', 'torch.unsqueeze', (['s_MISO1'], {'dim': '(2)'}), '(s_MISO1, dim=2)\n', (7832, 7848), False, 'import torch\n'), ((8002, 8030), 'torch.unsqueeze', 'torch.unsqueeze', (['ref_'], {'dim': '(1)'}), '(ref_, dim=1)\n', (8017, 8030), False, 'import torch\n'), ((8253, 8282), 'torch.unsqueeze', 'torch.unsqueeze', (['perms'], {'dim': '(2)'}), '(perms, dim=2)\n', (8268, 8282), False, 'import torch\n'), ((8431, 8495), 'torch.einsum', 'torch.einsum', (['"""bij,pij->bp"""', '[magnitude_distance, perms_one_hot]'], {}), "('bij,pij->bp', [magnitude_distance, perms_one_hot])\n", (8443, 8495), False, 'import torch\n'), ((8526, 8565), 'torch.argmin', 'torch.argmin', (['batchwise_distance'], {'dim': '(1)'}), '(batchwise_distance, dim=1)\n', (8538, 8565), False, 'import torch\n'), ((21033, 21096), 'torch.argmax', 'torch.argmax', (['perms_one_hot[min_distance_idx[batch_idx]]'], {'dim': '(1)'}), '(perms_one_hot[min_distance_idx[batch_idx]], dim=1)\n', (21045, 21096), False, 'import torch\n'), ((25977, 26000), 'numpy.trace', 'np.trace', (['x[b_idx, ...]'], {}), '(x[b_idx, ...])\n', (25985, 26000), True, 'import numpy as np\n'), ((4978, 5010), 'torch.unsqueeze', 'torch.unsqueeze', (['mix_stft'], {'dim': '(0)'}), '(mix_stft, dim=0)\n', (4993, 5010), False, 'import torch\n'), ((5499, 5544), 'torch.unsqueeze', 'torch.unsqueeze', (['ref_stft_1ch[spk_idx]'], {'dim': '(1)'}), '(ref_stft_1ch[spk_idx], dim=1)\n', (5514, 5544), False, 'import torch\n'), ((7904, 7955), 'torch.sqrt', 'torch.sqrt', (['(s_MISO1_.real ** 2 + s_MISO1_.imag ** 2)'], {}), '(s_MISO1_.real ** 2 + s_MISO1_.imag ** 2)\n', (7914, 7955), False, 'import torch\n'), ((8636, 8699), 'torch.argmax', 'torch.argmax', (['perms_one_hot[min_distance_idx[batch_idx]]'], {'dim': '(1)'}), '(perms_one_hot[min_distance_idx[batch_idx]], dim=1)\n', (8648, 8699), False, 'import torch\n'), ((14926, 14949), 'torch.squeeze', 'torch.squeeze', (['mix_stft'], {}), '(mix_stft)\n', (14939, 14949), False, 'import torch\n'), ((17244, 17259), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (17257, 17259), False, 'import pdb\n'), ((5298, 5339), 'torch.unsqueeze', 'torch.unsqueeze', (['ref_stft[spk_idx]'], {'dim': '(0)'}), '(ref_stft[spk_idx], dim=0)\n', (5313, 5339), False, 'import torch\n'), ((7656, 7703), 'torch.cat', 'torch.cat', (['(ref_, ref_stft_1ch[spk_idx])'], {'dim': '(1)'}), '((ref_, ref_stft_1ch[spk_idx]), dim=1)\n', (7665, 7703), False, 'import torch\n'), ((7733, 7795), 'torch.stack', 'torch.stack', (['(s_MISO1, MISO1_stft[spk_idx][:, 0, :, :])'], {'dim': '(1)'}), '((s_MISO1, MISO1_stft[spk_idx][:, 0, :, :]), dim=1)\n', (7744, 7795), False, 'import torch\n'), ((8853, 8911), 'torch.unsqueeze', 'torch.unsqueeze', (['ref_[batch_idx, target_index, ...]'], {'dim': '(0)'}), '(ref_[batch_idx, target_index, ...], dim=0)\n', (8868, 8911), False, 'import torch\n'), ((9641, 9784), 'convolutive_prediction.Apply_ConvolutivePrediction', 'Apply_ConvolutivePrediction', (['observe', 'source', 'self.num_spks', 'self.predictionType', 'self.tapDelay', 'self.nTap', 'self.reverb_variance_flowValue'], {}), '(observe, source, self.num_spks, self.\n predictionType, self.tapDelay, self.nTap, self.reverb_variance_flowValue)\n', (9668, 9784), False, 'from convolutive_prediction import Apply_ConvolutivePrediction\n'), ((11162, 11295), 'convolutive_prediction.Apply_ConvolutivePrediction', 'Apply_ConvolutivePrediction', (['observe', 'source', 'self.num_spks', '"""DNN_WPE"""', 'self.tapDelay', 'self.nTap', 'self.reverb_variance_flowValue'], {}), "(observe, source, self.num_spks, 'DNN_WPE', self\n .tapDelay, self.nTap, self.reverb_variance_flowValue)\n", (11189, 11295), False, 'from convolutive_prediction import Apply_ConvolutivePrediction\n'), ((11562, 11691), 'convolutive_prediction.Apply_ConvolutivePrediction', 'Apply_ConvolutivePrediction', (['observe', 'source', 'self.num_spks', '"""FCP"""', 'self.tapDelay', 'self.nTap', 'self.reverb_variance_flowValue'], {}), "(observe, source, self.num_spks, 'FCP', self.\n tapDelay, self.nTap, self.reverb_variance_flowValue)\n", (11589, 11691), False, 'from convolutive_prediction import Apply_ConvolutivePrediction\n'), ((13797, 13856), 'torch.permute', 'torch.permute', (['DNN_WPE_dereverb_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(DNN_WPE_dereverb_stft[spk_idx], [0, 3, 1, 2])\n', (13810, 13856), False, 'import torch\n'), ((14183, 14238), 'torch.permute', 'torch.permute', (['FCP_dereverb_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(FCP_dereverb_stft[spk_idx], [0, 3, 1, 2])\n', (14196, 14238), False, 'import torch\n'), ((14581, 14618), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (14594, 14618), False, 'import torch\n'), ((15096, 15130), 'torch.squeeze', 'torch.squeeze', (['MISO1_stft[spk_idx]'], {}), '(MISO1_stft[spk_idx])\n', (15109, 15130), False, 'import torch\n'), ((15233, 15270), 'torch.squeeze', 'torch.squeeze', (['dereverb_stft[spk_idx]'], {}), '(dereverb_stft[spk_idx])\n', (15246, 15270), False, 'import torch\n'), ((15387, 15420), 'numpy.transpose', 'np.transpose', (['mix_stft', '[0, 2, 1]'], {}), '(mix_stft, [0, 2, 1])\n', (15399, 15420), True, 'import numpy as np\n'), ((24178, 24226), 'numpy.linalg.norm', 'np.linalg.norm', (['source_steering[b_idx, f_idx, :]'], {}), '(source_steering[b_idx, f_idx, :])\n', (24192, 24226), True, 'import numpy as np\n'), ((26332, 26366), 'numpy.conjugate', 'np.conjugate', (['vector[b_idx, ii, :]'], {}), '(vector[b_idx, ii, :])\n', (26344, 26366), True, 'import numpy as np\n'), ((6502, 6535), 'numpy.expand_dims', 'np.expand_dims', (['MISO1_sig'], {'axis': '(1)'}), '(MISO1_sig, axis=1)\n', (6516, 6535), True, 'import numpy as np\n'), ((9982, 10125), 'convolutive_prediction.Apply_ConvolutivePrediction', 'Apply_ConvolutivePrediction', (['observe', 'source', 'self.num_spks', 'self.predictionType', 'self.tapDelay', 'self.nTap', 'self.reverb_variance_flowValue'], {}), '(observe, source, self.num_spks, self.\n predictionType, self.tapDelay, self.nTap, self.reverb_variance_flowValue)\n', (10009, 10125), False, 'from convolutive_prediction import Apply_ConvolutivePrediction\n'), ((12548, 12584), 'numpy.expand_dims', 'np.expand_dims', (['Beamform_sig'], {'axis': '(1)'}), '(Beamform_sig, axis=1)\n', (12562, 12584), True, 'import numpy as np\n'), ((13149, 13200), 'torch.permute', 'torch.permute', (['dereverb_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(dereverb_stft[spk_idx], [0, 3, 1, 2])\n', (13162, 13200), False, 'import torch\n'), ((15516, 15562), 'numpy.transpose', 'np.transpose', (['ref_stft_1ch[spk_idx]', '[0, 2, 1]'], {}), '(ref_stft_1ch[spk_idx], [0, 2, 1])\n', (15528, 15562), True, 'import numpy as np\n'), ((15625, 15669), 'numpy.transpose', 'np.transpose', (['MISO1_stft[spk_idx]', '[0, 2, 1]'], {}), '(MISO1_stft[spk_idx], [0, 2, 1])\n', (15637, 15669), True, 'import numpy as np\n'), ((16521, 16576), 'numpy.transpose', 'np.transpose', (['DNN_WPE_Beamform_stft[spk_idx]', '[0, 2, 1]'], {}), '(DNN_WPE_Beamform_stft[spk_idx], [0, 2, 1])\n', (16533, 16576), True, 'import numpy as np\n'), ((16810, 16861), 'numpy.transpose', 'np.transpose', (['FCP_Beamform_stft[spk_idx]', '[0, 2, 1]'], {}), '(FCP_Beamform_stft[spk_idx], [0, 2, 1])\n', (16822, 16861), True, 'import numpy as np\n'), ((16973, 17027), 'numpy.transpose', 'np.transpose', (['Origin_Beamform_stft[spk_idx]', '[0, 2, 1]'], {}), '(Origin_Beamform_stft[spk_idx], [0, 2, 1])\n', (16985, 17027), True, 'import numpy as np\n'), ((10421, 10564), 'convolutive_prediction.Apply_ConvolutivePrediction', 'Apply_ConvolutivePrediction', (['observe', 'source', 'self.num_spks', 'self.predictionType', 'self.tapDelay', 'self.nTap', 'self.reverb_variance_flowValue'], {}), '(observe, source, self.num_spks, self.\n predictionType, self.tapDelay, self.nTap, self.reverb_variance_flowValue)\n', (10448, 10564), False, 'from convolutive_prediction import Apply_ConvolutivePrediction\n'), ((10969, 11017), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (10982, 11017), False, 'import torch\n'), ((11373, 11421), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (11386, 11421), False, 'import torch\n'), ((13018, 13066), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (13031, 13066), False, 'import torch\n'), ((13714, 13762), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (13727, 13762), False, 'import torch\n'), ((14100, 14148), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (14113, 14148), False, 'import torch\n'), ((14498, 14546), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (14511, 14546), False, 'import torch\n'), ((15781, 15828), 'numpy.transpose', 'np.transpose', (['dereverb_stft[spk_idx]', '[0, 2, 1]'], {}), '(dereverb_stft[spk_idx], [0, 2, 1])\n', (15793, 15828), True, 'import numpy as np\n'), ((15912, 15959), 'numpy.transpose', 'np.transpose', (['Beamform_stft[spk_idx]', '[0, 2, 1]'], {}), '(Beamform_stft[spk_idx], [0, 2, 1])\n', (15924, 15959), True, 'import numpy as np\n'), ((16078, 16125), 'numpy.transpose', 'np.transpose', (['Beamform_stft[spk_idx]', '[0, 2, 1]'], {}), '(Beamform_stft[spk_idx], [0, 2, 1])\n', (16090, 16125), True, 'import numpy as np\n'), ((16393, 16443), 'numpy.squeeze', 'np.squeeze', (['DNN_WPE_dereverb_stft[spk_idx]'], {'axis': '(0)'}), '(DNN_WPE_dereverb_stft[spk_idx], axis=0)\n', (16403, 16443), True, 'import numpy as np\n'), ((16690, 16736), 'numpy.squeeze', 'np.squeeze', (['FCP_dereverb_stft[spk_idx]'], {'axis': '(0)'}), '(FCP_dereverb_stft[spk_idx], axis=0)\n', (16700, 16736), True, 'import numpy as np\n'), ((9515, 9563), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (9528, 9563), False, 'import torch\n'), ((9856, 9904), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (9869, 9904), False, 'import torch\n'), ((10228, 10276), 'torch.permute', 'torch.permute', (['MISO1_stft[spk_idx]', '[0, 3, 1, 2]'], {}), '(MISO1_stft[spk_idx], [0, 3, 1, 2])\n', (10241, 10276), False, 'import torch\n'), ((9378, 9415), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (9391, 9415), False, 'import torch\n'), ((13257, 13294), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (13270, 13294), False, 'import torch\n'), ((11052, 11089), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (11065, 11089), False, 'import torch\n'), ((11456, 11493), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (11469, 11493), False, 'import torch\n'), ((10315, 10352), 'torch.permute', 'torch.permute', (['mix_stft', '[0, 3, 1, 2]'], {}), '(mix_stft, [0, 3, 1, 2])\n', (10328, 10352), False, 'import torch\n')]
import argparse import os import shutil import numpy as np import torch as t from torch.optim import Adam from utils.batch_loader import BatchLoader from utils.parameters import Parameters from model.rvae_dilated import RVAE_dilated if __name__ == "__main__": parser = argparse.ArgumentParser(description='RVAE_dilated') parser.add_argument('--num-epochs', type=int, default=25000, metavar='ES', help='num epochs (default: 25000)') parser.add_argument('--start-epoch', default=0, type=int, metavar='E', help='manual epoch index (useful on restarts)') parser.add_argument('--batch-size', type=int, default=45, metavar='BS', help='batch size (default: 45)') parser.add_argument('--use-cuda', type=bool, default=True, metavar='CUDA', help='use cuda (default: True)') parser.add_argument('--learning-rate', type=float, default=0.0005, metavar='LR', help='learning rate (default: 0.0005)') parser.add_argument('--dropout', type=float, default=0.3, metavar='DR', help='dropout (default: 0.3)') parser.add_argument('--use-trained', default='', metavar='UT', help='load pretrained model (default: None)') parser.add_argument('--ret-result', default='', metavar='CE', help='ce result path (default: '')') parser.add_argument('--kld-result', default='', metavar='KLD', help='ce result path (default: '')') args = parser.parse_args() prefix = 'poem' word_is_char = True batch_loader = BatchLoader('', prefix, word_is_char) best_ret = 9999999 is_best = False if not os.path.exists('data/' + batch_loader.prefix + 'word_embeddings.npy'): raise FileNotFoundError("word embeddings file was't found") parameters = Parameters(batch_loader.max_word_len, batch_loader.max_seq_len, batch_loader.words_vocab_size, batch_loader.chars_vocab_size, word_is_char) rvae = RVAE_dilated(parameters, batch_loader.prefix) optimizer = Adam(rvae.learnable_parameters(), args.learning_rate) if args.use_trained: checkpoint = t.load(args.use_trained) args.start_epoch = checkpoint['epoch'] best_ret = checkpoint['best_ret'] rvae.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) if args.use_cuda and t.cuda.is_available(): rvae = rvae.cuda() train_step = rvae.trainer(optimizer, batch_loader) validate = rvae.validater(batch_loader) ret_result = [] kld_result = [] for epoch in range(args.start_epoch, args.num_epochs): train_ret, train_kld, train_kld_coef = train_step(epoch, args.batch_size, args.use_cuda and t.cuda.is_available(), args.dropout) train_ret = train_ret.data.cpu().numpy()[0] train_kld = train_kld.data.cpu().numpy()[0] valid_ret, valid_kld = validate(args.batch_size, args.use_cuda and t.cuda.is_available()) valid_ret = valid_ret.data.cpu().numpy()[0] valid_kld = valid_kld.data.cpu().numpy()[0] ret_result += [valid_ret] kld_result += [valid_kld] is_best = valid_ret < best_ret best_ret = min(valid_ret, best_ret) print('[%s]---TRAIN-ret[%s]kld[%s]------VALID-ret[%s]kld[%s]'%(epoch, train_ret, train_kld, valid_ret, valid_kld)) if epoch != 1 and epoch % 10 == 9: seed = np.random.normal(size=[1, parameters.latent_variable_size]) sample = rvae.sample(batch_loader, 50, seed, args.use_cuda and t.cuda.is_available(), None, 1) print('[%s]---SAMPLE: %s'%(epoch, sample)) if epoch != 0 and epoch % 100 == 99: checkpoint_filename = './data/%strained_%s_RVAE'%(batch_loader.prefix, epoch+1) t.save({'epoch': epoch+1, 'state_dict': rvae.state_dict(), 'best_ret': best_ret, 'optimizer': optimizer.state_dict()}, checkpoint_filename) oldest = epoch+1-3*100 oldest_checkpoint_filename = './data/%strained_%s_RVAE'%(batch_loader.prefix, oldest) if oldest>0 else None if oldest_checkpoint_filename and os.path.isfile(oldest_checkpoint_filename): os.remove(oldest_checkpoint_filename) if is_best: shutil.copyfile(checkpoint_filename, './data/'+batch_loader.prefix+'trained_best_RVAE') t.save({'epoch': args.num_epochs, 'state_dict': rvae.state_dict(), 'best_ret': best_ret, 'optimizer': optimizer.state_dict()}, './data/'+batch_loader.prefix+'trained_last_RVAE') np.save(batch_loader.prefix+'ret_result_{}.npy'.format(args.ret_result), np.array(ret_result)) np.save(batch_loader.prefix+'kld_result_npy_{}'.format(args.kld_result), np.array(kld_result))
[ "numpy.random.normal", "os.path.exists", "utils.batch_loader.BatchLoader", "argparse.ArgumentParser", "torch.load", "os.path.isfile", "numpy.array", "utils.parameters.Parameters", "torch.cuda.is_available", "shutil.copyfile", "model.rvae_dilated.RVAE_dilated", "os.remove" ]
[((281, 332), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""RVAE_dilated"""'}), "(description='RVAE_dilated')\n", (304, 332), False, 'import argparse\n'), ((1653, 1690), 'utils.batch_loader.BatchLoader', 'BatchLoader', (['""""""', 'prefix', 'word_is_char'], {}), "('', prefix, word_is_char)\n", (1664, 1690), False, 'from utils.batch_loader import BatchLoader\n'), ((1904, 2047), 'utils.parameters.Parameters', 'Parameters', (['batch_loader.max_word_len', 'batch_loader.max_seq_len', 'batch_loader.words_vocab_size', 'batch_loader.chars_vocab_size', 'word_is_char'], {}), '(batch_loader.max_word_len, batch_loader.max_seq_len,\n batch_loader.words_vocab_size, batch_loader.chars_vocab_size, word_is_char)\n', (1914, 2047), False, 'from utils.parameters import Parameters\n'), ((2140, 2185), 'model.rvae_dilated.RVAE_dilated', 'RVAE_dilated', (['parameters', 'batch_loader.prefix'], {}), '(parameters, batch_loader.prefix)\n', (2152, 2185), False, 'from model.rvae_dilated import RVAE_dilated\n'), ((1747, 1816), 'os.path.exists', 'os.path.exists', (["('data/' + batch_loader.prefix + 'word_embeddings.npy')"], {}), "('data/' + batch_loader.prefix + 'word_embeddings.npy')\n", (1761, 1816), False, 'import os\n'), ((2303, 2327), 'torch.load', 't.load', (['args.use_trained'], {}), '(args.use_trained)\n', (2309, 2327), True, 'import torch as t\n'), ((2564, 2585), 'torch.cuda.is_available', 't.cuda.is_available', ([], {}), '()\n', (2583, 2585), True, 'import torch as t\n'), ((4890, 4910), 'numpy.array', 'np.array', (['ret_result'], {}), '(ret_result)\n', (4898, 4910), True, 'import numpy as np\n'), ((4989, 5009), 'numpy.array', 'np.array', (['kld_result'], {}), '(kld_result)\n', (4997, 5009), True, 'import numpy as np\n'), ((3600, 3659), 'numpy.random.normal', 'np.random.normal', ([], {'size': '[1, parameters.latent_variable_size]'}), '(size=[1, parameters.latent_variable_size])\n', (3616, 3659), True, 'import numpy as np\n'), ((2916, 2937), 'torch.cuda.is_available', 't.cuda.is_available', ([], {}), '()\n', (2935, 2937), True, 'import torch as t\n'), ((3133, 3154), 'torch.cuda.is_available', 't.cuda.is_available', ([], {}), '()\n', (3152, 3154), True, 'import torch as t\n'), ((4364, 4406), 'os.path.isfile', 'os.path.isfile', (['oldest_checkpoint_filename'], {}), '(oldest_checkpoint_filename)\n', (4378, 4406), False, 'import os\n'), ((4424, 4461), 'os.remove', 'os.remove', (['oldest_checkpoint_filename'], {}), '(oldest_checkpoint_filename)\n', (4433, 4461), False, 'import os\n'), ((4502, 4597), 'shutil.copyfile', 'shutil.copyfile', (['checkpoint_filename', "('./data/' + batch_loader.prefix + 'trained_best_RVAE')"], {}), "(checkpoint_filename, './data/' + batch_loader.prefix +\n 'trained_best_RVAE')\n", (4517, 4597), False, 'import shutil\n'), ((3735, 3756), 'torch.cuda.is_available', 't.cuda.is_available', ([], {}), '()\n', (3754, 3756), True, 'import torch as t\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME> """ import sys sys.path.insert(0, '../PGP/') import numpy as np import matplotlib.pyplot as plt import pandas as pd from parametric_GP import PGP if __name__ == "__main__": # Import the data data = pd.read_pickle('airline.pickle') # Convert time of day from hhmm to minutes since midnight data.ArrTime = 60*np.floor(data.ArrTime/100)+np.mod(data.ArrTime, 100) data.DepTime = 60*np.floor(data.DepTime/100)+np.mod(data.DepTime, 100) # Pick out the data Y = data['ArrDelay'].values names = ['Month', 'DayofMonth', 'DayOfWeek', 'plane_age', 'AirTime', 'Distance', 'ArrTime', 'DepTime'] X = data[names].values N = len(data) np.random.seed(N) # Shuffle the data and only consider a subset of it perm = np.random.permutation(N) X = X[perm] Y = Y[perm] XT = X[int(2*N/3):N] YT = Y[int(2*N/3):N] X = X[:int(2*N/3)] Y = Y[:int(2*N/3)] # Normalize Y scale and offset Ymean = Y.mean() Ystd = Y.std() Y = (Y - Ymean) / Ystd Y = Y.reshape(-1, 1) YT = (YT - Ymean) / Ystd YT = YT.reshape(-1, 1) # Normalize X on [0, 1] Xmin, Xmax = X.min(0), X.max(0) X = (X - Xmin) / (Xmax - Xmin) XT = (XT - Xmin) / (Xmax - Xmin) # Model creation M = 500 pgp = PGP(X, Y, M, max_iter = 10000, N_batch = 1000, monitor_likelihood = 10, lrate = 1e-3) # Training pgp.train() # Prediction mean_star, var_star = pgp.predict(XT) # MSE print('MSE: %f' % ((mean_star-YT)**2).mean()) print('MSE_mean: %f' % ((Y.mean()-YT)**2).mean()) # ARD ARD = 1/np.sqrt(np.exp(pgp.hyp[1:-1])) ARD_x = np.arange(len(ARD)) fig, ax = plt.subplots(figsize=(10,5)) plt.rcParams.update({'font.size': 16}) ax.barh(ARD_x,ARD) ax.set_yticks(ARD_x) ax.set_yticklabels(names) ax.set_xlabel('ARD weights') plt.savefig('../Fig/Flights.eps', format='eps', dpi=1000) ##### # MSE: 0.832810 # MSE_mean: 0.999799
[ "pandas.read_pickle", "sys.path.insert", "matplotlib.pyplot.savefig", "parametric_GP.PGP", "numpy.floor", "numpy.exp", "matplotlib.pyplot.rcParams.update", "numpy.random.seed", "numpy.mod", "matplotlib.pyplot.subplots", "numpy.random.permutation" ]
[((83, 112), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../PGP/"""'], {}), "(0, '../PGP/')\n", (98, 112), False, 'import sys\n'), ((285, 317), 'pandas.read_pickle', 'pd.read_pickle', (['"""airline.pickle"""'], {}), "('airline.pickle')\n", (299, 317), True, 'import pandas as pd\n'), ((749, 766), 'numpy.random.seed', 'np.random.seed', (['N'], {}), '(N)\n', (763, 766), True, 'import numpy as np\n'), ((835, 859), 'numpy.random.permutation', 'np.random.permutation', (['N'], {}), '(N)\n', (856, 859), True, 'import numpy as np\n'), ((1357, 1435), 'parametric_GP.PGP', 'PGP', (['X', 'Y', 'M'], {'max_iter': '(10000)', 'N_batch': '(1000)', 'monitor_likelihood': '(10)', 'lrate': '(0.001)'}), '(X, Y, M, max_iter=10000, N_batch=1000, monitor_likelihood=10, lrate=0.001)\n', (1360, 1435), False, 'from parametric_GP import PGP\n'), ((1789, 1818), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (1801, 1818), True, 'import matplotlib.pyplot as plt\n'), ((1822, 1860), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 16}"], {}), "({'font.size': 16})\n", (1841, 1860), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2038), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../Fig/Flights.eps"""'], {'format': '"""eps"""', 'dpi': '(1000)'}), "('../Fig/Flights.eps', format='eps', dpi=1000)\n", (1992, 2038), True, 'import matplotlib.pyplot as plt\n'), ((430, 455), 'numpy.mod', 'np.mod', (['data.ArrTime', '(100)'], {}), '(data.ArrTime, 100)\n', (436, 455), True, 'import numpy as np\n'), ((505, 530), 'numpy.mod', 'np.mod', (['data.DepTime', '(100)'], {}), '(data.DepTime, 100)\n', (511, 530), True, 'import numpy as np\n'), ((403, 431), 'numpy.floor', 'np.floor', (['(data.ArrTime / 100)'], {}), '(data.ArrTime / 100)\n', (411, 431), True, 'import numpy as np\n'), ((478, 506), 'numpy.floor', 'np.floor', (['(data.DepTime / 100)'], {}), '(data.DepTime / 100)\n', (486, 506), True, 'import numpy as np\n'), ((1719, 1740), 'numpy.exp', 'np.exp', (['pgp.hyp[1:-1]'], {}), '(pgp.hyp[1:-1])\n', (1725, 1740), True, 'import numpy as np\n')]
import rospy from styx_msgs.msg import TrafficLight import numpy as np from keras.models import Model from keras import applications from keras.models import load_model from keras.preprocessing import image as img_preprocessing import cv2 # load the trained model from keras.utils.generic_utils import CustomObjectScope model_filepath = 'saved_models/model.MobileNet-3-classes.h5' n_classes = 3 class TLClassifier(object): def __init__(self): # load classifier # load keras libraies and load the MobileNet model self.model_loaded = False def load_model(self): rospy.loginfo("TLClassifier: Loading model...") with CustomObjectScope({'relu6': applications.mobilenet.relu6,'DepthwiseConv2D': applications.mobilenet.DepthwiseConv2D}): self.model = load_model(model_filepath) self.model._make_predict_function() # Otherwise there is a "Tensor %s is not an element of this grap..." when predicting self.model_loaded = True rospy.loginfo("TLClassifier: Model loaded - READY") def get_classification(self, image): """Determines the color of the traffic light in the image Args: image (cv::Mat): image containing the traffic light Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight) """ # Implement light color prediction if not self.model_loaded: rospy.logwarn("Model not loaded yet, clssification not possible!") return TrafficLight.UNKNOWN # The model was trained with RGB images. # So the image needs to be provided as RGB: # self.bridge.imgmsg_to_cv2(self.camera_image, "rgb8") # Otherwise a conversion would be necessary # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # The model expects RGB images in (224, 224) as input image = cv2.resize(image,(224,224)) # to tensors and normalize it x = img_preprocessing.img_to_array(image) x = np.expand_dims(x, axis=0).astype('float32')/255 # get index of predicted signal sign for the image signal_prediction = np.argmax(self.model.predict(x)) return signal_prediction
[ "keras.preprocessing.image.img_to_array", "keras.models.load_model", "rospy.logwarn", "keras.utils.generic_utils.CustomObjectScope", "numpy.expand_dims", "cv2.resize", "rospy.loginfo" ]
[((605, 652), 'rospy.loginfo', 'rospy.loginfo', (['"""TLClassifier: Loading model..."""'], {}), "('TLClassifier: Loading model...')\n", (618, 652), False, 'import rospy\n'), ((1010, 1061), 'rospy.loginfo', 'rospy.loginfo', (['"""TLClassifier: Model loaded - READY"""'], {}), "('TLClassifier: Model loaded - READY')\n", (1023, 1061), False, 'import rospy\n'), ((1918, 1947), 'cv2.resize', 'cv2.resize', (['image', '(224, 224)'], {}), '(image, (224, 224))\n', (1928, 1947), False, 'import cv2\n'), ((2005, 2042), 'keras.preprocessing.image.img_to_array', 'img_preprocessing.img_to_array', (['image'], {}), '(image)\n', (2035, 2042), True, 'from keras.preprocessing import image as img_preprocessing\n'), ((666, 787), 'keras.utils.generic_utils.CustomObjectScope', 'CustomObjectScope', (["{'relu6': applications.mobilenet.relu6, 'DepthwiseConv2D': applications.\n mobilenet.DepthwiseConv2D}"], {}), "({'relu6': applications.mobilenet.relu6, 'DepthwiseConv2D':\n applications.mobilenet.DepthwiseConv2D})\n", (683, 787), False, 'from keras.utils.generic_utils import CustomObjectScope\n'), ((809, 835), 'keras.models.load_model', 'load_model', (['model_filepath'], {}), '(model_filepath)\n', (819, 835), False, 'from keras.models import load_model\n'), ((1450, 1516), 'rospy.logwarn', 'rospy.logwarn', (['"""Model not loaded yet, clssification not possible!"""'], {}), "('Model not loaded yet, clssification not possible!')\n", (1463, 1516), False, 'import rospy\n'), ((2055, 2080), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (2069, 2080), True, 'import numpy as np\n')]
############################################################################### # Copyright (C) 2016 <NAME> # This is part of <NAME>'s PoDoCo project. # # This file is licensed under the MIT License. ############################################################################### """ Particle filters for tracking the incoming traffic intensity. See, the files script_test_poisson_1.py and script_test_negbin.py for usage. """ import numpy as np import resampling # resampling (c) <NAME> Jr (MIT License) from scipy.special import gammaln def pf_init(Nrep, params): """ Initialize particle filter from MCMC samples. """ for key in params.keys(): params[key] = np.tile(params[key], Nrep) N = params['A_x'].shape[0] W = np.repeat(1/N, N) x = np.random.normal(params['base'][0, :], params['sqrtQ_x'] / np.sqrt((1 - params['A_x']**2))) return x, params, W def pf_update_poisson(y, x, params, W): """Update weights according to measurement""" logW = np.log(W) + y * np.log(np.exp(x)) - np.exp(x) W = np.exp(logW - np.max(logW)) W = W / sum(W) return params, W def pf_step_poisson(y, x, params, W, resample=True): """One step (measurement) of the particle filter, Poisson obs. model (Resample) Propagate the particles using the prior model, Update weights Remove the first elements of baselines """ N = W.shape[0] if resample: ind = resampling.residual_resample(W) x = x[ind] params['base'] = params['base'][:, ind] params['sqrtQ_x'] = params['sqrtQ_x'][ind] params['A_x'] = params['A_x'][ind] W = np.repeat(1/N, N) x = np.random.normal(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]), params['sqrtQ_x']) params = trim_base(params) params, W = pf_update_poisson(y, x, params, W) return x, params, W def predict_mean(x, params, W): """Expected value of the next observation after the update step""" return np.sum(W * (np.exp(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]) + 0.5 * params['sqrtQ_x']**2))) def trim_base(params): """Cuts the first component of base""" params['base'] = params['base'][1:, :] return params def pf_update_negbin(y, x, params, W): """Update weights per measurement, NegBin obs. model""" phi = np.exp(x) / (params['omega'] - 1) logW = (gammaln(y + phi) - gammaln(phi) + y * (np.log(params['omega'] - 1) - np.log(params['omega'])) - phi * (np.log(params['omega']))) W = np.exp(logW - np.max(logW)) W = W / sum(W) return params, W def pf_step_negbin(y, x, params, W, resample=True): """ One step (measurement) of the particle filter, NegBin obs. model (Resample) Propagate the particles using the prior model, Update weights Remove the first elements of baselines """ N = W.shape[0] if resample: ind = resampling.residual_resample(W) x = x[ind] params['base'] = params['base'][:, ind] params['sqrtQ_x'] = params['sqrtQ_x'][ind] params['A_x'] = params['A_x'][ind] params['omega'] = params['omega'][ind] W = np.repeat(1/N, N) x = np.random.normal(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]), params['sqrtQ_x']) params = trim_base(params) params, W = pf_update_negbin(y, x, params, W) return x, params, W
[ "numpy.random.normal", "numpy.tile", "numpy.repeat", "numpy.sqrt", "numpy.log", "numpy.max", "numpy.exp", "scipy.special.gammaln", "resampling.residual_resample" ]
[((755, 774), 'numpy.repeat', 'np.repeat', (['(1 / N)', 'N'], {}), '(1 / N, N)\n', (764, 774), True, 'import numpy as np\n'), ((1700, 1807), 'numpy.random.normal', 'np.random.normal', (["(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]))", "params['sqrtQ_x']"], {}), "(params['base'][1, :] + params['A_x'] * (x - params['base']\n [0, :]), params['sqrtQ_x'])\n", (1716, 1807), True, 'import numpy as np\n'), ((3303, 3410), 'numpy.random.normal', 'np.random.normal', (["(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]))", "params['sqrtQ_x']"], {}), "(params['base'][1, :] + params['A_x'] * (x - params['base']\n [0, :]), params['sqrtQ_x'])\n", (3319, 3410), True, 'import numpy as np\n'), ((688, 714), 'numpy.tile', 'np.tile', (['params[key]', 'Nrep'], {}), '(params[key], Nrep)\n', (695, 714), True, 'import numpy as np\n'), ((1062, 1071), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1068, 1071), True, 'import numpy as np\n'), ((1468, 1499), 'resampling.residual_resample', 'resampling.residual_resample', (['W'], {}), '(W)\n', (1496, 1499), False, 'import resampling\n'), ((1673, 1692), 'numpy.repeat', 'np.repeat', (['(1 / N)', 'N'], {}), '(1 / N, N)\n', (1682, 1692), True, 'import numpy as np\n'), ((2429, 2438), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (2435, 2438), True, 'import numpy as np\n'), ((3024, 3055), 'resampling.residual_resample', 'resampling.residual_resample', (['W'], {}), '(W)\n', (3052, 3055), False, 'import resampling\n'), ((3276, 3295), 'numpy.repeat', 'np.repeat', (['(1 / N)', 'N'], {}), '(1 / N, N)\n', (3285, 3295), True, 'import numpy as np\n'), ((866, 897), 'numpy.sqrt', 'np.sqrt', (["(1 - params['A_x'] ** 2)"], {}), "(1 - params['A_x'] ** 2)\n", (873, 897), True, 'import numpy as np\n'), ((1026, 1035), 'numpy.log', 'np.log', (['W'], {}), '(W)\n', (1032, 1035), True, 'import numpy as np\n'), ((1094, 1106), 'numpy.max', 'np.max', (['logW'], {}), '(logW)\n', (1100, 1106), True, 'import numpy as np\n'), ((2065, 2174), 'numpy.exp', 'np.exp', (["(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]) + 0.5 * \n params['sqrtQ_x'] ** 2)"], {}), "(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]) + \n 0.5 * params['sqrtQ_x'] ** 2)\n", (2071, 2174), True, 'import numpy as np\n'), ((2603, 2626), 'numpy.log', 'np.log', (["params['omega']"], {}), "(params['omega'])\n", (2609, 2626), True, 'import numpy as np\n'), ((2652, 2664), 'numpy.max', 'np.max', (['logW'], {}), '(logW)\n', (2658, 2664), True, 'import numpy as np\n'), ((2476, 2492), 'scipy.special.gammaln', 'gammaln', (['(y + phi)'], {}), '(y + phi)\n', (2483, 2492), False, 'from scipy.special import gammaln\n'), ((2495, 2507), 'scipy.special.gammaln', 'gammaln', (['phi'], {}), '(phi)\n', (2502, 2507), False, 'from scipy.special import gammaln\n'), ((1049, 1058), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (1055, 1058), True, 'import numpy as np\n'), ((2527, 2554), 'numpy.log', 'np.log', (["(params['omega'] - 1)"], {}), "(params['omega'] - 1)\n", (2533, 2554), True, 'import numpy as np\n'), ((2557, 2580), 'numpy.log', 'np.log', (["params['omega']"], {}), "(params['omega'])\n", (2563, 2580), True, 'import numpy as np\n')]
import os import numpy as np import pandas as pd from Base import Train, Predict def getTest(boolNormalize, boolDeep, boolBias, strProjectFolder): if boolNormalize: if boolDeep: strOutputPath = "02-Output/" + "Deep" + "Normal" else: if boolBias: strOutputPath = "02-Output/" + "Bias" + "Normal" else: strOutputPath = "02-Output/" + "unBias" + "Normal" else: if boolDeep: strOutputPath = "02-Output/" + "Deep" else: if boolBias: strOutputPath = "02-Output/" + "Bias" else: strOutputPath = "02-Output/" + "unBias" strOutputPath = strOutputPath + "Test" DataTrain = pd.read_csv(os.path.join(strProjectFolder, "01-Data/Train.csv")) DataTest = pd.read_csv(os.path.join(strProjectFolder, "01-Data/Test.csv")) submisson = pd.read_csv(os.path.join(strProjectFolder, "01-Data/SampleSubmisson.csv")) DataTrain = DataTrain.sample(frac=1) intUserSize = len(DataTrain["UserID"].drop_duplicates()) intMovieSize = len(DataTrain["MovieID"].drop_duplicates()) arrayUsers = DataTrain["UserID"].values arrayMovies = DataTrain["MovieID"].values arrayRate = DataTrain["Rating"].values arrayTestUsers = DataTest["UserID"].values arrayTestMovies = DataTest["MovieID"].values intLatentSize = 32 if boolNormalize: arrayRateAvg = np.mean(arrayRate) arrayRateStd = np.std(arrayRate) arrayRate = (arrayRate - arrayRateAvg)/arrayRateStd Train.getTrain(arrayTrainUser=arrayUsers, arrayTrainMovie=arrayMovies, arrayTrainRate=arrayRate , arrayValidUser=arrayUsers, arrayValidMovie=arrayMovies, arrayValidRate=arrayRate , intUserSize=intUserSize , intMovieSize=intMovieSize , intLatentSize=intLatentSize , boolBias=boolBias , boolDeep=boolDeep , strProjectFolder=strProjectFolder, strOutputPath=strOutputPath) arrayPredict = Predict.makePredict(arrayTestUsers, arrayTestMovies, strProjectFolder, strOutputPath) if boolNormalize: arrayPredict = (arrayPredict * arrayRateStd) + arrayRateAvg submisson["Rating"] = pd.DataFrame(arrayPredict) submisson.to_csv(os.path.join(strProjectFolder, strOutputPath + "submission.csv"), index=False) if __name__ == "__main__": strProjectFolder = os.path.dirname(__file__) getTest(boolNormalize=True, boolDeep=False, boolBias=True, strProjectFolder=strProjectFolder)
[ "numpy.mean", "os.path.join", "Base.Predict.makePredict", "os.path.dirname", "Base.Train.getTrain", "numpy.std", "pandas.DataFrame" ]
[((1585, 1968), 'Base.Train.getTrain', 'Train.getTrain', ([], {'arrayTrainUser': 'arrayUsers', 'arrayTrainMovie': 'arrayMovies', 'arrayTrainRate': 'arrayRate', 'arrayValidUser': 'arrayUsers', 'arrayValidMovie': 'arrayMovies', 'arrayValidRate': 'arrayRate', 'intUserSize': 'intUserSize', 'intMovieSize': 'intMovieSize', 'intLatentSize': 'intLatentSize', 'boolBias': 'boolBias', 'boolDeep': 'boolDeep', 'strProjectFolder': 'strProjectFolder', 'strOutputPath': 'strOutputPath'}), '(arrayTrainUser=arrayUsers, arrayTrainMovie=arrayMovies,\n arrayTrainRate=arrayRate, arrayValidUser=arrayUsers, arrayValidMovie=\n arrayMovies, arrayValidRate=arrayRate, intUserSize=intUserSize,\n intMovieSize=intMovieSize, intLatentSize=intLatentSize, boolBias=\n boolBias, boolDeep=boolDeep, strProjectFolder=strProjectFolder,\n strOutputPath=strOutputPath)\n', (1599, 1968), False, 'from Base import Train, Predict\n'), ((2093, 2182), 'Base.Predict.makePredict', 'Predict.makePredict', (['arrayTestUsers', 'arrayTestMovies', 'strProjectFolder', 'strOutputPath'], {}), '(arrayTestUsers, arrayTestMovies, strProjectFolder,\n strOutputPath)\n', (2112, 2182), False, 'from Base import Train, Predict\n'), ((2298, 2324), 'pandas.DataFrame', 'pd.DataFrame', (['arrayPredict'], {}), '(arrayPredict)\n', (2310, 2324), True, 'import pandas as pd\n'), ((2478, 2503), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2493, 2503), False, 'import os\n'), ((770, 821), 'os.path.join', 'os.path.join', (['strProjectFolder', '"""01-Data/Train.csv"""'], {}), "(strProjectFolder, '01-Data/Train.csv')\n", (782, 821), False, 'import os\n'), ((850, 900), 'os.path.join', 'os.path.join', (['strProjectFolder', '"""01-Data/Test.csv"""'], {}), "(strProjectFolder, '01-Data/Test.csv')\n", (862, 900), False, 'import os\n'), ((930, 991), 'os.path.join', 'os.path.join', (['strProjectFolder', '"""01-Data/SampleSubmisson.csv"""'], {}), "(strProjectFolder, '01-Data/SampleSubmisson.csv')\n", (942, 991), False, 'import os\n'), ((1460, 1478), 'numpy.mean', 'np.mean', (['arrayRate'], {}), '(arrayRate)\n', (1467, 1478), True, 'import numpy as np\n'), ((1502, 1519), 'numpy.std', 'np.std', (['arrayRate'], {}), '(arrayRate)\n', (1508, 1519), True, 'import numpy as np\n'), ((2346, 2410), 'os.path.join', 'os.path.join', (['strProjectFolder', "(strOutputPath + 'submission.csv')"], {}), "(strProjectFolder, strOutputPath + 'submission.csv')\n", (2358, 2410), False, 'import os\n')]
from abc import ABCMeta, abstractmethod import numpy as np __all__ = ['Law', 'Bin', 'Poi', 'Gau'] class Law(metaclass=ABCMeta): @staticmethod @abstractmethod def sample(n, d): pass @staticmethod @abstractmethod def loglikely(n, d, k): pass @staticmethod def likelihood(n, d, k): return np.exp(loglikely(n, d, k)) class Bin(Law): def sample(n, d): return np.random.binomial(n, d) def loglikely(n, d, k): return k*np.log(d) + (n-k)*np.log(1-d) class Poi(Law): def sample(n, d): return np.random.poisson(n*d) def loglikely(n, d, k): return k*np.log(n*d) - n*d + k - k*np.log(1+k) # - np.sum(np.log(np.arange(k)+1)) class Gau(Law): def sample(n, d=1): return n * (1 + 0.1*np.random.randn()) def loglikely(n, d, k): return -50 * np.log(k/n)**2
[ "numpy.random.poisson", "numpy.log", "numpy.random.randn", "numpy.random.binomial" ]
[((432, 456), 'numpy.random.binomial', 'np.random.binomial', (['n', 'd'], {}), '(n, d)\n', (450, 456), True, 'import numpy as np\n'), ((592, 616), 'numpy.random.poisson', 'np.random.poisson', (['(n * d)'], {}), '(n * d)\n', (609, 616), True, 'import numpy as np\n'), ((507, 516), 'numpy.log', 'np.log', (['d'], {}), '(d)\n', (513, 516), True, 'import numpy as np\n'), ((525, 538), 'numpy.log', 'np.log', (['(1 - d)'], {}), '(1 - d)\n', (531, 538), True, 'import numpy as np\n'), ((691, 704), 'numpy.log', 'np.log', (['(1 + k)'], {}), '(1 + k)\n', (697, 704), True, 'import numpy as np\n'), ((885, 898), 'numpy.log', 'np.log', (['(k / n)'], {}), '(k / n)\n', (891, 898), True, 'import numpy as np\n'), ((812, 829), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (827, 829), True, 'import numpy as np\n'), ((665, 678), 'numpy.log', 'np.log', (['(n * d)'], {}), '(n * d)\n', (671, 678), True, 'import numpy as np\n')]
__all__ = ['plot_cum_error_dist'] import numpy as np # import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patches from mpl_toolkits.axes_grid.inset_locator import inset_axes import itertools from . import palettes # colors = itertools.cycle(npl.palettes.color_palette(palette="sweet", n_colors=15)) # from ..core import * # from ..auxiliary import * from .. import decoding # from . import utils # import plotting/utils def plot_cum_error_dist(*, cumhist=None, bincenters=None, bst=None, extern=None, decodefunc=None, k=None, transfunc=None, n_extern=None, n_bins = None, extmin=None, extmax=None, sigma=None, lw=None, ax=None, inset=True, inset_ax=None, color=None, **kwargs): """Plot (and optionally compute) the cumulative distribution of decoding errors, evaluated using a cross-validation procedure. See Fig 3.(b) of "Analysis of Hippocampal Memory Replay Using Neural Population Decoding", <NAME>, 2012. Parameters ---------- Returns ------- """ if ax is None: ax = plt.gca() if lw is None: lw=1.5 if decodefunc is None: decodefunc = decoding.decode1D if k is None: k=5 if n_extern is None: n_extern=100 if n_bins is None: n_bins = 200 if extmin is None: extmin=0 if extmax is None: extmax=100 if sigma is None: sigma = 3 # Get the color from the current color cycle if color is None: line, = ax.plot(0, 0.5) color = line.get_color() line.remove() # if cumhist or bincenters are NOT provided, then compute them if cumhist is None or bincenters is None: assert bst is not None, "if cumhist and bincenters are not given, then bst must be provided to recompute them!" assert extern is not None, "if cumhist and bincenters are not given, then extern must be provided to recompute them!" cumhist, bincenters = \ decoding.cumulative_dist_decoding_error_using_xval( bst=bst, extern=extern, decodefunc=decoding.decode1D, k=k, transfunc=transfunc, n_extern=n_extern, extmin=extmin, extmax=extmax, sigma=sigma, n_bins=n_bins) # now plot results ax.plot(bincenters, cumhist, lw=lw, color=color, **kwargs) ax.set_xlim(bincenters[0], bincenters[-1]) ax.set_xlabel('error [cm]') ax.set_ylabel('cumulative probability') ax.set_ylim(0) if inset: if inset_ax is None: inset_ax = inset_axes(parent_axes=ax, width="60%", height="50%", loc=4, borderpad=2) inset_ax.plot(bincenters, cumhist, lw=lw, color=color, **kwargs) # annotate inset thresh1 = 0.7 bcidx = np.asscalar(np.argwhere(cumhist>thresh1)[0]-1) inset_ax.hlines(thresh1, 0, bincenters[bcidx], color=color, alpha=0.9, linestyle='--') inset_ax.vlines(bincenters[bcidx], 0, thresh1, color=color, alpha=0.9, linestyle='--') inset_ax.set_xlim(0,12*np.ceil(bincenters[bcidx]/10)) thresh2 = 0.5 bcidx = np.asscalar(np.argwhere(cumhist>thresh2)[0]-1) inset_ax.hlines(thresh2, 0, bincenters[bcidx], color=color, alpha=0.6, linestyle='--') inset_ax.vlines(bincenters[bcidx], 0, thresh2, color=color, alpha=0.6, linestyle='--') inset_ax.set_yticks((0,thresh1, thresh2, 1)) inset_ax.set_ylim(0) return ax, inset_ax return ax
[ "matplotlib.pyplot.gca", "numpy.ceil", "mpl_toolkits.axes_grid.inset_locator.inset_axes", "numpy.argwhere" ]
[((1188, 1197), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1195, 1197), True, 'import matplotlib.pyplot as plt\n'), ((2724, 2797), 'mpl_toolkits.axes_grid.inset_locator.inset_axes', 'inset_axes', ([], {'parent_axes': 'ax', 'width': '"""60%"""', 'height': '"""50%"""', 'loc': '(4)', 'borderpad': '(2)'}), "(parent_axes=ax, width='60%', height='50%', loc=4, borderpad=2)\n", (2734, 2797), False, 'from mpl_toolkits.axes_grid.inset_locator import inset_axes\n'), ((3341, 3372), 'numpy.ceil', 'np.ceil', (['(bincenters[bcidx] / 10)'], {}), '(bincenters[bcidx] / 10)\n', (3348, 3372), True, 'import numpy as np\n'), ((3084, 3114), 'numpy.argwhere', 'np.argwhere', (['(cumhist > thresh1)'], {}), '(cumhist > thresh1)\n', (3095, 3114), True, 'import numpy as np\n'), ((3423, 3453), 'numpy.argwhere', 'np.argwhere', (['(cumhist > thresh2)'], {}), '(cumhist > thresh2)\n', (3434, 3453), True, 'import numpy as np\n')]
import pandas as pd import numpy as np from model.helper_functions import build_playlist_features print('Reading data into memory') pid_list = np.genfromtxt('../data/train_pids.csv', skip_header=1, dtype=int) playlistfile = '../data/playlists.csv' playlist_df = pd.read_csv(playlistfile) trackfile = '../data/songs_100000_feat_cleaned.csv' track_df = pd.read_csv(trackfile, index_col='track_uri') print('Finding playlist features') playlist_features = build_playlist_features(pid_list, playlist_df, track_df) playlist_features.to_csv('../data/playlist_features_train.csv') print('Finding top artists') # Find the top artists who dominate playlists top_playlist_defining_artists = playlist_features.artist_uri_top.value_counts(normalize=False) top_playlist_defining_artists.to_csv('../data/top_playlist_defining_artists_train_all.csv', header=True) top_playlist_defining_artists = playlist_features.artist_uri_top.value_counts().index.values[:50] np.savetxt('../data/top_playlist_defining_artists_train.csv', top_playlist_defining_artists, delimiter=',', fmt="%s") # Keep only those artists who dominate playlists and one hot encode artists_to_keep = playlist_features.artist_uri_top.isin(top_playlist_defining_artists) playlist_features.artist_uri_top = playlist_features.artist_uri_top[artists_to_keep] playlist_features.artist_uri_freq = playlist_features.artist_uri_freq[artists_to_keep] playlist_features.artist_uri_freq.fillna(0, inplace=True) top_artist_dummies = pd.get_dummies(playlist_features.artist_uri_top) playlist_features = pd.concat([playlist_features, top_artist_dummies], axis=1) playlist_features.drop(['artist_uri_top'], axis=1, inplace=True) playlist_features.to_csv('../data/playlist_features_with_artists_train.csv')
[ "pandas.read_csv", "model.helper_functions.build_playlist_features", "pandas.concat", "numpy.savetxt", "pandas.get_dummies", "numpy.genfromtxt" ]
[((144, 209), 'numpy.genfromtxt', 'np.genfromtxt', (['"""../data/train_pids.csv"""'], {'skip_header': '(1)', 'dtype': 'int'}), "('../data/train_pids.csv', skip_header=1, dtype=int)\n", (157, 209), True, 'import numpy as np\n'), ((263, 288), 'pandas.read_csv', 'pd.read_csv', (['playlistfile'], {}), '(playlistfile)\n', (274, 288), True, 'import pandas as pd\n'), ((352, 397), 'pandas.read_csv', 'pd.read_csv', (['trackfile'], {'index_col': '"""track_uri"""'}), "(trackfile, index_col='track_uri')\n", (363, 397), True, 'import pandas as pd\n'), ((454, 510), 'model.helper_functions.build_playlist_features', 'build_playlist_features', (['pid_list', 'playlist_df', 'track_df'], {}), '(pid_list, playlist_df, track_df)\n', (477, 510), False, 'from model.helper_functions import build_playlist_features\n'), ((949, 1070), 'numpy.savetxt', 'np.savetxt', (['"""../data/top_playlist_defining_artists_train.csv"""', 'top_playlist_defining_artists'], {'delimiter': '""","""', 'fmt': '"""%s"""'}), "('../data/top_playlist_defining_artists_train.csv',\n top_playlist_defining_artists, delimiter=',', fmt='%s')\n", (959, 1070), True, 'import numpy as np\n'), ((1475, 1523), 'pandas.get_dummies', 'pd.get_dummies', (['playlist_features.artist_uri_top'], {}), '(playlist_features.artist_uri_top)\n', (1489, 1523), True, 'import pandas as pd\n'), ((1544, 1602), 'pandas.concat', 'pd.concat', (['[playlist_features, top_artist_dummies]'], {'axis': '(1)'}), '([playlist_features, top_artist_dummies], axis=1)\n', (1553, 1602), True, 'import pandas as pd\n')]
import numpy as np import sys import scipy.interpolate as interpolate import asdf from .function import * from .basic_func import Basic class Func: ''' The list of (possible) `Func` attributes is given below: Attributes ---------- ''' def __init__(self, MB, dust_model=0): ''' Parameters ---------- dust_model : int 0 for Calzetti. ''' self.ID = MB.ID self.ZZ = MB.Zall self.age = MB.age self.AA = MB.nage self.tau0 = MB.tau0 self.MB = MB self.dust_model = dust_model self.DIR_TMP = MB.DIR_TMP if MB.f_dust: self.Temp = MB.Temp try: self.filts = MB.filts self.DIR_FIL = MB.DIR_FILT except: pass # Already Read or not; self.f_af = False self.f_af0 = False def demo(self): ZZ = self.ZZ AA = self.AA return ZZ, AA ############################# # Load template in obs range. ############################# def open_spec_fits(self, fall=0, orig=False): ''' ''' ID0 = self.MB.ID tau0= self.MB.tau0 #[0.01,0.02,0.03] from astropy.io import fits ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) # ASDF; if fall == 0: app = '' hdu0 = self.MB.af['spec'] elif fall == 1: app = 'all_' hdu0 = self.MB.af['spec_full'] DIR_TMP = self.DIR_TMP for pp in range(len(tau0)): for zz in range(len(ZZ)): Z = ZZ[zz] NZ = bfnc.Z2NZ(Z) if zz == 0 and pp == 0: nr = hdu0['colnum'] xx = hdu0['wavelength'] lib = np.zeros((len(nr), 2+len(AA)*len(ZZ)*len(tau0)), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] for aa in range(len(AA)): coln = int(2 + aa) if orig: colname = 'fspec_orig_' + str(zz) + '_' + str(aa) + '_' + str(pp) else: colname = 'fspec_' + str(zz) + '_' + str(aa) + '_' + str(pp) colnall = int(2 + pp*len(ZZ)*len(AA) + zz*len(AA) + aa) # 2 takes account of wavelength and AV columns. lib[:,colnall] = hdu0[colname] return lib def open_spec_dust_fits(self, fall=0): ''' Loads dust template in obs range. ''' ID0 = self.MB.ID tau0= self.MB.tau0 #[0.01,0.02,0.03] from astropy.io import fits ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) self.MB.af = asdf.open(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf') self.MB.af0 = asdf.open(self.DIR_TMP + 'spec_all.asdf') if fall == 0: app = '' hdu0 = self.MB.af['spec_dust'] elif fall == 1: app = 'all_' hdu0 = self.MB.af['spec_dust_full'] DIR_TMP = self.DIR_TMP nr = hdu0['colnum'] xx = hdu0['wavelength'] lib = np.zeros((len(nr), 2+len(self.Temp)), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] for aa in range(len(self.Temp)): coln = int(2 + aa) colname = 'fspec_' + str(aa) colnall = int(2 + aa) # 2 takes account of wavelength and AV columns. lib[:,colnall] = hdu0[colname] if fall==1 and False: import matplotlib.pyplot as plt plt.close() plt.plot(lib[:,1],lib[:,coln],linestyle='-') plt.show() return lib def open_spec_fits_dir(self, nage, nz, kk, Av00, zgal, A00): ''' Load template in obs range. But for weird template. ''' from astropy.io import fits tau0= self.tau0 #[0.01,0.02,0.03] ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) self.MB.af = asdf.open(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf') self.MB.af0 = asdf.open(self.DIR_TMP + 'spec_all.asdf') app = 'all' hdu0 = self.MB.af['spec_full'] DIR_TMP = self.DIR_TMP #'./templates/' pp = 0 zz = nz # Luminosity mshdu = self.MB.af0['ML'] Ls = mshdu['Ls_%d'%nz] xx = hdu0['wavelength'] # at RF; nr = np.arange(0,len(xx),1) #hdu0.data['colnum'] lib = np.zeros((len(nr), 2+1), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] aa = nage coln = int(2 + aa) colname = 'fspec_' + str(zz) + '_' + str(aa) + '_' + str(pp) yy0 = hdu0[colname]/Ls[aa] yy = flamtonu(xx, yy0) lib[:,2] = yy[:] if self.dust_model == 0: # Calzetti yyd, xxd, nrd = dust_calz(xx, yy, Av00, nr) elif self.dust_model == 1: # MW yyd, xxd, nrd = dust_mw(xx, yy, Av00, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx, yy, Av00, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx, yy, Av00, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx, yy, Av00, nr, Rv=4.05, gamma=-0.2) else: print('No entry. Dust model is set to Calzetti') yyd, xxd, nrd = dust_calz(xx, yy, Av00, nr) xxd *= (1.+zgal) nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] b = nrd_yyd nrd_yyd_sort = b[np.lexsort(([-1,1]*b[:,[1,0]]).T)] yyd_sort = nrd_yyd_sort[:,1] xxd_sort = nrd_yyd_sort[:,2] return A00 * yyd_sort, xxd_sort def get_template(self, lib, Amp=1.0, T=1.0, Av=0.0, Z=0.0, zgal=1.0, f_bb=False): ''' Gets an element template given a set of parameters. Not necessarily the most efficient way, but easy to use. Parameters: ----------- lib : dict library dictionary. Amp : float Amplitude of the target template. Note that each template has Lbol = 1e10Lsun. T : float Age, in Gyr. Av : float Dust attenuation, in mag. Z : float Metallicity, in log(Z/Zsun). zgal : float Redshift. f_bb: bool If calculate bb photometry for the spectrum requested. Returns flux : float array. Flux in Fnu. wavelength : float array. Wave in AA. lcen, lflux : , if f_bb==True. ''' bfnc = self.MB.bfnc DIR_TMP = self.MB.DIR_TMP NZ = bfnc.Z2NZ(Z) pp0 = np.random.uniform(low=0, high=len(self.tau0), size=(1,)) pp = int(pp0[0]) if pp>=len(self.tau0): pp += -1 nmodel = np.argmin(np.abs(T-self.age[:])) if T - self.age[nmodel] != 0: print('T=%.2f is not found in age library. T=%.2f is used.'%(T,self.age[nmodel])) coln= int(2 + pp*len(self.ZZ)*len(self.AA) + NZ*len(self.AA) + nmodel) nr = lib[:, 0] xx = lib[:, 1] # This is OBSERVED wavelength range at z=zgal yy = lib[:, coln] if self.dust_model == 0: yyd, xxd, nrd = dust_calz(xx/(1.+zgal), yy, Av, nr) elif self.dust_model == 1: yyd, xxd, nrd = dust_mw(xx/(1.+zgal), yy, Av, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx/(1.+zgal), yy, Av, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx/(1.+zgal), yy, Av, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx/(1.+zgal), yy, Av, nr, Rv=4.05, gamma=-0.2) else: yyd, xxd, nrd = dust_calz(xx/(1.+zgal), yy, Av, nr) xxd *= (1.+zgal) nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] b = nrd_yyd nrd_yyd_sort = b[np.lexsort(([-1,1]*b[:,[1,0]]).T)] yyd_sort = nrd_yyd_sort[:,1] xxd_sort = nrd_yyd_sort[:,2] if f_bb: #fil_cen, fil_flux = filconv(self.filts, xxd_sort, Amp * yyd_sort, self.DIR_FIL) fil_cen, fil_flux = filconv_fast(self.MB, xxd_sort, Amp * yyd_sort) return Amp * yyd_sort, xxd_sort, fil_flux, fil_cen else: return Amp * yyd_sort, xxd_sort def tmp03(self, A00, Av00, nmodel, Z, zgal, lib): ''' ''' tau0= self.tau0 #[0.01,0.02,0.03] ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) DIR_TMP = self.MB.DIR_TMP #'./templates/' NZ = bfnc.Z2NZ(Z) pp0 = np.random.uniform(low=0, high=len(tau0), size=(1,)) pp = int(pp0[0]) if pp>=len(tau0): pp += -1 coln= int(2 + pp*len(ZZ)*len(AA) + NZ*len(AA) + nmodel) nr = lib[:,0] xx = lib[:,1] # This is OBSERVED wavelength range at z=zgal yy = lib[:,coln] if self.dust_model == 0: yyd, xxd, nrd = dust_calz(xx/(1.+zgal), yy, Av00, nr) elif self.dust_model == 1: yyd, xxd, nrd = dust_mw(xx/(1.+zgal), yy, Av00, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx/(1.+zgal), yy, Av00, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx/(1.+zgal), yy, Av00, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx/(1.+zgal), yy, Av00, nr, Rv=4.05, gamma=-0.2) else: yyd, xxd, nrd = dust_calz(xx/(1.+zgal), yy, Av00, nr) xxd *= (1.+zgal) nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] b = nrd_yyd nrd_yyd_sort = b[np.lexsort(([-1,1]*b[:,[1,0]]).T)] yyd_sort = nrd_yyd_sort[:,1] xxd_sort = nrd_yyd_sort[:,2] return A00 * yyd_sort, xxd_sort def tmp04(self, par, f_Alog=True, nprec=1, f_val=False, lib_all=False, f_nrd=False): ''' Makes model template with a given param set. Also dust attenuation. Parameters ---------- nprec : int Precision when redshift is refined. ''' ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc Mtot = 0 if f_val: par = par.params if self.MB.fzmc == 1: try: zmc = par['zmc'].value except: zmc = self.MB.zgal else: zmc = self.MB.zgal pp = 0 # AV limit; if par['Av'] < self.MB.Avmin: par['Av'] = self.MB.Avmin if par['Av'] > self.MB.Avmax: par['Av'] = self.MB.Avmax Av00 = par['Av'] for aa in range(len(AA)): if self.MB.ZEVOL==1 or aa == 0: Z = par['Z'+str(aa)] NZ = bfnc.Z2NZ(Z) else: pass # Check limit; if par['A'+str(aa)] < self.MB.Amin: par['A'+str(aa)] = self.MB.Amin if par['A'+str(aa)] > self.MB.Amax: par['A'+str(aa)] = self.MB.Amax # Z limit: if aa == 0 or self.MB.ZEVOL == 1: if par['Z%d'%aa] < self.MB.Zmin: par['Z%d'%aa] = self.MB.Zmin if par['Z%d'%aa] > self.MB.Zmax: par['Z%d'%aa] = self.MB.Zmax # Is A in logspace? if f_Alog: A00 = 10**par['A'+str(aa)] else: A00 = par['A'+str(aa)] coln = int(2 + pp*len(ZZ)*len(AA) + NZ*len(AA) + aa) sedpar = self.MB.af['ML'] # For M/L mslist = sedpar['ML_'+str(NZ)][aa] Mtot += 10**(par['A%d'%aa] + np.log10(mslist)) if lib_all: if aa == 0: nr = self.MB.lib_all[:, 0] xx = self.MB.lib_all[:, 1] # This is OBSERVED wavelength range at z=zgal yy = A00 * self.MB.lib_all[:, coln] else: yy += A00 * self.MB.lib_all[:, coln] else: if aa == 0: nr = self.MB.lib[:, 0] xx = self.MB.lib[:, 1] # This is OBSERVED wavelength range at z=zgal yy = A00 * self.MB.lib[:, coln] else: yy += A00 * self.MB.lib[:, coln] self.MB.logMtmp = np.log10(Mtot) if round(zmc,nprec) != round(self.MB.zgal,nprec): xx_s = xx / (1+self.MB.zgal) * (1+zmc) fint = interpolate.interp1d(xx, yy, kind='nearest', fill_value="extrapolate") yy_s = fint(xx_s) else: xx_s = xx yy_s = yy xx = xx_s yy = yy_s if self.dust_model == 0: yyd, xxd, nrd = dust_calz(xx/(1.+zmc), yy, Av00, nr) elif self.dust_model == 1: yyd, xxd, nrd = dust_mw(xx/(1.+zmc), yy, Av00, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.2) else: yyd, xxd, nrd = dust_calz(xx/(1.+zmc), yy, Av00, nr) xxd *= (1.+zmc) nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] nrd_yyd_sort = nrd_yyd[nrd_yyd[:,0].argsort()] if not f_nrd: return nrd_yyd_sort[:,1],nrd_yyd_sort[:,2] else: return nrd_yyd_sort[:,0],nrd_yyd_sort[:,1],nrd_yyd_sort[:,2] def tmp04_dust(self, par, nprec=1): ''' Makes model template with a given param setself. Also dust attenuation. ''' tau0= self.tau0 ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc DIR_TMP = self.MB.DIR_TMP try: m_dust = par['MDUST'] t_dust = par['TDUST'] except: # This is exception for initial minimizing; m_dust = -99 t_dust = 0 nr = self.MB.lib_dust[:,0] xx = self.MB.lib_dust[:,1] # This is OBSERVED wavelength range at z=zgal coln= 2+int(t_dust+0.5) yy = 10**m_dust * self.MB.lib_dust[:,coln] if self.MB.fzmc == 1: zmc = par.params['zmc'].value else: zmc = self.MB.zgal # How much does this cost in time? if round(zmc,nprec) != round(self.MB.zgal,nprec): xx_s = xx / (1+self.MB.zgal) * (1+zmc) fint = interpolate.interp1d(xx, yy, kind='nearest', fill_value="extrapolate") yy_s = fint(xx_s) else: xx_s = xx yy_s = yy return yy_s, xx_s class Func_tau: ''' ''' def __init__(self, MB, dust_model=0): ''' Parameters: ----------- dust_model : int 0 for Calzetti. 1 for MW. 4 for Kriek Conroy ''' self.MB = MB self.ID = MB.ID self.ZZ = MB.Zall self.AA = MB.nage self.tau = MB.tau self.dust_model = dust_model self.DIR_TMP = MB.DIR_TMP if MB.f_dust: self.Temp = MB.Temp try: self.filts = MB.filts self.DIR_FIL = MB.DIR_FILT except: pass # Already Read or not; self.f_af = False self.f_af0 = False def demo(self): ZZ = self.ZZ AA = self.AA return ZZ, AA def open_spec_fits(self, fall=0, orig=False): ''' Loads template in obs range. ''' ID0 = self.MB.ID from astropy.io import fits ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc # ASDF; if fall == 0: app = '' hdu0 = self.MB.af['spec'] elif fall == 1: app = 'all_' hdu0 = self.MB.af['spec_full'] DIR_TMP = self.DIR_TMP NZ = len(ZZ) NT = self.MB.ntau NA = self.MB.nage for zz,Z in enumerate(ZZ): for tt,TT in enumerate(self.MB.tau): for ss,TA in enumerate(self.MB.ageparam): if zz == 0 and tt == 0 and ss == 0: nr = hdu0['colnum'] xx = hdu0['wavelength'] coln = int(2 + NZ * NT * NA) # + self.MB.ntau * self.MB.nage + NA) lib = np.zeros((len(nr), coln), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] if orig: colname = 'fspec_orig_' + str(zz) + '_' + str(tt) + '_' + str(ss) else: colname = 'fspec_' + str(zz) + '_' + str(tt) + '_' + str(ss) colnall = int(2 + zz * NT * NA + tt * NA + ss) # 2 takes account of wavelength and AV columns. lib[:,colnall] = hdu0[colname] return lib def open_spec_dust_fits(self, fall=0): ''' Load dust template in obs range. ''' ID0 = self.MB.ID tau0= self.MB.tau0 #[0.01,0.02,0.03] from astropy.io import fits ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) self.MB.af = asdf.open(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf') self.MB.af0 = asdf.open(self.DIR_TMP + 'spec_all.asdf') if fall == 0: app = '' hdu0 = self.MB.af['spec_dust'] elif fall == 1: app = 'all_' hdu0 = self.MB.af['spec_dust_full'] DIR_TMP = self.DIR_TMP nr = hdu0['colnum'] xx = hdu0['wavelength'] lib = np.zeros((len(nr), 2+len(self.Temp)), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] for aa in range(len(self.Temp)): coln = int(2 + aa) colname = 'fspec_' + str(aa) colnall = int(2 + aa) # 2 takes account of wavelength and AV columns. lib[:,colnall] = hdu0[colname] if fall==1 and False: import matplotlib.pyplot as plt plt.close() plt.plot(lib[:,1],lib[:,coln],linestyle='-') plt.show() return lib def open_spec_fits_dir(self, nage, nz, kk, Av00, zgal, A00): ''' Loads template in obs range. But for weird template. ''' from astropy.io import fits tau0= self.tau0 #[0.01,0.02,0.03] ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc #Basic(ZZ) self.MB.af = asdf.open(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf') self.MB.af0 = asdf.open(self.DIR_TMP + 'spec_all.asdf') app = 'all' hdu0 = self.MB.af['spec_full'] DIR_TMP = self.DIR_TMP #'./templates/' pp = 0 zz = nz # Luminosity mshdu = self.MB.af0['ML'] Ls = mshdu['Ls_%d'%nz] xx = hdu0['wavelength'] # at RF; nr = np.arange(0,len(xx),1) #hdu0.data['colnum'] lib = np.zeros((len(nr), 2+1), dtype='float') lib[:,0] = nr[:] lib[:,1] = xx[:] aa = nage coln = int(2 + aa) colname = 'fspec_' + str(zz) + '_' + str(aa) + '_' + str(pp) yy0 = hdu0[colname]/Ls[aa] yy = flamtonu(xx, yy0) lib[:,2] = yy[:] if self.dust_model == 0: # Calzetti yyd, xxd, nrd = dust_calz(xx, yy, Av00, nr) elif self.dust_model == 1: # MW yyd, xxd, nrd = dust_mw(xx, yy, Av00, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx, yy, Av00, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx, yy, Av00, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx, yy, Av00, nr, Rv=4.05, gamma=-0.2) else: print('No entry. Dust model is set to Calzetti') yyd, xxd, nrd = dust_calz(xx, yy, Av00, nr) xxd *= (1.+zgal) nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] b = nrd_yyd nrd_yyd_sort = b[np.lexsort(([-1,1]*b[:,[1,0]]).T)] yyd_sort = nrd_yyd_sort[:,1] xxd_sort = nrd_yyd_sort[:,2] return A00 * yyd_sort, xxd_sort def tmp04(self, par, f_Alog=True, nprec=1, f_val=False, check_bound=False, lib_all=False, f_nrd=False): ''' Makes model template with a given param set. Also dust attenuation. Parameters: ----------- nprec : int Precision when redshift is refined. ''' ZZ = self.ZZ AA = self.AA bfnc = self.MB.bfnc Mtot = 0 pp = 0 if f_val: par = par.params if self.MB.fzmc == 1: try: zmc = par['zmc'].value except: zmc = self.MB.zgal else: zmc = self.MB.zgal if check_bound: # AV limit; if par['Av'] < self.MB.Avmin: par['Av'] = self.MB.Avmin if par['Av'] > self.MB.Avmax: par['Av'] = self.MB.Avmax Av00 = par['Av'] for aa in range(self.MB.npeak): if self.MB.ZEVOL==1 or aa == 0: if check_bound: # Z limit: if par['Z%d'%aa] < self.MB.Zmin: par['Z%d'%aa] = self.MB.Zmin if par['Z%d'%aa] > self.MB.Zmax: par['Z%d'%aa] = self.MB.Zmax Z = par['Z%d'%aa] else: pass if check_bound: # A if par['A'+str(aa)] < self.MB.Amin: par['A'+str(aa)] = self.MB.Amin if par['A'+str(aa)] > self.MB.Amax: par['A'+str(aa)] = self.MB.Amax if par['TAU'+str(aa)] < self.MB.taumin: par['TAU'+str(aa)] = self.MB.taumin if par['TAU'+str(aa)] > self.MB.taumax: par['TAU'+str(aa)] = self.MB.taumax if par['AGE'+str(aa)] < self.MB.agemin: par['AGE'+str(aa)] = self.MB.agemin if par['AGE'+str(aa)] > self.MB.agemax: par['AGE'+str(aa)] = self.MB.agemax # Is A in logspace? if f_Alog: A00 = 10**par['A'+str(aa)] else: A00 = par['A'+str(aa)] tau,age = par['TAU%d'%aa],par['AGE%d'%aa] NZ, NT, NA = bfnc.Z2NZ(Z,tau,age) coln = int(2 + NZ*self.MB.ntau*self.MB.nage + NT*self.MB.nage + NA) mslist = self.MB.af['ML']['ML_'+str(NZ)+'_'+str(NT)][NA] Mtot += 10**(par['A%d'%aa] + np.log10(mslist)) if lib_all: if aa == 0: nr = self.MB.lib_all[:, 0] xx = self.MB.lib_all[:, 1] # This is OBSERVED wavelength range at z=zgal yy = A00 * self.MB.lib_all[:, coln] else: yy += A00 * self.MB.lib_all[:, coln] else: if aa == 0: nr = self.MB.lib[:, 0] xx = self.MB.lib[:, 1] # This is OBSERVED wavelength range at z=zgal yy = A00 * self.MB.lib[:, coln] else: yy += A00 * self.MB.lib[:, coln] # Keep logM self.MB.logMtmp = np.log10(Mtot) # Redshift refinement; if round(zmc,nprec) != round(self.MB.zgal,nprec): # Not sure how much this costs in time. xx_s = xx / (1+self.MB.zgal) * (1+zmc) fint = interpolate.interp1d(xx, yy, kind='nearest', fill_value="extrapolate") yy_s = fint(xx_s) else: xx_s = xx yy_s = yy xx = xx_s yy = yy_s if self.dust_model == 0: yyd, xxd, nrd = dust_calz(xx/(1.+zmc), yy, Av00, nr) elif self.dust_model == 1: yyd, xxd, nrd = dust_mw(xx/(1.+zmc), yy, Av00, nr) elif self.dust_model == 2: # LMC yyd, xxd, nrd = dust_gen(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.06, Eb=2.8) elif self.dust_model == 3: # SMC yyd, xxd, nrd = dust_gen(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.42, Eb=0.0) elif self.dust_model == 4: # Kriek&Conroy with gamma=-0.2 yyd, xxd, nrd = dust_kc(xx/(1.+zmc), yy, Av00, nr, Rv=4.05, gamma=-0.2) else: yyd, xxd, nrd = dust_calz(xx/(1.+zmc), yy, Av00, nr) xxd *= (1.+zmc) if self.dust_model == 0: if not f_nrd: return yyd,xxd else: return nrd,yyd,xxd else: nrd_yyd = np.zeros((len(nrd),3), dtype='float') nrd_yyd[:,0] = nrd[:] nrd_yyd[:,1] = yyd[:] nrd_yyd[:,2] = xxd[:] nrd_yyd_sort = nrd_yyd[nrd_yyd[:,0].argsort()] if not f_nrd: return nrd_yyd_sort[:,1],nrd_yyd_sort[:,2] else: return nrd_yyd_sort[:,0],nrd_yyd_sort[:,1],nrd_yyd_sort[:,2] def tmp04_dust(self, par, nprec=1): ''' Makes model template with a given param setself. Also dust attenuation. ''' bfnc = self.MB.bfnc #Basic(ZZ) DIR_TMP = self.MB.DIR_TMP #'./templates/' try: m_dust = par['MDUST'] t_dust = par['TDUST'] except: # This is exception for initial minimizing; m_dust = -99 t_dust = 0 nr = self.MB.lib_dust[:,0] xx = self.MB.lib_dust[:,1] # This is OBSERVED wavelength range at z=zgal coln= 2+int(t_dust+0.5) yy = 10**m_dust * self.MB.lib_dust[:,coln] if self.MB.fzmc == 1: zmc = par.params['zmc'].value else: zmc = self.MB.zgal # How much does this cost in time? if round(zmc,nprec) != round(self.MB.zgal,nprec): xx_s = xx / (1+self.MB.zgal) * (1+zmc) fint = interpolate.interp1d(xx, yy, kind='nearest', fill_value="extrapolate") yy_s = fint(xx_s) else: xx_s = xx yy_s = yy return yy_s, xx_s
[ "numpy.abs", "numpy.log10", "matplotlib.pyplot.plot", "scipy.interpolate.interp1d", "matplotlib.pyplot.close", "numpy.lexsort", "asdf.open", "matplotlib.pyplot.show" ]
[((2825, 2882), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')"], {}), "(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')\n", (2834, 2882), False, 'import asdf\n'), ((2905, 2946), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all.asdf')"], {}), "(self.DIR_TMP + 'spec_all.asdf')\n", (2914, 2946), False, 'import asdf\n'), ((4146, 4203), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')"], {}), "(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')\n", (4155, 4203), False, 'import asdf\n'), ((4226, 4267), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all.asdf')"], {}), "(self.DIR_TMP + 'spec_all.asdf')\n", (4235, 4267), False, 'import asdf\n'), ((13083, 13097), 'numpy.log10', 'np.log10', (['Mtot'], {}), '(Mtot)\n', (13091, 13097), True, 'import numpy as np\n'), ((18228, 18285), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')"], {}), "(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')\n", (18237, 18285), False, 'import asdf\n'), ((18308, 18349), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all.asdf')"], {}), "(self.DIR_TMP + 'spec_all.asdf')\n", (18317, 18349), False, 'import asdf\n'), ((19549, 19606), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')"], {}), "(self.DIR_TMP + 'spec_all_' + self.ID + '.asdf')\n", (19558, 19606), False, 'import asdf\n'), ((19629, 19670), 'asdf.open', 'asdf.open', (["(self.DIR_TMP + 'spec_all.asdf')"], {}), "(self.DIR_TMP + 'spec_all.asdf')\n", (19638, 19670), False, 'import asdf\n'), ((24598, 24612), 'numpy.log10', 'np.log10', (['Mtot'], {}), '(Mtot)\n', (24606, 24612), True, 'import numpy as np\n'), ((5848, 5886), 'numpy.lexsort', 'np.lexsort', (['([-1, 1] * b[:, [1, 0]]).T'], {}), '(([-1, 1] * b[:, [1, 0]]).T)\n', (5858, 5886), True, 'import numpy as np\n'), ((7152, 7175), 'numpy.abs', 'np.abs', (['(T - self.age[:])'], {}), '(T - self.age[:])\n', (7158, 7175), True, 'import numpy as np\n'), ((8417, 8455), 'numpy.lexsort', 'np.lexsort', (['([-1, 1] * b[:, [1, 0]]).T'], {}), '(([-1, 1] * b[:, [1, 0]]).T)\n', (8427, 8455), True, 'import numpy as np\n'), ((10371, 10409), 'numpy.lexsort', 'np.lexsort', (['([-1, 1] * b[:, [1, 0]]).T'], {}), '(([-1, 1] * b[:, [1, 0]]).T)\n', (10381, 10409), True, 'import numpy as np\n'), ((13227, 13297), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['xx', 'yy'], {'kind': '"""nearest"""', 'fill_value': '"""extrapolate"""'}), "(xx, yy, kind='nearest', fill_value='extrapolate')\n", (13247, 13297), True, 'import scipy.interpolate as interpolate\n'), ((15470, 15540), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['xx', 'yy'], {'kind': '"""nearest"""', 'fill_value': '"""extrapolate"""'}), "(xx, yy, kind='nearest', fill_value='extrapolate')\n", (15490, 15540), True, 'import scipy.interpolate as interpolate\n'), ((21246, 21284), 'numpy.lexsort', 'np.lexsort', (['([-1, 1] * b[:, [1, 0]]).T'], {}), '(([-1, 1] * b[:, [1, 0]]).T)\n', (21256, 21284), True, 'import numpy as np\n'), ((24813, 24883), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['xx', 'yy'], {'kind': '"""nearest"""', 'fill_value': '"""extrapolate"""'}), "(xx, yy, kind='nearest', fill_value='extrapolate')\n", (24833, 24883), True, 'import scipy.interpolate as interpolate\n'), ((27211, 27281), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['xx', 'yy'], {'kind': '"""nearest"""', 'fill_value': '"""extrapolate"""'}), "(xx, yy, kind='nearest', fill_value='extrapolate')\n", (27231, 27281), True, 'import scipy.interpolate as interpolate\n'), ((3687, 3698), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3696, 3698), True, 'import matplotlib.pyplot as plt\n'), ((3715, 3763), 'matplotlib.pyplot.plot', 'plt.plot', (['lib[:, 1]', 'lib[:, coln]'], {'linestyle': '"""-"""'}), "(lib[:, 1], lib[:, coln], linestyle='-')\n", (3723, 3763), True, 'import matplotlib.pyplot as plt\n'), ((3776, 3786), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3784, 3786), True, 'import matplotlib.pyplot as plt\n'), ((19090, 19101), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (19099, 19101), True, 'import matplotlib.pyplot as plt\n'), ((19118, 19166), 'matplotlib.pyplot.plot', 'plt.plot', (['lib[:, 1]', 'lib[:, coln]'], {'linestyle': '"""-"""'}), "(lib[:, 1], lib[:, coln], linestyle='-')\n", (19126, 19166), True, 'import matplotlib.pyplot as plt\n'), ((19179, 19189), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19187, 19189), True, 'import matplotlib.pyplot as plt\n'), ((12397, 12413), 'numpy.log10', 'np.log10', (['mslist'], {}), '(mslist)\n', (12405, 12413), True, 'import numpy as np\n'), ((23900, 23916), 'numpy.log10', 'np.log10', (['mslist'], {}), '(mslist)\n', (23908, 23916), True, 'import numpy as np\n')]
import numpy as np import torch from torch import optim from torch.nn import functional import torch.nn as nn import torch.utils.data from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,Sigmoid from torch.nn import functional as F from opendp.smartnoise.synthesizers.base import SDGYMBaseSynthesizer import ctgan from ctgan.transformer import DataTransformer from ctgan.conditional import ConditionalGenerator from ctgan.models import Generator from ctgan.sampler import Sampler from ctgan import CTGANSynthesizer import opacus from opacus import autograd_grad_sample from opacus import PrivacyEngine, utils class Discriminator(Module): def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10): alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device) alpha = alpha.repeat(1, pac, real_data.size(1)) alpha = alpha.view(-1, real_data.size(1)) interpolates = alpha * real_data + ((1 - alpha) * fake_data) disc_interpolates = self(interpolates) gradients = torch.autograd.grad( outputs=disc_interpolates, inputs=interpolates, grad_outputs=torch.ones(disc_interpolates.size(), device=device), create_graph=True, retain_graph=True, only_inputs=True )[0] gradient_penalty = (( gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1 ) ** 2).mean() * lambda_ return gradient_penalty def __init__(self, input_dim, dis_dims, loss, pack): super(Discriminator, self).__init__() torch.cuda.manual_seed(0) torch.manual_seed(0) dim = input_dim * pack # print ('now dim is {}'.format(dim)) self.pack = pack self.packdim = dim seq = [] for item in list(dis_dims): seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(0.5)] dim = item seq += [Linear(dim, 1)] if loss == 'cross_entropy': seq += [Sigmoid()] self.seq = Sequential(*seq) def forward(self, input): assert input.size()[0] % self.pack == 0 return self.seq(input.view(-1, self.packdim)) # custom for calcuate grad_sample for multiple loss.backward() def _custom_create_or_extend_grad_sample( param: torch.Tensor, grad_sample: torch.Tensor, batch_dim: int ) -> None: """ Create a 'grad_sample' attribute in the given parameter, or accumulate it if the 'grad_sample' attribute already exists. This custom code will not work when using optimizer.virtual_step() """ #print ("now this happen") if hasattr(param, "grad_sample"): param.grad_sample = param.grad_sample + grad_sample #param.grad_sample = torch.cat((param.grad_sample, grad_sample), batch_dim) else: param.grad_sample = grad_sample class DPCTGAN(CTGANSynthesizer): """Differential Private Conditional Table GAN Synthesizer This code adds Differential Privacy to CTGANSynthesizer from https://github.com/sdv-dev/CTGAN """ def __init__(self, embedding_dim=128, gen_dim=(256, 256), dis_dim=(256, 256), l2scale=1e-6, batch_size=500, epochs=300, pack=1, log_frequency=True, disabled_dp=False, target_delta=None, sigma = 5, max_per_sample_grad_norm=1.0, epsilon = 1, verbose=True, loss = 'cross_entropy'): # CTGAN model specific parameters self.embedding_dim = embedding_dim self.gen_dim = gen_dim self.dis_dim = dis_dim self.l2scale = l2scale self.batch_size = batch_size self.epochs = epochs self.pack=pack self.log_frequency = log_frequency self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # opacus parameters self.sigma = sigma self.disabled_dp = disabled_dp self.target_delta = target_delta self.max_per_sample_grad_norm = max_per_sample_grad_norm self.epsilon = epsilon self.epsilon_list = [] self.alpha_list = [] self.loss_d_list = [] self.loss_g_list = [] self.verbose=verbose self.loss=loss if self.loss != "cross_entropy": # Monkeypatches the _create_or_extend_grad_sample function when calling opacus opacus.supported_layers_grad_samplers._create_or_extend_grad_sample = _custom_create_or_extend_grad_sample def train(self, data, categorical_columns=None, ordinal_columns=None, update_epsilon=None): if update_epsilon: self.epsilon = update_epsilon self.transformer = DataTransformer() self.transformer.fit(data, discrete_columns=categorical_columns) train_data = self.transformer.transform(data) data_sampler = Sampler(train_data, self.transformer.output_info) data_dim = self.transformer.output_dimensions self.cond_generator = ConditionalGenerator(train_data, self.transformer.output_info, self.log_frequency) self.generator = Generator( self.embedding_dim + self.cond_generator.n_opt, self.gen_dim, data_dim).to(self.device) discriminator = Discriminator( data_dim + self.cond_generator.n_opt, self.dis_dim, self.loss, self.pack).to(self.device) optimizerG = optim.Adam( self.generator.parameters(), lr=2e-4, betas=(0.5, 0.9), weight_decay=self.l2scale) optimizerD = optim.Adam(discriminator.parameters(), lr=2e-4, betas=(0.5, 0.9)) privacy_engine = opacus.PrivacyEngine( discriminator, batch_size=self.batch_size, sample_size=train_data.shape[0], alphas=[1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64)), noise_multiplier=self.sigma, max_grad_norm=self.max_per_sample_grad_norm, clip_per_layer=True ) if not self.disabled_dp: privacy_engine.attach(optimizerD) one = torch.tensor(1, dtype=torch.float).to(self.device) mone = one * -1 REAL_LABEL = 1 FAKE_LABEL = 0 criterion = nn.BCELoss() assert self.batch_size % 2 == 0 mean = torch.zeros(self.batch_size, self.embedding_dim, device=self.device) std = mean + 1 steps_per_epoch = len(train_data) // self.batch_size for i in range(self.epochs): for id_ in range(steps_per_epoch): fakez = torch.normal(mean=mean, std=std) condvec = self.cond_generator.sample(self.batch_size) if condvec is None: c1, m1, col, opt = None, None, None, None real = data_sampler.sample(self.batch_size, col, opt) else: c1, m1, col, opt = condvec c1 = torch.from_numpy(c1).to(self.device) m1 = torch.from_numpy(m1).to(self.device) fakez = torch.cat([fakez, c1], dim=1) perm = np.arange(self.batch_size) np.random.shuffle(perm) real = data_sampler.sample(self.batch_size, col[perm], opt[perm]) c2 = c1[perm] fake = self.generator(fakez) fakeact = self._apply_activate(fake) real = torch.from_numpy(real.astype('float32')).to(self.device) if c1 is not None: fake_cat = torch.cat([fakeact, c1], dim=1) real_cat = torch.cat([real, c2], dim=1) else: real_cat = real fake_cat = fake optimizerD.zero_grad() if self.loss == 'cross_entropy': y_fake = discriminator(fake_cat) # print ('y_fake is {}'.format(y_fake)) label_fake = torch.full((int(self.batch_size/self.pack),), FAKE_LABEL, dtype=torch.float, device=self.device) # print ('label_fake is {}'.format(label_fake)) errD_fake = criterion(y_fake, label_fake) errD_fake.backward() optimizerD.step() # train with real label_true = torch.full((int(self.batch_size/self.pack),), REAL_LABEL, dtype=torch.float, device=self.device) y_real = discriminator(real_cat) errD_real = criterion(y_real, label_true) errD_real.backward() optimizerD.step() loss_d = errD_real + errD_fake else: y_fake = discriminator(fake_cat) mean_fake = torch.mean(y_fake) mean_fake.backward(one) y_real = discriminator(real_cat) mean_real = torch.mean(y_real) mean_real.backward(mone) optimizerD.step() loss_d = -(mean_real - mean_fake) max_grad_norm = [] for p in discriminator.parameters(): param_norm = p.grad.data.norm(2).item() max_grad_norm.append(param_norm) #pen = calc_gradient_penalty(discriminator, real_cat, fake_cat, self.device) #pen.backward(retain_graph=True) #loss_d.backward() #optimizerD.step() fakez = torch.normal(mean=mean, std=std) condvec = self.cond_generator.sample(self.batch_size) if condvec is None: c1, m1, col, opt = None, None, None, None else: c1, m1, col, opt = condvec c1 = torch.from_numpy(c1).to(self.device) m1 = torch.from_numpy(m1).to(self.device) fakez = torch.cat([fakez, c1], dim=1) fake = self.generator(fakez) fakeact = self._apply_activate(fake) if c1 is not None: y_fake = discriminator(torch.cat([fakeact, c1], dim=1)) else: y_fake = discriminator(fakeact) #if condvec is None: cross_entropy = 0 #else: # cross_entropy = self._cond_loss(fake, c1, m1) if self.loss=='cross_entropy': label_g = torch.full((int(self.batch_size/self.pack),), REAL_LABEL, dtype=torch.float, device=self.device) #label_g = torch.full(int(self.batch_size/self.pack,),1,device=self.device) loss_g = criterion(y_fake, label_g) loss_g = loss_g + cross_entropy else: loss_g = -torch.mean(y_fake) + cross_entropy optimizerG.zero_grad() loss_g.backward() optimizerG.step() if not self.disabled_dp: #if self.loss == 'cross_entropy': # autograd_grad_sample.clear_backprops(discriminator) #else: for p in discriminator.parameters(): if hasattr(p, "grad_sample"): del p.grad_sample if self.target_delta is None: self.target_delta = 1/train_data.shape[0] epsilon, best_alpha = optimizerD.privacy_engine.get_privacy_spent(self.target_delta) self.epsilon_list.append(epsilon) self.alpha_list.append(best_alpha) #if self.verbose: if not self.disabled_dp: if self.epsilon < epsilon: break self.loss_d_list.append(loss_d) self.loss_g_list.append(loss_g) if self.verbose: print("Epoch %d, Loss G: %.4f, Loss D: %.4f" % (i + 1, loss_g.detach().cpu(), loss_d.detach().cpu()), flush=True) print ('epsilon is {e}, alpha is {a}'.format(e=epsilon, a = best_alpha)) return self.loss_d_list, self.loss_g_list, self.epsilon_list, self.alpha_list def generate(self, n): self.generator.eval() #output_info = self.transformer.output_info steps = n // self.batch_size + 1 data = [] for i in range(steps): mean = torch.zeros(self.batch_size, self.embedding_dim) std = mean + 1 fakez = torch.normal(mean=mean, std=std).to(self.device) condvec = self.cond_generator.sample_zero(self.batch_size) if condvec is None: pass else: c1 = condvec c1 = torch.from_numpy(c1).to(self.device) fakez = torch.cat([fakez, c1], dim=1) fake = self.generator(fakez) fakeact = self._apply_activate(fake) data.append(fakeact.detach().cpu().numpy()) data = np.concatenate(data, axis=0) data = data[:n] return self.transformer.inverse_transform(data, None)
[ "ctgan.models.Generator", "torch.nn.Dropout", "torch.nn.Sequential", "ctgan.sampler.Sampler", "torch.from_numpy", "ctgan.conditional.ConditionalGenerator", "torch.cuda.is_available", "torch.normal", "numpy.arange", "torch.nn.Sigmoid", "torch.mean", "numpy.concatenate", "torch.nn.LeakyReLU", "ctgan.transformer.DataTransformer", "torch.cat", "torch.manual_seed", "torch.tensor", "torch.nn.BCELoss", "torch.nn.Linear", "torch.cuda.manual_seed", "torch.zeros", "numpy.random.shuffle" ]
[((1613, 1638), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(0)'], {}), '(0)\n', (1635, 1638), False, 'import torch\n'), ((1647, 1667), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (1664, 1667), False, 'import torch\n'), ((2061, 2077), 'torch.nn.Sequential', 'Sequential', (['*seq'], {}), '(*seq)\n', (2071, 2077), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((4866, 4883), 'ctgan.transformer.DataTransformer', 'DataTransformer', ([], {}), '()\n', (4881, 4883), False, 'from ctgan.transformer import DataTransformer\n'), ((5035, 5084), 'ctgan.sampler.Sampler', 'Sampler', (['train_data', 'self.transformer.output_info'], {}), '(train_data, self.transformer.output_info)\n', (5042, 5084), False, 'from ctgan.sampler import Sampler\n'), ((5170, 5257), 'ctgan.conditional.ConditionalGenerator', 'ConditionalGenerator', (['train_data', 'self.transformer.output_info', 'self.log_frequency'], {}), '(train_data, self.transformer.output_info, self.\n log_frequency)\n', (5190, 5257), False, 'from ctgan.conditional import ConditionalGenerator\n'), ((6425, 6437), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6435, 6437), True, 'import torch.nn as nn\n'), ((6494, 6562), 'torch.zeros', 'torch.zeros', (['self.batch_size', 'self.embedding_dim'], {'device': 'self.device'}), '(self.batch_size, self.embedding_dim, device=self.device)\n', (6505, 6562), False, 'import torch\n'), ((13355, 13383), 'numpy.concatenate', 'np.concatenate', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (13369, 13383), True, 'import numpy as np\n'), ((1959, 1973), 'torch.nn.Linear', 'Linear', (['dim', '(1)'], {}), '(dim, 1)\n', (1965, 1973), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((12763, 12811), 'torch.zeros', 'torch.zeros', (['self.batch_size', 'self.embedding_dim'], {}), '(self.batch_size, self.embedding_dim)\n', (12774, 12811), False, 'import torch\n'), ((1870, 1887), 'torch.nn.Linear', 'Linear', (['dim', 'item'], {}), '(dim, item)\n', (1876, 1887), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((1889, 1903), 'torch.nn.LeakyReLU', 'LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (1898, 1903), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((1905, 1917), 'torch.nn.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1912, 1917), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((2031, 2040), 'torch.nn.Sigmoid', 'Sigmoid', ([], {}), '()\n', (2038, 2040), False, 'from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, Sigmoid\n'), ((3978, 4003), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4001, 4003), False, 'import torch\n'), ((5279, 5364), 'ctgan.models.Generator', 'Generator', (['(self.embedding_dim + self.cond_generator.n_opt)', 'self.gen_dim', 'data_dim'], {}), '(self.embedding_dim + self.cond_generator.n_opt, self.gen_dim,\n data_dim)\n', (5288, 5364), False, 'from ctgan.models import Generator\n'), ((6283, 6317), 'torch.tensor', 'torch.tensor', (['(1)'], {'dtype': 'torch.float'}), '(1, dtype=torch.float)\n', (6295, 6317), False, 'import torch\n'), ((6756, 6788), 'torch.normal', 'torch.normal', ([], {'mean': 'mean', 'std': 'std'}), '(mean=mean, std=std)\n', (6768, 6788), False, 'import torch\n'), ((9753, 9785), 'torch.normal', 'torch.normal', ([], {'mean': 'mean', 'std': 'std'}), '(mean=mean, std=std)\n', (9765, 9785), False, 'import torch\n'), ((13162, 13191), 'torch.cat', 'torch.cat', (['[fakez, c1]'], {'dim': '(1)'}), '([fakez, c1], dim=1)\n', (13171, 13191), False, 'import torch\n'), ((7253, 7282), 'torch.cat', 'torch.cat', (['[fakez, c1]'], {'dim': '(1)'}), '([fakez, c1], dim=1)\n', (7262, 7282), False, 'import torch\n'), ((7311, 7337), 'numpy.arange', 'np.arange', (['self.batch_size'], {}), '(self.batch_size)\n', (7320, 7337), True, 'import numpy as np\n'), ((7358, 7381), 'numpy.random.shuffle', 'np.random.shuffle', (['perm'], {}), '(perm)\n', (7375, 7381), True, 'import numpy as np\n'), ((7749, 7780), 'torch.cat', 'torch.cat', (['[fakeact, c1]'], {'dim': '(1)'}), '([fakeact, c1], dim=1)\n', (7758, 7780), False, 'import torch\n'), ((7812, 7840), 'torch.cat', 'torch.cat', (['[real, c2]'], {'dim': '(1)'}), '([real, c2], dim=1)\n', (7821, 7840), False, 'import torch\n'), ((9003, 9021), 'torch.mean', 'torch.mean', (['y_fake'], {}), '(y_fake)\n', (9013, 9021), False, 'import torch\n'), ((9153, 9171), 'torch.mean', 'torch.mean', (['y_real'], {}), '(y_real)\n', (9163, 9171), False, 'import torch\n'), ((10176, 10205), 'torch.cat', 'torch.cat', (['[fakez, c1]'], {'dim': '(1)'}), '([fakez, c1], dim=1)\n', (10185, 10205), False, 'import torch\n'), ((12859, 12891), 'torch.normal', 'torch.normal', ([], {'mean': 'mean', 'std': 'std'}), '(mean=mean, std=std)\n', (12871, 12891), False, 'import torch\n'), ((10384, 10415), 'torch.cat', 'torch.cat', (['[fakeact, c1]'], {'dim': '(1)'}), '([fakeact, c1], dim=1)\n', (10393, 10415), False, 'import torch\n'), ((13101, 13121), 'torch.from_numpy', 'torch.from_numpy', (['c1'], {}), '(c1)\n', (13117, 13121), False, 'import torch\n'), ((7126, 7146), 'torch.from_numpy', 'torch.from_numpy', (['c1'], {}), '(c1)\n', (7142, 7146), False, 'import torch\n'), ((7188, 7208), 'torch.from_numpy', 'torch.from_numpy', (['m1'], {}), '(m1)\n', (7204, 7208), False, 'import torch\n'), ((10049, 10069), 'torch.from_numpy', 'torch.from_numpy', (['c1'], {}), '(c1)\n', (10065, 10069), False, 'import torch\n'), ((10111, 10131), 'torch.from_numpy', 'torch.from_numpy', (['m1'], {}), '(m1)\n', (10127, 10131), False, 'import torch\n'), ((11104, 11122), 'torch.mean', 'torch.mean', (['y_fake'], {}), '(y_fake)\n', (11114, 11122), False, 'import torch\n')]
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: <NAME> ## Email: <EMAIL> ## Copyright (c) 2020 ## ## LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """ResNet variants""" import os import math import torch import numpy as np import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F from models.attention_map import SEModule, SpatialCGNL, SAModule from models.feature_extraction.splat import SplAtConv2d from models.utils import gen_adj_num, gen_adj from models.common import conv1x1 _url_format = 'https://hangzh.s3.amazonaws.com/encoding/models/{}-{}.pth' _model_sha256 = {name: checksum for checksum, name in [('528c19ca', 'resnest50'), ('22405ba7', 'resnest101'), ('75117900', 'resnest200'), ('0cc87c48', 'resnest269'), ]} def short_hash(name): if name not in _model_sha256: raise ValueError('Pretrained model for {name} is not available.'.format(name=name)) return _model_sha256[name][:8] resnest_model_urls = {name: _url_format.format(name, short_hash(name)) for name in _model_sha256.keys()} __all__ = ['ResNet', 'Bottleneck'] class DropBlock2D(object): def __init__(self, *args, **kwargs): raise NotImplementedError class Bottleneck(nn.Module): """ResNet Bottleneck """ # pylint: disable=unused-argument expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, radix=1, cardinality=1, bottleneck_width=64, avd=False, avd_first=False, dilation=1, is_first=False, rectified_conv=False, rectify_avg=False, norm_layer=None, dropblock_prob=0.0, last_gamma=False, use_se=False): super(Bottleneck, self).__init__() group_width = int(planes * (bottleneck_width / 64.)) * cardinality self.conv1 = nn.Conv2d(inplanes, group_width, kernel_size=1, bias=False) self.bn1 = norm_layer(group_width) self.dropblock_prob = dropblock_prob self.radix = radix self.avd = avd and (stride > 1 or is_first) self.avd_first = avd_first if self.avd: self.avd_layer = nn.AvgPool2d(3, stride, padding=1) stride = 1 if dropblock_prob > 0.0: self.dropblock1 = DropBlock2D(dropblock_prob, 3) if radix == 1: self.dropblock2 = DropBlock2D(dropblock_prob, 3) self.dropblock3 = DropBlock2D(dropblock_prob, 3) if radix >= 1: self.conv2 = SplAtConv2d(group_width, group_width, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, groups=cardinality, bias=False, radix=radix, rectify=rectified_conv, rectify_avg=rectify_avg, norm_layer=norm_layer, dropblock_prob=dropblock_prob) elif rectified_conv: from rfconv import RFConv2d self.conv2 = RFConv2d(group_width, group_width, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, groups=cardinality, bias=False, average_mode=rectify_avg) self.bn2 = norm_layer(group_width) else: self.conv2 = nn.Conv2d(group_width, group_width, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, groups=cardinality, bias=False) self.bn2 = norm_layer(group_width) self.conv3 = nn.Conv2d(group_width, planes * 4, kernel_size=1, bias=False) self.bn3 = norm_layer(planes * 4) if last_gamma: from torch.nn.init import zeros_ zeros_(self.bn3.weight) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.dilation = dilation self.stride = stride self.use_se = use_se if use_se: self.se = SEModule(planes * 4) def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) if self.dropblock_prob > 0.0: out = self.dropblock1(out) out = self.relu(out) if self.avd and self.avd_first: out = self.avd_layer(out) out = self.conv2(out) if self.radix == 0: out = self.bn2(out) if self.dropblock_prob > 0.0: out = self.dropblock2(out) out = self.relu(out) if self.avd and not self.avd_first: out = self.avd_layer(out) out = self.conv3(out) out = self.bn3(out) if self.dropblock_prob > 0.0: out = self.dropblock3(out) if self.downsample is not None: residual = self.downsample(x) if self.use_se: out = self.se(out) + residual else: out += residual out = self.relu(out) return out class ResNet(nn.Module): """ResNet Variants Parameters ---------- block : Block Class for the residual block. Options are BasicBlockV1, BottleneckV1. layers : list of int Numbers of layers in each block classes : int, default 1000 Number of classification classes. dilated : bool, default False Applying dilation strategy to pretrained ResNet yielding a stride-8 model, typically used in Semantic Segmentation. norm_layer : object Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`; for Synchronized Cross-GPU BachNormalization). Reference: - <NAME>, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016. - <NAME>, and <NAME>. "Multi-scale context aggregation by dilated convolutions." """ # pylint: disable=unused-variable def __init__(self, block, layers, radix=1, groups=1, bottleneck_width=64, num_classes=1000, dilated=False, dilation=1, deep_stem=False, stem_width=64, avg_down=False, rectified_conv=False, rectify_avg=False, avd=False, avd_first=False, final_drop=0.0, dropblock_prob=0, last_gamma=False, use_se=False, in_channels=300, word_file='/workspace/Projects/cxr/models/feature_extraction/diseases_embeddings.npy', # word_file='diseases_embeddings.npy', # word_file='/home/hoangvu/Projects/cxr/models/feature_extraction/diseases_embeddings.npy', extract_fields='0,1,2,3,4,5', agree_rate=0.5, csv_path='', norm_layer=nn.BatchNorm2d): self.cardinality = groups self.bottleneck_width = bottleneck_width # ResNet-D params self.inplanes = stem_width * 2 if deep_stem else 64 self.avg_down = avg_down self.last_gamma = last_gamma # ResNeSt params self.radix = radix self.avd = avd self.avd_first = avd_first self.use_se = use_se super(ResNet, self).__init__() self.rectified_conv = rectified_conv self.rectify_avg = rectify_avg if rectified_conv: from rfconv import RFConv2d conv_layer = RFConv2d else: conv_layer = nn.Conv2d conv_kwargs = {'average_mode': rectify_avg} if rectified_conv else {} if deep_stem: self.conv1 = nn.Sequential( conv_layer(3, stem_width, kernel_size=3, stride=2, padding=1, bias=False, **conv_kwargs), norm_layer(stem_width), nn.ReLU(inplace=True), conv_layer(stem_width, stem_width, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs), norm_layer(stem_width), nn.ReLU(inplace=True), conv_layer(stem_width, stem_width * 2, kernel_size=3, stride=1, padding=1, bias=False, **conv_kwargs), ) else: self.conv1 = conv_layer(3, 64, kernel_size=7, stride=2, padding=3, bias=False, **conv_kwargs) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0], norm_layer=norm_layer, is_first=False) self.layer2 = self._make_layer(block, 128, layers[1], stride=2, norm_layer=norm_layer) if dilated or dilation == 4: self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2, norm_layer=norm_layer, dropblock_prob=dropblock_prob) self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4, norm_layer=norm_layer, dropblock_prob=dropblock_prob) elif dilation == 2: self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilation=1, norm_layer=norm_layer, dropblock_prob=dropblock_prob) self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=2, norm_layer=norm_layer, dropblock_prob=dropblock_prob) else: self.layer3 = self._make_layer(block, 256, layers[2], stride=2, norm_layer=norm_layer, dropblock_prob=dropblock_prob) self.layer4 = self._make_layer(block, 512, layers[3], stride=2, norm_layer=norm_layer, dropblock_prob=dropblock_prob) self.global_pool = nn.AdaptiveAvgPool2d((1, 1)) self.drop = nn.Dropout(final_drop) if final_drop > 0.0 else None # self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, norm_layer): m.weight.data.fill_(1) m.bias.data.zero_() num_classes = len(extract_fields.split(',')) _adj = gen_adj_num(labels=extract_fields, agree_rate=agree_rate, csv_path=csv_path) self.adj = Parameter(torch.from_numpy(_adj).float()) if not os.path.exists(word_file): word = np.random.randn(num_classes, 300) print('graph input: random') else: with open(word_file, 'rb') as point: word = np.load(point) print('graph input: loaded from {}'.format(word_file)) self.word = Parameter(torch.from_numpy(word).float()) self.gc0 = GraphConvolution(in_channels, 128, bias=True) self.gc1 = GraphConvolution(128, 256, bias=True) self.gc2 = GraphConvolution(256, 512, bias=True) self.gc3 = GraphConvolution(512, 1024, bias=True) self.gc4 = GraphConvolution(1024, 2048, bias=True) self.gc_relu = nn.LeakyReLU(0.2) self.gc_tanh = nn.Tanh() self.merge_conv0 = nn.Conv2d(num_classes, 128, kernel_size=1, stride=1, bias=False) self.merge_conv1 = nn.Conv2d(num_classes, 256, kernel_size=1, stride=1, bias=False) self.merge_conv2 = nn.Conv2d(num_classes, 512, kernel_size=1, stride=1, bias=False) self.merge_conv3 = nn.Conv2d(num_classes, 1024, kernel_size=1, stride=1, bias=False) self.conv1x1 = conv1x1(in_channels=2048, out_channels=num_classes, bias=True) # self.spatial_attention = SAModule(2048) # self.spatial_attention = SpatialCGNL(2048, 1024) def _make_layer(self, block, planes, blocks, stride=1, dilation=1, norm_layer=None, dropblock_prob=0.0, is_first=True): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: down_layers = [] if self.avg_down: if dilation == 1: down_layers.append( nn.AvgPool2d(kernel_size=stride, stride=stride, ceil_mode=True, count_include_pad=False)) else: down_layers.append(nn.AvgPool2d(kernel_size=1, stride=1, ceil_mode=True, count_include_pad=False)) down_layers.append( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=1, bias=False)) else: down_layers.append( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False)) down_layers.append(norm_layer(planes * block.expansion)) downsample = nn.Sequential(*down_layers) layers = [] if dilation == 1 or dilation == 2: layers.append( block(self.inplanes, planes, stride, downsample=downsample, radix=self.radix, cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd, avd_first=self.avd_first, dilation=1, is_first=is_first, rectified_conv=self.rectified_conv, rectify_avg=self.rectify_avg, norm_layer=norm_layer, dropblock_prob=dropblock_prob, last_gamma=self.last_gamma, use_se=self.use_se)) elif dilation == 4: layers.append( block(self.inplanes, planes, stride, downsample=downsample, radix=self.radix, cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd, avd_first=self.avd_first, dilation=2, is_first=is_first, rectified_conv=self.rectified_conv, rectify_avg=self.rectify_avg, norm_layer=norm_layer, dropblock_prob=dropblock_prob, last_gamma=self.last_gamma, use_se=self.use_se)) else: raise RuntimeError("=> unknown dilation size: {}".format(dilation)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append( block(self.inplanes, planes, radix=self.radix, cardinality=self.cardinality, bottleneck_width=self.bottleneck_width, avd=self.avd, avd_first=self.avd_first, dilation=dilation, rectified_conv=self.rectified_conv, rectify_avg=self.rectify_avg, norm_layer=norm_layer, dropblock_prob=dropblock_prob, last_gamma=self.last_gamma, use_se=self.use_se)) return nn.Sequential(*layers) def forward(self, feature): adj = gen_adj(self.adj).detach() word = self.word.detach() feature = self.conv1(feature) feature = self.bn1(feature) feature = self.relu(feature) feature = self.maxpool(feature) x_raw = self.gc0(word, adj) x = self.gc_tanh(x_raw) feature = merge_gcn_residual(feature, x, self.merge_conv0) feature = self.layer1(feature) x = self.gc_relu(x_raw) x_raw = self.gc1(x, adj) x = self.gc_tanh(x_raw) feature = merge_gcn_residual(feature, x, self.merge_conv1) feature = self.layer2(feature) x = self.gc_relu(x_raw) x_raw = self.gc2(x, adj) x = self.gc_tanh(x_raw) feature = merge_gcn_residual(feature, x, self.merge_conv2) feature = self.layer3(feature) x = self.gc_relu(x_raw) x_raw = self.gc3(x, adj) x = self.gc_tanh(x_raw) feature = merge_gcn_residual(feature, x, self.merge_conv3) feature = self.layer4(feature) # feature = self.spatial_attention(feature) feature_raw = self.global_pool(feature) if self.drop is not None: feature_raw = self.drop(feature_raw) feature = feature_raw.view(feature_raw.size(0), -1) x = self.gc_relu(x_raw) x = self.gc4(x, adj) x = self.gc_tanh(x) x = x.transpose(0, 1) x = torch.matmul(feature, x) y = self.conv1x1(feature_raw) y = y.view(y.size(0), -1) x = x + y return x def gcn_resnest200(cfg=None, **kwargs): model = ResNet(Bottleneck, [3, 24, 36, 3], radix=2, groups=1, bottleneck_width=64, deep_stem=True, stem_width=64, avg_down=True, avd=True, avd_first=False, use_se=cfg.use_se, extract_fields=cfg.extract_fields, agree_rate=cfg.agree_rate, csv_path=cfg.csv_path, **kwargs) # model = ResNet(Bottleneck, [3, 24, 36, 3], radix=2, groups=1, bottleneck_width=64, # deep_stem=True, stem_width=64, avg_down=True, avd=True, avd_first=False, # use_se=False, extract_fields='0,1,2,3,4,5', agree_rate=0.5, # csv_path='D:/Dataset/Vinmec/Noise/train_sss.csv', **kwargs) if cfg.pretrained: model.load_state_dict( torch.hub.load_state_dict_from_url(resnest_model_urls['resnest200'], progress=True), strict=False) return model def gcn_resnest101(cfg=None, **kwargs): model = ResNet(Bottleneck, [3, 4, 23, 3], radix=2, groups=1, bottleneck_width=64, deep_stem=True, stem_width=64, avg_down=True, avd=True, avd_first=False, use_se=cfg.use_se, extract_fields=cfg.extract_fields, agree_rate=cfg.agree_rate, csv_path=cfg.csv_path, **kwargs) if cfg.pretrained: model.load_state_dict( torch.hub.load_state_dict_from_url(resnest_model_urls['resnest101'], progress=True), strict=False) return model def gcn_resnest50(cfg=None, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], radix=2, groups=1, bottleneck_width=64, deep_stem=True, stem_width=32, avg_down=True, avd=True, avd_first=False, use_se=cfg.use_se, extract_fields=cfg.extract_fields, agree_rate=cfg.agree_rate, csv_path=cfg.csv_path, **kwargs) if cfg.pretrained: model.load_state_dict( torch.hub.load_state_dict_from_url(resnest_model_urls['resnest50'], progress=True), strict=False) return model class GraphConvolution(nn.Module): """ Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 """ def __init__(self, in_features, out_features, bias=False): super(GraphConvolution, self).__init__() self.in_features = in_features self.out_features = out_features middle_features = max(32, (in_features + out_features) // 16) self.weight1 = Parameter(torch.Tensor(in_features, middle_features)) self.weight2 = Parameter(torch.Tensor(middle_features, out_features)) if bias: self.bias = Parameter(torch.Tensor(1, out_features)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): stdv = 1. / math.sqrt(self.weight1.size(1)) self.weight1.data.uniform_(-stdv, stdv) stdv = 1. / math.sqrt(self.weight2.size(1)) self.weight2.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, input, adj): support = torch.matmul(input, self.weight1) support = torch.matmul(support, self.weight2) output = torch.matmul(adj, support) if self.bias is not None: output = output + self.bias return output def __repr__(self): return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str( self.out_features) + ')' class GraphAttentionLayer(nn.Module): """ Simple GAT layer, similar to https://arxiv.org/abs/1710.10903 """ def __init__(self, in_features, out_features, dropout=0, alpha=0.2, concat=True, bias=False): super(GraphAttentionLayer, self).__init__() self.dropout = dropout self.in_features = in_features self.out_features = out_features self.alpha = alpha self.concat = concat self.W = nn.Parameter(torch.zeros(size=(in_features, out_features))) nn.init.xavier_uniform_(self.W.data, gain=1.414) self.a = nn.Parameter(torch.zeros(size=(2 * out_features, 1))) nn.init.xavier_uniform_(self.a.data, gain=1.414) if bias: self.bias = Parameter(torch.Tensor(1, out_features)) else: self.register_parameter('bias', None) self.leakyrelu = nn.LeakyReLU(self.alpha) self.reset_parameters() def reset_parameters(self): stdv = 1. / math.sqrt(self.W.size(1)) self.W.data.uniform_(-stdv, stdv) stdv = 1. / math.sqrt(self.a.size(1)) self.a.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, input, adj): h = torch.mm(input, self.W) N = h.size()[0] a_input = torch.cat([h.repeat(1, N).view(N * N, -1), h.repeat(N, 1)], dim=1).view(N, -1, 2 * self.out_features) e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2)) zero_vec = -9e15 * torch.ones_like(e) attention = torch.where(adj > 0, e, zero_vec) attention = F.softmax(attention, dim=1) attention = F.dropout(attention, self.dropout, training=self.training) h_prime = torch.matmul(attention, h) if self.bias is not None: h_prime = h_prime + self.bias if self.concat: return F.elu(h_prime) else: return h_prime def __repr__(self): return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str( self.out_features) + ')' def merge_gcn_residual(feature, x, merge_conv): feature_raw = feature feature = feature_raw.transpose(1, 2) feature = feature.transpose(2, 3).contiguous() feature = feature.view(-1, feature.shape[-1]) reshape_x = x.transpose(0, 1) feature = torch.matmul(feature, reshape_x) feature = feature.view(feature_raw.shape[0], feature_raw.shape[2], feature_raw.shape[3], -1) feature = feature.transpose(2, 3) feature = feature.transpose(1, 2) feature = merge_conv(feature) return feature_raw + feature if __name__ == "__main__": import torchsummary x = torch.randn([2, 3, 224, 224]) model = gcn_resnest200(num_classes=6, word_file='diseases_embeddings.npy') logits = model(x) # print(torchsummary.summary(model, input_size=(3, 512, 512), device='cpu')) print(logits) # x = torch.randn([2, 2048, 7, 7]) # word = torch.randn([6, 300]) # adj = torch.randn([6, 6]) # # # gcn = GraphConvolution(in_features=300, out_features=256, bias=True) # gcn = GraphAttentionLayer(in_features=300, out_features=256, bias=True) # output = gcn(word, adj) # print(output) # feature = torch.randn([2, 128, 56, 56]) # x = torch.randn([11, 128]) # merge_conv = nn.Conv2d(11, 128, kernel_size=1, stride=1, bias=False) # # output = merge_gcn_residual(feature, x, merge_conv) # print(output.size())
[ "models.attention_map.SEModule", "torch.nn.ReLU", "torch.nn.Dropout", "torch.nn.Tanh", "torch.nn.Sequential", "rfconv.RFConv2d", "math.sqrt", "models.utils.gen_adj", "torch.from_numpy", "torch.nn.AvgPool2d", "torch.nn.functional.softmax", "os.path.exists", "torch.nn.init.xavier_uniform_", "torch.nn.init.zeros_", "torch.hub.load_state_dict_from_url", "models.utils.gen_adj_num", "torch.matmul", "torch.nn.AdaptiveAvgPool2d", "torch.randn", "torch.ones_like", "torch.nn.LeakyReLU", "torch.Tensor", "torch.nn.functional.dropout", "numpy.random.randn", "models.feature_extraction.splat.SplAtConv2d", "torch.where", "models.common.conv1x1", "torch.nn.functional.elu", "torch.nn.Conv2d", "torch.mm", "torch.nn.MaxPool2d", "numpy.load", "torch.zeros" ]
[((22501, 22533), 'torch.matmul', 'torch.matmul', (['feature', 'reshape_x'], {}), '(feature, reshape_x)\n', (22513, 22533), False, 'import torch\n'), ((22837, 22866), 'torch.randn', 'torch.randn', (['[2, 3, 224, 224]'], {}), '([2, 3, 224, 224])\n', (22848, 22866), False, 'import torch\n'), ((1961, 2020), 'torch.nn.Conv2d', 'nn.Conv2d', (['inplanes', 'group_width'], {'kernel_size': '(1)', 'bias': '(False)'}), '(inplanes, group_width, kernel_size=1, bias=False)\n', (1970, 2020), True, 'import torch.nn as nn\n'), ((3712, 3773), 'torch.nn.Conv2d', 'nn.Conv2d', (['group_width', '(planes * 4)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(group_width, planes * 4, kernel_size=1, bias=False)\n', (3721, 3773), True, 'import torch.nn as nn\n'), ((3941, 3962), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3948, 3962), True, 'import torch.nn as nn\n'), ((8378, 8399), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (8385, 8399), True, 'import torch.nn as nn\n'), ((8423, 8471), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(3)', 'stride': '(2)', 'padding': '(1)'}), '(kernel_size=3, stride=2, padding=1)\n', (8435, 8471), True, 'import torch.nn as nn\n'), ((9859, 9887), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (9879, 9887), True, 'import torch.nn as nn\n'), ((10423, 10499), 'models.utils.gen_adj_num', 'gen_adj_num', ([], {'labels': 'extract_fields', 'agree_rate': 'agree_rate', 'csv_path': 'csv_path'}), '(labels=extract_fields, agree_rate=agree_rate, csv_path=csv_path)\n', (10434, 10499), False, 'from models.utils import gen_adj_num, gen_adj\n'), ((11252, 11269), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (11264, 11269), True, 'import torch.nn as nn\n'), ((11293, 11302), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (11300, 11302), True, 'import torch.nn as nn\n'), ((11330, 11394), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_classes', '(128)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(num_classes, 128, kernel_size=1, stride=1, bias=False)\n', (11339, 11394), True, 'import torch.nn as nn\n'), ((11422, 11486), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_classes', '(256)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(num_classes, 256, kernel_size=1, stride=1, bias=False)\n', (11431, 11486), True, 'import torch.nn as nn\n'), ((11514, 11578), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_classes', '(512)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(num_classes, 512, kernel_size=1, stride=1, bias=False)\n', (11523, 11578), True, 'import torch.nn as nn\n'), ((11606, 11671), 'torch.nn.Conv2d', 'nn.Conv2d', (['num_classes', '(1024)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(num_classes, 1024, kernel_size=1, stride=1, bias=False)\n', (11615, 11671), True, 'import torch.nn as nn\n'), ((11695, 11757), 'models.common.conv1x1', 'conv1x1', ([], {'in_channels': '(2048)', 'out_channels': 'num_classes', 'bias': '(True)'}), '(in_channels=2048, out_channels=num_classes, bias=True)\n', (11702, 11757), False, 'from models.common import conv1x1\n'), ((14946, 14968), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (14959, 14968), True, 'import torch.nn as nn\n'), ((16393, 16417), 'torch.matmul', 'torch.matmul', (['feature', 'x'], {}), '(feature, x)\n', (16405, 16417), False, 'import torch\n'), ((19654, 19687), 'torch.matmul', 'torch.matmul', (['input', 'self.weight1'], {}), '(input, self.weight1)\n', (19666, 19687), False, 'import torch\n'), ((19706, 19741), 'torch.matmul', 'torch.matmul', (['support', 'self.weight2'], {}), '(support, self.weight2)\n', (19718, 19741), False, 'import torch\n'), ((19759, 19785), 'torch.matmul', 'torch.matmul', (['adj', 'support'], {}), '(adj, support)\n', (19771, 19785), False, 'import torch\n'), ((20558, 20606), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.W.data'], {'gain': '(1.414)'}), '(self.W.data, gain=1.414)\n', (20581, 20606), True, 'import torch.nn as nn\n'), ((20686, 20734), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.a.data'], {'gain': '(1.414)'}), '(self.a.data, gain=1.414)\n', (20709, 20734), True, 'import torch.nn as nn\n'), ((20908, 20932), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['self.alpha'], {}), '(self.alpha)\n', (20920, 20932), True, 'import torch.nn as nn\n'), ((21308, 21331), 'torch.mm', 'torch.mm', (['input', 'self.W'], {}), '(input, self.W)\n', (21316, 21331), False, 'import torch\n'), ((21703, 21736), 'torch.where', 'torch.where', (['(adj > 0)', 'e', 'zero_vec'], {}), '(adj > 0, e, zero_vec)\n', (21714, 21736), False, 'import torch\n'), ((21757, 21784), 'torch.nn.functional.softmax', 'F.softmax', (['attention'], {'dim': '(1)'}), '(attention, dim=1)\n', (21766, 21784), True, 'import torch.nn.functional as F\n'), ((21805, 21863), 'torch.nn.functional.dropout', 'F.dropout', (['attention', 'self.dropout'], {'training': 'self.training'}), '(attention, self.dropout, training=self.training)\n', (21814, 21863), True, 'import torch.nn.functional as F\n'), ((21882, 21908), 'torch.matmul', 'torch.matmul', (['attention', 'h'], {}), '(attention, h)\n', (21894, 21908), False, 'import torch\n'), ((2274, 2308), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (['(3)', 'stride'], {'padding': '(1)'}), '(3, stride, padding=1)\n', (2286, 2308), True, 'import torch.nn as nn\n'), ((2629, 2896), 'models.feature_extraction.splat.SplAtConv2d', 'SplAtConv2d', (['group_width', 'group_width'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': 'dilation', 'dilation': 'dilation', 'groups': 'cardinality', 'bias': '(False)', 'radix': 'radix', 'rectify': 'rectified_conv', 'rectify_avg': 'rectify_avg', 'norm_layer': 'norm_layer', 'dropblock_prob': 'dropblock_prob'}), '(group_width, group_width, kernel_size=3, stride=stride, padding\n =dilation, dilation=dilation, groups=cardinality, bias=False, radix=\n radix, rectify=rectified_conv, rectify_avg=rectify_avg, norm_layer=\n norm_layer, dropblock_prob=dropblock_prob)\n', (2640, 2896), False, 'from models.feature_extraction.splat import SplAtConv2d\n'), ((3897, 3920), 'torch.nn.init.zeros_', 'zeros_', (['self.bn3.weight'], {}), '(self.bn3.weight)\n', (3903, 3920), False, 'from torch.nn.init import zeros_\n'), ((4133, 4153), 'models.attention_map.SEModule', 'SEModule', (['(planes * 4)'], {}), '(planes * 4)\n', (4141, 4153), False, 'from models.attention_map import SEModule, SpatialCGNL, SAModule\n'), ((9908, 9930), 'torch.nn.Dropout', 'nn.Dropout', (['final_drop'], {}), '(final_drop)\n', (9918, 9930), True, 'import torch.nn as nn\n'), ((10577, 10602), 'os.path.exists', 'os.path.exists', (['word_file'], {}), '(word_file)\n', (10591, 10602), False, 'import os\n'), ((10623, 10656), 'numpy.random.randn', 'np.random.randn', (['num_classes', '(300)'], {}), '(num_classes, 300)\n', (10638, 10656), True, 'import numpy as np\n'), ((13051, 13078), 'torch.nn.Sequential', 'nn.Sequential', (['*down_layers'], {}), '(*down_layers)\n', (13064, 13078), True, 'import torch.nn as nn\n'), ((17310, 17397), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (["resnest_model_urls['resnest200']"], {'progress': '(True)'}), "(resnest_model_urls['resnest200'],\n progress=True)\n", (17344, 17397), False, 'import torch\n'), ((17876, 17963), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (["resnest_model_urls['resnest101']"], {'progress': '(True)'}), "(resnest_model_urls['resnest101'],\n progress=True)\n", (17910, 17963), False, 'import torch\n'), ((18440, 18526), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (["resnest_model_urls['resnest50']"], {'progress': '(True)'}), "(resnest_model_urls['resnest50'],\n progress=True)\n", (18474, 18526), False, 'import torch\n'), ((18982, 19024), 'torch.Tensor', 'torch.Tensor', (['in_features', 'middle_features'], {}), '(in_features, middle_features)\n', (18994, 19024), False, 'import torch\n'), ((19059, 19102), 'torch.Tensor', 'torch.Tensor', (['middle_features', 'out_features'], {}), '(middle_features, out_features)\n', (19071, 19102), False, 'import torch\n'), ((20503, 20548), 'torch.zeros', 'torch.zeros', ([], {'size': '(in_features, out_features)'}), '(size=(in_features, out_features))\n', (20514, 20548), False, 'import torch\n'), ((20637, 20676), 'torch.zeros', 'torch.zeros', ([], {'size': '(2 * out_features, 1)'}), '(size=(2 * out_features, 1))\n', (20648, 20676), False, 'import torch\n'), ((21664, 21682), 'torch.ones_like', 'torch.ones_like', (['e'], {}), '(e)\n', (21679, 21682), False, 'import torch\n'), ((22030, 22044), 'torch.nn.functional.elu', 'F.elu', (['h_prime'], {}), '(h_prime)\n', (22035, 22044), True, 'import torch.nn.functional as F\n'), ((3124, 3292), 'rfconv.RFConv2d', 'RFConv2d', (['group_width', 'group_width'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': 'dilation', 'dilation': 'dilation', 'groups': 'cardinality', 'bias': '(False)', 'average_mode': 'rectify_avg'}), '(group_width, group_width, kernel_size=3, stride=stride, padding=\n dilation, dilation=dilation, groups=cardinality, bias=False,\n average_mode=rectify_avg)\n', (3132, 3292), False, 'from rfconv import RFConv2d\n'), ((3438, 3577), 'torch.nn.Conv2d', 'nn.Conv2d', (['group_width', 'group_width'], {'kernel_size': '(3)', 'stride': 'stride', 'padding': 'dilation', 'dilation': 'dilation', 'groups': 'cardinality', 'bias': '(False)'}), '(group_width, group_width, kernel_size=3, stride=stride, padding=\n dilation, dilation=dilation, groups=cardinality, bias=False)\n', (3447, 3577), True, 'import torch.nn as nn\n'), ((7797, 7818), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (7804, 7818), True, 'import torch.nn as nn\n'), ((7986, 8007), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (7993, 8007), True, 'import torch.nn as nn\n'), ((10784, 10798), 'numpy.load', 'np.load', (['point'], {}), '(point)\n', (10791, 10798), True, 'import numpy as np\n'), ((15016, 15033), 'models.utils.gen_adj', 'gen_adj', (['self.adj'], {}), '(self.adj)\n', (15023, 15033), False, 'from models.utils import gen_adj_num, gen_adj\n'), ((19155, 19184), 'torch.Tensor', 'torch.Tensor', (['(1)', 'out_features'], {}), '(1, out_features)\n', (19167, 19184), False, 'import torch\n'), ((20787, 20816), 'torch.Tensor', 'torch.Tensor', (['(1)', 'out_features'], {}), '(1, out_features)\n', (20799, 20816), False, 'import torch\n'), ((10216, 10234), 'math.sqrt', 'math.sqrt', (['(2.0 / n)'], {}), '(2.0 / n)\n', (10225, 10234), False, 'import math\n'), ((10529, 10551), 'torch.from_numpy', 'torch.from_numpy', (['_adj'], {}), '(_adj)\n', (10545, 10551), False, 'import torch\n'), ((10900, 10922), 'torch.from_numpy', 'torch.from_numpy', (['word'], {}), '(word)\n', (10916, 10922), False, 'import torch\n'), ((12640, 12731), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.inplanes', '(planes * block.expansion)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(self.inplanes, planes * block.expansion, kernel_size=1, stride=1,\n bias=False)\n', (12649, 12731), True, 'import torch.nn as nn\n'), ((12833, 12930), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.inplanes', '(planes * block.expansion)'], {'kernel_size': '(1)', 'stride': 'stride', 'bias': '(False)'}), '(self.inplanes, planes * block.expansion, kernel_size=1, stride=\n stride, bias=False)\n', (12842, 12930), True, 'import torch.nn as nn\n'), ((21594, 21623), 'torch.matmul', 'torch.matmul', (['a_input', 'self.a'], {}), '(a_input, self.a)\n', (21606, 21623), False, 'import torch\n'), ((12264, 12356), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', ([], {'kernel_size': 'stride', 'stride': 'stride', 'ceil_mode': '(True)', 'count_include_pad': '(False)'}), '(kernel_size=stride, stride=stride, ceil_mode=True,\n count_include_pad=False)\n', (12276, 12356), True, 'import torch.nn as nn\n'), ((12452, 12530), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', ([], {'kernel_size': '(1)', 'stride': '(1)', 'ceil_mode': '(True)', 'count_include_pad': '(False)'}), '(kernel_size=1, stride=1, ceil_mode=True, count_include_pad=False)\n', (12464, 12530), True, 'import torch.nn as nn\n')]
# https://stackoverflow.com/questions/47295473/how-to-plot-using-matplotlib-python-colahs-deformed-grid """ 这个形状仍然不对。靠近坐标轴的地方变化太大。不管是横轴还是纵轴。应该是以原点为圆心,各个网格均匀分担才对 而不管是否靠近坐标轴 变形的目标,是在某处给定一个球体或者立方体,整个坐标中的网格,靠近这个物体的,受到变形影响,距离越远,影响 越小,直到可以忽略不计 但有个要求是靠近物体的网格,是均匀的受到影响,不能有的多,有的少 或许用极坐标是更好的选择?但是也不行。极坐标如何体现原有的坐标系呢? 极坐标没有平直的地方,到处都不均匀。 """ import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection EDGE = 5 STEP = 2 * EDGE + 1 def plot_grid(x, y, ax=None, **kwargs): ax = ax or plt.gca() segs1 = np.stack((x, y), axis=2) segs2 = segs1.transpose(1, 0, 2) ax.add_collection(LineCollection(segs1, **kwargs)) ax.add_collection(LineCollection(segs2, **kwargs)) ax.autoscale() def sig(i): # return 1 return -1 if (i < 0) else 1 def f1(x: np.array, y: np.array): u = [] v = [] for i in range(0, len(x)): ui = [] vi = [] for j in range(0, len(x[i])): # 这样取到的是网格中每个点的坐标,逐行取,从左到右。 xx = x[i][j] yy = y[i][j] print("x=", xx, "y=", yy) expn = - 0.2 * (xx ** 2 + yy ** 2) # 坐标越远离中心,delta越小。当x=+-1或者y=+-1, delta = np.exp(expn) print(expn) uu = xx if xx == 0 else xx + sig(xx) * delta vv = yy if yy == 0 else yy + sig(yy) * delta print("uu=", uu, "vv=", vv) ui.append(uu) vi.append(vv) # vi.append(yy) # ui.append(xx) u.append(ui) v.append(vi) return u, v fig, ax = plt.subplots() ax.set_aspect('equal') grid_x, grid_y = np.meshgrid(np.linspace(-EDGE, EDGE, STEP), np.linspace(-EDGE, EDGE, STEP)) plot_grid(grid_x, grid_y, ax=ax, color="lightgrey") distx, disty = f1(grid_x, grid_y) plot_grid(distx, disty, ax=ax, color="C0") plt.show()
[ "matplotlib.pyplot.gca", "matplotlib.collections.LineCollection", "numpy.exp", "numpy.stack", "numpy.linspace", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((1565, 1579), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1577, 1579), True, 'import matplotlib.pyplot as plt\n'), ((1827, 1837), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1835, 1837), True, 'import matplotlib.pyplot as plt\n'), ((544, 568), 'numpy.stack', 'np.stack', (['(x, y)'], {'axis': '(2)'}), '((x, y), axis=2)\n', (552, 568), True, 'import numpy as np\n'), ((1632, 1662), 'numpy.linspace', 'np.linspace', (['(-EDGE)', 'EDGE', 'STEP'], {}), '(-EDGE, EDGE, STEP)\n', (1643, 1662), True, 'import numpy as np\n'), ((1664, 1694), 'numpy.linspace', 'np.linspace', (['(-EDGE)', 'EDGE', 'STEP'], {}), '(-EDGE, EDGE, STEP)\n', (1675, 1694), True, 'import numpy as np\n'), ((522, 531), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (529, 531), True, 'import matplotlib.pyplot as plt\n'), ((628, 659), 'matplotlib.collections.LineCollection', 'LineCollection', (['segs1'], {}), '(segs1, **kwargs)\n', (642, 659), False, 'from matplotlib.collections import LineCollection\n'), ((683, 714), 'matplotlib.collections.LineCollection', 'LineCollection', (['segs2'], {}), '(segs2, **kwargs)\n', (697, 714), False, 'from matplotlib.collections import LineCollection\n'), ((1195, 1207), 'numpy.exp', 'np.exp', (['expn'], {}), '(expn)\n', (1201, 1207), True, 'import numpy as np\n')]
import argparse from os import listdir, path import numpy as np def convert(main_folder, output): ret = [] for label, class_folder in listdir(main_folder): class_folder_path = path.join(main_folder, class_folder) for img_name in listdir(class_folder_path): image_path = path.join(class_folder, img_name) ret.append([image_path, str(label)]) np.savetxt(output, ret, delimiter=" ", fmt="%s %i") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Folder with classes subfolders to a file to train." ) parser.add_argument("--folder", "-f", help="Folder to convert.") parser.add_argument("--output", "-o", help="Output file.") args = parser.parse_args() convert(args.folder, args.output)
[ "os.path.join", "os.listdir", "argparse.ArgumentParser", "numpy.savetxt" ]
[((146, 166), 'os.listdir', 'listdir', (['main_folder'], {}), '(main_folder)\n', (153, 166), False, 'from os import listdir, path\n'), ((399, 450), 'numpy.savetxt', 'np.savetxt', (['output', 'ret'], {'delimiter': '""" """', 'fmt': '"""%s %i"""'}), "(output, ret, delimiter=' ', fmt='%s %i')\n", (409, 450), True, 'import numpy as np\n'), ((493, 587), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Folder with classes subfolders to a file to train."""'}), "(description=\n 'Folder with classes subfolders to a file to train.')\n", (516, 587), False, 'import argparse\n'), ((196, 232), 'os.path.join', 'path.join', (['main_folder', 'class_folder'], {}), '(main_folder, class_folder)\n', (205, 232), False, 'from os import listdir, path\n'), ((258, 284), 'os.listdir', 'listdir', (['class_folder_path'], {}), '(class_folder_path)\n', (265, 284), False, 'from os import listdir, path\n'), ((311, 344), 'os.path.join', 'path.join', (['class_folder', 'img_name'], {}), '(class_folder, img_name)\n', (320, 344), False, 'from os import listdir, path\n')]
# Copyright 2018 <NAME> and <NAME> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import scipy.sparse as sp from sklearn.base import BaseEstimator, ClusterMixin class NormalizedKMeans(BaseEstimator, ClusterMixin): def __init__(self, iterations=20, center_num=5): self.center_num = center_num self.iterations = iterations def fit(self, X, k_center): self.k_center, self.ya = self.k_means(X, self.iterations, self.center_num, k_center, X.shape[0]) return self def k_means(self, data, iterations, center_num, k_center, rows): all_one = np.matrix([1] * rows).T all_one_k = np.matrix([1] * center_num) all_one_c = np.matrix([1] * k_center.shape[0]).T if sp.issparse(data): t2 = (data.power(2)).sum(axis=1).dot(all_one_k) else: t2 = (np.power(data, 2)).sum(axis=1).reshape((-1, 1)) * all_one_k t22 = data * 2 ya = None for _ in range(iterations): dist = t2 - t22 * k_center + all_one * np.power(k_center, 2).sum(axis=0) ya = (dist == (np.amin(dist) * all_one_k)) k_center = (data.T * ya) / (all_one_c * ya.sum(axis=0)) return k_center, ya
[ "numpy.matrix", "numpy.amin", "scipy.sparse.issparse", "numpy.power" ]
[((1145, 1172), 'numpy.matrix', 'np.matrix', (['([1] * center_num)'], {}), '([1] * center_num)\n', (1154, 1172), True, 'import numpy as np\n'), ((1241, 1258), 'scipy.sparse.issparse', 'sp.issparse', (['data'], {}), '(data)\n', (1252, 1258), True, 'import scipy.sparse as sp\n'), ((1101, 1122), 'numpy.matrix', 'np.matrix', (['([1] * rows)'], {}), '([1] * rows)\n', (1110, 1122), True, 'import numpy as np\n'), ((1193, 1227), 'numpy.matrix', 'np.matrix', (['([1] * k_center.shape[0])'], {}), '([1] * k_center.shape[0])\n', (1202, 1227), True, 'import numpy as np\n'), ((1602, 1615), 'numpy.amin', 'np.amin', (['dist'], {}), '(dist)\n', (1609, 1615), True, 'import numpy as np\n'), ((1541, 1562), 'numpy.power', 'np.power', (['k_center', '(2)'], {}), '(k_center, 2)\n', (1549, 1562), True, 'import numpy as np\n'), ((1352, 1369), 'numpy.power', 'np.power', (['data', '(2)'], {}), '(data, 2)\n', (1360, 1369), True, 'import numpy as np\n')]
import numpy as np import sqlalchemy as sa from sqlalchemy.dialects import postgresql as psql from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.schema import UniqueConstraint from astropy import units as u from .core import Base from .constants import APER_KEY, APERTURE_RADIUS __all__ = ['ForcedPhotometry', 'raw_aperture_photometry', 'aperture_photometry'] class ForcedPhotometry(Base): id = sa.Column(sa.Integer, primary_key=True) __tablename__ = 'forcedphotometry' flags = sa.Column(sa.Integer) ra = sa.Column(psql.DOUBLE_PRECISION) dec = sa.Column(psql.DOUBLE_PRECISION) @property def mag(self): return -2.5 * np.log10(self.flux) + self.image.header['MAGZP'] + \ self.image.header[self.apcorkey] @property def magerr(self): return 1.08573620476 * self.fluxerr / self.flux image_id = sa.Column(sa.Integer, sa.ForeignKey('calibratedimages.id', ondelete='CASCADE'), index=True) image = relationship('CalibratedImage', back_populates='forced_photometry', cascade='all') # thumbnails = relationship('Thumbnail', cascade='all') source_id = sa.Column(sa.Text, sa.ForeignKey('sources.id', ondelete='CASCADE'), index=True) source = relationship('Source', cascade='all') apcorkey='APCOR5' flux = sa.Column(sa.Float) fluxerr = sa.Column(sa.Float) zp = sa.Column(sa.Float) filtercode = sa.Column(sa.Text) obsjd = sa.Column(sa.Float) uniq = UniqueConstraint(image_id, source_id) reverse_idx = sa.Index('source_image', source_id, image_id) @hybrid_property def snr(self): return self.flux / self.fluxerr def raw_aperture_photometry(sci_path, rms_path, mask_path, ra, dec, apply_calibration=False): import photutils from astropy.coordinates import SkyCoord from astropy.io import fits from astropy.table import vstack from astropy.wcs import WCS ra = np.atleast_1d(ra) dec = np.atleast_1d(dec) coord = SkyCoord(ra, dec, unit='deg') with fits.open(sci_path, memmap=False) as shdu: header = shdu[0].header swcs = WCS(header) scipix = shdu[0].data with fits.open(rms_path, memmap=False) as rhdu: rmspix = rhdu[0].data with fits.open(mask_path, memmap=False) as mhdu: maskpix = mhdu[0].data apertures = photutils.SkyCircularAperture(coord, r=APERTURE_RADIUS) phot_table = photutils.aperture_photometry(scipix, apertures, error=rmspix, wcs=swcs) pixap = apertures.to_pixel(swcs) annulus_masks = pixap.to_mask(method='center') maskpix = [annulus_mask.cutout(maskpix) for annulus_mask in annulus_masks] magzp = header['MAGZP'] apcor = header[APER_KEY] # check for invalid photometry on masked pixels phot_table['flags'] = [int(np.bitwise_or.reduce(m, axis=(0, 1))) for m in maskpix] phot_table['zp'] = magzp + apcor phot_table['obsjd'] = header['OBSJD'] phot_table['filtercode'] = 'z' + header['FILTER'][-1] # rename some columns phot_table.rename_column('aperture_sum', 'flux') phot_table.rename_column('aperture_sum_err', 'fluxerr') return phot_table def aperture_photometry(calibratable, ra, dec, apply_calibration=False, assume_background_subtracted=False, use_cutout=False, direct_load=None, survey='ZTF',apfactor=1.0,seeing=1.0): import photutils from astropy.coordinates import SkyCoord from astropy.io import fits from astropy.table import vstack from astropy.wcs import WCS ra = np.atleast_1d(ra) dec = np.atleast_1d(dec) coord = SkyCoord(ra, dec, unit='deg') if not use_cutout: wcs = calibratable.wcs if seeing*3*apfactor < 2.5: apcorkey='APCOR1' aprad=2.0 elif seeing*3*apfactor >=2.5 and seeing*3*apfactor<3.5: apcorkey='APCOR2' aprad=3.0 elif seeing*3*apfactor >=3.5 and 3*apfactor*seeing<5.0: apcorkey='APCOR3' aprad=4.0 elif seeing*3*apfactor >=5.0 and 3*apfactor*seeing<8.0: apcorkey='APCOR4' aprad=6.0 elif seeing*3*apfactor >=8.0 and 3*apfactor*seeing<12.0: apcorkey='APCOR5' aprad=10.0 elif seeing*3*apfactor >=12.0: apcorkey='APCOR6' aprad=14 aprad=aprad*u.pixel apertures = photutils.SkyCircularAperture(coord, r=aprad)#APERTURE_RADIUS*apfactor*seeing) # something that is photometerable implements mask, background, and wcs if not assume_background_subtracted: pixels_bkgsub = calibratable.background_subtracted_image.data else: pixels_bkgsub = calibratable.data bkgrms = calibratable.rms_image.data mask = calibratable.mask_image.data phot_table = photutils.aperture_photometry(pixels_bkgsub, apertures, error=bkgrms, wcs=wcs) if survey=='PTF': phot_table['zp'] = calibratable.header['IMAGEZPT']#['LMGAPCZP']# + calibratable.header['APCOR4'] else: phot_table['zp'] = calibratable.header['MAGZP'] + calibratable.header[apcorkey]#'APCOR4'] phot_table['obsjd'] = calibratable.header['OBSJD'] phot_table['filtercode'] = 'z' + calibratable.header['FILTER'][-1] pixap = apertures.to_pixel(wcs) annulus_masks = pixap.to_mask(method='center') maskpix = [annulus_mask.cutout(mask.data) for annulus_mask in annulus_masks] else: phot_table = [] maskpix = [] for s in coord: if direct_load is not None and 'sci' in direct_load: sci_path = direct_load['sci'] else: if assume_background_subtracted: sci_path = calibratable.local_path else: sci_path = calibratable.background_subtracted_image.local_path if direct_load is not None and 'mask' in direct_load: mask_path = direct_load['mask'] else: mask_path = calibratable.mask_image.local_path if direct_load is not None and 'rms' in direct_load: rms_path = direct_load['rms'] else: rms_path = calibratable.rms_image.local_path with fits.open( sci_path, memmap=True ) as f: wcs = WCS(f[0].header) pixcoord = wcs.all_world2pix([[s.ra.deg, s.dec.deg]], 0)[0] pixx, pixy = pixcoord nx = calibratable.header['NAXIS1'] ny = calibratable.header['NAXIS2'] xmin = max(0, pixx - 1.5 * aprad)#APERTURE_RADIUS.value * seeing * apfactor) xmax = min(nx, pixx + 1.5 * aprad)#APERTURE_RADIUS.value * seeing * apfactor) ymin = max(0, pixy - 1.5 * aprad)#APERTURE_RADIUS.value * seeing * apfactor) ymax = min(ny, pixy + 1.5 * aprad)#APERTURE_RADIUS.value * seeing * apfactor) ixmin = int(np.floor(xmin)) ixmax = int(np.ceil(xmax)) iymin = int(np.floor(ymin)) iymax = int(np.ceil(ymax)) ap = photutils.CircularAperture([pixx - ixmin, pixy - iymin], aprad)#APERTURE_RADIUS.value * seeing * apfactor) # something that is photometerable implements mask, background, and wcs with fits.open( sci_path, memmap=True ) as f: pixels_bkgsub = f[0].data[iymin:iymax, ixmin:ixmax] with fits.open(rms_path, memmap=True) as f: bkgrms = f[0].data[iymin:iymax, ixmin:ixmax] with fits.open(mask_path, memmap=True) as f: mask = f[0].data[iymin:iymax, ixmin:ixmax] pt = photutils.aperture_photometry(pixels_bkgsub, ap, error=bkgrms) annulus_mask = ap.to_mask(method='center') mp = annulus_mask.cutout(mask.data) maskpix.append(mp) phot_table.append(pt) phot_table = vstack(phot_table) if apply_calibration: if survey=='PTF': magzp = calibratable.header['IMAGEZPT'] #apcor = calibratable.header[APER_KEY] phot_table['mag'] = -2.5 * np.log10(phot_table['aperture_sum']) + magzp# + apcor phot_table['magerr'] = 1.0826 * phot_table['aperture_sum_err'] / phot_table['aperture_sum'] else: magzp = calibratable.header['MAGZP'] apcor = calibratable.header[apcorkey]#APER_KEY] phot_table['mag'] = -2.5 * np.log10(phot_table['aperture_sum']) + magzp + apcor phot_table['magerr'] = 1.0826 * phot_table['aperture_sum_err'] / phot_table['aperture_sum'] # check for invalid photometry on masked pixels phot_table['flags'] = [int(np.bitwise_or.reduce(m, axis=(0, 1))) for m in maskpix] # rename some columns phot_table.rename_column('aperture_sum', 'flux') phot_table.rename_column('aperture_sum_err', 'fluxerr') return phot_table
[ "sqlalchemy.orm.relationship", "numpy.ceil", "numpy.log10", "astropy.table.vstack", "sqlalchemy.ForeignKey", "astropy.coordinates.SkyCoord", "photutils.aperture_photometry", "astropy.wcs.WCS", "numpy.floor", "photutils.CircularAperture", "numpy.bitwise_or.reduce", "sqlalchemy.Index", "sqlalchemy.schema.UniqueConstraint", "photutils.SkyCircularAperture", "astropy.io.fits.open", "sqlalchemy.Column", "numpy.atleast_1d" ]
[((458, 497), 'sqlalchemy.Column', 'sa.Column', (['sa.Integer'], {'primary_key': '(True)'}), '(sa.Integer, primary_key=True)\n', (467, 497), True, 'import sqlalchemy as sa\n'), ((550, 571), 'sqlalchemy.Column', 'sa.Column', (['sa.Integer'], {}), '(sa.Integer)\n', (559, 571), True, 'import sqlalchemy as sa\n'), ((581, 613), 'sqlalchemy.Column', 'sa.Column', (['psql.DOUBLE_PRECISION'], {}), '(psql.DOUBLE_PRECISION)\n', (590, 613), True, 'import sqlalchemy as sa\n'), ((624, 656), 'sqlalchemy.Column', 'sa.Column', (['psql.DOUBLE_PRECISION'], {}), '(psql.DOUBLE_PRECISION)\n', (633, 656), True, 'import sqlalchemy as sa\n'), ((1103, 1190), 'sqlalchemy.orm.relationship', 'relationship', (['"""CalibratedImage"""'], {'back_populates': '"""forced_photometry"""', 'cascade': '"""all"""'}), "('CalibratedImage', back_populates='forced_photometry', cascade\n ='all')\n", (1115, 1190), False, 'from sqlalchemy.orm import relationship\n'), ((1434, 1471), 'sqlalchemy.orm.relationship', 'relationship', (['"""Source"""'], {'cascade': '"""all"""'}), "('Source', cascade='all')\n", (1446, 1471), False, 'from sqlalchemy.orm import relationship\n'), ((1510, 1529), 'sqlalchemy.Column', 'sa.Column', (['sa.Float'], {}), '(sa.Float)\n', (1519, 1529), True, 'import sqlalchemy as sa\n'), ((1544, 1563), 'sqlalchemy.Column', 'sa.Column', (['sa.Float'], {}), '(sa.Float)\n', (1553, 1563), True, 'import sqlalchemy as sa\n'), ((1574, 1593), 'sqlalchemy.Column', 'sa.Column', (['sa.Float'], {}), '(sa.Float)\n', (1583, 1593), True, 'import sqlalchemy as sa\n'), ((1611, 1629), 'sqlalchemy.Column', 'sa.Column', (['sa.Text'], {}), '(sa.Text)\n', (1620, 1629), True, 'import sqlalchemy as sa\n'), ((1642, 1661), 'sqlalchemy.Column', 'sa.Column', (['sa.Float'], {}), '(sa.Float)\n', (1651, 1661), True, 'import sqlalchemy as sa\n'), ((1674, 1711), 'sqlalchemy.schema.UniqueConstraint', 'UniqueConstraint', (['image_id', 'source_id'], {}), '(image_id, source_id)\n', (1690, 1711), False, 'from sqlalchemy.schema import UniqueConstraint\n'), ((1730, 1775), 'sqlalchemy.Index', 'sa.Index', (['"""source_image"""', 'source_id', 'image_id'], {}), "('source_image', source_id, image_id)\n", (1738, 1775), True, 'import sqlalchemy as sa\n'), ((2160, 2177), 'numpy.atleast_1d', 'np.atleast_1d', (['ra'], {}), '(ra)\n', (2173, 2177), True, 'import numpy as np\n'), ((2188, 2206), 'numpy.atleast_1d', 'np.atleast_1d', (['dec'], {}), '(dec)\n', (2201, 2206), True, 'import numpy as np\n'), ((2219, 2248), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': '"""deg"""'}), "(ra, dec, unit='deg')\n", (2227, 2248), False, 'from astropy.coordinates import SkyCoord\n'), ((2577, 2632), 'photutils.SkyCircularAperture', 'photutils.SkyCircularAperture', (['coord'], {'r': 'APERTURE_RADIUS'}), '(coord, r=APERTURE_RADIUS)\n', (2606, 2632), False, 'import photutils\n'), ((2650, 2722), 'photutils.aperture_photometry', 'photutils.aperture_photometry', (['scipix', 'apertures'], {'error': 'rmspix', 'wcs': 'swcs'}), '(scipix, apertures, error=rmspix, wcs=swcs)\n', (2679, 2722), False, 'import photutils\n'), ((3925, 3942), 'numpy.atleast_1d', 'np.atleast_1d', (['ra'], {}), '(ra)\n', (3938, 3942), True, 'import numpy as np\n'), ((3953, 3971), 'numpy.atleast_1d', 'np.atleast_1d', (['dec'], {}), '(dec)\n', (3966, 3971), True, 'import numpy as np\n'), ((3984, 4013), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': '"""deg"""'}), "(ra, dec, unit='deg')\n", (3992, 4013), False, 'from astropy.coordinates import SkyCoord\n'), ((945, 1001), 'sqlalchemy.ForeignKey', 'sa.ForeignKey', (['"""calibratedimages.id"""'], {'ondelete': '"""CASCADE"""'}), "('calibratedimages.id', ondelete='CASCADE')\n", (958, 1001), True, 'import sqlalchemy as sa\n'), ((1334, 1381), 'sqlalchemy.ForeignKey', 'sa.ForeignKey', (['"""sources.id"""'], {'ondelete': '"""CASCADE"""'}), "('sources.id', ondelete='CASCADE')\n", (1347, 1381), True, 'import sqlalchemy as sa\n'), ((2259, 2292), 'astropy.io.fits.open', 'fits.open', (['sci_path'], {'memmap': '(False)'}), '(sci_path, memmap=False)\n', (2268, 2292), False, 'from astropy.io import fits\n'), ((2349, 2360), 'astropy.wcs.WCS', 'WCS', (['header'], {}), '(header)\n', (2352, 2360), False, 'from astropy.wcs import WCS\n'), ((2401, 2434), 'astropy.io.fits.open', 'fits.open', (['rms_path'], {'memmap': '(False)'}), '(rms_path, memmap=False)\n', (2410, 2434), False, 'from astropy.io import fits\n'), ((2484, 2518), 'astropy.io.fits.open', 'fits.open', (['mask_path'], {'memmap': '(False)'}), '(mask_path, memmap=False)\n', (2493, 2518), False, 'from astropy.io import fits\n'), ((4782, 4827), 'photutils.SkyCircularAperture', 'photutils.SkyCircularAperture', (['coord'], {'r': 'aprad'}), '(coord, r=aprad)\n', (4811, 4827), False, 'import photutils\n'), ((5234, 5312), 'photutils.aperture_photometry', 'photutils.aperture_photometry', (['pixels_bkgsub', 'apertures'], {'error': 'bkgrms', 'wcs': 'wcs'}), '(pixels_bkgsub, apertures, error=bkgrms, wcs=wcs)\n', (5263, 5312), False, 'import photutils\n'), ((8602, 8620), 'astropy.table.vstack', 'vstack', (['phot_table'], {}), '(phot_table)\n', (8608, 8620), False, 'from astropy.table import vstack\n'), ((3129, 3165), 'numpy.bitwise_or.reduce', 'np.bitwise_or.reduce', (['m'], {'axis': '(0, 1)'}), '(m, axis=(0, 1))\n', (3149, 3165), True, 'import numpy as np\n'), ((7688, 7751), 'photutils.CircularAperture', 'photutils.CircularAperture', (['[pixx - ixmin, pixy - iymin]', 'aprad'], {}), '([pixx - ixmin, pixy - iymin], aprad)\n', (7714, 7751), False, 'import photutils\n'), ((8347, 8409), 'photutils.aperture_photometry', 'photutils.aperture_photometry', (['pixels_bkgsub', 'ap'], {'error': 'bkgrms'}), '(pixels_bkgsub, ap, error=bkgrms)\n', (8376, 8409), False, 'import photutils\n'), ((9404, 9440), 'numpy.bitwise_or.reduce', 'np.bitwise_or.reduce', (['m'], {'axis': '(0, 1)'}), '(m, axis=(0, 1))\n', (9424, 9440), True, 'import numpy as np\n'), ((6824, 6856), 'astropy.io.fits.open', 'fits.open', (['sci_path'], {'memmap': '(True)'}), '(sci_path, memmap=True)\n', (6833, 6856), False, 'from astropy.io import fits\n'), ((6931, 6947), 'astropy.wcs.WCS', 'WCS', (['f[0].header'], {}), '(f[0].header)\n', (6934, 6947), False, 'from astropy.wcs import WCS\n'), ((7535, 7549), 'numpy.floor', 'np.floor', (['xmin'], {}), '(xmin)\n', (7543, 7549), True, 'import numpy as np\n'), ((7575, 7588), 'numpy.ceil', 'np.ceil', (['xmax'], {}), '(xmax)\n', (7582, 7588), True, 'import numpy as np\n'), ((7615, 7629), 'numpy.floor', 'np.floor', (['ymin'], {}), '(ymin)\n', (7623, 7629), True, 'import numpy as np\n'), ((7655, 7668), 'numpy.ceil', 'np.ceil', (['ymax'], {}), '(ymax)\n', (7662, 7668), True, 'import numpy as np\n'), ((7941, 7973), 'astropy.io.fits.open', 'fits.open', (['sci_path'], {'memmap': '(True)'}), '(sci_path, memmap=True)\n', (7950, 7973), False, 'from astropy.io import fits\n'), ((8112, 8144), 'astropy.io.fits.open', 'fits.open', (['rms_path'], {'memmap': '(True)'}), '(rms_path, memmap=True)\n', (8121, 8144), False, 'from astropy.io import fits\n'), ((8230, 8263), 'astropy.io.fits.open', 'fits.open', (['mask_path'], {'memmap': '(True)'}), '(mask_path, memmap=True)\n', (8239, 8263), False, 'from astropy.io import fits\n'), ((713, 732), 'numpy.log10', 'np.log10', (['self.flux'], {}), '(self.flux)\n', (721, 732), True, 'import numpy as np\n'), ((8839, 8875), 'numpy.log10', 'np.log10', (["phot_table['aperture_sum']"], {}), "(phot_table['aperture_sum'])\n", (8847, 8875), True, 'import numpy as np\n'), ((9162, 9198), 'numpy.log10', 'np.log10', (["phot_table['aperture_sum']"], {}), "(phot_table['aperture_sum'])\n", (9170, 9198), True, 'import numpy as np\n')]
""" Purpose of this file is to give examples of structured arrays This script is partially dirived from the LinkedIn learning course https://www.linkedin.com/learning/numpy-data-science-essential-training/create-arrays-from-python-structures """ import numpy as np person_data_def = [('name', 'S6'), ('height', 'f8'), ('weight', 'f8'), ('age', 'i8')] # create a structured array people_array = np.zeros(4, dtype=person_data_def) print(f'The structured array is of type {type(people_array)}\n{people_array}') # let us change some the data values # note that any int for height or weight will processed as default people_array[2] = ('Cat', 130, 56, 22) people_array[0] = ('Amy', 126, 60, 25) people_array[1] = ('Bell', 146, 60, 20) people_array[3] = ('Amy', 140, 80, 55) print(people_array) # we can print the information for name, height, weight and age ages = people_array['age'] print(f'the ages of the people are {ages}') print(f'The names of the people are {people_array["name"]}') print(f'The heights of the people are {people_array["height"]}') print(f'The weights of the people are {people_array["weight"]}') youthful = ages/2 print(f'The young ages are {youthful}') # Note that youthful does not change the original data print(f'The original ages are {ages}') print(people_array[['name', 'age']]) # Record array is a thin wrapper around structured array person_record_array = np.rec.array([('a', 100, 80, 50), ('b', 190, 189, 20)]) print(type(person_record_array[0]))
[ "numpy.zeros", "numpy.rec.array" ]
[((398, 432), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'person_data_def'}), '(4, dtype=person_data_def)\n', (406, 432), True, 'import numpy as np\n'), ((1396, 1451), 'numpy.rec.array', 'np.rec.array', (["[('a', 100, 80, 50), ('b', 190, 189, 20)]"], {}), "([('a', 100, 80, 50), ('b', 190, 189, 20)])\n", (1408, 1451), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt plt.close('all') # From section 3.8.3 of wind energy explained # Prandlt tip loss calc B = 3 # number of blades R = 1 # blade length phi = np.deg2rad(10) # relative wind angle r = np.linspace(0,R,100) F = 2/np.pi * np.arccos(np.exp(-((B/2)*(1-(r/R)))/((r/R)*np.sin(phi)))) plt.figure(num='Tip loss for phi = %2.1f deg and %d blades' % (np.rad2deg(phi), B)) plt.plot(r,F) plt.xlabel('Non-Dimensional Blade Radius (r/R)') plt.ylabel('Tip Loss Factor')
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "numpy.deg2rad", "numpy.linspace", "numpy.sin", "numpy.rad2deg" ]
[((51, 67), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (60, 67), True, 'import matplotlib.pyplot as plt\n'), ((191, 205), 'numpy.deg2rad', 'np.deg2rad', (['(10)'], {}), '(10)\n', (201, 205), True, 'import numpy as np\n'), ((232, 254), 'numpy.linspace', 'np.linspace', (['(0)', 'R', '(100)'], {}), '(0, R, 100)\n', (243, 254), True, 'import numpy as np\n'), ((410, 424), 'matplotlib.pyplot.plot', 'plt.plot', (['r', 'F'], {}), '(r, F)\n', (418, 424), True, 'import matplotlib.pyplot as plt\n'), ((424, 472), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Non-Dimensional Blade Radius (r/R)"""'], {}), "('Non-Dimensional Blade Radius (r/R)')\n", (434, 472), True, 'import matplotlib.pyplot as plt\n'), ((473, 502), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Tip Loss Factor"""'], {}), "('Tip Loss Factor')\n", (483, 502), True, 'import matplotlib.pyplot as plt\n'), ((389, 404), 'numpy.rad2deg', 'np.rad2deg', (['phi'], {}), '(phi)\n', (399, 404), True, 'import numpy as np\n'), ((310, 321), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (316, 321), True, 'import numpy as np\n')]
# Project: SwarmAggregation # Filename: exp.py # Authors: <NAME> (<EMAIL>) and <NAME> # (<EMAIL>). """ exp: A flexible, unifying framework for defining and running experiments for swarm aggregation. """ import argparse from aggregation import aggregation, ideal from itertools import product from math import sin, cos, hypot, ceil from matplotlib.animation import FFMpegWriter, ArtistAnimation import matplotlib.cm as cm from matplotlib.collections import LineCollection, PatchCollection, PolyCollection import matplotlib.pyplot as plt from metrics import * import numpy as np import pickle from tqdm import tqdm class Experiment(object): """ A flexible, unifying framework for experiments. """ def __init__(self, id, params={}, iters=1, savehist=True, seed=None): """ Inputs: - id (str): identifier for the experiment - params (dict): the full parameter set for the simulation runs { 'N' : [int > 0] number of robots, 'R' : [float > 0] radius of rotation (m), 'r' : [float > 0] radius of a robot (m), 'm' : [float > 0] mass of a robot (kg), 'w0' : [float] rot. speed of a robot about its center (rad/s), 'w1' : [float] rot. speed of a robot in place (rad/s), 'sensor' : [0 <= float <= pi] size of the sight sensor (rad), 'noise' : [(str, float)] either ('err', p) for error probability with probability p or ('mot', f) for motion noise with maximum force f (N), 'time' : [float > 0] wall-clock duration of simulation (s), 'step' : [float > 0] wall-clock duration of a time step (s), 'stop' : [float >= 0] if not None, simulation stops if system's dispersion is within stop% of the ideal value, 'init' : ['rand', 'symm'] initialization mode } - iters (int): the number of iterated runs for each parameter setting - savehist (bool): True if a run's history should be saved - seed (int): random seed """ # Unpack singular parameters. self.id, self.iters, self.savehist, self.seed, = id, iters, savehist, seed # Unpack aggregation parameters. defaults = {'N' : [100], 'R' : [0.1445], 'r' : [0.037], 'm' : [0.125], \ 'w0' : [-0.75], 'w1' : [-5.02], 'sensor' : [0], \ 'noise' : [('err', 0)], 'time' : [300], 'step' : [0.005], \ 'stop' : [None], 'init' : ['rand']} plist = [params[p] if p in params else defaults[p] for p in defaults] self.params = list(product(*plist)) # Set up data and results filenames. self.fname = 'exp_{}_{}'.format(self.id, self.seed) # Instantiate a list to hold runs data. This data will have shape # A x B x [S x N x 3, 1] where A is the number of runs (i.e., unique # parameter combinations), B is the number of iterations per run, S is # the number of time steps simulated, N is the number of robots, and 3 # represents each robot's X/Y/Theta data. self.runs_data = [[] for p in self.params] def run(self): """ Run this experiment according to the input parameters. """ tqdm.write('Running Experiment ' + self.id + '...') # Set up random seeds for iterated runs. rng = np.random.default_rng(self.seed) run_seeds = rng.integers(0, 2**32, size=self.iters) # For each parameter combination, do iterated runs of aggregation. silent = len(self.params) > 1 or self.iters > 1 for i, param in enumerate(tqdm(self.params, desc='Simulating runs')): N, R, r, m, w0, w1, sensor, noise, time, step, stop, init = param for seed in tqdm(run_seeds, desc='Iterating run', \ leave=bool(i == len(self.params) - 1)): run_data = aggregation(N, R, r, m, w0, w1, sensor, noise, time,\ step, stop, init, seed, silent) if not self.savehist: # Only save the final configuration. history, final = run_data self.runs_data[i].append((np.copy(history[final-1]), final)) else: # Save the entire configuration history. self.runs_data[i].append(run_data) def save(self): """ Saves this experiment, including all parameters and run data, to a file named according to the experiment's ID and seed. """ tqdm.write('Saving Experiment ' + self.id + '...') with open('data/' + self.fname + '.pkl', 'wb') as f: pickle.dump(self, f) def plot_evo(self, runs, iters, metrics=['sed', 'hull', 'disp', 'clus'], \ labels=None, title='', anno=''): """ Takes indices of either (i) one run and multiple iterations or (ii) one iteration of multiple runs and plots the given metrics against time. """ tqdm.write('Plotting metrics over time...') # Sanity checks and setup. Assumes N, r, time, and step are static. assert self.savehist, 'ERROR: No history to calculate metrics per step' assert len(runs) == 1 or len(iters) == 1, 'ERROR: One run or one iter' runits = [i for i in product(runs, iters)] # Set up colors. cmap = np.vectorize(lambda x : cm.inferno(x)) c = np.array(cmap(np.linspace(0, 1, len(runits) + 2))).T # Plot metrics over time for each run/iteration. names = {'sed' : 'Smallest Enclosing Disc Circumference', \ 'hull' : 'Convex Hull Perimeter', \ 'disp' : 'Dispersion', \ 'clus' : 'Cluster Fraction'} for metric in metrics: fig, ax = plt.subplots() for i, runit in enumerate(tqdm(runits)): # Plot the given metric over time. N, r, time, step = [self.params[runit[0]][j] for j in [0,2,8,9]] configs, final = self.runs_data[runit[0]][runit[1]] x = np.arange(0, time + step, step)[:final] y = [] for config in tqdm(configs, desc='Calculating '+names[metric]): if metric == 'sed': y.append(sed_circumference(config)) elif metric == 'hull': y.append(hull_perimeter(config)) elif metric == 'disp': y.append(dispersion(config)) else: # metric == 'clus' y.append(cluster_fraction(config, r)) if labels != None: ax.plot(x, y, color=c[i+1], label=labels[i], zorder=4) else: ax.plot(x, y, color=c[i+1], zorder=4) # Plot the minimum value for this metric as a dashed line. if metric == 'sed': metric_min = sed_circumference(ideal(N, r)) elif metric == 'hull': metric_min = hull_perimeter(ideal(N, r)) elif metric == 'disp': metric_min = dispersion(ideal(N, r)) else: # metric == 'clus' metric_min = cluster_fraction(ideal(N, r), r) ax.plot(x, np.full(len(x), metric_min), color=c[i+1], \ linestyle='dashed', zorder=3) # Save figure. ax.set(title=title, xlabel='Time (s)', ylabel=names[metric]) ax.set_ylim(bottom=0) ax.grid() if labels != None: ax.legend(loc='upper right') plt.tight_layout() fig.savefig('figs/' + self.fname + '_' + metric + anno + '.png', \ dpi=300) plt.close() def plot_aggtime(self, N, ps, plabel, title='', anno=''): """ Plots final and average time to aggregation per parameter value per number of robots. Assumes that the only parameters that are varied are the number of robots (N) and one non-time related parameter. """ tqdm.write('Plotting average time to aggregation...') # Set up figure and colors. fig, ax = plt.subplots() cmap = np.vectorize(lambda x : cm.inferno(x)) c = np.array(cmap(np.linspace(0, 1, len(N) + 2))).T # Plot simulation time cutoff as a dashed line. time, step = self.params[0][8], self.params[0][9] ax.plot(ps, np.full(len(ps), time), color='k', linestyle='dashed') # Plot iteration times as a scatter plot and averages as lines. for i, ni in enumerate(N): xs, ys, aves = [], [], [] for j, run in enumerate(self.runs_data[i*len(ps):(i+1)*len(ps)]): agg_times = [] for iter in run: xs.append(ps[j]) agg_times.append(iter[1] * step) ys += agg_times aves.append(np.mean(agg_times)) ax.scatter(xs, ys, color=c[i+1], s=15, alpha=0.4) ax.plot(ps, aves, color=c[i+1], label='{} robots'.format(ni)) # Save figure. ax.set(title=title, xlabel=plabel, ylabel='Aggregation Time (s)') ax.set_ylim(bottom=0) ax.grid() ax.legend(loc='upper left') plt.tight_layout() fig.savefig('figs/' + self.fname + '_aggtime' + anno + '.png', dpi=300) plt.close() def animate(self, run, iter, frame=25, anno=''): """ Animate the robots' movement over time. """ tqdm.write('Animating robots\' movement...') # Check that a configuration history exists. assert self.savehist, 'ERROR: No history to animate' # Check that the desired frame rate is valid. assert frame > 0, 'ERROR: Frame rate must be positive value' # Get data and parameters. configs, final = self.runs_data[run][iter] N, r, sensor, time, step = [self.params[run][i] for i in [0,2,6,8,9]] # Set up plot. fig, ax = plt.subplots(figsize=(5,5), dpi=300) all_xy = configs[:,:,:2].flatten() fig_min, fig_max = np.min(all_xy) - r, np.max(all_xy) + r ax.set(xlim=[fig_min, fig_max], ylim=[fig_min, fig_max]) # Set up colors for the various robots. cmap = np.vectorize(lambda x : cm.inferno(x)) c = np.array(cmap(np.linspace(0, 0.9, N))).T # Set up frame rate to target at most 'frame' fps in real time. frame_step = 1 if step >= 1 / frame else ceil(1 / frame / step) interval = (step * frame_step) * 1000 # ms ims = [] max_dist = hypot(*np.full(2, fig_max-fig_min)) for s in tqdm(np.arange(0, min(len(configs), final), frame_step)): title = plt.text(1.0, 1.02, '{:.2f}s of {}s'.format(s*step, time), \ ha='right', va='bottom', transform=ax.transAxes) robots, lines, cones = [], [], [] for i in range(N): xy, theta = configs[s][i][:2], configs[s][i][2] sensor_xy = xy + np.array([r * cos(theta), r * sin(theta)]) # Add this robot's circle artist. robots.append(plt.Circle(xy, radius=r, linewidth=0, color=c[i])) # Add this robot's sight sensor direction artist. vec = max_dist * np.array([cos(theta), sin(theta)]) lines.append([sensor_xy, sensor_xy + vec]) # Add this robot's cone-of-sight polygon artist. if sensor > 0: cw, ccw = theta - sensor / 2, theta + sensor / 2 vec_cw = max_dist * np.array([cos(cw), sin(cw)]) vec_ccw = max_dist * np.array([cos(ccw), sin(ccw)]) tri_pts = [sensor_xy, sensor_xy+vec_cw, sensor_xy+vec_ccw] cones.append(plt.Polygon(tri_pts, color=c[i], alpha=0.15)) # Add this step's artists to the list of artists. robots = PatchCollection(robots, match_original=True, zorder=3) lines = LineCollection(lines, linewidths=0.5, colors=c, alpha=0.75,\ zorder=2) cones = PatchCollection(cones, match_original=True, zorder=1) ims.append([title, ax.add_collection(robots), \ ax.add_collection(lines), ax.add_collection(cones)]) # Animate. ani = ArtistAnimation(fig, ims, interval=interval, blit=True) ani.save('anis/' + self.fname + '_ani' + anno + '.mp4') plt.close() def load_exp(fname): """ Load an experiment from the specified file. """ with open(fname, 'rb') as f: exp = pickle.load(f) return exp ### DATA EXPERIMENTS ### def exp_base(seed=None): """ With default parameters, investigate aggregation over time. """ params = {} # This uses all default values. exp = Experiment('base', params, seed=seed) exp.run() exp.save() exp.plot_evo(runs=[0], iters=[0]) exp.animate(run=0, iter=0) def exp_symm(seed=None): """ With default parameters and symmetric initialization, investigate aggregation over time for a few system sizes. """ N = [3, 5, 10] params = {'N' : N, 'init' : ['symm']} exp = Experiment('symm', params, seed=seed) exp.run() exp.save() exp.plot_evo(runs=np.arange(len(exp.params)), iters=[0], metrics=['disp'], \ labels=['{} robots'.format(i) for i in N], \ title='Symmetric Initial Configuration') def exp_errprob(seed=None): """ With default parameters and a range of error probabilities, investigate average time to aggregation with a 15% stopping condition. """ N = [10, 25, 50, 100] errprob = np.arange(0, 0.501, 0.0125) params = {'N' : N, 'noise' : [('err', p) for p in errprob], 'stop' : [0.15]} exp = Experiment('errprob', params, iters=25, savehist=False, seed=seed) exp.run() exp.save() exp.plot_aggtime(N, errprob, 'Error Probability') def exp_motion(seed=None): """ With default parameters and a range of motion noise strengths, investigate average time to aggregation with a 15% stopping condition. """ N = [10, 25, 50, 100] fmax = np.arange(0, 40.1, 1.25) params = {'N' : N, 'noise' : [('mot', f) for f in fmax], 'stop' : [0.15]} exp = Experiment('motion', params, iters=25, savehist=False, seed=seed) exp.run() exp.save() exp.plot_aggtime(N, fmax, 'Max. Noise Force (N)') def exp_cone(seed=None): """ With default parameters and a range of sight sensor sizes, investigate average time to aggregation with a 15% stopping condition. """ N = [10, 25, 50, 100] sensor = np.arange(0, np.pi, 0.1) params = {'N' : N, 'sensor' : sensor, 'stop' : [0.15]} exp = Experiment('cone', params, iters=25, savehist=False, seed=seed) exp.run() exp.save() exp.plot_aggtime(N, sensor, 'Sight Sensor Size (rad)') ### CALIBRATION EXPERIMENTS ### def exp_step(seed=None): """ With default parameters and a range of time step durations, investigate aggregation over time. """ step = [0.0005, 0.001, 0.005, 0.01, 0.025] params = {'N' : [50], 'time' : [120], 'step' : step} exp = Experiment('step', params, seed=seed) exp.run() exp.save() exp.plot_evo(runs=np.arange(len(exp.params)), iters=[0], metrics=['disp'], \ labels=['{}s'.format(i) for i in step]) if __name__ == '__main__': # Parse command line arguments. parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-E', '--exps', type=str, nargs='+', required=True, \ help='IDs of experiments to run') parser.add_argument('-R', '--rand_seed', type=int, default=None, \ help='Seed for random number generation') args = parser.parse_args() # Run selected experiments. exps = {'base' : exp_base, 'symm' : exp_symm, 'errprob' : exp_errprob, \ 'motion' : exp_motion, 'cone' : exp_cone, 'step' : exp_step} for id in args.exps: exps[id](args.rand_seed)
[ "numpy.random.default_rng", "matplotlib.pyplot.Polygon", "matplotlib.collections.LineCollection", "math.cos", "aggregation.aggregation", "aggregation.ideal", "numpy.arange", "numpy.mean", "argparse.ArgumentParser", "tqdm.tqdm.write", "itertools.product", "numpy.max", "matplotlib.pyplot.close", "numpy.linspace", "numpy.min", "matplotlib.pyplot.Circle", "pickle.load", "matplotlib.cm.inferno", "numpy.copy", "pickle.dump", "math.ceil", "tqdm.tqdm", "matplotlib.collections.PatchCollection", "matplotlib.animation.ArtistAnimation", "matplotlib.pyplot.tight_layout", "numpy.full", "math.sin", "matplotlib.pyplot.subplots" ]
[((14036, 14063), 'numpy.arange', 'np.arange', (['(0)', '(0.501)', '(0.0125)'], {}), '(0, 0.501, 0.0125)\n', (14045, 14063), True, 'import numpy as np\n'), ((14529, 14553), 'numpy.arange', 'np.arange', (['(0)', '(40.1)', '(1.25)'], {}), '(0, 40.1, 1.25)\n', (14538, 14553), True, 'import numpy as np\n'), ((15011, 15035), 'numpy.arange', 'np.arange', (['(0)', 'np.pi', '(0.1)'], {}), '(0, np.pi, 0.1)\n', (15020, 15035), True, 'import numpy as np\n'), ((15833, 15877), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (15856, 15877), False, 'import argparse\n'), ((3384, 3435), 'tqdm.tqdm.write', 'tqdm.write', (["('Running Experiment ' + self.id + '...')"], {}), "('Running Experiment ' + self.id + '...')\n", (3394, 3435), False, 'from tqdm import tqdm\n'), ((3500, 3532), 'numpy.random.default_rng', 'np.random.default_rng', (['self.seed'], {}), '(self.seed)\n', (3521, 3532), True, 'import numpy as np\n'), ((4717, 4767), 'tqdm.tqdm.write', 'tqdm.write', (["('Saving Experiment ' + self.id + '...')"], {}), "('Saving Experiment ' + self.id + '...')\n", (4727, 4767), False, 'from tqdm import tqdm\n'), ((5182, 5225), 'tqdm.tqdm.write', 'tqdm.write', (['"""Plotting metrics over time..."""'], {}), "('Plotting metrics over time...')\n", (5192, 5225), False, 'from tqdm import tqdm\n'), ((8330, 8383), 'tqdm.tqdm.write', 'tqdm.write', (['"""Plotting average time to aggregation..."""'], {}), "('Plotting average time to aggregation...')\n", (8340, 8383), False, 'from tqdm import tqdm\n'), ((8439, 8453), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8451, 8453), True, 'import matplotlib.pyplot as plt\n'), ((9542, 9560), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9558, 9560), True, 'import matplotlib.pyplot as plt\n'), ((9649, 9660), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9658, 9660), True, 'import matplotlib.pyplot as plt\n'), ((9796, 9839), 'tqdm.tqdm.write', 'tqdm.write', (['"""Animating robots\' movement..."""'], {}), '("Animating robots\' movement...")\n', (9806, 9839), False, 'from tqdm import tqdm\n'), ((10287, 10324), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)', 'dpi': '(300)'}), '(figsize=(5, 5), dpi=300)\n', (10299, 10324), True, 'import matplotlib.pyplot as plt\n'), ((12676, 12731), 'matplotlib.animation.ArtistAnimation', 'ArtistAnimation', (['fig', 'ims'], {'interval': 'interval', 'blit': '(True)'}), '(fig, ims, interval=interval, blit=True)\n', (12691, 12731), False, 'from matplotlib.animation import FFMpegWriter, ArtistAnimation\n'), ((12804, 12815), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12813, 12815), True, 'import matplotlib.pyplot as plt\n'), ((12950, 12964), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12961, 12964), False, 'import pickle\n'), ((2734, 2749), 'itertools.product', 'product', (['*plist'], {}), '(*plist)\n', (2741, 2749), False, 'from itertools import product\n'), ((3759, 3800), 'tqdm.tqdm', 'tqdm', (['self.params'], {'desc': '"""Simulating runs"""'}), "(self.params, desc='Simulating runs')\n", (3763, 3800), False, 'from tqdm import tqdm\n'), ((4841, 4861), 'pickle.dump', 'pickle.dump', (['self', 'f'], {}), '(self, f)\n', (4852, 4861), False, 'import pickle\n'), ((5979, 5993), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5991, 5993), True, 'import matplotlib.pyplot as plt\n'), ((7855, 7873), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7871, 7873), True, 'import matplotlib.pyplot as plt\n'), ((7998, 8009), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8007, 8009), True, 'import matplotlib.pyplot as plt\n'), ((10776, 10798), 'math.ceil', 'ceil', (['(1 / frame / step)'], {}), '(1 / frame / step)\n', (10780, 10798), False, 'from math import sin, cos, hypot, ceil\n'), ((12250, 12304), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['robots'], {'match_original': '(True)', 'zorder': '(3)'}), '(robots, match_original=True, zorder=3)\n', (12265, 12304), False, 'from matplotlib.collections import LineCollection, PatchCollection, PolyCollection\n'), ((12325, 12394), 'matplotlib.collections.LineCollection', 'LineCollection', (['lines'], {'linewidths': '(0.5)', 'colors': 'c', 'alpha': '(0.75)', 'zorder': '(2)'}), '(lines, linewidths=0.5, colors=c, alpha=0.75, zorder=2)\n', (12339, 12394), False, 'from matplotlib.collections import LineCollection, PatchCollection, PolyCollection\n'), ((12451, 12504), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['cones'], {'match_original': '(True)', 'zorder': '(1)'}), '(cones, match_original=True, zorder=1)\n', (12466, 12504), False, 'from matplotlib.collections import LineCollection, PatchCollection, PolyCollection\n'), ((4041, 4129), 'aggregation.aggregation', 'aggregation', (['N', 'R', 'r', 'm', 'w0', 'w1', 'sensor', 'noise', 'time', 'step', 'stop', 'init', 'seed', 'silent'], {}), '(N, R, r, m, w0, w1, sensor, noise, time, step, stop, init, seed,\n silent)\n', (4052, 4129), False, 'from aggregation import aggregation, ideal\n'), ((5491, 5511), 'itertools.product', 'product', (['runs', 'iters'], {}), '(runs, iters)\n', (5498, 5511), False, 'from itertools import product\n'), ((5578, 5591), 'matplotlib.cm.inferno', 'cm.inferno', (['x'], {}), '(x)\n', (5588, 5591), True, 'import matplotlib.cm as cm\n'), ((6032, 6044), 'tqdm.tqdm', 'tqdm', (['runits'], {}), '(runits)\n', (6036, 6044), False, 'from tqdm import tqdm\n'), ((6360, 6410), 'tqdm.tqdm', 'tqdm', (['configs'], {'desc': "('Calculating ' + names[metric])"}), "(configs, desc='Calculating ' + names[metric])\n", (6364, 6410), False, 'from tqdm import tqdm\n'), ((8493, 8506), 'matplotlib.cm.inferno', 'cm.inferno', (['x'], {}), '(x)\n', (8503, 8506), True, 'import matplotlib.cm as cm\n'), ((10394, 10408), 'numpy.min', 'np.min', (['all_xy'], {}), '(all_xy)\n', (10400, 10408), True, 'import numpy as np\n'), ((10414, 10428), 'numpy.max', 'np.max', (['all_xy'], {}), '(all_xy)\n', (10420, 10428), True, 'import numpy as np\n'), ((10586, 10599), 'matplotlib.cm.inferno', 'cm.inferno', (['x'], {}), '(x)\n', (10596, 10599), True, 'import matplotlib.cm as cm\n'), ((10895, 10924), 'numpy.full', 'np.full', (['(2)', '(fig_max - fig_min)'], {}), '(2, fig_max - fig_min)\n', (10902, 10924), True, 'import numpy as np\n'), ((6267, 6298), 'numpy.arange', 'np.arange', (['(0)', '(time + step)', 'step'], {}), '(0, time + step, step)\n', (6276, 6298), True, 'import numpy as np\n'), ((9196, 9214), 'numpy.mean', 'np.mean', (['agg_times'], {}), '(agg_times)\n', (9203, 9214), True, 'import numpy as np\n'), ((10627, 10649), 'numpy.linspace', 'np.linspace', (['(0)', '(0.9)', 'N'], {}), '(0, 0.9, N)\n', (10638, 10649), True, 'import numpy as np\n'), ((11456, 11505), 'matplotlib.pyplot.Circle', 'plt.Circle', (['xy'], {'radius': 'r', 'linewidth': '(0)', 'color': 'c[i]'}), '(xy, radius=r, linewidth=0, color=c[i])\n', (11466, 11505), True, 'import matplotlib.pyplot as plt\n'), ((7167, 7178), 'aggregation.ideal', 'ideal', (['N', 'r'], {}), '(N, r)\n', (7172, 7178), False, 'from aggregation import aggregation, ideal\n'), ((12120, 12164), 'matplotlib.pyplot.Polygon', 'plt.Polygon', (['tri_pts'], {'color': 'c[i]', 'alpha': '(0.15)'}), '(tri_pts, color=c[i], alpha=0.15)\n', (12131, 12164), True, 'import matplotlib.pyplot as plt\n'), ((4353, 4380), 'numpy.copy', 'np.copy', (['history[final - 1]'], {}), '(history[final - 1])\n', (4360, 4380), True, 'import numpy as np\n'), ((7267, 7278), 'aggregation.ideal', 'ideal', (['N', 'r'], {}), '(N, r)\n', (7272, 7278), False, 'from aggregation import aggregation, ideal\n'), ((11617, 11627), 'math.cos', 'cos', (['theta'], {}), '(theta)\n', (11620, 11627), False, 'from math import sin, cos, hypot, ceil\n'), ((11629, 11639), 'math.sin', 'sin', (['theta'], {}), '(theta)\n', (11632, 11639), False, 'from math import sin, cos, hypot, ceil\n'), ((7363, 7374), 'aggregation.ideal', 'ideal', (['N', 'r'], {}), '(N, r)\n', (7368, 7374), False, 'from aggregation import aggregation, ideal\n'), ((7468, 7479), 'aggregation.ideal', 'ideal', (['N', 'r'], {}), '(N, r)\n', (7473, 7479), False, 'from aggregation import aggregation, ideal\n'), ((11346, 11356), 'math.cos', 'cos', (['theta'], {}), '(theta)\n', (11349, 11356), False, 'from math import sin, cos, hypot, ceil\n'), ((11362, 11372), 'math.sin', 'sin', (['theta'], {}), '(theta)\n', (11365, 11372), False, 'from math import sin, cos, hypot, ceil\n'), ((11917, 11924), 'math.cos', 'cos', (['cw'], {}), '(cw)\n', (11920, 11924), False, 'from math import sin, cos, hypot, ceil\n'), ((11926, 11933), 'math.sin', 'sin', (['cw'], {}), '(cw)\n', (11929, 11933), False, 'from math import sin, cos, hypot, ceil\n'), ((11987, 11995), 'math.cos', 'cos', (['ccw'], {}), '(ccw)\n', (11990, 11995), False, 'from math import sin, cos, hypot, ceil\n'), ((11997, 12005), 'math.sin', 'sin', (['ccw'], {}), '(ccw)\n', (12000, 12005), False, 'from math import sin, cos, hypot, ceil\n')]
from abc import ABCMeta, abstractmethod import numpy as np class BaseSubspace(metaclass=ABCMeta): def __init__(self, measurements=None, A=None, k=None, rank=None, pks=[], name=''): # Check A if A is None: self.__A = np.asarray(a=1, dtype=measurements.dtype) else: # Check the type and number of dimensions of A if not (type(A) is np.ndarray): raise ValueError('A must be an array') else: if not (len(A.shape) == 2): raise ValueError("Dimensions of A must be 2") self.__A = np.asarray(A) # Shape of A m, n = A.shape self.__At = np.transpose(np.conjugate(self.__A)) # Check measurements if measurements is None: self._measurements = np.asarray(1) else: if not (type(measurements) is np.ndarray): raise ValueError('measurements must be an array') # Check the dimensions of the measurements if not (measurements.shape[0] == A.shape[0]): raise ValueError("The dimension of y is not consistent with the dimensions of A") self.__measurements = np.asarray(a=measurements, dtype=measurements.dtype) # Control of the value of k if k is None: print('WARNING: Unknown sparsity considered. Some of the algorithms may not be applicable.') self.__k = k else: if k > self.A.shape[1]: raise ValueError("k cannot be larger than the number of atoms") else: self.__k = k # Assign the given rank if rank is not None: if rank < 0: raise ValueError('rank must be positive.') self._rank = rank # Check the partially known support if not(type(pks) is list): self._pks = pks.tolist() else: self._pks = pks # Create the solution self.sol = np.zeros(shape=(n, measurements.shape[1]), dtype=measurements.dtype) self.support_sol = [] # Assign the name self.__name = name @abstractmethod def solve(self, threshold): pass @property def A(self): return self.__A @property def At(self): return self.__At @property def measurements(self): return self.__measurements @property def k(self): return self.__k @property def name(self): return self.__name @property def rank(self): return self._rank @property def pks(self): return self._pks def estimate_measurement_rank(self): return np.linalg.matrix_rank(M=self.measurements, tol=None, hermitian=False) def compute_covariance_matrix(self): return np.matmul(self.measurements, np.conjugate(self.measurements.T)) / self.measurements.shape[1] def estimate_signal_subspace(self, threshold=0.01): # Compute the covariance matrix gamma = self.compute_covariance_matrix() # EVD eig_vals, eig_vecs = np.linalg.eigh(gamma, UPLO='L') eig_vals = eig_vals[::-1] eig_vecs = eig_vecs[:, ::-1] # If the rank is not known - Estimate the rank if self._rank is None: # Shape of the measurements m = self.measurements.shape[0] # Estimate the dimension of the signal subspace eig_diff = np.abs(np.diff(eig_vals)) ind = np.where(eig_diff >= threshold*eig_vals[0])[0][-1] self._rank = m - ind # r dominant eigenvectors of the covariance matrix U = eig_vecs[:,:self._rank] # Projection matrix P = np.matmul(U, np.conjugate(U.T)) return P def estimate_noise_subspace(self, threshold=0.1): # Compute the covariance matrix gamma = self.compute_covariance_matrix() # EVD eig_vals, eig_vecs = np.linalg.eigh(gamma, UPLO='L') eig_vals = eig_vals[::-1] eig_vecs = eig_vecs[:, ::-1] # If the rank is not known - Estimate the rank if self._rank is None: # Shape of the measurements m = self.measurements.shape[0] # Estimate the dimension of the signal subspace eig_diff = np.diff(eig_vals) ind = np.where(eig_diff >= threshold*eig_vals[0])[0] self._rank = m - ind # n-r lowest eigenvectors of the covariance matrix U = eig_vecs[:,self.rank:] # Projection matrix P = np.matmul(U, np.conjugate(U.T)) return P
[ "numpy.linalg.matrix_rank", "numpy.where", "numpy.conjugate", "numpy.asarray", "numpy.diff", "numpy.zeros", "numpy.linalg.eigh" ]
[((2029, 2097), 'numpy.zeros', 'np.zeros', ([], {'shape': '(n, measurements.shape[1])', 'dtype': 'measurements.dtype'}), '(shape=(n, measurements.shape[1]), dtype=measurements.dtype)\n', (2037, 2097), True, 'import numpy as np\n'), ((2735, 2804), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', ([], {'M': 'self.measurements', 'tol': 'None', 'hermitian': '(False)'}), '(M=self.measurements, tol=None, hermitian=False)\n', (2756, 2804), True, 'import numpy as np\n'), ((3145, 3176), 'numpy.linalg.eigh', 'np.linalg.eigh', (['gamma'], {'UPLO': '"""L"""'}), "(gamma, UPLO='L')\n", (3159, 3176), True, 'import numpy as np\n'), ((4005, 4036), 'numpy.linalg.eigh', 'np.linalg.eigh', (['gamma'], {'UPLO': '"""L"""'}), "(gamma, UPLO='L')\n", (4019, 4036), True, 'import numpy as np\n'), ((249, 290), 'numpy.asarray', 'np.asarray', ([], {'a': '(1)', 'dtype': 'measurements.dtype'}), '(a=1, dtype=measurements.dtype)\n', (259, 290), True, 'import numpy as np\n'), ((614, 627), 'numpy.asarray', 'np.asarray', (['A'], {}), '(A)\n', (624, 627), True, 'import numpy as np\n'), ((713, 735), 'numpy.conjugate', 'np.conjugate', (['self.__A'], {}), '(self.__A)\n', (725, 735), True, 'import numpy as np\n'), ((833, 846), 'numpy.asarray', 'np.asarray', (['(1)'], {}), '(1)\n', (843, 846), True, 'import numpy as np\n'), ((1229, 1281), 'numpy.asarray', 'np.asarray', ([], {'a': 'measurements', 'dtype': 'measurements.dtype'}), '(a=measurements, dtype=measurements.dtype)\n', (1239, 1281), True, 'import numpy as np\n'), ((3780, 3797), 'numpy.conjugate', 'np.conjugate', (['U.T'], {}), '(U.T)\n', (3792, 3797), True, 'import numpy as np\n'), ((4362, 4379), 'numpy.diff', 'np.diff', (['eig_vals'], {}), '(eig_vals)\n', (4369, 4379), True, 'import numpy as np\n'), ((4627, 4644), 'numpy.conjugate', 'np.conjugate', (['U.T'], {}), '(U.T)\n', (4639, 4644), True, 'import numpy as np\n'), ((2891, 2924), 'numpy.conjugate', 'np.conjugate', (['self.measurements.T'], {}), '(self.measurements.T)\n', (2903, 2924), True, 'import numpy as np\n'), ((3509, 3526), 'numpy.diff', 'np.diff', (['eig_vals'], {}), '(eig_vals)\n', (3516, 3526), True, 'import numpy as np\n'), ((4398, 4443), 'numpy.where', 'np.where', (['(eig_diff >= threshold * eig_vals[0])'], {}), '(eig_diff >= threshold * eig_vals[0])\n', (4406, 4443), True, 'import numpy as np\n'), ((3546, 3591), 'numpy.where', 'np.where', (['(eig_diff >= threshold * eig_vals[0])'], {}), '(eig_diff >= threshold * eig_vals[0])\n', (3554, 3591), True, 'import numpy as np\n')]
import os import pytest import numpy as np from laserembeddings import Laser SIMILARITY_TEST = os.getenv('SIMILARITY_TEST') def test_laser(): with open(Laser.DEFAULT_ENCODER_FILE, 'rb') as f_encoder: laser = Laser( Laser.DEFAULT_BPE_CODES_FILE, None, f_encoder, ) assert laser.embed_sentences( ['hello world!', 'i hope the tests are passing'], lang='en').shape == (2, 1024) def test_similarity(test_data): if not SIMILARITY_TEST: pytest.skip("SIMILARITY_TEST not set") if not test_data: raise FileNotFoundError( 'laserembeddings-test-data.npz is missing, run "python -m laserembeddings download-test-data" to fix that 🔧' ) report = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'report', 'comparison-with-LASER.md') laser = Laser() with open(report, 'w', encoding='utf-8') as f_report: f_report.write( '# Comparison of the embeddings computed with original LASER with the embeddings computed with this package\n' ) f_report.write( '| |language|avg. cosine similarity|min. cosine similarity|\n') f_report.write( '|-|--------|----------------------|----------------------|\n') for lang in test_data['langs']: if lang in ('cmn', 'wuu', 'yue', 'zh', 'jpn', 'ja', 'el'): # language not supported, ignoring continue sents = test_data[f'{lang}_sentences'] orig_embeddings = test_data[f'{lang}_embeddings'] embeddings = laser.embed_sentences(sents, lang) assert embeddings.shape == orig_embeddings.shape cosine_similarities = np.sum( orig_embeddings * embeddings, axis=1) / (np.linalg.norm(orig_embeddings, axis=1) * np.linalg.norm(embeddings, axis=1)) similarity_mean = np.mean(cosine_similarities) similarity_min = np.min(cosine_similarities) f_report.write( f'|{"✅" if similarity_min > 0.99999 else "⚠️" if similarity_mean > 0.99 else "❌"}|{lang}|{similarity_mean:.5f}|{similarity_min:.5f}|\n' )
[ "numpy.mean", "os.getenv", "numpy.linalg.norm", "os.path.realpath", "numpy.sum", "numpy.min", "pytest.skip", "laserembeddings.Laser" ]
[((98, 126), 'os.getenv', 'os.getenv', (['"""SIMILARITY_TEST"""'], {}), "('SIMILARITY_TEST')\n", (107, 126), False, 'import os\n'), ((912, 919), 'laserembeddings.Laser', 'Laser', ([], {}), '()\n', (917, 919), False, 'from laserembeddings import Laser\n'), ((225, 277), 'laserembeddings.Laser', 'Laser', (['Laser.DEFAULT_BPE_CODES_FILE', 'None', 'f_encoder'], {}), '(Laser.DEFAULT_BPE_CODES_FILE, None, f_encoder)\n', (230, 277), False, 'from laserembeddings import Laser\n'), ((537, 575), 'pytest.skip', 'pytest.skip', (['"""SIMILARITY_TEST not set"""'], {}), "('SIMILARITY_TEST not set')\n", (548, 575), False, 'import pytest\n'), ((806, 832), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (822, 832), False, 'import os\n'), ((2014, 2042), 'numpy.mean', 'np.mean', (['cosine_similarities'], {}), '(cosine_similarities)\n', (2021, 2042), True, 'import numpy as np\n'), ((2072, 2099), 'numpy.min', 'np.min', (['cosine_similarities'], {}), '(cosine_similarities)\n', (2078, 2099), True, 'import numpy as np\n'), ((1797, 1841), 'numpy.sum', 'np.sum', (['(orig_embeddings * embeddings)'], {'axis': '(1)'}), '(orig_embeddings * embeddings, axis=1)\n', (1803, 1841), True, 'import numpy as np\n'), ((1878, 1917), 'numpy.linalg.norm', 'np.linalg.norm', (['orig_embeddings'], {'axis': '(1)'}), '(orig_embeddings, axis=1)\n', (1892, 1917), True, 'import numpy as np\n'), ((1947, 1981), 'numpy.linalg.norm', 'np.linalg.norm', (['embeddings'], {'axis': '(1)'}), '(embeddings, axis=1)\n', (1961, 1981), True, 'import numpy as np\n')]
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here data_file='subset_1000.csv' data=np.genfromtxt(path,delimiter=",",skip_header=1) print(data) census=np.concatenate((new_record,data),axis=0) print(census) # -------------- #Code starts here age=census[:,0] max_age=np.max(age) min_age=np.min(age) age_mean=np.mean(age) age_std=np.std(age) # -------------- #Code starts here race_0=census[census[:,2]==0] race_1=census[census[:,2]==1] race_2=census[census[:,2]==2] race_3=census[census[:,2]==3] race_4=census[census[:,2]==4] len_0=len(race_0) len_1=len(race_1) len_2=len(race_2) len_3=len(race_3) len_4=len(race_4) print(len_0,len_1,len_2,len_3,len_4) minority_race=3 # -------------- #Code starts here senior_citizens=census[census[:,0]>60] working_hours_sum=senior_citizens.sum(axis=0)[6] senior_citizens_len=len(senior_citizens) avg_working_hours=working_hours_sum/senior_citizens_len print(avg_working_hours) # -------------- #Code starts here high=census[census[:,1]>10] low=census[census[:,1]<=10] avg_pay_high=round(high.mean(axis=0)[7],2) avg_pay_low=round(low.mean(axis=0)[7],2) print(avg_pay_high,avg_pay_low) a=avg_pay_high-avg_pay_low print(a)
[ "numpy.mean", "numpy.std", "numpy.max", "numpy.concatenate", "numpy.min", "numpy.genfromtxt" ]
[((244, 293), 'numpy.genfromtxt', 'np.genfromtxt', (['path'], {'delimiter': '""","""', 'skip_header': '(1)'}), "(path, delimiter=',', skip_header=1)\n", (257, 293), True, 'import numpy as np\n'), ((313, 355), 'numpy.concatenate', 'np.concatenate', (['(new_record, data)'], {'axis': '(0)'}), '((new_record, data), axis=0)\n', (327, 355), True, 'import numpy as np\n'), ((432, 443), 'numpy.max', 'np.max', (['age'], {}), '(age)\n', (438, 443), True, 'import numpy as np\n'), ((453, 464), 'numpy.min', 'np.min', (['age'], {}), '(age)\n', (459, 464), True, 'import numpy as np\n'), ((475, 487), 'numpy.mean', 'np.mean', (['age'], {}), '(age)\n', (482, 487), True, 'import numpy as np\n'), ((497, 508), 'numpy.std', 'np.std', (['age'], {}), '(age)\n', (503, 508), True, 'import numpy as np\n')]
import numpy as np from matplotlib import pyplot as plt """ https://stackoverflow.com/questions/42750910/convert-rgb-image-to-index-image/62980021#62980021 convert semantic labels from RGB coding to index coding Steps: 1. define COLORS (see below) 2. hash colors 3. run rgb2index(segmentation_rgb) see example below TODO: apparently, using cv2.LUT is much simpler (and maybe faster?) """ COLORS = np.array([[0, 0, 0], [0, 0, 255], [255, 0, 0], [0, 255, 0]]) W = np.power(255, [0, 1, 2]) HASHES = np.sum(W * COLORS, axis=-1) HASH2COLOR = {h: c for h, c in zip(HASHES, COLORS)} HASH2IDX = {h: i for i, h in enumerate(HASHES)} def rgb2index(segmentation_rgb): """ turn a 3 channel RGB color to 1 channel index color """ s_shape = segmentation_rgb.shape s_hashes = np.sum(W * segmentation_rgb, axis=-1) print(np.unique(segmentation_rgb.reshape((-1, 3)), axis=0)) func = lambda x: HASH2IDX[int(x)] # noqa segmentation_idx = np.apply_along_axis(func, 0, s_hashes.reshape((1, -1))) segmentation_idx = segmentation_idx.reshape(s_shape[:2]) return segmentation_idx segmentation = np.array([[0, 0, 0], [0, 0, 255], [255, 0, 0]] * 3).reshape((3, 3, 3)) segmentation_idx = rgb2index(segmentation) print(segmentation) print(segmentation_idx) fig, axes = plt.subplots(1, 2, figsize=(6, 3)) axes[0].imshow(segmentation) axes[0].set_title("Segmentation RGB") axes[1].imshow(segmentation_idx) axes[1].set_title("Segmentation IDX") plt.show()
[ "numpy.power", "numpy.array", "numpy.sum", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((402, 462), 'numpy.array', 'np.array', (['[[0, 0, 0], [0, 0, 255], [255, 0, 0], [0, 255, 0]]'], {}), '([[0, 0, 0], [0, 0, 255], [255, 0, 0], [0, 255, 0]])\n', (410, 462), True, 'import numpy as np\n'), ((467, 491), 'numpy.power', 'np.power', (['(255)', '[0, 1, 2]'], {}), '(255, [0, 1, 2])\n', (475, 491), True, 'import numpy as np\n'), ((502, 529), 'numpy.sum', 'np.sum', (['(W * COLORS)'], {'axis': '(-1)'}), '(W * COLORS, axis=-1)\n', (508, 529), True, 'import numpy as np\n'), ((1294, 1328), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(6, 3)'}), '(1, 2, figsize=(6, 3))\n', (1306, 1328), True, 'from matplotlib import pyplot as plt\n'), ((1467, 1477), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1475, 1477), True, 'from matplotlib import pyplot as plt\n'), ((789, 826), 'numpy.sum', 'np.sum', (['(W * segmentation_rgb)'], {'axis': '(-1)'}), '(W * segmentation_rgb, axis=-1)\n', (795, 826), True, 'import numpy as np\n'), ((1122, 1173), 'numpy.array', 'np.array', (['([[0, 0, 0], [0, 0, 255], [255, 0, 0]] * 3)'], {}), '([[0, 0, 0], [0, 0, 255], [255, 0, 0]] * 3)\n', (1130, 1173), True, 'import numpy as np\n')]
import os import wandb import torch import warnings import numpy as np import torchvision.transforms from fvcore.nn import FlopCountAnalysis from dpt.models import DPTDepthModel def get_flops(model, x, unit="G", quiet=True): _prefix = {'k': 1e3, # kilo 'M': 1e6, # mega 'G': 1e9, # giga 'T': 1e12, # tera 'P': 1e15, # peta } flops = FlopCountAnalysis(model, x) num_flops = flops.total() / _prefix[unit] if not quiet: print(f"Model FLOPs: {num_flops:.2f} {unit}FLOPs") return num_flops def get_model_size(model): torch.save(model.state_dict(), "tmp.pt") model_size = os.path.getsize("tmp.pt")/1e6 os.remove('tmp.pt') return model_size # Hyperparameters and config # Input net_w, net_h = 640, 192 h_kitti, w_kitti = 352, 1216 # Model architecture backbone = "vitb_rn50_384" # "vitb_effb0" transformer_hooks = "str:8,11" attention_variant = None # "performer" attention_heads = 12 mixed_precision = False config_dict = { "input_size": f"{net_h},{net_w}", "downsampling": "Resize image along w and h", "mixed_precision": mixed_precision, "backbone": backbone, "transformer_hooks": transformer_hooks, "attention_variant": attention_variant, "attention_heads": attention_heads, } if __name__ == "__main__": warnings.simplefilter("ignore", UserWarning) # Init wandb wandb.init(config=config_dict) config = wandb.config # Re-read config for wandb-sweep-managed inference mixed_precision = config["mixed_precision"] backbone = config["backbone"] transformer_hooks = config["transformer_hooks"] attention_variant = config["attention_variant"] if attention_variant == "None": attention_variant = None attention_heads = config["attention_heads"] input_size = config["input_size"] net_h = int(input_size.split(",")[0]) net_w = int(input_size.split(",")[1]) # Convert str hooks to list (wandb hacky solution to display hooks correctly) assert isinstance(transformer_hooks, str) and transformer_hooks[:4] == "str:", \ 'Hooks are not in the format "str:[att_hook1, att_hook2]"' conv_hooks = {"vitb_rn50_384": [0, 1], "vitb_effb0": [1, 2]}[backbone] transformer_hooks = [int(hook) for hook in transformer_hooks.split(":")[-1].split(",")] hooks = conv_hooks + transformer_hooks # Get cpu or gpu device for training. device = "cuda" if torch.cuda.is_available() else "cpu" print("Using {} device".format(device)) torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True # Create model model = DPTDepthModel( path=None, scale=0.00006016, # KITTI shift=0.00579, invert=True, backbone=backbone, attention_heads=attention_heads, hooks=hooks, non_negative=True, enable_attention_hooks=False, attention_variant=attention_variant).to(device) n_inferences = 500 wandb.log({"num_inferences": n_inferences}) measures = np.zeros((n_inferences, 1)) x = torch.rand(1, 3, h_kitti, w_kitti).to(device) print(f"Kitti size: {h_kitti}, {w_kitti} | Network input size: {net_h}, {net_w}") # Cuda events t0 = torch.cuda.Event(enable_timing=True) end = torch.cuda.Event(enable_timing=True) # Measure inference time with torch.no_grad(): with torch.cuda.amp.autocast(enabled=mixed_precision): dummy = torchvision.transforms.Resize((net_h, net_w))(x) _ = model(dummy) # Warm-up for i in range(n_inferences): t0.record() if net_h != h_kitti or net_w != w_kitti: x = torchvision.transforms.Resize((net_h, net_w))(x) y = model(x) if net_h != h_kitti or net_w != w_kitti: _ = torch.nn.functional.interpolate(y.unsqueeze(1), size=(h_kitti, w_kitti), mode="bicubic", align_corners=True) end.record() torch.cuda.synchronize() measures[i] = t0.elapsed_time(end) mean_ms = np.mean(measures) std_ms = np.std(measures) fps = 1000/measures mean_fps = np.mean(fps) std_fps = np.std(fps) GFLOPs = get_flops(model.to("cpu"), x.to("cpu")) model_MB = get_model_size(model) wandb.log({"FPS": mean_fps, "std_fps": std_fps, "ms": mean_ms, "std_ms": std_ms, "GFLOPs": GFLOPs, "MB": model_MB}) print(f"FPS: {mean_fps:.2f} +- {1/std_fps:.2f} || Inference speed (ms): {mean_ms:.4f} +- {std_ms:.4f}") print(f"GFLOPs: {GFLOPs:.3f} || Model size (MB): {model_MB:.2f}")
[ "torch.cuda.Event", "numpy.mean", "os.path.getsize", "wandb.log", "fvcore.nn.FlopCountAnalysis", "wandb.init", "torch.cuda.synchronize", "numpy.zeros", "torch.cuda.is_available", "torch.cuda.amp.autocast", "numpy.std", "warnings.simplefilter", "torch.no_grad", "dpt.models.DPTDepthModel", "torch.rand", "os.remove" ]
[((424, 451), 'fvcore.nn.FlopCountAnalysis', 'FlopCountAnalysis', (['model', 'x'], {}), '(model, x)\n', (441, 451), False, 'from fvcore.nn import FlopCountAnalysis\n'), ((721, 740), 'os.remove', 'os.remove', (['"""tmp.pt"""'], {}), "('tmp.pt')\n", (730, 740), False, 'import os\n'), ((1369, 1413), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (1390, 1413), False, 'import warnings\n'), ((1436, 1466), 'wandb.init', 'wandb.init', ([], {'config': 'config_dict'}), '(config=config_dict)\n', (1446, 1466), False, 'import wandb\n'), ((3111, 3154), 'wandb.log', 'wandb.log', (["{'num_inferences': n_inferences}"], {}), "({'num_inferences': n_inferences})\n", (3120, 3154), False, 'import wandb\n'), ((3170, 3197), 'numpy.zeros', 'np.zeros', (['(n_inferences, 1)'], {}), '((n_inferences, 1))\n', (3178, 3197), True, 'import numpy as np\n'), ((3366, 3402), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (3382, 3402), False, 'import torch\n'), ((3413, 3449), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (3429, 3449), False, 'import torch\n'), ((4400, 4417), 'numpy.mean', 'np.mean', (['measures'], {}), '(measures)\n', (4407, 4417), True, 'import numpy as np\n'), ((4431, 4447), 'numpy.std', 'np.std', (['measures'], {}), '(measures)\n', (4437, 4447), True, 'import numpy as np\n'), ((4487, 4499), 'numpy.mean', 'np.mean', (['fps'], {}), '(fps)\n', (4494, 4499), True, 'import numpy as np\n'), ((4514, 4525), 'numpy.std', 'np.std', (['fps'], {}), '(fps)\n', (4520, 4525), True, 'import numpy as np\n'), ((4621, 4740), 'wandb.log', 'wandb.log', (["{'FPS': mean_fps, 'std_fps': std_fps, 'ms': mean_ms, 'std_ms': std_ms,\n 'GFLOPs': GFLOPs, 'MB': model_MB}"], {}), "({'FPS': mean_fps, 'std_fps': std_fps, 'ms': mean_ms, 'std_ms':\n std_ms, 'GFLOPs': GFLOPs, 'MB': model_MB})\n", (4630, 4740), False, 'import wandb\n'), ((687, 712), 'os.path.getsize', 'os.path.getsize', (['"""tmp.pt"""'], {}), "('tmp.pt')\n", (702, 712), False, 'import os\n'), ((2484, 2509), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2507, 2509), False, 'import torch\n'), ((3489, 3504), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3502, 3504), False, 'import torch\n'), ((2680, 2913), 'dpt.models.DPTDepthModel', 'DPTDepthModel', ([], {'path': 'None', 'scale': '(6.016e-05)', 'shift': '(0.00579)', 'invert': '(True)', 'backbone': 'backbone', 'attention_heads': 'attention_heads', 'hooks': 'hooks', 'non_negative': '(True)', 'enable_attention_hooks': '(False)', 'attention_variant': 'attention_variant'}), '(path=None, scale=6.016e-05, shift=0.00579, invert=True,\n backbone=backbone, attention_heads=attention_heads, hooks=hooks,\n non_negative=True, enable_attention_hooks=False, attention_variant=\n attention_variant)\n', (2693, 2913), False, 'from dpt.models import DPTDepthModel\n'), ((3206, 3240), 'torch.rand', 'torch.rand', (['(1)', '(3)', 'h_kitti', 'w_kitti'], {}), '(1, 3, h_kitti, w_kitti)\n', (3216, 3240), False, 'import torch\n'), ((3519, 3567), 'torch.cuda.amp.autocast', 'torch.cuda.amp.autocast', ([], {'enabled': 'mixed_precision'}), '(enabled=mixed_precision)\n', (3542, 3567), False, 'import torch\n'), ((4310, 4334), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (4332, 4334), False, 'import torch\n')]
# -*- coding: utf-8 -*- import json import os import numpy as np import tensorflow.compat.v1 as tf from src import model, sample, encoder from flask import Flask from flask import request, jsonify import time ######model def interact_model( model_name='run1', seed=None, nsamples=1, batch_size=1, length=None, temperature=1, top_k=0, top_p=1, models_dir='checkpoint', ): models_dir = os.path.expanduser(os.path.expandvars(models_dir)) if batch_size is None: batch_size = 1 assert nsamples % batch_size == 0 enc = encoder.get_encoder(model_name, models_dir) hparams = model.default_hparams() with open(os.path.join(models_dir, model_name, 'hparams.json')) as f: hparams.override_from_dict(json.load(f)) if length is None: length = hparams.n_ctx // 2 elif length > hparams.n_ctx: raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx) with tf.Session(graph=tf.Graph()) as sess: context = tf.placeholder(tf.int32, [batch_size, None]) np.random.seed(seed) tf.set_random_seed(seed) output = sample.sample_sequence( hparams=hparams, length=length, context=context, batch_size=batch_size, temperature=temperature, top_k=top_k, top_p=top_p ) saver = tf.train.Saver() ckpt = tf.train.latest_checkpoint(os.path.join(models_dir, "run1")) saver.restore(sess, ckpt) yield sess, context, output, enc def output_something(bio, sess, context, output, enc): raw_text = bio#input("Model prompt >>> ") context_tokens = enc.encode(raw_text) generated = 0 out = sess.run(output, feed_dict={ context: [context_tokens for _ in range(1)] })[:, len(context_tokens):] #Get samples text = enc.decode(out[0]) #decodes samples print(text) return text ########API gen = interact_model() sess, context, output, enc = next(gen) app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def welcome(): start_time = time.time() bio = request.args.get('bio') res = output_something(bio, sess, context, output, enc) sentences = res.split("\n")[:3] print("----------------------------------------------------------- %s seconds ----------------------------------------------" % (time.time() - start_time)) return jsonify(sentences=sentences) if __name__ == '__main__': app.run(host='0.0.0.0', port=105)
[ "tensorflow.compat.v1.placeholder", "flask.request.args.get", "src.model.default_hparams", "src.encoder.get_encoder", "tensorflow.compat.v1.Graph", "flask.Flask", "os.path.expandvars", "os.path.join", "numpy.random.seed", "tensorflow.compat.v1.set_random_seed", "src.sample.sample_sequence", "json.load", "time.time", "tensorflow.compat.v1.train.Saver", "flask.jsonify" ]
[((2062, 2077), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (2067, 2077), False, 'from flask import Flask\n'), ((583, 626), 'src.encoder.get_encoder', 'encoder.get_encoder', (['model_name', 'models_dir'], {}), '(model_name, models_dir)\n', (602, 626), False, 'from src import model, sample, encoder\n'), ((641, 664), 'src.model.default_hparams', 'model.default_hparams', ([], {}), '()\n', (662, 664), False, 'from src import model, sample, encoder\n'), ((2152, 2163), 'time.time', 'time.time', ([], {}), '()\n', (2161, 2163), False, 'import time\n'), ((2175, 2198), 'flask.request.args.get', 'request.args.get', (['"""bio"""'], {}), "('bio')\n", (2191, 2198), False, 'from flask import request, jsonify\n'), ((2471, 2499), 'flask.jsonify', 'jsonify', ([], {'sentences': 'sentences'}), '(sentences=sentences)\n', (2478, 2499), False, 'from flask import request, jsonify\n'), ((452, 482), 'os.path.expandvars', 'os.path.expandvars', (['models_dir'], {}), '(models_dir)\n', (470, 482), False, 'import os\n'), ((1037, 1081), 'tensorflow.compat.v1.placeholder', 'tf.placeholder', (['tf.int32', '[batch_size, None]'], {}), '(tf.int32, [batch_size, None])\n', (1051, 1081), True, 'import tensorflow.compat.v1 as tf\n'), ((1090, 1110), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1104, 1110), True, 'import numpy as np\n'), ((1119, 1143), 'tensorflow.compat.v1.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (1137, 1143), True, 'import tensorflow.compat.v1 as tf\n'), ((1161, 1310), 'src.sample.sample_sequence', 'sample.sample_sequence', ([], {'hparams': 'hparams', 'length': 'length', 'context': 'context', 'batch_size': 'batch_size', 'temperature': 'temperature', 'top_k': 'top_k', 'top_p': 'top_p'}), '(hparams=hparams, length=length, context=context,\n batch_size=batch_size, temperature=temperature, top_k=top_k, top_p=top_p)\n', (1183, 1310), False, 'from src import model, sample, encoder\n'), ((1382, 1398), 'tensorflow.compat.v1.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (1396, 1398), True, 'import tensorflow.compat.v1 as tf\n'), ((679, 731), 'os.path.join', 'os.path.join', (['models_dir', 'model_name', '"""hparams.json"""'], {}), "(models_dir, model_name, 'hparams.json')\n", (691, 731), False, 'import os\n'), ((774, 786), 'json.load', 'json.load', (['f'], {}), '(f)\n', (783, 786), False, 'import json\n'), ((1441, 1473), 'os.path.join', 'os.path.join', (['models_dir', '"""run1"""'], {}), "(models_dir, 'run1')\n", (1453, 1473), False, 'import os\n'), ((998, 1008), 'tensorflow.compat.v1.Graph', 'tf.Graph', ([], {}), '()\n', (1006, 1008), True, 'import tensorflow.compat.v1 as tf\n'), ((2433, 2444), 'time.time', 'time.time', ([], {}), '()\n', (2442, 2444), False, 'import time\n')]
import numpy as np from copy import copy from .utils.thresholdcurator import ThresholdCurator from .quality_metric import QualityMetric import spiketoolkit as st import spikemetrics.metrics as metrics from spikemetrics.utils import printProgressBar from collections import OrderedDict from sklearn.neighbors import NearestNeighbors from .parameter_dictionaries import update_all_param_dicts_with_kwargs class NoiseOverlap(QualityMetric): installed = True # check at class level if installed or not installation_mesg = "" # err params = OrderedDict([('max_spikes_per_unit_for_noise_overlap', 1000), ('num_features', 10), ('num_knn', 6)]) curator_name = "ThresholdNoiseOverlaps" def __init__(self, metric_data): QualityMetric.__init__(self, metric_data, metric_name="noise_overlap") if not metric_data.has_recording(): raise ValueError("MetricData object must have a recording") def compute_metric(self, max_spikes_per_unit_for_noise_overlap, num_features, num_knn, **kwargs): params_dict = update_all_param_dicts_with_kwargs(kwargs) save_property_or_features = params_dict['save_property_or_features'] seed = params_dict['seed'] waveforms = st.postprocessing.get_unit_waveforms( self._metric_data._recording, self._metric_data._sorting, unit_ids=self._metric_data._unit_ids, max_spikes_per_unit=max_spikes_per_unit_for_noise_overlap, **kwargs ) if seed is not None: np.random.seed(seed) noise_overlaps = [] for i_u, unit in enumerate(self._metric_data._unit_ids): if self._metric_data.verbose: printProgressBar(i_u + 1, len(self._metric_data._unit_ids)) wfs = waveforms[i_u] times = self._metric_data._sorting.get_unit_spike_train(unit_id=unit) if len(wfs) > max_spikes_per_unit_for_noise_overlap: selecte_idxs = np.random.choice(times, size=max_spikes_per_unit_for_noise_overlap) wfs = wfs[selecte_idxs] # get clip_size from waveforms shape clip_size = wfs.shape[-1] num_clips = len(wfs) min_time = np.min(times) max_time = np.max(times) times_control = np.random.choice(np.arange(min_time, max_time), size=num_clips) clips = copy(wfs) clips_control = np.stack(self._metric_data._recording.get_snippets(snippet_len=clip_size, reference_frames=times_control)) template = np.median(wfs, axis=0) max_ind = np.unravel_index(np.argmax(np.abs(template)), template.shape) chmax = max_ind[0] tmax = max_ind[1] max_val = template[chmax, tmax] weighted_clips_control = np.zeros(clips_control.shape) weights = np.zeros(num_clips) for j in range(num_clips): clip0 = clips_control[j, :, :] val0 = clip0[chmax, tmax] weight0 = val0 * max_val weights[j] = weight0 weighted_clips_control[j, :, :] = clip0 * weight0 noise_template = np.sum(weighted_clips_control, axis=0) noise_template = noise_template / np.sum(np.abs(noise_template)) * np.sum(np.abs(template)) for j in range(num_clips): clips[j, :, :] = _subtract_clip_component(clips[j, :, :], noise_template) clips_control[j, :, :] = _subtract_clip_component(clips_control[j, :, :], noise_template) all_clips = np.concatenate([clips, clips_control], axis=0) num_channels_wfs = all_clips.shape[1] num_samples_wfs = all_clips.shape[2] all_features = _compute_pca_features(all_clips.reshape((num_clips * 2, num_channels_wfs * num_samples_wfs)), num_features) num_all_clips=len(all_clips) distances, indices = NearestNeighbors(n_neighbors=min(num_knn + 1, num_all_clips - 1), algorithm='auto').fit( all_features.T).kneighbors() group_id = np.zeros((num_clips * 2)) group_id[0:num_clips] = 1 group_id[num_clips:] = 2 num_match = 0 total = 0 for j in range(num_clips * 2): for k in range(1, min(num_knn + 1, num_all_clips - 1)): ind = indices[j][k] if group_id[j] == group_id[ind]: num_match = num_match + 1 total = total + 1 pct_match = num_match / total noise_overlap = 1 - pct_match noise_overlaps.append(noise_overlap) noise_overlaps = np.asarray(noise_overlaps) if save_property_or_features: self.save_property_or_features(self._metric_data._sorting, noise_overlaps, self._metric_name) return noise_overlaps def threshold_metric(self, threshold, threshold_sign, max_spikes_per_unit_for_noise_overlap, num_features, num_knn, **kwargs): noise_overlaps = self.compute_metric(max_spikes_per_unit_for_noise_overlap, num_features, num_knn, **kwargs) threshold_curator = ThresholdCurator(sorting=self._metric_data._sorting, metric=noise_overlaps) threshold_curator.threshold_sorting(threshold=threshold, threshold_sign=threshold_sign) return threshold_curator def _compute_pca_features(X, num_components): u, s, vt = np.linalg.svd(X) return u[:, :num_components].T def _subtract_clip_component(clip1, component): V1 = clip1.flatten() V2 = component.flatten() V1 = V1 - np.mean(V1) V2 = V2 - np.mean(V2) V1 = V1 - V2 * np.dot(V1, V2) / np.dot(V2, V2) return V1.reshape(clip1.shape)
[ "numpy.mean", "collections.OrderedDict", "spiketoolkit.postprocessing.get_unit_waveforms", "numpy.median", "numpy.abs", "numpy.random.choice", "numpy.asarray", "numpy.max", "numpy.sum", "numpy.zeros", "numpy.dot", "numpy.random.seed", "numpy.concatenate", "numpy.min", "numpy.linalg.svd", "copy.copy", "numpy.arange" ]
[((552, 657), 'collections.OrderedDict', 'OrderedDict', (["[('max_spikes_per_unit_for_noise_overlap', 1000), ('num_features', 10), (\n 'num_knn', 6)]"], {}), "([('max_spikes_per_unit_for_noise_overlap', 1000), (\n 'num_features', 10), ('num_knn', 6)])\n", (563, 657), False, 'from collections import OrderedDict\n'), ((5662, 5678), 'numpy.linalg.svd', 'np.linalg.svd', (['X'], {}), '(X)\n', (5675, 5678), True, 'import numpy as np\n'), ((1258, 1468), 'spiketoolkit.postprocessing.get_unit_waveforms', 'st.postprocessing.get_unit_waveforms', (['self._metric_data._recording', 'self._metric_data._sorting'], {'unit_ids': 'self._metric_data._unit_ids', 'max_spikes_per_unit': 'max_spikes_per_unit_for_noise_overlap'}), '(self._metric_data._recording, self.\n _metric_data._sorting, unit_ids=self._metric_data._unit_ids,\n max_spikes_per_unit=max_spikes_per_unit_for_noise_overlap, **kwargs)\n', (1294, 1468), True, 'import spiketoolkit as st\n'), ((4891, 4917), 'numpy.asarray', 'np.asarray', (['noise_overlaps'], {}), '(noise_overlaps)\n', (4901, 4917), True, 'import numpy as np\n'), ((5832, 5843), 'numpy.mean', 'np.mean', (['V1'], {}), '(V1)\n', (5839, 5843), True, 'import numpy as np\n'), ((5858, 5869), 'numpy.mean', 'np.mean', (['V2'], {}), '(V2)\n', (5865, 5869), True, 'import numpy as np\n'), ((1572, 1592), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1586, 1592), True, 'import numpy as np\n'), ((2270, 2283), 'numpy.min', 'np.min', (['times'], {}), '(times)\n', (2276, 2283), True, 'import numpy as np\n'), ((2307, 2320), 'numpy.max', 'np.max', (['times'], {}), '(times)\n', (2313, 2320), True, 'import numpy as np\n'), ((2433, 2442), 'copy.copy', 'copy', (['wfs'], {}), '(wfs)\n', (2437, 2442), False, 'from copy import copy\n'), ((2680, 2702), 'numpy.median', 'np.median', (['wfs'], {'axis': '(0)'}), '(wfs, axis=0)\n', (2689, 2702), True, 'import numpy as np\n'), ((2929, 2958), 'numpy.zeros', 'np.zeros', (['clips_control.shape'], {}), '(clips_control.shape)\n', (2937, 2958), True, 'import numpy as np\n'), ((2981, 3000), 'numpy.zeros', 'np.zeros', (['num_clips'], {}), '(num_clips)\n', (2989, 3000), True, 'import numpy as np\n'), ((3303, 3341), 'numpy.sum', 'np.sum', (['weighted_clips_control'], {'axis': '(0)'}), '(weighted_clips_control, axis=0)\n', (3309, 3341), True, 'import numpy as np\n'), ((3707, 3753), 'numpy.concatenate', 'np.concatenate', (['[clips, clips_control]'], {'axis': '(0)'}), '([clips, clips_control], axis=0)\n', (3721, 3753), True, 'import numpy as np\n'), ((4288, 4311), 'numpy.zeros', 'np.zeros', (['(num_clips * 2)'], {}), '(num_clips * 2)\n', (4296, 4311), True, 'import numpy as np\n'), ((5906, 5920), 'numpy.dot', 'np.dot', (['V2', 'V2'], {}), '(V2, V2)\n', (5912, 5920), True, 'import numpy as np\n'), ((2017, 2084), 'numpy.random.choice', 'np.random.choice', (['times'], {'size': 'max_spikes_per_unit_for_noise_overlap'}), '(times, size=max_spikes_per_unit_for_noise_overlap)\n', (2033, 2084), True, 'import numpy as np\n'), ((2366, 2395), 'numpy.arange', 'np.arange', (['min_time', 'max_time'], {}), '(min_time, max_time)\n', (2375, 2395), True, 'import numpy as np\n'), ((5889, 5903), 'numpy.dot', 'np.dot', (['V1', 'V2'], {}), '(V1, V2)\n', (5895, 5903), True, 'import numpy as np\n'), ((2752, 2768), 'numpy.abs', 'np.abs', (['template'], {}), '(template)\n', (2758, 2768), True, 'import numpy as np\n'), ((3428, 3444), 'numpy.abs', 'np.abs', (['template'], {}), '(template)\n', (3434, 3444), True, 'import numpy as np\n'), ((3395, 3417), 'numpy.abs', 'np.abs', (['noise_template'], {}), '(noise_template)\n', (3401, 3417), True, 'import numpy as np\n')]
# Open3D: www.open3d.org # The MIT License (MIT) # See license file or visit www.open3d.org for details # examples/Python/Advanced/global_registration.py import open3d as o3d import numpy as np import copy def draw_registration_result(source, target, transformation): source_temp = copy.deepcopy(source) target_temp = copy.deepcopy(target) source_temp.paint_uniform_color([1, 0.706, 0]) target_temp.paint_uniform_color([0, 0.651, 0.929]) source_temp.transform(transformation) o3d.visualization.draw_geometries([source_temp, target_temp]) def preprocess_point_cloud(pcd, voxel_size): print(":: Downsample with a voxel size %.3f." % voxel_size) pcd_down = pcd.voxel_down_sample(voxel_size) radius_normal = voxel_size * 2 print(":: Estimate normal with search radius %.3f." % radius_normal) pcd_down.estimate_normals( o3d.geometry.KDTreeSearchParamHybrid(radius=radius_normal, max_nn=30)) radius_feature = voxel_size * 5 print(":: Compute FPFH feature with search radius %.3f." % radius_feature) pcd_fpfh = o3d.registration.compute_fpfh_feature( pcd_down, o3d.geometry.KDTreeSearchParamHybrid(radius=radius_feature, max_nn=100)) return pcd_down, pcd_fpfh def prepare_dataset(voxel_size): print(":: Load two point clouds and disturb initial pose.") source = o3d.io.read_point_cloud("../../TestData/ICP/cloud_bin_0.pcd") target = o3d.io.read_point_cloud("../../TestData/ICP/cloud_bin_1.pcd") trans_init = np.asarray([[0.0, 0.0, 1.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) source.transform(trans_init) draw_registration_result(source, target, np.identity(4)) source_down, source_fpfh = preprocess_point_cloud(source, voxel_size) target_down, target_fpfh = preprocess_point_cloud(target, voxel_size) return source, target, source_down, target_down, source_fpfh, target_fpfh def execute_global_registration(source_down, target_down, source_fpfh, target_fpfh, voxel_size): distance_threshold = voxel_size * 1.5 print(":: RANSAC registration on downsampled point clouds.") print(" Since the downsampling voxel size is %.3f," % voxel_size) print(" we use a liberal distance threshold %.3f." % distance_threshold) result = o3d.registration.registration_ransac_based_on_feature_matching( source_down, target_down, source_fpfh, target_fpfh, distance_threshold, o3d.registration.TransformationEstimationPointToPoint(False), 4, [ o3d.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9), o3d.registration.CorrespondenceCheckerBasedOnDistance( distance_threshold) ], o3d.registration.RANSACConvergenceCriteria(4000000, 500)) return result def refine_registration(source, target, source_fpfh, target_fpfh, voxel_size): distance_threshold = voxel_size * 0.4 print(":: Point-to-plane ICP registration is applied on original point") print(" clouds to refine the alignment. This time we use a strict") print(" distance threshold %.3f." % distance_threshold) result = o3d.registration.registration_icp( source, target, distance_threshold, result_ransac.transformation, o3d.registration.TransformationEstimationPointToPlane()) return result if __name__ == "__main__": voxel_size = 0.05 # means 5cm for the dataset source, target, source_down, target_down, source_fpfh, target_fpfh = \ prepare_dataset(voxel_size) result_ransac = execute_global_registration(source_down, target_down, source_fpfh, target_fpfh, voxel_size) print(result_ransac) draw_registration_result(source_down, target_down, result_ransac.transformation) result_icp = refine_registration(source, target, source_fpfh, target_fpfh, voxel_size) print(result_icp) draw_registration_result(source, target, result_icp.transformation)
[ "numpy.identity", "open3d.registration.TransformationEstimationPointToPlane", "open3d.registration.CorrespondenceCheckerBasedOnEdgeLength", "numpy.asarray", "open3d.geometry.KDTreeSearchParamHybrid", "open3d.registration.RANSACConvergenceCriteria", "open3d.visualization.draw_geometries", "open3d.io.read_point_cloud", "copy.deepcopy", "open3d.registration.TransformationEstimationPointToPoint", "open3d.registration.CorrespondenceCheckerBasedOnDistance" ]
[((290, 311), 'copy.deepcopy', 'copy.deepcopy', (['source'], {}), '(source)\n', (303, 311), False, 'import copy\n'), ((330, 351), 'copy.deepcopy', 'copy.deepcopy', (['target'], {}), '(target)\n', (343, 351), False, 'import copy\n'), ((504, 565), 'open3d.visualization.draw_geometries', 'o3d.visualization.draw_geometries', (['[source_temp, target_temp]'], {}), '([source_temp, target_temp])\n', (537, 565), True, 'import open3d as o3d\n'), ((1356, 1417), 'open3d.io.read_point_cloud', 'o3d.io.read_point_cloud', (['"""../../TestData/ICP/cloud_bin_0.pcd"""'], {}), "('../../TestData/ICP/cloud_bin_0.pcd')\n", (1379, 1417), True, 'import open3d as o3d\n'), ((1431, 1492), 'open3d.io.read_point_cloud', 'o3d.io.read_point_cloud', (['"""../../TestData/ICP/cloud_bin_1.pcd"""'], {}), "('../../TestData/ICP/cloud_bin_1.pcd')\n", (1454, 1492), True, 'import open3d as o3d\n'), ((1510, 1615), 'numpy.asarray', 'np.asarray', (['[[0.0, 0.0, 1.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, \n 0.0, 0.0, 1.0]]'], {}), '([[0.0, 0.0, 1.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0\n ], [0.0, 0.0, 0.0, 1.0]])\n', (1520, 1615), True, 'import numpy as np\n'), ((874, 943), 'open3d.geometry.KDTreeSearchParamHybrid', 'o3d.geometry.KDTreeSearchParamHybrid', ([], {'radius': 'radius_normal', 'max_nn': '(30)'}), '(radius=radius_normal, max_nn=30)\n', (910, 943), True, 'import open3d as o3d\n'), ((1141, 1212), 'open3d.geometry.KDTreeSearchParamHybrid', 'o3d.geometry.KDTreeSearchParamHybrid', ([], {'radius': 'radius_feature', 'max_nn': '(100)'}), '(radius=radius_feature, max_nn=100)\n', (1177, 1212), True, 'import open3d as o3d\n'), ((1718, 1732), 'numpy.identity', 'np.identity', (['(4)'], {}), '(4)\n', (1729, 1732), True, 'import numpy as np\n'), ((2515, 2575), 'open3d.registration.TransformationEstimationPointToPoint', 'o3d.registration.TransformationEstimationPointToPoint', (['(False)'], {}), '(False)\n', (2568, 2575), True, 'import open3d as o3d\n'), ((2770, 2826), 'open3d.registration.RANSACConvergenceCriteria', 'o3d.registration.RANSACConvergenceCriteria', (['(4000000)', '(500)'], {}), '(4000000, 500)\n', (2812, 2826), True, 'import open3d as o3d\n'), ((3312, 3367), 'open3d.registration.TransformationEstimationPointToPlane', 'o3d.registration.TransformationEstimationPointToPlane', ([], {}), '()\n', (3365, 3367), True, 'import open3d as o3d\n'), ((2594, 2654), 'open3d.registration.CorrespondenceCheckerBasedOnEdgeLength', 'o3d.registration.CorrespondenceCheckerBasedOnEdgeLength', (['(0.9)'], {}), '(0.9)\n', (2649, 2654), True, 'import open3d as o3d\n'), ((2668, 2741), 'open3d.registration.CorrespondenceCheckerBasedOnDistance', 'o3d.registration.CorrespondenceCheckerBasedOnDistance', (['distance_threshold'], {}), '(distance_threshold)\n', (2721, 2741), True, 'import open3d as o3d\n')]
# =============================================================================== # Copyright 2019 ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== from numpy import linspace from traits.api import HasTraits, Int, Float, Instance, on_trait_change from traitsui.api import View, VGroup, UItem, Item, HGroup from pychron.graph.graph import Graph from pychron.processing.argon_calculations import calculate_fractional_loss class FractionalLossCalculator(HasTraits): graph = Instance(Graph) temp = Float(475) min_age = Int(1) max_age = Int(1000) radius = Float(0.1) def __init__(self, *args, **kw): super(FractionalLossCalculator, self).__init__(*args, **kw) self.graph = g = Graph() g.new_plot() xs, ys = self._calculate_data() g.new_series(xs, ys) def _calculate_data(self): xs = linspace(self.min_age, self.max_age) fs = [calculate_fractional_loss(ti, self.temp, self.radius) for ti in xs] return xs, fs @on_trait_change("temp, radius, max_age, min_age") def _replot(self): xs, ys = self._calculate_data() self.graph.set_data(xs) self.graph.set_data(ys, axis=1) def traits_view(self): a = HGroup(Item("temp"), Item("radius"), Item("min_age"), Item("max_age")) v = View(VGroup(a, UItem("graph", style="custom"))) return v if __name__ == "__main__": f = FractionalLossCalculator() f.configure_traits() # ============= EOF =============================================
[ "traits.api.Instance", "traits.api.on_trait_change", "pychron.graph.graph.Graph", "traitsui.api.Item", "numpy.linspace", "traits.api.Int", "traitsui.api.UItem", "pychron.processing.argon_calculations.calculate_fractional_loss", "traits.api.Float" ]
[((1058, 1073), 'traits.api.Instance', 'Instance', (['Graph'], {}), '(Graph)\n', (1066, 1073), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1085, 1095), 'traits.api.Float', 'Float', (['(475)'], {}), '(475)\n', (1090, 1095), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1110, 1116), 'traits.api.Int', 'Int', (['(1)'], {}), '(1)\n', (1113, 1116), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1131, 1140), 'traits.api.Int', 'Int', (['(1000)'], {}), '(1000)\n', (1134, 1140), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1154, 1164), 'traits.api.Float', 'Float', (['(0.1)'], {}), '(0.1)\n', (1159, 1164), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1588, 1637), 'traits.api.on_trait_change', 'on_trait_change', (['"""temp, radius, max_age, min_age"""'], {}), "('temp, radius, max_age, min_age')\n", (1603, 1637), False, 'from traits.api import HasTraits, Int, Float, Instance, on_trait_change\n'), ((1297, 1304), 'pychron.graph.graph.Graph', 'Graph', ([], {}), '()\n', (1302, 1304), False, 'from pychron.graph.graph import Graph\n'), ((1441, 1477), 'numpy.linspace', 'linspace', (['self.min_age', 'self.max_age'], {}), '(self.min_age, self.max_age)\n', (1449, 1477), False, 'from numpy import linspace\n'), ((1492, 1545), 'pychron.processing.argon_calculations.calculate_fractional_loss', 'calculate_fractional_loss', (['ti', 'self.temp', 'self.radius'], {}), '(ti, self.temp, self.radius)\n', (1517, 1545), False, 'from pychron.processing.argon_calculations import calculate_fractional_loss\n'), ((1821, 1833), 'traitsui.api.Item', 'Item', (['"""temp"""'], {}), "('temp')\n", (1825, 1833), False, 'from traitsui.api import View, VGroup, UItem, Item, HGroup\n'), ((1835, 1849), 'traitsui.api.Item', 'Item', (['"""radius"""'], {}), "('radius')\n", (1839, 1849), False, 'from traitsui.api import View, VGroup, UItem, Item, HGroup\n'), ((1851, 1866), 'traitsui.api.Item', 'Item', (['"""min_age"""'], {}), "('min_age')\n", (1855, 1866), False, 'from traitsui.api import View, VGroup, UItem, Item, HGroup\n'), ((1868, 1883), 'traitsui.api.Item', 'Item', (['"""max_age"""'], {}), "('max_age')\n", (1872, 1883), False, 'from traitsui.api import View, VGroup, UItem, Item, HGroup\n'), ((1912, 1942), 'traitsui.api.UItem', 'UItem', (['"""graph"""'], {'style': '"""custom"""'}), "('graph', style='custom')\n", (1917, 1942), False, 'from traitsui.api import View, VGroup, UItem, Item, HGroup\n')]
# main imports import numpy as np import sys # image transform imports from PIL import Image from skimage import color from sklearn.decomposition import FastICA from sklearn.decomposition import IncrementalPCA from sklearn.decomposition import TruncatedSVD from numpy.linalg import svd as lin_svd from scipy.signal import medfilt2d, wiener, cwt import pywt import cv2 from ipfml.processing import transform, compression, segmentation from ipfml.filters import convolution, kernels from ipfml import utils # modules and config imports sys.path.insert(0, '') # trick to enable import of main folder module import custom_config as cfg from modules.utils import data as dt def get_image_features(data_type, block): """ Method which returns the data type expected """ if data_type == 'lab': block_file_path = '/tmp/lab_img.png' block.save(block_file_path) data = transform.get_LAB_L_SVD_s(Image.open(block_file_path)) if data_type == 'mscn': img_mscn_revisited = transform.rgb_to_mscn(block) # save tmp as img img_output = Image.fromarray(img_mscn_revisited.astype('uint8'), 'L') mscn_revisited_file_path = '/tmp/mscn_revisited_img.png' img_output.save(mscn_revisited_file_path) img_block = Image.open(mscn_revisited_file_path) # extract from temp image data = compression.get_SVD_s(img_block) """if data_type == 'mscn': img_gray = np.array(color.rgb2gray(np.asarray(block))*255, 'uint8') img_mscn = transform.calculate_mscn_coefficients(img_gray, 7) img_mscn_norm = transform.normalize_2D_arr(img_mscn) img_mscn_gray = np.array(img_mscn_norm*255, 'uint8') data = compression.get_SVD_s(img_mscn_gray) """ if data_type == 'low_bits_6': low_bits_6 = transform.rgb_to_LAB_L_low_bits(block, 6) data = compression.get_SVD_s(low_bits_6) if data_type == 'low_bits_5': low_bits_5 = transform.rgb_to_LAB_L_low_bits(block, 5) data = compression.get_SVD_s(low_bits_5) if data_type == 'low_bits_4': low_bits_4 = transform.rgb_to_LAB_L_low_bits(block, 4) data = compression.get_SVD_s(low_bits_4) if data_type == 'low_bits_3': low_bits_3 = transform.rgb_to_LAB_L_low_bits(block, 3) data = compression.get_SVD_s(low_bits_3) if data_type == 'low_bits_2': low_bits_2 = transform.rgb_to_LAB_L_low_bits(block, 2) data = compression.get_SVD_s(low_bits_2) if data_type == 'low_bits_4_shifted_2': data = compression.get_SVD_s(transform.rgb_to_LAB_L_bits(block, (3, 6))) if data_type == 'sub_blocks_stats': block = np.asarray(block) width, height, _= block.shape sub_width, sub_height = int(width / 4), int(height / 4) sub_blocks = segmentation.divide_in_blocks(block, (sub_width, sub_height)) data = [] for sub_b in sub_blocks: # by default use the whole lab L canal l_svd_data = np.array(transform.get_LAB_L_SVD_s(sub_b)) # get information we want from svd data.append(np.mean(l_svd_data)) data.append(np.median(l_svd_data)) data.append(np.percentile(l_svd_data, 25)) data.append(np.percentile(l_svd_data, 75)) data.append(np.var(l_svd_data)) area_under_curve = utils.integral_area_trapz(l_svd_data, dx=100) data.append(area_under_curve) # convert into numpy array after computing all stats data = np.asarray(data) if data_type == 'sub_blocks_stats_reduced': block = np.asarray(block) width, height, _= block.shape sub_width, sub_height = int(width / 4), int(height / 4) sub_blocks = segmentation.divide_in_blocks(block, (sub_width, sub_height)) data = [] for sub_b in sub_blocks: # by default use the whole lab L canal l_svd_data = np.array(transform.get_LAB_L_SVD_s(sub_b)) # get information we want from svd data.append(np.mean(l_svd_data)) data.append(np.median(l_svd_data)) data.append(np.percentile(l_svd_data, 25)) data.append(np.percentile(l_svd_data, 75)) data.append(np.var(l_svd_data)) # convert into numpy array after computing all stats data = np.asarray(data) if data_type == 'sub_blocks_area': block = np.asarray(block) width, height, _= block.shape sub_width, sub_height = int(width / 8), int(height / 8) sub_blocks = segmentation.divide_in_blocks(block, (sub_width, sub_height)) data = [] for sub_b in sub_blocks: # by default use the whole lab L canal l_svd_data = np.array(transform.get_LAB_L_SVD_s(sub_b)) area_under_curve = utils.integral_area_trapz(l_svd_data, dx=50) data.append(area_under_curve) # convert into numpy array after computing all stats data = np.asarray(data) if data_type == 'sub_blocks_area_normed': block = np.asarray(block) width, height, _= block.shape sub_width, sub_height = int(width / 8), int(height / 8) sub_blocks = segmentation.divide_in_blocks(block, (sub_width, sub_height)) data = [] for sub_b in sub_blocks: # by default use the whole lab L canal l_svd_data = np.array(transform.get_LAB_L_SVD_s(sub_b)) l_svd_data = utils.normalize_arr(l_svd_data) area_under_curve = utils.integral_area_trapz(l_svd_data, dx=50) data.append(area_under_curve) # convert into numpy array after computing all stats data = np.asarray(data) if data_type == 'mscn_var_4': data = _get_mscn_variance(block, (100, 100)) if data_type == 'mscn_var_16': data = _get_mscn_variance(block, (50, 50)) if data_type == 'mscn_var_64': data = _get_mscn_variance(block, (25, 25)) if data_type == 'mscn_var_16_max': data = _get_mscn_variance(block, (50, 50)) data = np.asarray(data) size = int(len(data) / 4) indices = data.argsort()[-size:][::-1] data = data[indices] if data_type == 'mscn_var_64_max': data = _get_mscn_variance(block, (25, 25)) data = np.asarray(data) size = int(len(data) / 4) indices = data.argsort()[-size:][::-1] data = data[indices] if data_type == 'ica_diff': current_image = transform.get_LAB_L(block) ica = FastICA(n_components=50) ica.fit(current_image) image_ica = ica.fit_transform(current_image) image_restored = ica.inverse_transform(image_ica) final_image = utils.normalize_2D_arr(image_restored) final_image = np.array(final_image * 255, 'uint8') sv_values = utils.normalize_arr(compression.get_SVD_s(current_image)) ica_sv_values = utils.normalize_arr(compression.get_SVD_s(final_image)) data = abs(np.array(sv_values) - np.array(ica_sv_values)) if data_type == 'svd_trunc_diff': current_image = transform.get_LAB_L(block) svd = TruncatedSVD(n_components=30, n_iter=100, random_state=42) transformed_image = svd.fit_transform(current_image) restored_image = svd.inverse_transform(transformed_image) reduced_image = (current_image - restored_image) U, s, V = compression.get_SVD(reduced_image) data = s if data_type == 'ipca_diff': current_image = transform.get_LAB_L(block) transformer = IncrementalPCA(n_components=20, batch_size=25) transformed_image = transformer.fit_transform(current_image) restored_image = transformer.inverse_transform(transformed_image) reduced_image = (current_image - restored_image) U, s, V = compression.get_SVD(reduced_image) data = s if data_type == 'svd_reconstruct': reconstructed_interval = (90, 200) begin, end = reconstructed_interval lab_img = transform.get_LAB_L(block) lab_img = np.array(lab_img, 'uint8') U, s, V = lin_svd(lab_img, full_matrices=True) smat = np.zeros((end-begin, end-begin), dtype=complex) smat[:, :] = np.diag(s[begin:end]) output_img = np.dot(U[:, begin:end], np.dot(smat, V[begin:end, :])) output_img = np.array(output_img, 'uint8') data = compression.get_SVD_s(output_img) if 'sv_std_filters' in data_type: # convert into lab by default to apply filters lab_img = transform.get_LAB_L(block) arr = np.array(lab_img) images = [] # Apply list of filter on arr images.append(medfilt2d(arr, [3, 3])) images.append(medfilt2d(arr, [5, 5])) images.append(wiener(arr, [3, 3])) images.append(wiener(arr, [5, 5])) # By default computation of current block image s_arr = compression.get_SVD_s(arr) sv_vector = [s_arr] # for each new image apply SVD and get SV for img in images: s = compression.get_SVD_s(img) sv_vector.append(s) sv_array = np.array(sv_vector) _, length = sv_array.shape sv_std = [] # normalize each SV vectors and compute standard deviation for each sub vectors for i in range(length): sv_array[:, i] = utils.normalize_arr(sv_array[:, i]) sv_std.append(np.std(sv_array[:, i])) indices = [] if 'lowest' in data_type: indices = utils.get_indices_of_lowest_values(sv_std, 200) if 'highest' in data_type: indices = utils.get_indices_of_highest_values(sv_std, 200) # data are arranged following std trend computed data = s_arr[indices] # with the use of wavelet if 'wave_sv_std_filters' in data_type: # convert into lab by default to apply filters lab_img = transform.get_LAB_L(block) arr = np.array(lab_img) images = [] # Apply list of filter on arr images.append(medfilt2d(arr, [3, 3])) # By default computation of current block image s_arr = compression.get_SVD_s(arr) sv_vector = [s_arr] # for each new image apply SVD and get SV for img in images: s = compression.get_SVD_s(img) sv_vector.append(s) sv_array = np.array(sv_vector) _, length = sv_array.shape sv_std = [] # normalize each SV vectors and compute standard deviation for each sub vectors for i in range(length): sv_array[:, i] = utils.normalize_arr(sv_array[:, i]) sv_std.append(np.std(sv_array[:, i])) indices = [] if 'lowest' in data_type: indices = utils.get_indices_of_lowest_values(sv_std, 200) if 'highest' in data_type: indices = utils.get_indices_of_highest_values(sv_std, 200) # data are arranged following std trend computed data = s_arr[indices] # with the use of wavelet if 'sv_std_filters_full' in data_type: # convert into lab by default to apply filters lab_img = transform.get_LAB_L(block) arr = np.array(lab_img) images = [] # Apply list of filter on arr kernel = np.ones((3,3),np.float32)/9 images.append(cv2.filter2D(arr,-1,kernel)) kernel = np.ones((5,5),np.float32)/25 images.append(cv2.filter2D(arr,-1,kernel)) images.append(cv2.GaussianBlur(arr, (3, 3), 0.5)) images.append(cv2.GaussianBlur(arr, (3, 3), 1)) images.append(cv2.GaussianBlur(arr, (3, 3), 1.5)) images.append(cv2.GaussianBlur(arr, (5, 5), 0.5)) images.append(cv2.GaussianBlur(arr, (5, 5), 1)) images.append(cv2.GaussianBlur(arr, (5, 5), 1.5)) images.append(medfilt2d(arr, [3, 3])) images.append(medfilt2d(arr, [5, 5])) images.append(wiener(arr, [3, 3])) images.append(wiener(arr, [5, 5])) wave = w2d(arr, 'db1', 2) images.append(np.array(wave, 'float64')) # By default computation of current block image s_arr = compression.get_SVD_s(arr) sv_vector = [s_arr] # for each new image apply SVD and get SV for img in images: s = compression.get_SVD_s(img) sv_vector.append(s) sv_array = np.array(sv_vector) _, length = sv_array.shape sv_std = [] # normalize each SV vectors and compute standard deviation for each sub vectors for i in range(length): sv_array[:, i] = utils.normalize_arr(sv_array[:, i]) sv_std.append(np.std(sv_array[:, i])) indices = [] if 'lowest' in data_type: indices = utils.get_indices_of_lowest_values(sv_std, 200) if 'highest' in data_type: indices = utils.get_indices_of_highest_values(sv_std, 200) # data are arranged following std trend computed data = s_arr[indices] if 'sv_entropy_std_filters' in data_type: lab_img = transform.get_LAB_L(block) arr = np.array(lab_img) images = [] kernel = np.ones((3,3),np.float32)/9 images.append(cv2.filter2D(arr,-1,kernel)) kernel = np.ones((5,5),np.float32)/25 images.append(cv2.filter2D(arr,-1,kernel)) images.append(cv2.GaussianBlur(arr, (3, 3), 0.5)) images.append(cv2.GaussianBlur(arr, (3, 3), 1)) images.append(cv2.GaussianBlur(arr, (3, 3), 1.5)) images.append(cv2.GaussianBlur(arr, (5, 5), 0.5)) images.append(cv2.GaussianBlur(arr, (5, 5), 1)) images.append(cv2.GaussianBlur(arr, (5, 5), 1.5)) images.append(medfilt2d(arr, [3, 3])) images.append(medfilt2d(arr, [5, 5])) images.append(wiener(arr, [3, 3])) images.append(wiener(arr, [5, 5])) wave = w2d(arr, 'db1', 2) images.append(np.array(wave, 'float64')) sv_vector = [] sv_entropy_list = [] # for each new image apply SVD and get SV for img in images: s = compression.get_SVD_s(img) sv_vector.append(s) sv_entropy = [utils.get_entropy_contribution_of_i(s, id_sv) for id_sv, sv in enumerate(s)] sv_entropy_list.append(sv_entropy) sv_std = [] sv_array = np.array(sv_vector) _, length = sv_array.shape # normalize each SV vectors and compute standard deviation for each sub vectors for i in range(length): sv_array[:, i] = utils.normalize_arr(sv_array[:, i]) sv_std.append(np.std(sv_array[:, i])) indices = [] if 'lowest' in data_type: indices = utils.get_indices_of_lowest_values(sv_std, 200) if 'highest' in data_type: indices = utils.get_indices_of_highest_values(sv_std, 200) # data are arranged following std trend computed s_arr = compression.get_SVD_s(arr) data = s_arr[indices] if 'convolutional_kernels' in data_type: sub_zones = segmentation.divide_in_blocks(block, (20, 20)) data = [] diff_std_list_3 = [] diff_std_list_5 = [] diff_mean_list_3 = [] diff_mean_list_5 = [] plane_std_list_3 = [] plane_std_list_5 = [] plane_mean_list_3 = [] plane_mean_list_5 = [] plane_max_std_list_3 = [] plane_max_std_list_5 = [] plane_max_mean_list_3 = [] plane_max_mean_list_5 = [] for sub_zone in sub_zones: l_img = transform.get_LAB_L(sub_zone) normed_l_img = utils.normalize_2D_arr(l_img) # bilateral with window of size (3, 3) normed_diff = convolution.convolution2D(normed_l_img, kernels.min_bilateral_diff, (3, 3)) std_diff = np.std(normed_diff) mean_diff = np.mean(normed_diff) diff_std_list_3.append(std_diff) diff_mean_list_3.append(mean_diff) # bilateral with window of size (5, 5) normed_diff = convolution.convolution2D(normed_l_img, kernels.min_bilateral_diff, (5, 5)) std_diff = np.std(normed_diff) mean_diff = np.mean(normed_diff) diff_std_list_5.append(std_diff) diff_mean_list_5.append(mean_diff) # plane mean with window of size (3, 3) normed_plane_mean = convolution.convolution2D(normed_l_img, kernels.plane_mean, (3, 3)) std_plane_mean = np.std(normed_plane_mean) mean_plane_mean = np.mean(normed_plane_mean) plane_std_list_3.append(std_plane_mean) plane_mean_list_3.append(mean_plane_mean) # plane mean with window of size (5, 5) normed_plane_mean = convolution.convolution2D(normed_l_img, kernels.plane_mean, (5, 5)) std_plane_mean = np.std(normed_plane_mean) mean_plane_mean = np.mean(normed_plane_mean) plane_std_list_5.append(std_plane_mean) plane_mean_list_5.append(mean_plane_mean) # plane max error with window of size (3, 3) normed_plane_max = convolution.convolution2D(normed_l_img, kernels.plane_max_error, (3, 3)) std_plane_max = np.std(normed_plane_max) mean_plane_max = np.mean(normed_plane_max) plane_max_std_list_3.append(std_plane_max) plane_max_mean_list_3.append(mean_plane_max) # plane max error with window of size (5, 5) normed_plane_max = convolution.convolution2D(normed_l_img, kernels.plane_max_error, (5, 5)) std_plane_max = np.std(normed_plane_max) mean_plane_max = np.mean(normed_plane_max) plane_max_std_list_5.append(std_plane_max) plane_max_mean_list_5.append(mean_plane_max) diff_std_list_3 = np.array(diff_std_list_3) diff_std_list_5 = np.array(diff_std_list_5) diff_mean_list_3 = np.array(diff_mean_list_3) diff_mean_list_5 = np.array(diff_mean_list_5) plane_std_list_3 = np.array(plane_std_list_3) plane_std_list_5 = np.array(plane_std_list_5) plane_mean_list_3 = np.array(plane_mean_list_3) plane_mean_list_5 = np.array(plane_mean_list_5) plane_max_std_list_3 = np.array(plane_max_std_list_3) plane_max_std_list_5 = np.array(plane_max_std_list_5) plane_max_mean_list_3 = np.array(plane_max_mean_list_3) plane_max_mean_list_5 = np.array(plane_max_mean_list_5) if 'std_max_blocks' in data_type: data.append(np.std(diff_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(diff_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(diff_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.std(diff_mean_list_5[0:int(len(sub_zones)/5)])) data.append(np.std(plane_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(plane_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(plane_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.std(plane_mean_list_5[0:int(len(sub_zones)/5)])) data.append(np.std(plane_max_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(plane_max_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.std(plane_max_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.std(plane_max_mean_list_5[0:int(len(sub_zones)/5)])) if 'mean_max_blocks' in data_type: data.append(np.mean(diff_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(diff_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(diff_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.mean(diff_mean_list_5[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_mean_list_5[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_max_std_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_max_mean_list_3[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_max_std_list_5[0:int(len(sub_zones)/5)])) data.append(np.mean(plane_max_mean_list_5[0:int(len(sub_zones)/5)])) if 'std_normed' in data_type: data.append(np.std(diff_std_list_3)) data.append(np.std(diff_mean_list_3)) data.append(np.std(diff_std_list_5)) data.append(np.std(diff_mean_list_5)) data.append(np.std(plane_std_list_3)) data.append(np.std(plane_mean_list_3)) data.append(np.std(plane_std_list_5)) data.append(np.std(plane_mean_list_5)) data.append(np.std(plane_max_std_list_3)) data.append(np.std(plane_max_mean_list_3)) data.append(np.std(plane_max_std_list_5)) data.append(np.std(plane_max_mean_list_5)) if 'mean_normed' in data_type: data.append(np.mean(diff_std_list_3)) data.append(np.mean(diff_mean_list_3)) data.append(np.mean(diff_std_list_5)) data.append(np.mean(diff_mean_list_5)) data.append(np.mean(plane_std_list_3)) data.append(np.mean(plane_mean_list_3)) data.append(np.mean(plane_std_list_5)) data.append(np.mean(plane_mean_list_5)) data.append(np.mean(plane_max_std_list_3)) data.append(np.mean(plane_max_mean_list_3)) data.append(np.mean(plane_max_std_list_5)) data.append(np.mean(plane_max_mean_list_5)) data = np.array(data) if data_type == 'convolutional_kernel_stats_svd': l_img = transform.get_LAB_L(block) normed_l_img = utils.normalize_2D_arr(l_img) # bilateral with window of size (5, 5) normed_diff = convolution.convolution2D(normed_l_img, kernels.min_bilateral_diff, (5, 5)) # getting sigma vector from SVD compression s = compression.get_SVD_s(normed_diff) data = s if data_type == 'svd_entropy': l_img = transform.get_LAB_L(block) blocks = segmentation.divide_in_blocks(l_img, (20, 20)) values = [] for b in blocks: sv = compression.get_SVD_s(b) values.append(utils.get_entropy(sv)) data = np.array(values) if data_type == 'svd_entropy_20': l_img = transform.get_LAB_L(block) blocks = segmentation.divide_in_blocks(l_img, (20, 20)) values = [] for b in blocks: sv = compression.get_SVD_s(b) values.append(utils.get_entropy(sv)) data = np.array(values) if data_type == 'svd_entropy_noise_20': l_img = transform.get_LAB_L(block) blocks = segmentation.divide_in_blocks(l_img, (20, 20)) values = [] for b in blocks: sv = compression.get_SVD_s(b) sv_size = len(sv) values.append(utils.get_entropy(sv[int(sv_size / 4):])) data = np.array(values) return data def w2d(arr, mode='haar', level=1): #convert to float imArray = arr np.divide(imArray, 255) # compute coefficients coeffs=pywt.wavedec2(imArray, mode, level=level) #Process Coefficients coeffs_H=list(coeffs) coeffs_H[0] *= 0 # reconstruction imArray_H = pywt.waverec2(coeffs_H, mode) imArray_H *= 255 imArray_H = np.uint8(imArray_H) return imArray_H def _get_mscn_variance(block, sub_block_size=(50, 50)): blocks = segmentation.divide_in_blocks(block, sub_block_size) data = [] for block in blocks: mscn_coefficients = transform.get_mscn_coefficients(block) flat_coeff = mscn_coefficients.flatten() data.append(np.var(flat_coeff)) return np.sort(data)
[ "numpy.uint8", "sys.path.insert", "ipfml.utils.get_entropy_contribution_of_i", "ipfml.utils.normalize_2D_arr", "ipfml.utils.get_indices_of_lowest_values", "cv2.filter2D", "numpy.array", "sklearn.decomposition.FastICA", "pywt.waverec2", "ipfml.processing.transform.rgb_to_mscn", "numpy.divide", "ipfml.processing.segmentation.divide_in_blocks", "numpy.mean", "pywt.wavedec2", "numpy.sort", "numpy.asarray", "ipfml.processing.transform.get_LAB_L_SVD_s", "numpy.dot", "ipfml.processing.transform.get_LAB_L", "ipfml.utils.get_indices_of_highest_values", "sklearn.decomposition.IncrementalPCA", "ipfml.utils.integral_area_trapz", "scipy.signal.medfilt2d", "numpy.ones", "ipfml.utils.normalize_arr", "ipfml.processing.transform.rgb_to_LAB_L_low_bits", "sklearn.decomposition.TruncatedSVD", "ipfml.filters.convolution.convolution2D", "ipfml.processing.transform.rgb_to_LAB_L_bits", "ipfml.processing.transform.get_mscn_coefficients", "numpy.std", "numpy.linalg.svd", "cv2.GaussianBlur", "PIL.Image.open", "numpy.median", "ipfml.processing.compression.get_SVD", "numpy.diag", "ipfml.processing.compression.get_SVD_s", "numpy.zeros", "numpy.percentile", "scipy.signal.wiener", "numpy.var", "ipfml.utils.get_entropy" ]
[((538, 560), 'sys.path.insert', 'sys.path.insert', (['(0)', '""""""'], {}), "(0, '')\n", (553, 560), False, 'import sys\n'), ((23763, 23786), 'numpy.divide', 'np.divide', (['imArray', '(255)'], {}), '(imArray, 255)\n', (23772, 23786), True, 'import numpy as np\n'), ((23827, 23868), 'pywt.wavedec2', 'pywt.wavedec2', (['imArray', 'mode'], {'level': 'level'}), '(imArray, mode, level=level)\n', (23840, 23868), False, 'import pywt\n'), ((23983, 24012), 'pywt.waverec2', 'pywt.waverec2', (['coeffs_H', 'mode'], {}), '(coeffs_H, mode)\n', (23996, 24012), False, 'import pywt\n'), ((24050, 24069), 'numpy.uint8', 'np.uint8', (['imArray_H'], {}), '(imArray_H)\n', (24058, 24069), True, 'import numpy as np\n'), ((24163, 24215), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', 'sub_block_size'], {}), '(block, sub_block_size)\n', (24192, 24215), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((24425, 24438), 'numpy.sort', 'np.sort', (['data'], {}), '(data)\n', (24432, 24438), True, 'import numpy as np\n'), ((1021, 1049), 'ipfml.processing.transform.rgb_to_mscn', 'transform.rgb_to_mscn', (['block'], {}), '(block)\n', (1042, 1049), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((1290, 1326), 'PIL.Image.open', 'Image.open', (['mscn_revisited_file_path'], {}), '(mscn_revisited_file_path)\n', (1300, 1326), False, 'from PIL import Image\n'), ((1377, 1409), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['img_block'], {}), '(img_block)\n', (1398, 1409), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((1830, 1871), 'ipfml.processing.transform.rgb_to_LAB_L_low_bits', 'transform.rgb_to_LAB_L_low_bits', (['block', '(6)'], {}), '(block, 6)\n', (1861, 1871), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((1887, 1920), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['low_bits_6'], {}), '(low_bits_6)\n', (1908, 1920), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((1978, 2019), 'ipfml.processing.transform.rgb_to_LAB_L_low_bits', 'transform.rgb_to_LAB_L_low_bits', (['block', '(5)'], {}), '(block, 5)\n', (2009, 2019), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2035, 2068), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['low_bits_5'], {}), '(low_bits_5)\n', (2056, 2068), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2126, 2167), 'ipfml.processing.transform.rgb_to_LAB_L_low_bits', 'transform.rgb_to_LAB_L_low_bits', (['block', '(4)'], {}), '(block, 4)\n', (2157, 2167), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2183, 2216), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['low_bits_4'], {}), '(low_bits_4)\n', (2204, 2216), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2274, 2315), 'ipfml.processing.transform.rgb_to_LAB_L_low_bits', 'transform.rgb_to_LAB_L_low_bits', (['block', '(3)'], {}), '(block, 3)\n', (2305, 2315), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2331, 2364), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['low_bits_3'], {}), '(low_bits_3)\n', (2352, 2364), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2422, 2463), 'ipfml.processing.transform.rgb_to_LAB_L_low_bits', 'transform.rgb_to_LAB_L_low_bits', (['block', '(2)'], {}), '(block, 2)\n', (2453, 2463), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2479, 2512), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['low_bits_2'], {}), '(low_bits_2)\n', (2500, 2512), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((2698, 2715), 'numpy.asarray', 'np.asarray', (['block'], {}), '(block)\n', (2708, 2715), True, 'import numpy as np\n'), ((2840, 2901), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', '(sub_width, sub_height)'], {}), '(block, (sub_width, sub_height))\n', (2869, 2901), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((3566, 3582), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (3576, 3582), True, 'import numpy as np\n'), ((3649, 3666), 'numpy.asarray', 'np.asarray', (['block'], {}), '(block)\n', (3659, 3666), True, 'import numpy as np\n'), ((3791, 3852), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', '(sub_width, sub_height)'], {}), '(block, (sub_width, sub_height))\n', (3820, 3852), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((4397, 4413), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (4407, 4413), True, 'import numpy as np\n'), ((4471, 4488), 'numpy.asarray', 'np.asarray', (['block'], {}), '(block)\n', (4481, 4488), True, 'import numpy as np\n'), ((4613, 4674), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', '(sub_width, sub_height)'], {}), '(block, (sub_width, sub_height))\n', (4642, 4674), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((5044, 5060), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (5054, 5060), True, 'import numpy as np\n'), ((5125, 5142), 'numpy.asarray', 'np.asarray', (['block'], {}), '(block)\n', (5135, 5142), True, 'import numpy as np\n'), ((5267, 5328), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', '(sub_width, sub_height)'], {}), '(block, (sub_width, sub_height))\n', (5296, 5328), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((5755, 5771), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (5765, 5771), True, 'import numpy as np\n'), ((6144, 6160), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (6154, 6160), True, 'import numpy as np\n'), ((6378, 6394), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (6388, 6394), True, 'import numpy as np\n'), ((6562, 6588), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (6581, 6588), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((6604, 6628), 'sklearn.decomposition.FastICA', 'FastICA', ([], {'n_components': '(50)'}), '(n_components=50)\n', (6611, 6628), False, 'from sklearn.decomposition import FastICA\n'), ((6795, 6833), 'ipfml.utils.normalize_2D_arr', 'utils.normalize_2D_arr', (['image_restored'], {}), '(image_restored)\n', (6817, 6833), False, 'from ipfml import utils\n'), ((6856, 6892), 'numpy.array', 'np.array', (['(final_image * 255)', '"""uint8"""'], {}), "(final_image * 255, 'uint8')\n", (6864, 6892), True, 'import numpy as np\n'), ((7183, 7209), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (7202, 7209), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((7225, 7283), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', ([], {'n_components': '(30)', 'n_iter': '(100)', 'random_state': '(42)'}), '(n_components=30, n_iter=100, random_state=42)\n', (7237, 7283), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((7488, 7522), 'ipfml.processing.compression.get_SVD', 'compression.get_SVD', (['reduced_image'], {}), '(reduced_image)\n', (7507, 7522), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((7599, 7625), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (7618, 7625), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((7649, 7695), 'sklearn.decomposition.IncrementalPCA', 'IncrementalPCA', ([], {'n_components': '(20)', 'batch_size': '(25)'}), '(n_components=20, batch_size=25)\n', (7663, 7695), False, 'from sklearn.decomposition import IncrementalPCA\n'), ((7916, 7950), 'ipfml.processing.compression.get_SVD', 'compression.get_SVD', (['reduced_image'], {}), '(reduced_image)\n', (7935, 7950), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((8115, 8141), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (8134, 8141), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((8160, 8186), 'numpy.array', 'np.array', (['lab_img', '"""uint8"""'], {}), "(lab_img, 'uint8')\n", (8168, 8186), True, 'import numpy as np\n'), ((8206, 8242), 'numpy.linalg.svd', 'lin_svd', (['lab_img'], {'full_matrices': '(True)'}), '(lab_img, full_matrices=True)\n', (8213, 8242), True, 'from numpy.linalg import svd as lin_svd\n'), ((8259, 8310), 'numpy.zeros', 'np.zeros', (['(end - begin, end - begin)'], {'dtype': 'complex'}), '((end - begin, end - begin), dtype=complex)\n', (8267, 8310), True, 'import numpy as np\n'), ((8328, 8349), 'numpy.diag', 'np.diag', (['s[begin:end]'], {}), '(s[begin:end])\n', (8335, 8349), True, 'import numpy as np\n'), ((8449, 8478), 'numpy.array', 'np.array', (['output_img', '"""uint8"""'], {}), "(output_img, 'uint8')\n", (8457, 8478), True, 'import numpy as np\n'), ((8495, 8528), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['output_img'], {}), '(output_img)\n', (8516, 8528), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((8642, 8668), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (8661, 8668), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((8683, 8700), 'numpy.array', 'np.array', (['lab_img'], {}), '(lab_img)\n', (8691, 8700), True, 'import numpy as np\n'), ((9027, 9053), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['arr'], {}), '(arr)\n', (9048, 9053), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((9268, 9287), 'numpy.array', 'np.array', (['sv_vector'], {}), '(sv_vector)\n', (9276, 9287), True, 'import numpy as np\n'), ((10083, 10109), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (10102, 10109), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((10124, 10141), 'numpy.array', 'np.array', (['lab_img'], {}), '(lab_img)\n', (10132, 10141), True, 'import numpy as np\n'), ((10336, 10362), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['arr'], {}), '(arr)\n', (10357, 10362), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((10577, 10596), 'numpy.array', 'np.array', (['sv_vector'], {}), '(sv_vector)\n', (10585, 10596), True, 'import numpy as np\n'), ((11392, 11418), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (11411, 11418), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((11433, 11450), 'numpy.array', 'np.array', (['lab_img'], {}), '(lab_img)\n', (11441, 11450), True, 'import numpy as np\n'), ((12409, 12435), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['arr'], {}), '(arr)\n', (12430, 12435), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((12650, 12669), 'numpy.array', 'np.array', (['sv_vector'], {}), '(sv_vector)\n', (12658, 12669), True, 'import numpy as np\n'), ((13383, 13409), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (13402, 13409), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((13424, 13441), 'numpy.array', 'np.array', (['lab_img'], {}), '(lab_img)\n', (13432, 13441), True, 'import numpy as np\n'), ((14697, 14716), 'numpy.array', 'np.array', (['sv_vector'], {}), '(sv_vector)\n', (14705, 14716), True, 'import numpy as np\n'), ((15312, 15338), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['arr'], {}), '(arr)\n', (15333, 15338), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((15436, 15482), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['block', '(20, 20)'], {}), '(block, (20, 20))\n', (15465, 15482), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((18233, 18258), 'numpy.array', 'np.array', (['diff_std_list_3'], {}), '(diff_std_list_3)\n', (18241, 18258), True, 'import numpy as np\n'), ((18285, 18310), 'numpy.array', 'np.array', (['diff_std_list_5'], {}), '(diff_std_list_5)\n', (18293, 18310), True, 'import numpy as np\n'), ((18339, 18365), 'numpy.array', 'np.array', (['diff_mean_list_3'], {}), '(diff_mean_list_3)\n', (18347, 18365), True, 'import numpy as np\n'), ((18393, 18419), 'numpy.array', 'np.array', (['diff_mean_list_5'], {}), '(diff_mean_list_5)\n', (18401, 18419), True, 'import numpy as np\n'), ((18448, 18474), 'numpy.array', 'np.array', (['plane_std_list_3'], {}), '(plane_std_list_3)\n', (18456, 18474), True, 'import numpy as np\n'), ((18502, 18528), 'numpy.array', 'np.array', (['plane_std_list_5'], {}), '(plane_std_list_5)\n', (18510, 18528), True, 'import numpy as np\n'), ((18558, 18585), 'numpy.array', 'np.array', (['plane_mean_list_3'], {}), '(plane_mean_list_3)\n', (18566, 18585), True, 'import numpy as np\n'), ((18614, 18641), 'numpy.array', 'np.array', (['plane_mean_list_5'], {}), '(plane_mean_list_5)\n', (18622, 18641), True, 'import numpy as np\n'), ((18674, 18704), 'numpy.array', 'np.array', (['plane_max_std_list_3'], {}), '(plane_max_std_list_3)\n', (18682, 18704), True, 'import numpy as np\n'), ((18736, 18766), 'numpy.array', 'np.array', (['plane_max_std_list_5'], {}), '(plane_max_std_list_5)\n', (18744, 18766), True, 'import numpy as np\n'), ((18800, 18831), 'numpy.array', 'np.array', (['plane_max_mean_list_3'], {}), '(plane_max_mean_list_3)\n', (18808, 18831), True, 'import numpy as np\n'), ((18864, 18895), 'numpy.array', 'np.array', (['plane_max_mean_list_5'], {}), '(plane_max_mean_list_5)\n', (18872, 18895), True, 'import numpy as np\n'), ((22222, 22236), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (22230, 22236), True, 'import numpy as np\n'), ((22309, 22335), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (22328, 22335), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((22359, 22388), 'ipfml.utils.normalize_2D_arr', 'utils.normalize_2D_arr', (['l_img'], {}), '(l_img)\n', (22381, 22388), False, 'from ipfml import utils\n'), ((22459, 22534), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.min_bilateral_diff', '(5, 5)'], {}), '(normed_l_img, kernels.min_bilateral_diff, (5, 5))\n', (22484, 22534), False, 'from ipfml.filters import convolution, kernels\n'), ((22600, 22634), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['normed_diff'], {}), '(normed_diff)\n', (22621, 22634), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((22705, 22731), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (22724, 22731), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((22750, 22796), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['l_img', '(20, 20)'], {}), '(l_img, (20, 20))\n', (22779, 22796), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((22949, 22965), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (22957, 22965), True, 'import numpy as np\n'), ((23021, 23047), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (23040, 23047), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23066, 23112), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['l_img', '(20, 20)'], {}), '(l_img, (20, 20))\n', (23095, 23112), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23265, 23281), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (23273, 23281), True, 'import numpy as np\n'), ((23343, 23369), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['block'], {}), '(block)\n', (23362, 23369), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23388, 23434), 'ipfml.processing.segmentation.divide_in_blocks', 'segmentation.divide_in_blocks', (['l_img', '(20, 20)'], {}), '(l_img, (20, 20))\n', (23417, 23434), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23636, 23652), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (23644, 23652), True, 'import numpy as np\n'), ((24285, 24323), 'ipfml.processing.transform.get_mscn_coefficients', 'transform.get_mscn_coefficients', (['block'], {}), '(block)\n', (24316, 24323), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((933, 960), 'PIL.Image.open', 'Image.open', (['block_file_path'], {}), '(block_file_path)\n', (943, 960), False, 'from PIL import Image\n'), ((2596, 2638), 'ipfml.processing.transform.rgb_to_LAB_L_bits', 'transform.rgb_to_LAB_L_bits', (['block', '(3, 6)'], {}), '(block, (3, 6))\n', (2623, 2638), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((3401, 3446), 'ipfml.utils.integral_area_trapz', 'utils.integral_area_trapz', (['l_svd_data'], {'dx': '(100)'}), '(l_svd_data, dx=100)\n', (3426, 3446), False, 'from ipfml import utils\n'), ((4880, 4924), 'ipfml.utils.integral_area_trapz', 'utils.integral_area_trapz', (['l_svd_data'], {'dx': '(50)'}), '(l_svd_data, dx=50)\n', (4905, 4924), False, 'from ipfml import utils\n'), ((5527, 5558), 'ipfml.utils.normalize_arr', 'utils.normalize_arr', (['l_svd_data'], {}), '(l_svd_data)\n', (5546, 5558), False, 'from ipfml import utils\n'), ((5591, 5635), 'ipfml.utils.integral_area_trapz', 'utils.integral_area_trapz', (['l_svd_data'], {'dx': '(50)'}), '(l_svd_data, dx=50)\n', (5616, 5635), False, 'from ipfml import utils\n'), ((6934, 6970), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['current_image'], {}), '(current_image)\n', (6955, 6970), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((7016, 7050), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['final_image'], {}), '(final_image)\n', (7037, 7050), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((8396, 8425), 'numpy.dot', 'np.dot', (['smat', 'V[begin:end, :]'], {}), '(smat, V[begin:end, :])\n', (8402, 8425), True, 'import numpy as np\n'), ((8790, 8812), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (8799, 8812), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((8836, 8858), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (8845, 8858), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((8882, 8901), 'scipy.signal.wiener', 'wiener', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (8888, 8901), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((8925, 8944), 'scipy.signal.wiener', 'wiener', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (8931, 8944), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((9177, 9203), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['img'], {}), '(img)\n', (9198, 9203), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((9519, 9554), 'ipfml.utils.normalize_arr', 'utils.normalize_arr', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (9538, 9554), False, 'from ipfml import utils\n'), ((9692, 9739), 'ipfml.utils.get_indices_of_lowest_values', 'utils.get_indices_of_lowest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (9726, 9739), False, 'from ipfml import utils\n'), ((9798, 9846), 'ipfml.utils.get_indices_of_highest_values', 'utils.get_indices_of_highest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (9833, 9846), False, 'from ipfml import utils\n'), ((10231, 10253), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (10240, 10253), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((10486, 10512), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['img'], {}), '(img)\n', (10507, 10512), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((10828, 10863), 'ipfml.utils.normalize_arr', 'utils.normalize_arr', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (10847, 10863), False, 'from ipfml import utils\n'), ((11001, 11048), 'ipfml.utils.get_indices_of_lowest_values', 'utils.get_indices_of_lowest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (11035, 11048), False, 'from ipfml import utils\n'), ((11107, 11155), 'ipfml.utils.get_indices_of_highest_values', 'utils.get_indices_of_highest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (11142, 11155), False, 'from ipfml import utils\n'), ((11535, 11562), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.float32'], {}), '((3, 3), np.float32)\n', (11542, 11562), True, 'import numpy as np\n'), ((11585, 11614), 'cv2.filter2D', 'cv2.filter2D', (['arr', '(-1)', 'kernel'], {}), '(arr, -1, kernel)\n', (11597, 11614), False, 'import cv2\n'), ((11632, 11659), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.float32'], {}), '((5, 5), np.float32)\n', (11639, 11659), True, 'import numpy as np\n'), ((11683, 11712), 'cv2.filter2D', 'cv2.filter2D', (['arr', '(-1)', 'kernel'], {}), '(arr, -1, kernel)\n', (11695, 11712), False, 'import cv2\n'), ((11735, 11769), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(0.5)'], {}), '(arr, (3, 3), 0.5)\n', (11751, 11769), False, 'import cv2\n'), ((11794, 11826), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(1)'], {}), '(arr, (3, 3), 1)\n', (11810, 11826), False, 'import cv2\n'), ((11851, 11885), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(1.5)'], {}), '(arr, (3, 3), 1.5)\n', (11867, 11885), False, 'import cv2\n'), ((11910, 11944), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(0.5)'], {}), '(arr, (5, 5), 0.5)\n', (11926, 11944), False, 'import cv2\n'), ((11969, 12001), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(1)'], {}), '(arr, (5, 5), 1)\n', (11985, 12001), False, 'import cv2\n'), ((12026, 12060), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(1.5)'], {}), '(arr, (5, 5), 1.5)\n', (12042, 12060), False, 'import cv2\n'), ((12085, 12107), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (12094, 12107), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((12132, 12154), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (12141, 12154), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((12179, 12198), 'scipy.signal.wiener', 'wiener', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (12185, 12198), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((12223, 12242), 'scipy.signal.wiener', 'wiener', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (12229, 12242), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((12301, 12326), 'numpy.array', 'np.array', (['wave', '"""float64"""'], {}), "(wave, 'float64')\n", (12309, 12326), True, 'import numpy as np\n'), ((12559, 12585), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['img'], {}), '(img)\n', (12580, 12585), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((12901, 12936), 'ipfml.utils.normalize_arr', 'utils.normalize_arr', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (12920, 12936), False, 'from ipfml import utils\n'), ((13074, 13121), 'ipfml.utils.get_indices_of_lowest_values', 'utils.get_indices_of_lowest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (13108, 13121), False, 'from ipfml import utils\n'), ((13180, 13228), 'ipfml.utils.get_indices_of_highest_values', 'utils.get_indices_of_highest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (13215, 13228), False, 'from ipfml import utils\n'), ((13481, 13508), 'numpy.ones', 'np.ones', (['(3, 3)', 'np.float32'], {}), '((3, 3), np.float32)\n', (13488, 13508), True, 'import numpy as np\n'), ((13531, 13560), 'cv2.filter2D', 'cv2.filter2D', (['arr', '(-1)', 'kernel'], {}), '(arr, -1, kernel)\n', (13543, 13560), False, 'import cv2\n'), ((13578, 13605), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.float32'], {}), '((5, 5), np.float32)\n', (13585, 13605), True, 'import numpy as np\n'), ((13629, 13658), 'cv2.filter2D', 'cv2.filter2D', (['arr', '(-1)', 'kernel'], {}), '(arr, -1, kernel)\n', (13641, 13658), False, 'import cv2\n'), ((13681, 13715), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(0.5)'], {}), '(arr, (3, 3), 0.5)\n', (13697, 13715), False, 'import cv2\n'), ((13740, 13772), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(1)'], {}), '(arr, (3, 3), 1)\n', (13756, 13772), False, 'import cv2\n'), ((13797, 13831), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(3, 3)', '(1.5)'], {}), '(arr, (3, 3), 1.5)\n', (13813, 13831), False, 'import cv2\n'), ((13856, 13890), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(0.5)'], {}), '(arr, (5, 5), 0.5)\n', (13872, 13890), False, 'import cv2\n'), ((13915, 13947), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(1)'], {}), '(arr, (5, 5), 1)\n', (13931, 13947), False, 'import cv2\n'), ((13972, 14006), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['arr', '(5, 5)', '(1.5)'], {}), '(arr, (5, 5), 1.5)\n', (13988, 14006), False, 'import cv2\n'), ((14031, 14053), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (14040, 14053), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((14078, 14100), 'scipy.signal.medfilt2d', 'medfilt2d', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (14087, 14100), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((14125, 14144), 'scipy.signal.wiener', 'wiener', (['arr', '[3, 3]'], {}), '(arr, [3, 3])\n', (14131, 14144), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((14169, 14188), 'scipy.signal.wiener', 'wiener', (['arr', '[5, 5]'], {}), '(arr, [5, 5])\n', (14175, 14188), False, 'from scipy.signal import medfilt2d, wiener, cwt\n'), ((14247, 14272), 'numpy.array', 'np.array', (['wave', '"""float64"""'], {}), "(wave, 'float64')\n", (14255, 14272), True, 'import numpy as np\n'), ((14430, 14456), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['img'], {}), '(img)\n', (14451, 14456), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((14910, 14945), 'ipfml.utils.normalize_arr', 'utils.normalize_arr', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (14929, 14945), False, 'from ipfml import utils\n'), ((15083, 15130), 'ipfml.utils.get_indices_of_lowest_values', 'utils.get_indices_of_lowest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (15117, 15130), False, 'from ipfml import utils\n'), ((15189, 15237), 'ipfml.utils.get_indices_of_highest_values', 'utils.get_indices_of_highest_values', (['sv_std', '(200)'], {}), '(sv_std, 200)\n', (15224, 15237), False, 'from ipfml import utils\n'), ((15939, 15968), 'ipfml.processing.transform.get_LAB_L', 'transform.get_LAB_L', (['sub_zone'], {}), '(sub_zone)\n', (15958, 15968), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((15996, 16025), 'ipfml.utils.normalize_2D_arr', 'utils.normalize_2D_arr', (['l_img'], {}), '(l_img)\n', (16018, 16025), False, 'from ipfml import utils\n'), ((16104, 16179), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.min_bilateral_diff', '(3, 3)'], {}), '(normed_l_img, kernels.min_bilateral_diff, (3, 3))\n', (16129, 16179), False, 'from ipfml.filters import convolution, kernels\n'), ((16203, 16222), 'numpy.std', 'np.std', (['normed_diff'], {}), '(normed_diff)\n', (16209, 16222), True, 'import numpy as np\n'), ((16247, 16267), 'numpy.mean', 'np.mean', (['normed_diff'], {}), '(normed_diff)\n', (16254, 16267), True, 'import numpy as np\n'), ((16439, 16514), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.min_bilateral_diff', '(5, 5)'], {}), '(normed_l_img, kernels.min_bilateral_diff, (5, 5))\n', (16464, 16514), False, 'from ipfml.filters import convolution, kernels\n'), ((16538, 16557), 'numpy.std', 'np.std', (['normed_diff'], {}), '(normed_diff)\n', (16544, 16557), True, 'import numpy as np\n'), ((16582, 16602), 'numpy.mean', 'np.mean', (['normed_diff'], {}), '(normed_diff)\n', (16589, 16602), True, 'import numpy as np\n'), ((16781, 16848), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.plane_mean', '(3, 3)'], {}), '(normed_l_img, kernels.plane_mean, (3, 3))\n', (16806, 16848), False, 'from ipfml.filters import convolution, kernels\n'), ((16878, 16903), 'numpy.std', 'np.std', (['normed_plane_mean'], {}), '(normed_plane_mean)\n', (16884, 16903), True, 'import numpy as np\n'), ((16934, 16960), 'numpy.mean', 'np.mean', (['normed_plane_mean'], {}), '(normed_plane_mean)\n', (16941, 16960), True, 'import numpy as np\n'), ((17153, 17220), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.plane_mean', '(5, 5)'], {}), '(normed_l_img, kernels.plane_mean, (5, 5))\n', (17178, 17220), False, 'from ipfml.filters import convolution, kernels\n'), ((17250, 17275), 'numpy.std', 'np.std', (['normed_plane_mean'], {}), '(normed_plane_mean)\n', (17256, 17275), True, 'import numpy as np\n'), ((17306, 17332), 'numpy.mean', 'np.mean', (['normed_plane_mean'], {}), '(normed_plane_mean)\n', (17313, 17332), True, 'import numpy as np\n'), ((17529, 17601), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.plane_max_error', '(3, 3)'], {}), '(normed_l_img, kernels.plane_max_error, (3, 3))\n', (17554, 17601), False, 'from ipfml.filters import convolution, kernels\n'), ((17630, 17654), 'numpy.std', 'np.std', (['normed_plane_max'], {}), '(normed_plane_max)\n', (17636, 17654), True, 'import numpy as np\n'), ((17684, 17709), 'numpy.mean', 'np.mean', (['normed_plane_max'], {}), '(normed_plane_max)\n', (17691, 17709), True, 'import numpy as np\n'), ((17912, 17984), 'ipfml.filters.convolution.convolution2D', 'convolution.convolution2D', (['normed_l_img', 'kernels.plane_max_error', '(5, 5)'], {}), '(normed_l_img, kernels.plane_max_error, (5, 5))\n', (17937, 17984), False, 'from ipfml.filters import convolution, kernels\n'), ((18013, 18037), 'numpy.std', 'np.std', (['normed_plane_max'], {}), '(normed_plane_max)\n', (18019, 18037), True, 'import numpy as np\n'), ((18067, 18092), 'numpy.mean', 'np.mean', (['normed_plane_max'], {}), '(normed_plane_max)\n', (18074, 18092), True, 'import numpy as np\n'), ((22860, 22884), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['b'], {}), '(b)\n', (22881, 22884), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23176, 23200), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['b'], {}), '(b)\n', (23197, 23200), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((23498, 23522), 'ipfml.processing.compression.get_SVD_s', 'compression.get_SVD_s', (['b'], {}), '(b)\n', (23519, 23522), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((24393, 24411), 'numpy.var', 'np.var', (['flat_coeff'], {}), '(flat_coeff)\n', (24399, 24411), True, 'import numpy as np\n'), ((3041, 3073), 'ipfml.processing.transform.get_LAB_L_SVD_s', 'transform.get_LAB_L_SVD_s', (['sub_b'], {}), '(sub_b)\n', (3066, 3073), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((3147, 3166), 'numpy.mean', 'np.mean', (['l_svd_data'], {}), '(l_svd_data)\n', (3154, 3166), True, 'import numpy as np\n'), ((3192, 3213), 'numpy.median', 'np.median', (['l_svd_data'], {}), '(l_svd_data)\n', (3201, 3213), True, 'import numpy as np\n'), ((3239, 3268), 'numpy.percentile', 'np.percentile', (['l_svd_data', '(25)'], {}), '(l_svd_data, 25)\n', (3252, 3268), True, 'import numpy as np\n'), ((3294, 3323), 'numpy.percentile', 'np.percentile', (['l_svd_data', '(75)'], {}), '(l_svd_data, 75)\n', (3307, 3323), True, 'import numpy as np\n'), ((3349, 3367), 'numpy.var', 'np.var', (['l_svd_data'], {}), '(l_svd_data)\n', (3355, 3367), True, 'import numpy as np\n'), ((3992, 4024), 'ipfml.processing.transform.get_LAB_L_SVD_s', 'transform.get_LAB_L_SVD_s', (['sub_b'], {}), '(sub_b)\n', (4017, 4024), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((4098, 4117), 'numpy.mean', 'np.mean', (['l_svd_data'], {}), '(l_svd_data)\n', (4105, 4117), True, 'import numpy as np\n'), ((4143, 4164), 'numpy.median', 'np.median', (['l_svd_data'], {}), '(l_svd_data)\n', (4152, 4164), True, 'import numpy as np\n'), ((4190, 4219), 'numpy.percentile', 'np.percentile', (['l_svd_data', '(25)'], {}), '(l_svd_data, 25)\n', (4203, 4219), True, 'import numpy as np\n'), ((4245, 4274), 'numpy.percentile', 'np.percentile', (['l_svd_data', '(75)'], {}), '(l_svd_data, 75)\n', (4258, 4274), True, 'import numpy as np\n'), ((4300, 4318), 'numpy.var', 'np.var', (['l_svd_data'], {}), '(l_svd_data)\n', (4306, 4318), True, 'import numpy as np\n'), ((4814, 4846), 'ipfml.processing.transform.get_LAB_L_SVD_s', 'transform.get_LAB_L_SVD_s', (['sub_b'], {}), '(sub_b)\n', (4839, 4846), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((5468, 5500), 'ipfml.processing.transform.get_LAB_L_SVD_s', 'transform.get_LAB_L_SVD_s', (['sub_b'], {}), '(sub_b)\n', (5493, 5500), False, 'from ipfml.processing import transform, compression, segmentation\n'), ((7072, 7091), 'numpy.array', 'np.array', (['sv_values'], {}), '(sv_values)\n', (7080, 7091), True, 'import numpy as np\n'), ((7094, 7117), 'numpy.array', 'np.array', (['ica_sv_values'], {}), '(ica_sv_values)\n', (7102, 7117), True, 'import numpy as np\n'), ((9581, 9603), 'numpy.std', 'np.std', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (9587, 9603), True, 'import numpy as np\n'), ((10890, 10912), 'numpy.std', 'np.std', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (10896, 10912), True, 'import numpy as np\n'), ((12963, 12985), 'numpy.std', 'np.std', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (12969, 12985), True, 'import numpy as np\n'), ((14516, 14561), 'ipfml.utils.get_entropy_contribution_of_i', 'utils.get_entropy_contribution_of_i', (['s', 'id_sv'], {}), '(s, id_sv)\n', (14551, 14561), False, 'from ipfml import utils\n'), ((14972, 14994), 'numpy.std', 'np.std', (['sv_array[:, i]'], {}), '(sv_array[:, i])\n', (14978, 14994), True, 'import numpy as np\n'), ((20913, 20936), 'numpy.std', 'np.std', (['diff_std_list_3'], {}), '(diff_std_list_3)\n', (20919, 20936), True, 'import numpy as np\n'), ((20962, 20986), 'numpy.std', 'np.std', (['diff_mean_list_3'], {}), '(diff_mean_list_3)\n', (20968, 20986), True, 'import numpy as np\n'), ((21012, 21035), 'numpy.std', 'np.std', (['diff_std_list_5'], {}), '(diff_std_list_5)\n', (21018, 21035), True, 'import numpy as np\n'), ((21061, 21085), 'numpy.std', 'np.std', (['diff_mean_list_5'], {}), '(diff_mean_list_5)\n', (21067, 21085), True, 'import numpy as np\n'), ((21112, 21136), 'numpy.std', 'np.std', (['plane_std_list_3'], {}), '(plane_std_list_3)\n', (21118, 21136), True, 'import numpy as np\n'), ((21162, 21187), 'numpy.std', 'np.std', (['plane_mean_list_3'], {}), '(plane_mean_list_3)\n', (21168, 21187), True, 'import numpy as np\n'), ((21213, 21237), 'numpy.std', 'np.std', (['plane_std_list_5'], {}), '(plane_std_list_5)\n', (21219, 21237), True, 'import numpy as np\n'), ((21263, 21288), 'numpy.std', 'np.std', (['plane_mean_list_5'], {}), '(plane_mean_list_5)\n', (21269, 21288), True, 'import numpy as np\n'), ((21327, 21355), 'numpy.std', 'np.std', (['plane_max_std_list_3'], {}), '(plane_max_std_list_3)\n', (21333, 21355), True, 'import numpy as np\n'), ((21381, 21410), 'numpy.std', 'np.std', (['plane_max_mean_list_3'], {}), '(plane_max_mean_list_3)\n', (21387, 21410), True, 'import numpy as np\n'), ((21436, 21464), 'numpy.std', 'np.std', (['plane_max_std_list_5'], {}), '(plane_max_std_list_5)\n', (21442, 21464), True, 'import numpy as np\n'), ((21490, 21519), 'numpy.std', 'np.std', (['plane_max_mean_list_5'], {}), '(plane_max_mean_list_5)\n', (21496, 21519), True, 'import numpy as np\n'), ((21586, 21610), 'numpy.mean', 'np.mean', (['diff_std_list_3'], {}), '(diff_std_list_3)\n', (21593, 21610), True, 'import numpy as np\n'), ((21636, 21661), 'numpy.mean', 'np.mean', (['diff_mean_list_3'], {}), '(diff_mean_list_3)\n', (21643, 21661), True, 'import numpy as np\n'), ((21687, 21711), 'numpy.mean', 'np.mean', (['diff_std_list_5'], {}), '(diff_std_list_5)\n', (21694, 21711), True, 'import numpy as np\n'), ((21737, 21762), 'numpy.mean', 'np.mean', (['diff_mean_list_5'], {}), '(diff_mean_list_5)\n', (21744, 21762), True, 'import numpy as np\n'), ((21789, 21814), 'numpy.mean', 'np.mean', (['plane_std_list_3'], {}), '(plane_std_list_3)\n', (21796, 21814), True, 'import numpy as np\n'), ((21840, 21866), 'numpy.mean', 'np.mean', (['plane_mean_list_3'], {}), '(plane_mean_list_3)\n', (21847, 21866), True, 'import numpy as np\n'), ((21892, 21917), 'numpy.mean', 'np.mean', (['plane_std_list_5'], {}), '(plane_std_list_5)\n', (21899, 21917), True, 'import numpy as np\n'), ((21943, 21969), 'numpy.mean', 'np.mean', (['plane_mean_list_5'], {}), '(plane_mean_list_5)\n', (21950, 21969), True, 'import numpy as np\n'), ((22008, 22037), 'numpy.mean', 'np.mean', (['plane_max_std_list_3'], {}), '(plane_max_std_list_3)\n', (22015, 22037), True, 'import numpy as np\n'), ((22063, 22093), 'numpy.mean', 'np.mean', (['plane_max_mean_list_3'], {}), '(plane_max_mean_list_3)\n', (22070, 22093), True, 'import numpy as np\n'), ((22119, 22148), 'numpy.mean', 'np.mean', (['plane_max_std_list_5'], {}), '(plane_max_std_list_5)\n', (22126, 22148), True, 'import numpy as np\n'), ((22174, 22204), 'numpy.mean', 'np.mean', (['plane_max_mean_list_5'], {}), '(plane_max_mean_list_5)\n', (22181, 22204), True, 'import numpy as np\n'), ((22911, 22932), 'ipfml.utils.get_entropy', 'utils.get_entropy', (['sv'], {}), '(sv)\n', (22928, 22932), False, 'from ipfml import utils\n'), ((23227, 23248), 'ipfml.utils.get_entropy', 'utils.get_entropy', (['sv'], {}), '(sv)\n', (23244, 23248), False, 'from ipfml import utils\n')]
# Code apapted from https://github.com/mseitzer/pytorch-fid """Calculates the Frechet Inception Distance (FID) to evalulate GANs The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd distribution is given by a GAN. When run as a stand-alone program, it compares the distribution of images that are stored as PNG/JPEG at a specified location with a distribution given by summary statistics (in pickle format). The FID is calculated by assuming that X_1 and X_2 are the activations of the pool_3 layer of the inception net for generated samples and real world samples respectively. See --help to see further details. Code apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead of Tensorflow Copyright 2018 Institute of Bioinformatics, JKU Linz Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import time import numpy as np import torch from scipy import linalg from torch.nn.functional import adaptive_avg_pool2d from util import tools def get_activations(dataset, model, size=1000, batch_size=50, dims=2048, device='cpu'): """Calculates the activations of the pool_3 layer for all images. Params: -- files : List of image files paths -- model : Instance of inception model -- batch_size : Batch size of images for the model to process at once. Make sure that the number of samples is a multiple of the batch size, otherwise some samples are ignored. This behavior is retained to match the original FID score implementation. -- dims : Dimensionality of features returned by Inception -- device : Device to run calculations Returns: -- A numpy array of dimension (num images, dims) that contains the activations of the given tensor when feeding inception with the query tensor. """ model.eval() if batch_size > size: print(('Warning: batch size is bigger than the data size. ' 'Setting batch size to data size')) batch_size = size dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, drop_last=False) pred_arr = np.empty((size, dims)) start_idx = 0 for batch, _ in dataloader: if batch.shape[1] == 1: batch = torch.cat((batch, batch, batch), 1) batch = batch.to(device) with torch.no_grad(): pred = model(batch)[0] # If model output is not scalar, apply global spatial average pooling. # This happens if you choose a dimensionality not equal 2048. if pred.size(2) != 1 or pred.size(3) != 1: pred = adaptive_avg_pool2d(pred, output_size=(1, 1)) pred = pred.squeeze(3).squeeze(2).cpu().numpy() pred_arr[start_idx:start_idx + pred.shape[0]] = pred start_idx = start_idx + pred.shape[0] if start_idx >= size: break return pred_arr def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by <NAME>. Params: -- mu1 : Numpy array containing the activations of a layer of the inception net (like returned by the function 'get_predictions') for generated samples. -- mu2 : The sample mean over activations, precalculated on an representative data set. -- sigma1: The covariance matrix over activations for generated samples. -- sigma2: The covariance matrix over activations, precalculated on an representative data set. Returns: -- : The Frechet Distance. """ mu1 = np.atleast_1d(mu1) mu2 = np.atleast_1d(mu2) sigma1 = np.atleast_2d(sigma1) sigma2 = np.atleast_2d(sigma2) assert mu1.shape == mu2.shape, 'Training and test mean vectors have different lengths' assert sigma1.shape == sigma2.shape, 'Training and test covariances have different dimensions' diff = mu1 - mu2 # Product might be almost singular start_time = time.time() covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) print("FID: sqrtm --- %s seconds ---" % (time.time() - start_time)) if not np.isfinite(covmean).all(): msg = ('fid calculation produces singular product; ' 'adding %s to diagonal of cov estimates') % eps print(msg) offset = np.eye(sigma1.shape[0]) * eps covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset)) # Numerical error might give slight imaginary component if np.iscomplexobj(covmean): if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): m = np.max(np.abs(covmean.imag)) # raise ValueError('Imaginary component {}'.format(m)) print('Imaginary component {}'.format(m)) covmean = covmean.real tr_covmean = np.trace(covmean) return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean def calculate_activation_statistics(dataset, model, size=1000, batch_size=50, dims=2048): act = get_activations(dataset, model, size, batch_size, dims, tools.device_name()) mu = np.mean(act, axis=0) sigma = np.cov(act, rowvar=False) return mu, sigma
[ "numpy.atleast_2d", "numpy.trace", "numpy.mean", "torch.nn.functional.adaptive_avg_pool2d", "numpy.eye", "numpy.abs", "numpy.diagonal", "util.tools.device_name", "numpy.iscomplexobj", "numpy.empty", "numpy.isfinite", "torch.utils.data.DataLoader", "torch.no_grad", "numpy.cov", "time.time", "torch.cat", "numpy.atleast_1d" ]
[((2677, 2772), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'drop_last': '(False)'}), '(dataset, batch_size=batch_size, shuffle=False,\n drop_last=False)\n', (2704, 2772), False, 'import torch\n'), ((2785, 2807), 'numpy.empty', 'np.empty', (['(size, dims)'], {}), '((size, dims))\n', (2793, 2807), True, 'import numpy as np\n'), ((4443, 4461), 'numpy.atleast_1d', 'np.atleast_1d', (['mu1'], {}), '(mu1)\n', (4456, 4461), True, 'import numpy as np\n'), ((4472, 4490), 'numpy.atleast_1d', 'np.atleast_1d', (['mu2'], {}), '(mu2)\n', (4485, 4490), True, 'import numpy as np\n'), ((4505, 4526), 'numpy.atleast_2d', 'np.atleast_2d', (['sigma1'], {}), '(sigma1)\n', (4518, 4526), True, 'import numpy as np\n'), ((4540, 4561), 'numpy.atleast_2d', 'np.atleast_2d', (['sigma2'], {}), '(sigma2)\n', (4553, 4561), True, 'import numpy as np\n'), ((4832, 4843), 'time.time', 'time.time', ([], {}), '()\n', (4841, 4843), False, 'import time\n'), ((5346, 5370), 'numpy.iscomplexobj', 'np.iscomplexobj', (['covmean'], {}), '(covmean)\n', (5361, 5370), True, 'import numpy as np\n'), ((5656, 5673), 'numpy.trace', 'np.trace', (['covmean'], {}), '(covmean)\n', (5664, 5673), True, 'import numpy as np\n'), ((5943, 5963), 'numpy.mean', 'np.mean', (['act'], {'axis': '(0)'}), '(act, axis=0)\n', (5950, 5963), True, 'import numpy as np\n'), ((5976, 6001), 'numpy.cov', 'np.cov', (['act'], {'rowvar': '(False)'}), '(act, rowvar=False)\n', (5982, 6001), True, 'import numpy as np\n'), ((5913, 5932), 'util.tools.device_name', 'tools.device_name', ([], {}), '()\n', (5930, 5932), False, 'from util import tools\n'), ((2911, 2946), 'torch.cat', 'torch.cat', (['(batch, batch, batch)', '(1)'], {}), '((batch, batch, batch), 1)\n', (2920, 2946), False, 'import torch\n'), ((2993, 3008), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3006, 3008), False, 'import torch\n'), ((3265, 3310), 'torch.nn.functional.adaptive_avg_pool2d', 'adaptive_avg_pool2d', (['pred'], {'output_size': '(1, 1)'}), '(pred, output_size=(1, 1))\n', (3284, 3310), False, 'from torch.nn.functional import adaptive_avg_pool2d\n'), ((5177, 5200), 'numpy.eye', 'np.eye', (['sigma1.shape[0]'], {}), '(sigma1.shape[0])\n', (5183, 5200), True, 'import numpy as np\n'), ((5721, 5737), 'numpy.trace', 'np.trace', (['sigma2'], {}), '(sigma2)\n', (5729, 5737), True, 'import numpy as np\n'), ((4951, 4962), 'time.time', 'time.time', ([], {}), '()\n', (4960, 4962), False, 'import time\n'), ((4989, 5009), 'numpy.isfinite', 'np.isfinite', (['covmean'], {}), '(covmean)\n', (5000, 5009), True, 'import numpy as np\n'), ((5464, 5484), 'numpy.abs', 'np.abs', (['covmean.imag'], {}), '(covmean.imag)\n', (5470, 5484), True, 'import numpy as np\n'), ((5702, 5718), 'numpy.trace', 'np.trace', (['sigma1'], {}), '(sigma1)\n', (5710, 5718), True, 'import numpy as np\n'), ((5399, 5419), 'numpy.diagonal', 'np.diagonal', (['covmean'], {}), '(covmean)\n', (5410, 5419), True, 'import numpy as np\n')]
import torch import torch.nn as nn import numpy as np import cv2 import os import shutil from matplotlib import pyplot as plt from Model_Definition import VC3D from mypath import NICKNAME, DATA_DIR, PATH # TODO: Now can display images with plt.show(), need to solve display on cloud instance OUT_DIR = PATH + os.path.sep + 'Result' DEMO_DIR = PATH + os.path.sep + 'Demo' # %% def check_folder_exist(folder_name): if os.path.exists(folder_name): shutil.rmtree(folder_name) os.makedirs(folder_name) else: os.makedirs(folder_name) check_folder_exist(OUT_DIR) # %% def center_crop(frame): frame = frame[:120, 22:142, :] return np.array(frame).astype(np.uint8) # %% def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("Device being used:", device) with open('ucf_9_labels.txt', 'r') as f: class_names = f.readlines() f.close() # init model model = VC3D() checkpoint = torch.load(f'model_{NICKNAME}.pt', map_location=device) model.load_state_dict(checkpoint) model.to(device) model.eval() # read video video_name = 'PlayingGuitar' video = DATA_DIR + os.path.sep + video_name + os.path.sep + 'v_' + video_name + '_g09_c04.avi' # video = DEMO_DIR + os.path.sep + video_name + '.mp4' cap = cv2.VideoCapture(video) retaining = True fps = int(cap.get(5)) size = (int(cap.get(3)), int(cap.get(4))) fourcc = int(cap.get(6)) frames_num = cap.get(7) print('Video Readed, with fps %s, size %s and format %s' % (fps, size, chr(fourcc & 0xFF) + chr((fourcc >> 8) & 0xFF) + chr( (fourcc >> 16) & 0xFF) + chr( (fourcc >> 24) & 0xFF))) out = cv2.VideoWriter(os.path.join(OUT_DIR, video_name + '_result.mp4'), 1983148141, fps, size) clip = [] count = 0 while retaining: count += 1 retaining, frame = cap.read() if not retaining and frame is None: continue tmp_ = center_crop(cv2.resize(frame, (171, 128))) tmp = tmp_ - np.array([[[90.0, 98.0, 102.0]]]) clip.append(tmp) if len(clip) == 16: inputs = np.array(clip).astype(np.float32) inputs = np.expand_dims(inputs, axis=0) inputs = np.transpose(inputs, (0, 4, 1, 2, 3)) inputs = torch.from_numpy(inputs) inputs = torch.autograd.Variable(inputs, requires_grad=False).to(device) with torch.no_grad(): outputs = model.forward(inputs) probs = nn.Softmax(dim=1)(outputs) label = torch.max(probs, 1)[1].detach().cpu().numpy()[0] cv2.putText(frame, class_names[label].split(' ')[-1].strip(), (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 1) cv2.putText(frame, "prob: %.4f" % probs[0][label], (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 1) out.write(frame) clip.pop(0) if count % 10 == 0: print(str(count / frames_num * 100) + '%') if cv2.waitKey(1) & 0xFF == ord('q'): break # cv2.imshow('result', frame) # cv2.waitKey(30) # plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # plt.title('result') # plt.show() out.release() cap.release() cv2.destroyAllWindows() if __name__ == '__main__': main()
[ "Model_Definition.VC3D", "torch.max", "torch.from_numpy", "numpy.array", "torch.cuda.is_available", "cv2.destroyAllWindows", "os.path.exists", "torch.autograd.Variable", "cv2.waitKey", "cv2.putText", "cv2.resize", "numpy.transpose", "os.makedirs", "torch.nn.Softmax", "torch.load", "os.path.join", "cv2.VideoCapture", "numpy.expand_dims", "shutil.rmtree", "torch.no_grad" ]
[((424, 451), 'os.path.exists', 'os.path.exists', (['folder_name'], {}), '(folder_name)\n', (438, 451), False, 'import os\n'), ((967, 973), 'Model_Definition.VC3D', 'VC3D', ([], {}), '()\n', (971, 973), False, 'from Model_Definition import VC3D\n'), ((991, 1046), 'torch.load', 'torch.load', (['f"""model_{NICKNAME}.pt"""'], {'map_location': 'device'}), "(f'model_{NICKNAME}.pt', map_location=device)\n", (1001, 1046), False, 'import torch\n'), ((1342, 1365), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video'], {}), '(video)\n', (1358, 1365), False, 'import cv2\n'), ((3628, 3651), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3649, 3651), False, 'import cv2\n'), ((461, 487), 'shutil.rmtree', 'shutil.rmtree', (['folder_name'], {}), '(folder_name)\n', (474, 487), False, 'import shutil\n'), ((496, 520), 'os.makedirs', 'os.makedirs', (['folder_name'], {}), '(folder_name)\n', (507, 520), False, 'import os\n'), ((539, 563), 'os.makedirs', 'os.makedirs', (['folder_name'], {}), '(folder_name)\n', (550, 563), False, 'import os\n'), ((1938, 1987), 'os.path.join', 'os.path.join', (['OUT_DIR', "(video_name + '_result.mp4')"], {}), "(OUT_DIR, video_name + '_result.mp4')\n", (1950, 1987), False, 'import os\n'), ((670, 685), 'numpy.array', 'np.array', (['frame'], {}), '(frame)\n', (678, 685), True, 'import numpy as np\n'), ((760, 785), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (783, 785), False, 'import torch\n'), ((2210, 2239), 'cv2.resize', 'cv2.resize', (['frame', '(171, 128)'], {}), '(frame, (171, 128))\n', (2220, 2239), False, 'import cv2\n'), ((2262, 2295), 'numpy.array', 'np.array', (['[[[90.0, 98.0, 102.0]]]'], {}), '([[[90.0, 98.0, 102.0]]])\n', (2270, 2295), True, 'import numpy as np\n'), ((2425, 2455), 'numpy.expand_dims', 'np.expand_dims', (['inputs'], {'axis': '(0)'}), '(inputs, axis=0)\n', (2439, 2455), True, 'import numpy as np\n'), ((2477, 2514), 'numpy.transpose', 'np.transpose', (['inputs', '(0, 4, 1, 2, 3)'], {}), '(inputs, (0, 4, 1, 2, 3))\n', (2489, 2514), True, 'import numpy as np\n'), ((2536, 2560), 'torch.from_numpy', 'torch.from_numpy', (['inputs'], {}), '(inputs)\n', (2552, 2560), False, 'import torch\n'), ((3037, 3149), 'cv2.putText', 'cv2.putText', (['frame', "('prob: %.4f' % probs[0][label])", '(20, 40)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.6)', '(0, 0, 255)', '(1)'], {}), "(frame, 'prob: %.4f' % probs[0][label], (20, 40), cv2.\n FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 1)\n", (3048, 3149), False, 'import cv2\n'), ((2663, 2678), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2676, 2678), False, 'import torch\n'), ((2749, 2766), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (2759, 2766), True, 'import torch.nn as nn\n'), ((2370, 2384), 'numpy.array', 'np.array', (['clip'], {}), '(clip)\n', (2378, 2384), True, 'import numpy as np\n'), ((2582, 2634), 'torch.autograd.Variable', 'torch.autograd.Variable', (['inputs'], {'requires_grad': '(False)'}), '(inputs, requires_grad=False)\n', (2605, 2634), False, 'import torch\n'), ((3352, 3366), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3363, 3366), False, 'import cv2\n'), ((2796, 2815), 'torch.max', 'torch.max', (['probs', '(1)'], {}), '(probs, 1)\n', (2805, 2815), False, 'import torch\n')]
"""Transform signaling data to smoothed trajectories.""" import sys import numpy import pandas as pd import geopandas as gpd import shapely.geometry import matplotlib.patches import matplotlib.pyplot as plt import mobilib.voronoi SAMPLING = pd.Timedelta('00:01:00') STD = pd.Timedelta('00:05:00') def smoothen(array, std_quant): return pd.Series(array).rolling( int(numpy.ceil(8 * std_quant)), min_periods=0, center=True, win_type='gaussian' ).mean(std=std_quant) def trajectory(df, xcol, ycol, sampling, std): ts = pd.date_range(df.index.min(), df.index.max(), freq=sampling) obs_ind = ts.searchsorted(df.index) xs_src = numpy.full(ts.size, numpy.nan) xs_src[obs_ind] = df[xcol] ys_src = numpy.full(ts.size, numpy.nan) ys_src[obs_ind] = df[ycol] std_quant = std / sampling return smoothen(xs_src, std_quant), smoothen(ys_src, std_quant), ts if __name__ == '__main__': signals = pd.read_csv(sys.argv[1], sep=';') signals = signals[signals['phone_nr'] == int(sys.argv[3])] signals['pos_time'] = pd.to_datetime(signals['pos_time']) timeweights = (1 / signals.groupby('pos_time')['phone_nr'].count()).reset_index().rename(columns={'phone_nr' : 'weight'}) signals = pd.merge(signals, timeweights, on='pos_time') antennas = pd.read_csv(sys.argv[2], sep=';') siglocs = pd.merge(signals, antennas, on='cell_name').groupby('pos_time').agg({ 'xcent': 'mean', 'ycent': 'mean', }) xpos, ypos, tpos = trajectory(siglocs, 'xcent', 'ycent', sampling=SAMPLING, std=STD) plt.plot(xpos, ypos) plt.scatter(antennas.xcent, antennas.ycent, s=9, color='orange') plt.gca().set_aspect('equal') plt.show() pd.DataFrame({'x': xpos, 'y': ypos, 't': tpos}).to_csv(sys.argv[4], sep=';', index=False)
[ "pandas.Series", "numpy.ceil", "pandas.read_csv", "matplotlib.pyplot.gca", "pandas.Timedelta", "pandas.merge", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "pandas.DataFrame", "numpy.full", "pandas.to_datetime", "matplotlib.pyplot.show" ]
[((246, 270), 'pandas.Timedelta', 'pd.Timedelta', (['"""00:01:00"""'], {}), "('00:01:00')\n", (258, 270), True, 'import pandas as pd\n'), ((277, 301), 'pandas.Timedelta', 'pd.Timedelta', (['"""00:05:00"""'], {}), "('00:05:00')\n", (289, 301), True, 'import pandas as pd\n'), ((683, 713), 'numpy.full', 'numpy.full', (['ts.size', 'numpy.nan'], {}), '(ts.size, numpy.nan)\n', (693, 713), False, 'import numpy\n'), ((758, 788), 'numpy.full', 'numpy.full', (['ts.size', 'numpy.nan'], {}), '(ts.size, numpy.nan)\n', (768, 788), False, 'import numpy\n'), ((966, 999), 'pandas.read_csv', 'pd.read_csv', (['sys.argv[1]'], {'sep': '""";"""'}), "(sys.argv[1], sep=';')\n", (977, 999), True, 'import pandas as pd\n'), ((1089, 1124), 'pandas.to_datetime', 'pd.to_datetime', (["signals['pos_time']"], {}), "(signals['pos_time'])\n", (1103, 1124), True, 'import pandas as pd\n'), ((1265, 1310), 'pandas.merge', 'pd.merge', (['signals', 'timeweights'], {'on': '"""pos_time"""'}), "(signals, timeweights, on='pos_time')\n", (1273, 1310), True, 'import pandas as pd\n'), ((1326, 1359), 'pandas.read_csv', 'pd.read_csv', (['sys.argv[2]'], {'sep': '""";"""'}), "(sys.argv[2], sep=';')\n", (1337, 1359), True, 'import pandas as pd\n'), ((1594, 1614), 'matplotlib.pyplot.plot', 'plt.plot', (['xpos', 'ypos'], {}), '(xpos, ypos)\n', (1602, 1614), True, 'import matplotlib.pyplot as plt\n'), ((1619, 1683), 'matplotlib.pyplot.scatter', 'plt.scatter', (['antennas.xcent', 'antennas.ycent'], {'s': '(9)', 'color': '"""orange"""'}), "(antennas.xcent, antennas.ycent, s=9, color='orange')\n", (1630, 1683), True, 'import matplotlib.pyplot as plt\n'), ((1722, 1732), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1730, 1732), True, 'import matplotlib.pyplot as plt\n'), ((1688, 1697), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1695, 1697), True, 'import matplotlib.pyplot as plt\n'), ((1737, 1784), 'pandas.DataFrame', 'pd.DataFrame', (["{'x': xpos, 'y': ypos, 't': tpos}"], {}), "({'x': xpos, 'y': ypos, 't': tpos})\n", (1749, 1784), True, 'import pandas as pd\n'), ((347, 363), 'pandas.Series', 'pd.Series', (['array'], {}), '(array)\n', (356, 363), True, 'import pandas as pd\n'), ((385, 410), 'numpy.ceil', 'numpy.ceil', (['(8 * std_quant)'], {}), '(8 * std_quant)\n', (395, 410), False, 'import numpy\n'), ((1374, 1417), 'pandas.merge', 'pd.merge', (['signals', 'antennas'], {'on': '"""cell_name"""'}), "(signals, antennas, on='cell_name')\n", (1382, 1417), True, 'import pandas as pd\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 3 17:20:06 2018 @author: chrispedder A routine to crop sections from the images of different manuscripts in the two datasets to the same size, and with the same magnification, so that the average script size doesn't create a feature that the neural networks can learn. Reading the data description of the CLaMM dataset, we find that the images are 150mm*100mm, so we need to take similar-sized crops from our new target data. Looking at the bar on the left, we find that 6000px =(341-47) = 294mm So 1mm = 20.41px. We therefore need to crop 3062 * 2041px from the original However, to not give away too much, we need to make this crop a little random. Looking at the test images, 1) Their heights vary by around 100px AFTER downsampling, so around 170px BEFORE downsampling. 2) Their widths vary by proportionately less, around 65px AFTER, so 110px BEFORE. We define a crop function below which achieves precisely this. To run this routine, call something like `python -m src.data.data_processing --thow_input_path data/raw/MS157/ --thow_output_path data/external/thow_out --clamm_input_path data/raw/ICDAR2017_CLaMM_Training/ --clamm_output_path data/external/clamm_out` The four command line args given here are all required. """ import numpy as np import scipy.io import random import scipy.ndimage import glob import os import argparse from PIL import Image from random import randint from typing import List # helper function to clean up file list for scraped THoW filenames def clean_THoW_file_list(file_list: List): # clean out folio views etc, whose filenames start with a letter # rather than a number cleaned_THoW_list = [element for element in file_list if not element[-5].isalpha()] return cleaned_THoW_list class ImageProcessor(object): def __init__(self, args): # Crop images from point CORNER, to size given by DIM self.CORNER = [1000,1400] self.DIM = [3062,2041] # To match the training data, we need to downsample images by a # factor of 1.7 self.SCALE = 1.7 # Set size of training tiles here (we could pick 224*224 to match the # expected input size of VGG16 here too) self.IM_HEIGHT = 300 self.IM_WIDTH = 300 # Set random seed to get the same train-test split when run self.SEED = 42 random.seed(self.SEED) self.args = args def read_raw_from_dir(self, filename): """ Define function to read bytes directly from tar by filename. """ x = Image.open(filename) x = x.convert('L') # makes it greyscale - CLaMM data is already grayscale y = np.asarray(x.getdata(), dtype='uint8') return y.reshape((x.size[1], x.size[0])) def image_oc_crop(self, img): """ Makes a crop of an img, with coordinates of the top left corner top_left_pt and of side lengths "dimensions" using numpy slicing. """ lh, lw = self.CORNER dim_x, dim_y = self.DIM cropped_img = img[lh:lh+dim_x,lw:lw+dim_y] return cropped_img def resample_image(self, img): """ Resample scraped images to make them a similar number of pixels to CLaMM dataset images. """ # retain a single image channel, use cubic splines for resampling resampled = scipy.ndimage.zoom(img, 1/self.SCALE, order=3) output = resampled.astype('uint8') return output def prepare_raw_bytes_for_model(self, input_path): """ Put everything together into one function to read, crop & scale data """ input_image = self.read_raw_from_dir(input_path) cropped_input = self.image_oc_crop(input_image) img = self.resample_image(cropped_input) return img def tile_crop(self, array): """ function to crop tile_height by tile_width sections from the original cropped files. """ array_height, array_width = array.shape height_tiles_number = array_height//self.IM_HEIGHT width_tiles_number = array_width//self.IM_WIDTH tile_list = [] for i in range(height_tiles_number): for j in range(width_tiles_number): new_tile = array[i * self.IM_HEIGHT: (i + 1) * self.IM_HEIGHT, j * self.IM_WIDTH: (j + 1)* self.IM_WIDTH] tile_list.append(new_tile) return tile_list def write_input_data_to_jpg(self, input_path, output_path, THOW=False): """ Read files, process and write out processed files to an external folder, defined by the argparse args """ counter = 0 file_suffix = '*.jpg' if THOW else '*.tif' file_name = 'THOW' if THOW else 'CLaMM' # get list of files in the raw data directory input_files_list = sorted(glob.glob(input_path + file_suffix)) if THOW: input_files_list = clean_THoW_file_list(input_files_list) else: input_files_list = input_files_list[:500] #check output directory exists, if not create it if not os.path.exists(output_path): os.mkdir(output_path) for element in input_files_list: image = self.prepare_raw_bytes_for_model(element) new_tile_list = self.tile_crop(image) for i, tile in enumerate(new_tile_list): # define file names for training example tile_file_name = os.path.join( output_path, file_name + str(counter + i) + ".jpg") # write three copies of the grayscale image to three separate # layers as the VGG16 net expects an RGB input tensorized = np.dstack([tile] * 3) # create image from tensorized array im = Image.fromarray(tensorized) # save to path specified in arguments im.save(tile_file_name) print( "Tile with name {} written to disk".format(tile_file_name)) counter += len(new_tile_list) print("So far {} files written".format(counter)) print("File writing completed") def process_all_files(self): print(f'Reading data from {self.args.thow_input_path}, writing to\ {self.args.thow_output_path}') self.write_input_data_to_jpg(self.args.thow_input_path, self.args.thow_output_path, THOW=True) print(f'Reading data from {self.args.clamm_input_path}, writing to\ {self.args.clamm_output_path}') self.write_input_data_to_jpg(self.args.clamm_input_path, self.args.clamm_output_path) print('All files processed and written to file') def parse_args(): parser = argparse.ArgumentParser(description='Command line options for ' 'processing the data files needed to train the model.') parser.add_argument('--thow_input_path', type=str, required=True, help='give the path to the THOW raw files') parser.add_argument('--thow_output_path', type=str, required=True, help='path to where we should write the processed THOW tile files') parser.add_argument('--clamm_input_path', type=str, required=True, help='give the path to the CLaMM raw files') parser.add_argument('--clamm_output_path', type=str, required=True, help='path to where we should write the processed CLaMM tile files') args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() processor = ImageProcessor(args) processor.process_all_files()
[ "os.path.exists", "numpy.dstack", "PIL.Image.open", "PIL.Image.fromarray", "argparse.ArgumentParser", "random.seed", "os.mkdir", "glob.glob" ]
[((7029, 7155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Command line options for processing the data files needed to train the model."""'}), "(description=\n 'Command line options for processing the data files needed to train the model.'\n )\n", (7052, 7155), False, 'import argparse\n'), ((2434, 2456), 'random.seed', 'random.seed', (['self.SEED'], {}), '(self.SEED)\n', (2445, 2456), False, 'import random\n'), ((2632, 2652), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (2642, 2652), False, 'from PIL import Image\n'), ((4987, 5022), 'glob.glob', 'glob.glob', (['(input_path + file_suffix)'], {}), '(input_path + file_suffix)\n', (4996, 5022), False, 'import glob\n'), ((5252, 5279), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (5266, 5279), False, 'import os\n'), ((5297, 5318), 'os.mkdir', 'os.mkdir', (['output_path'], {}), '(output_path)\n', (5305, 5318), False, 'import os\n'), ((5893, 5914), 'numpy.dstack', 'np.dstack', (['([tile] * 3)'], {}), '([tile] * 3)\n', (5902, 5914), True, 'import numpy as np\n'), ((5989, 6016), 'PIL.Image.fromarray', 'Image.fromarray', (['tensorized'], {}), '(tensorized)\n', (6004, 6016), False, 'from PIL import Image\n')]
import time import random import pygame import pygame.midi import numpy as np from typing import Tuple __author__ = "<NAME>" AV_SIZE = 20 WIN_X = 30 * AV_SIZE WIN_Y = 30 * AV_SIZE DIFF_MAX = np.sqrt(WIN_X**2 + WIN_Y**2) def adapt_avatar_position(event, user_x_pos:int, user_y_pos:int) -> Tuple[int, int]: if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: if user_x_pos >= AV_SIZE: user_x_pos -= AV_SIZE if event.key == pygame.K_RIGHT: if user_x_pos < WIN_X-AV_SIZE: user_x_pos += AV_SIZE if event.key == pygame.K_UP: if user_y_pos >= AV_SIZE: user_y_pos -= AV_SIZE if event.key == pygame.K_DOWN: if user_y_pos < WIN_Y-AV_SIZE: user_y_pos += AV_SIZE return user_x_pos, user_y_pos def calculate_difference(win_position:tuple, user_x_pos:int, user_y_pos:int): difference = abs(win_position[0] - user_x_pos), abs(win_position[1] - user_y_pos) return np.sqrt(np.sqrt(difference[0]**2 + difference[1]**2) / DIFF_MAX) def main(): # setup pygame.init() pygame.midi.init() player = pygame.midi.Output(0) player.set_instrument(0) current_note = random.randint(60,84) window = pygame.display.set_mode((WIN_X,WIN_Y)) user_x_pos, user_y_pos = int(WIN_X/2), int(WIN_Y/2) pos_x = [ii for ii in range(0,WIN_X-AV_SIZE,AV_SIZE)] pos_y = [ii for ii in range(0,WIN_Y-AV_SIZE,AV_SIZE)] win_position = (random.choice(pos_x), random.choice(pos_y)) difference = calculate_difference(win_position, user_x_pos, user_y_pos) player.note_on(current_note, int(127*(1-difference))) old_time = time.time() # program loop running = True while running: if win_position == (user_x_pos, user_y_pos): window.fill((255,255,0)) else: window.fill((255,255,255)) difference = calculate_difference(win_position, user_x_pos, user_y_pos) pygame.draw.rect(window,(0,50,255,50),(user_x_pos,user_y_pos,AV_SIZE,AV_SIZE)) # Rect(left, top, width, height) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False user_x_pos, user_y_pos = adapt_avatar_position(event, user_x_pos, user_y_pos) pygame.display.flip() # Documentation: Update the full display Surface to the screen if time.time()-old_time > 1: player.note_off(current_note) current_note = random.randint(60,84) player.note_on(current_note, int(127*(1-difference))) old_time = time.time() # teardown del player pygame.midi.quit() if __name__=="__main__": main()
[ "random.choice", "numpy.sqrt", "pygame.init", "pygame.midi.quit", "pygame.event.get", "pygame.display.set_mode", "pygame.display.flip", "pygame.midi.init", "pygame.draw.rect", "pygame.midi.Output", "time.time", "random.randint" ]
[((200, 232), 'numpy.sqrt', 'np.sqrt', (['(WIN_X ** 2 + WIN_Y ** 2)'], {}), '(WIN_X ** 2 + WIN_Y ** 2)\n', (207, 232), True, 'import numpy as np\n'), ((1126, 1139), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1137, 1139), False, 'import pygame\n'), ((1145, 1163), 'pygame.midi.init', 'pygame.midi.init', ([], {}), '()\n', (1161, 1163), False, 'import pygame\n'), ((1177, 1198), 'pygame.midi.Output', 'pygame.midi.Output', (['(0)'], {}), '(0)\n', (1195, 1198), False, 'import pygame\n'), ((1247, 1269), 'random.randint', 'random.randint', (['(60)', '(84)'], {}), '(60, 84)\n', (1261, 1269), False, 'import random\n'), ((1287, 1326), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIN_X, WIN_Y)'], {}), '((WIN_X, WIN_Y))\n', (1310, 1326), False, 'import pygame\n'), ((1719, 1730), 'time.time', 'time.time', ([], {}), '()\n', (1728, 1730), False, 'import time\n'), ((2705, 2723), 'pygame.midi.quit', 'pygame.midi.quit', ([], {}), '()\n', (2721, 2723), False, 'import pygame\n'), ((1520, 1540), 'random.choice', 'random.choice', (['pos_x'], {}), '(pos_x)\n', (1533, 1540), False, 'import random\n'), ((1542, 1562), 'random.choice', 'random.choice', (['pos_y'], {}), '(pos_y)\n', (1555, 1562), False, 'import random\n'), ((2022, 2112), 'pygame.draw.rect', 'pygame.draw.rect', (['window', '(0, 50, 255, 50)', '(user_x_pos, user_y_pos, AV_SIZE, AV_SIZE)'], {}), '(window, (0, 50, 255, 50), (user_x_pos, user_y_pos, AV_SIZE,\n AV_SIZE))\n', (2038, 2112), False, 'import pygame\n'), ((2158, 2176), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (2174, 2176), False, 'import pygame\n'), ((2350, 2371), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (2369, 2371), False, 'import pygame\n'), ((1039, 1087), 'numpy.sqrt', 'np.sqrt', (['(difference[0] ** 2 + difference[1] ** 2)'], {}), '(difference[0] ** 2 + difference[1] ** 2)\n', (1046, 1087), True, 'import numpy as np\n'), ((2543, 2565), 'random.randint', 'random.randint', (['(60)', '(84)'], {}), '(60, 84)\n', (2557, 2565), False, 'import random\n'), ((2654, 2665), 'time.time', 'time.time', ([], {}), '()\n', (2663, 2665), False, 'import time\n'), ((2448, 2459), 'time.time', 'time.time', ([], {}), '()\n', (2457, 2459), False, 'import time\n')]
import abc import os import pandas as pd import numpy as np from EoraReader import EoraReader class PrimaryInputs(EoraReader): def __init__(self, file_path): super().__init__(file_path) self.df = None def get_dataset(self, extended = False): """ Returns a pandas dataframe containing domestic transactions from the input-output table """ value_add_coefficients = [] primary_inputs = [] industry_count = self.industry_header.count("Industries") primary_inputs_pos = 0 line = self.file.readline().strip().split('\t') while line[2] != "Primary Inputs": line = self.file.readline().strip().split('\t') while line[2] == "Primary Inputs": primary_inputs.append(line[3]) value_add_coefficients.append(line[4:(4 + industry_count)]) line = self.file.readline().strip().split('\t') numpy_data = np.array(value_add_coefficients) df = pd.DataFrame(data = numpy_data, index = primary_inputs) df.columns = self.industries[0:industry_count] if extended: df.loc[:, 'year'] = self.year df.loc[:, 'country'] = self.country self.df = df self.extended = extended return df
[ "pandas.DataFrame", "numpy.array" ]
[((948, 980), 'numpy.array', 'np.array', (['value_add_coefficients'], {}), '(value_add_coefficients)\n', (956, 980), True, 'import numpy as np\n'), ((994, 1045), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'numpy_data', 'index': 'primary_inputs'}), '(data=numpy_data, index=primary_inputs)\n', (1006, 1045), True, 'import pandas as pd\n')]
import attr import types from typing import Union from enum import Enum import numpy as np from scipy.optimize import differential_evolution import pygmo as pg class OptimizationMethod(Enum): """ Available optimization solvers. """ SCIPY_DE = 1 PYGMO_DE1220 = 2 @attr.s(auto_attribs=True) class ScipyDifferentialEvolutionSettings: """ Optional arguments to pass for SciPy's differential evolution caller. Members ---------------- :ivar str strategy: The differential evolution strategy to use. Should be one of: - 'best1bin' - 'best1exp' - 'rand1exp' - 'randtobest1exp' - 'currenttobest1exp' - 'best2exp' - 'rand2exp' - 'randtobest1bin' - 'currenttobest1bin' - 'best2bin' - 'rand2bin' - 'rand1bin' The default is 'best1bin'. :ivar float recombination: The recombination constant, should be in the range [0, 1]. In the literature this is also known as the crossover probability, being denoted by CR. Increasing this value allows a larger number of mutants to progress into the next generation, but at the risk of population stability. :ivar float mutation: The mutation constant. In the literature this is also known as differential weight, being denoted by F. If specified as a float it should be in the range [0, 2]. :ivar float tol: Relative tolerance for convergence, the solving stops when `np.std(pop) = atol + tol * np.abs(np.mean(population_energies))`, where and `atol` and `tol` are the absolute and relative tolerance respectively. :ivar int|numpy.random.RandomState seed: If `seed` is not specified the `np.RandomState` singleton is used. If `seed` is an int, a new `np.random.RandomState` instance is used, seeded with seed. If `seed` is already a `np.random.RandomState instance`, then that `np.random.RandomState` instance is used. Specify `seed` for repeatable minimizations. :ivar int workers: If `workers` is an int the population is subdivided into `workers` sections and evaluated in parallel (uses `multiprocessing.Pool`). Supply -1 to use all available CPU cores. Alternatively supply a map-like callable, such as `multiprocessing.Pool.map` for evaluating the population in parallel. This evaluation is carried out as `workers(func, iterable)`. :ivar bool disp: Display status messages during optimization iterations. :ivar polish: If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` method is used to polish the best population member at the end, which can improve the minimization slightly. """ number_of_decision_variables: int strategy: str = 'best1bin' recombination: float = 0.3 mutation: float = 0.6 tol: float = 1e-5 seed: Union[np.random.RandomState, int] = np.random.RandomState() workers: int = 1 disp: bool = False polish: bool = True popsize: int = None population_size_for_each_variable: int = 15 total_population_size_limit: int = 100 def __attrs_post_init__(self): if self.popsize is None: self.popsize = self._estimate_population_size() elif self.popsize <= 0: raise ValueError('Number of individuals must be greater than 0.') if type(self.popsize) != int: raise TypeError('Population size must be an integer number.') if not 0 < self.recombination <= 1: raise ValueError('Recombination must be a value between 0 and 1.') if type(self.mutation) == tuple: mutation_dithering_array = np.array(self.mutation) if len(self.mutation) > 2: raise ValueError('Mutation can be a tuple with two numbers, not more.') if mutation_dithering_array.min() < 0 or mutation_dithering_array.max() > 2: raise ValueError('Mutation must be floats between 0 and 2.') elif mutation_dithering_array.min() == mutation_dithering_array.max(): raise ValueError("Values for mutation dithering can't be equal.") else: if type(self.mutation) != int and type(self.mutation) != float: raise TypeError('When mutation is provided as a single number, it must be a float or an int.') if not 0 < self.mutation < 2: raise ValueError('Mutation must be a number between 0 and 2.') if self.tol < 0: raise ValueError('Tolerance must be a positive float.') def _estimate_population_size(self): population_size = self.population_size_for_each_variable * self.number_of_decision_variables if population_size > self.total_population_size_limit: population_size = self.total_population_size_limit return population_size @attr.s(auto_attribs=True) class PygmoSelfAdaptiveDESettings: # TODO: docs and validations gen: int popsize: int allowed_variants: list = [2, 6, 7] variant_adptv: int = 2 ftol: float = 1e-6 xtol: float = 1e-6 memory: bool = True seed: int = int(np.random.randint(0, 2000)) polish: bool = True polish_method: str = 'tnewton_precond_restart' parallel_execution: bool = False number_of_islands: int = 2 archipelago_gen: int = 50 @attr.s(auto_attribs=True) class PygmoOptimizationProblemWrapper: # TODO: docs and validations objective_function: types.FunctionType bounds: list args: list = [] def fitness(self, x): return [self.objective_function(x, *self.args)] def get_bounds(self): return self._transform_bounds_to_pygmo_standard def gradient(self, x): return pg.estimate_gradient_h(lambda x: self.fitness(x), x) @property def _transform_bounds_to_pygmo_standard(self): bounds_numpy = np.array(self.bounds, dtype=np.float64) lower_bounds = list(bounds_numpy[:, 0]) upper_bounds = list(bounds_numpy[:, 1]) return lower_bounds, upper_bounds @attr.s(auto_attribs=True) class PygmoSolutionWrapperSerial: # TODO: docs and validations solution: pg.core.population @property def fun(self): return self.solution.champion_f @property def x(self): return self.solution.champion_x @attr.s(auto_attribs=True) class PygmoSolutionWrapperParallel: # TODO: docs and validations champion_x: np.ndarray champion_f: Union[float, np.float64, np.ndarray] @property def fun(self): return self.champion_f @property def x(self): return self.champion_x @attr.s(auto_attribs=True) class OptimizationProblem: """ This class stores and solve optimization problems with the available solvers. """ # TODO: docs and validations objective_function: types.FunctionType bounds: list optimization_method: OptimizationMethod solver_args: Union[ScipyDifferentialEvolutionSettings, PygmoSelfAdaptiveDESettings] args: list = [] def __attrs_post_init__(self): if self.optimization_method == OptimizationMethod.SCIPY_DE and self.solver_args is None: self.solver_args = ScipyDifferentialEvolutionSettings(self._number_of_decision_variables) @property def _number_of_decision_variables(self): return len(self.bounds) def solve_minimization(self): if self.optimization_method == OptimizationMethod.SCIPY_DE: result = differential_evolution( self.objective_function, bounds=self.bounds, args=self.args, strategy=self.solver_args.strategy, popsize=self.solver_args.popsize, recombination=self.solver_args.recombination, mutation=self.solver_args.mutation, tol=self.solver_args.tol, disp=self.solver_args.disp, polish=self.solver_args.polish, seed=self.solver_args.seed, workers=self.solver_args.workers ) return result elif self.optimization_method == OptimizationMethod.PYGMO_DE1220: problem_wrapper = PygmoOptimizationProblemWrapper( objective_function=self.objective_function, bounds=self.bounds, args=self.args ) pygmo_algorithm = pg.algorithm( pg.de1220( gen=self.solver_args.gen, allowed_variants=self.solver_args.allowed_variants, variant_adptv=self.solver_args.variant_adptv, ftol=self.solver_args.ftol, xtol=self.solver_args.xtol, memory=self.solver_args.memory, seed=self.solver_args.seed ) ) pygmo_problem = pg.problem(problem_wrapper) if self.solver_args.parallel_execution: solution_wrapper = self._run_pygmo_parallel( pygmo_algorithm, pygmo_problem, number_of_islands=self.solver_args.number_of_islands, archipelago_gen=self.solver_args.archipelago_gen ) else: pygmo_solution = self._run_pygmo_serial(pygmo_algorithm, pygmo_problem) if self.solver_args.polish: pygmo_solution = self._polish_pygmo_population(pygmo_solution) solution_wrapper = PygmoSolutionWrapperSerial(pygmo_solution) return solution_wrapper else: raise NotImplementedError('Unavailable optimization method.') @staticmethod def _select_best_pygmo_archipelago_solution(champions_x, champions_f): best_index = np.argmin(champions_f) return champions_x[best_index], champions_f[best_index] def _run_pygmo_parallel(self, algorithm, problem, number_of_islands=2, archipelago_gen=50): pygmo_archipelago = pg.archipelago( n=number_of_islands, algo=algorithm, prob=problem, pop_size=self.solver_args.popsize, seed=self.solver_args.seed ) pygmo_archipelago.evolve(n=archipelago_gen) pygmo_archipelago.wait() champions_x = pygmo_archipelago.get_champions_x() champions_f = pygmo_archipelago.get_champions_f() champion_x, champion_f = self._select_best_pygmo_archipelago_solution(champions_x, champions_f) return PygmoSolutionWrapperParallel(champion_x=champion_x, champion_f=champion_f) def _run_pygmo_serial(self, algorithm, problem): population = pg.population( prob=problem, size=self.solver_args.popsize, seed=self.solver_args.seed ) solution = algorithm.evolve(population) return solution def _polish_pygmo_population(self, population): pygmo_nlopt_wrapper = pg.nlopt(self.solver_args.polish_method) nlopt_algorithm = pg.algorithm(pygmo_nlopt_wrapper) solution_wrapper = nlopt_algorithm.evolve(population) return solution_wrapper
[ "attr.s", "pygmo.archipelago", "scipy.optimize.differential_evolution", "pygmo.problem", "pygmo.population", "numpy.array", "numpy.random.randint", "pygmo.algorithm", "pygmo.de1220", "numpy.argmin", "numpy.random.RandomState", "pygmo.nlopt" ]
[((287, 312), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (293, 312), False, 'import attr\n'), ((4837, 4862), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (4843, 4862), False, 'import attr\n'), ((5322, 5347), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (5328, 5347), False, 'import attr\n'), ((6033, 6058), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (6039, 6058), False, 'import attr\n'), ((6309, 6334), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (6315, 6334), False, 'import attr\n'), ((6616, 6641), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (6622, 6641), False, 'import attr\n'), ((2875, 2898), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2896, 2898), True, 'import numpy as np\n'), ((5118, 5144), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2000)'], {}), '(0, 2000)\n', (5135, 5144), True, 'import numpy as np\n'), ((5852, 5891), 'numpy.array', 'np.array', (['self.bounds'], {'dtype': 'np.float64'}), '(self.bounds, dtype=np.float64)\n', (5860, 5891), True, 'import numpy as np\n'), ((9796, 9818), 'numpy.argmin', 'np.argmin', (['champions_f'], {}), '(champions_f)\n', (9805, 9818), True, 'import numpy as np\n'), ((10008, 10141), 'pygmo.archipelago', 'pg.archipelago', ([], {'n': 'number_of_islands', 'algo': 'algorithm', 'prob': 'problem', 'pop_size': 'self.solver_args.popsize', 'seed': 'self.solver_args.seed'}), '(n=number_of_islands, algo=algorithm, prob=problem, pop_size=\n self.solver_args.popsize, seed=self.solver_args.seed)\n', (10022, 10141), True, 'import pygmo as pg\n'), ((10677, 10768), 'pygmo.population', 'pg.population', ([], {'prob': 'problem', 'size': 'self.solver_args.popsize', 'seed': 'self.solver_args.seed'}), '(prob=problem, size=self.solver_args.popsize, seed=self.\n solver_args.seed)\n', (10690, 10768), True, 'import pygmo as pg\n'), ((10965, 11005), 'pygmo.nlopt', 'pg.nlopt', (['self.solver_args.polish_method'], {}), '(self.solver_args.polish_method)\n', (10973, 11005), True, 'import pygmo as pg\n'), ((11032, 11065), 'pygmo.algorithm', 'pg.algorithm', (['pygmo_nlopt_wrapper'], {}), '(pygmo_nlopt_wrapper)\n', (11044, 11065), True, 'import pygmo as pg\n'), ((3636, 3659), 'numpy.array', 'np.array', (['self.mutation'], {}), '(self.mutation)\n', (3644, 3659), True, 'import numpy as np\n'), ((7463, 7870), 'scipy.optimize.differential_evolution', 'differential_evolution', (['self.objective_function'], {'bounds': 'self.bounds', 'args': 'self.args', 'strategy': 'self.solver_args.strategy', 'popsize': 'self.solver_args.popsize', 'recombination': 'self.solver_args.recombination', 'mutation': 'self.solver_args.mutation', 'tol': 'self.solver_args.tol', 'disp': 'self.solver_args.disp', 'polish': 'self.solver_args.polish', 'seed': 'self.solver_args.seed', 'workers': 'self.solver_args.workers'}), '(self.objective_function, bounds=self.bounds, args=\n self.args, strategy=self.solver_args.strategy, popsize=self.solver_args\n .popsize, recombination=self.solver_args.recombination, mutation=self.\n solver_args.mutation, tol=self.solver_args.tol, disp=self.solver_args.\n disp, polish=self.solver_args.polish, seed=self.solver_args.seed,\n workers=self.solver_args.workers)\n', (7485, 7870), False, 'from scipy.optimize import differential_evolution\n'), ((8868, 8895), 'pygmo.problem', 'pg.problem', (['problem_wrapper'], {}), '(problem_wrapper)\n', (8878, 8895), True, 'import pygmo as pg\n'), ((8418, 8682), 'pygmo.de1220', 'pg.de1220', ([], {'gen': 'self.solver_args.gen', 'allowed_variants': 'self.solver_args.allowed_variants', 'variant_adptv': 'self.solver_args.variant_adptv', 'ftol': 'self.solver_args.ftol', 'xtol': 'self.solver_args.xtol', 'memory': 'self.solver_args.memory', 'seed': 'self.solver_args.seed'}), '(gen=self.solver_args.gen, allowed_variants=self.solver_args.\n allowed_variants, variant_adptv=self.solver_args.variant_adptv, ftol=\n self.solver_args.ftol, xtol=self.solver_args.xtol, memory=self.\n solver_args.memory, seed=self.solver_args.seed)\n', (8427, 8682), True, 'import pygmo as pg\n')]
#!/usr/bin/env python3 import fire import json import os import numpy as np import tensorflow as tf import model, sample, encoder def interact_model( model_name='117M', seed=None, nsamples=1000, batch_size=1, length=None, temperature=1, top_k=0, top_p=0.0 ): """ Interactively run the model :model_name=117M : String, which model to use :seed=None : Integer seed for random number generators, fix seed to reproduce results :nsamples=1 : Number of samples to return total :batch_size=1 : Number of batches (only affects speed/memory). Must divide nsamples. :length=None : Number of tokens in generated text, if None (default), is determined by model hyperparameters :temperature=1 : Float value controlling randomness in boltzmann distribution. Lower temperature results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive. Higher temperature results in more random completions. :top_k=0 : Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting meaning no restrictions. 40 generally is a good value. :top_p=0.0 : Float value controlling diversity. Implements nucleus sampling, overriding top_k if set to a value > 0. A good setting is 0.9. """ if batch_size is None: batch_size = 1 assert nsamples % batch_size == 0 enc = encoder.get_encoder(model_name) hparams = model.default_hparams() with open(os.path.join('models', model_name, 'hparams.json')) as f: hparams.override_from_dict(json.load(f)) if length is None: length = hparams.n_ctx // 2 print(length) #elif length > hparams.n_ctx: # raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx) #config = tf.ConfigProto(device_count={'GPU': 0}) config = tf.ConfigProto() with tf.Session(graph=tf.Graph(),config=config) as sess: context = tf.placeholder(tf.int32, [batch_size, None]) np.random.seed(seed) tf.set_random_seed(seed) raw_text = """Model {""" #input("Model prompt >>> ") context_tokens = enc.encode(raw_text) output = sample.sample_sequence( hparams=hparams, length=length, context=context, batch_size=batch_size, temperature=temperature, top_k=top_k, top_p=top_p ) saver = tf.train.Saver() ckpt = tf.train.latest_checkpoint(os.path.join('models', model_name)) saver.restore(sess, ckpt) from datetime import datetime #while True: generated = 0 import time grand_start = time.time() for cnt in range(nsamples // batch_size): start_per_sample = time.time() output_text = raw_text text = raw_text context_tokens = enc.encode(text) #raw_text = input("Model prompt >>> ") # while not raw_text: # print('Prompt should not be empty!') # raw_text = input("Model prompt >>> ") #print(context_tokens) #file_to_save.write(raw_text) #for cnt in range(nsamples // batch_size): while "<|endoftext|>" not in text: out = sess.run(output, feed_dict={context: [context_tokens for _ in range(batch_size)]})[:, len(context_tokens):] for i in range(batch_size): #generated += 1 text = enc.decode(out[i]) if "<|endoftext|>" in text: sep = "<|endoftext|>" rest = text.split(sep, 1)[0] output_text += rest break context_tokens = enc.encode(text) output_text += text print("=" * 40 + " SAMPLE " + str(cnt+12) + " " + "=" * 40) minutes, seconds = divmod(time.time() - start_per_sample, 60) print("Output Done : {:0>2}:{:05.2f}".format(int(minutes),seconds) ) print("=" * 80) with open("Simulink_sample/sample__"+str(cnt+12)+".mdl","w+") as f: f.write(output_text) elapsed_total = time.time()-grand_start hours, rem = divmod(elapsed_total,3600) minutes, seconds = divmod(rem, 60) print("Total time to generate 1000 samples :{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds)) if __name__ == '__main__': fire.Fire(interact_model)
[ "tensorflow.Graph", "encoder.get_encoder", "fire.Fire", "tensorflow.placeholder", "tensorflow.train.Saver", "os.path.join", "sample.sample_sequence", "model.default_hparams", "numpy.random.seed", "json.load", "tensorflow.ConfigProto", "tensorflow.set_random_seed", "time.time" ]
[((1595, 1626), 'encoder.get_encoder', 'encoder.get_encoder', (['model_name'], {}), '(model_name)\n', (1614, 1626), False, 'import model, sample, encoder\n'), ((1641, 1664), 'model.default_hparams', 'model.default_hparams', ([], {}), '()\n', (1662, 1664), False, 'import model, sample, encoder\n'), ((2059, 2075), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (2073, 2075), True, 'import tensorflow as tf\n'), ((4691, 4716), 'fire.Fire', 'fire.Fire', (['interact_model'], {}), '(interact_model)\n', (4700, 4716), False, 'import fire\n'), ((2155, 2199), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[batch_size, None]'], {}), '(tf.int32, [batch_size, None])\n', (2169, 2199), True, 'import tensorflow as tf\n'), ((2208, 2228), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2222, 2228), True, 'import numpy as np\n'), ((2237, 2261), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (2255, 2261), True, 'import tensorflow as tf\n'), ((2405, 2554), 'sample.sample_sequence', 'sample.sample_sequence', ([], {'hparams': 'hparams', 'length': 'length', 'context': 'context', 'batch_size': 'batch_size', 'temperature': 'temperature', 'top_k': 'top_k', 'top_p': 'top_p'}), '(hparams=hparams, length=length, context=context,\n batch_size=batch_size, temperature=temperature, top_k=top_k, top_p=top_p)\n', (2427, 2554), False, 'import model, sample, encoder\n'), ((2626, 2642), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (2640, 2642), True, 'import tensorflow as tf\n'), ((2878, 2889), 'time.time', 'time.time', ([], {}), '()\n', (2887, 2889), False, 'import time\n'), ((1679, 1729), 'os.path.join', 'os.path.join', (['"""models"""', 'model_name', '"""hparams.json"""'], {}), "('models', model_name, 'hparams.json')\n", (1691, 1729), False, 'import os\n'), ((1772, 1784), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1781, 1784), False, 'import json\n'), ((2685, 2719), 'os.path.join', 'os.path.join', (['"""models"""', 'model_name'], {}), "('models', model_name)\n", (2697, 2719), False, 'import os\n'), ((2971, 2982), 'time.time', 'time.time', ([], {}), '()\n', (2980, 2982), False, 'import time\n'), ((4428, 4439), 'time.time', 'time.time', ([], {}), '()\n', (4437, 4439), False, 'import time\n'), ((2102, 2112), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2110, 2112), True, 'import tensorflow as tf\n'), ((4142, 4153), 'time.time', 'time.time', ([], {}), '()\n', (4151, 4153), False, 'import time\n')]
#!/usr/bin/python3 from typing import Dict import optparse import numpy as np import rasterio from rasterio import features def main(county_pop_file, spatial_dist_file, fname_out, no_data_val=-9999): ''' county_pop_file: County level population estimates spatial_dist_file: Spatial projection of population distribution ''' # ------------------------------------- # Open and read raster file with county # level population estimates # ------------------------------------- with rasterio.open(county_pop_file) as rastf: county_pop = rastf.read() nodatacp = rastf.nodata # -------------------------------------------------------------- # Open and read raster file with spatial population distribution # -------------------------------------------------------------- with rasterio.open(spatial_dist_file) as rastf: pop_dist = rastf.read() nodatasp = rastf.nodata prf = rastf.profile county_pop = np.squeeze(county_pop) pop_dist = np.squeeze(pop_dist) pop_est = np.ones(pop_dist.shape)*no_data_val ind1 = np.where(county_pop.flatten() != nodatacp)[0] ind2 = np.where(pop_dist.flatten() != nodatasp)[0] ind = np.intersect1d(ind1, ind2) ind2d = np.unravel_index(ind, pop_dist.shape) pop_est[ind2d] = county_pop[ind2d] * pop_dist[ind2d] pop_est[ind2d] = np.round(pop_est[ind2d]) # Update raster meta-data prf.update(nodata=no_data_val) # Write out spatially distributed population estimate to raster with open(fname_out, "wb") as fout: with rasterio.open(fout.name, 'w', **prf) as out_raster: out_raster.write(pop_est.astype(rasterio.float32), 1) argparser = optparse.OptionParser() argparser.add_option('--population-file', action='store', dest='pop_file', help='County level population estimates') argparser.add_option('--dist-file', action='store', dest='dist_file', help='Spatial projection of population distribution') argparser.add_option('--out-file', action='store', dest='out_file', help='Filename of the output') (options, args) = argparser.parse_args() if not options.pop_file: print('Please specify a population file with --population-file') sys.exit(1) if not options.dist_file: print('Please specify a distribution file with --dist-file') sys.exit(1) if not options.out_file: print('Please specify the name of the output with --out-file') sys.exit(1) main(options.pop_file, options.dist_file, options.out_file)
[ "numpy.intersect1d", "numpy.ones", "rasterio.open", "optparse.OptionParser", "numpy.squeeze", "numpy.unravel_index", "numpy.round" ]
[((1730, 1753), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (1751, 1753), False, 'import optparse\n'), ((996, 1018), 'numpy.squeeze', 'np.squeeze', (['county_pop'], {}), '(county_pop)\n', (1006, 1018), True, 'import numpy as np\n'), ((1034, 1054), 'numpy.squeeze', 'np.squeeze', (['pop_dist'], {}), '(pop_dist)\n', (1044, 1054), True, 'import numpy as np\n'), ((1229, 1255), 'numpy.intersect1d', 'np.intersect1d', (['ind1', 'ind2'], {}), '(ind1, ind2)\n', (1243, 1255), True, 'import numpy as np\n'), ((1268, 1305), 'numpy.unravel_index', 'np.unravel_index', (['ind', 'pop_dist.shape'], {}), '(ind, pop_dist.shape)\n', (1284, 1305), True, 'import numpy as np\n'), ((1385, 1409), 'numpy.round', 'np.round', (['pop_est[ind2d]'], {}), '(pop_est[ind2d])\n', (1393, 1409), True, 'import numpy as np\n'), ((519, 549), 'rasterio.open', 'rasterio.open', (['county_pop_file'], {}), '(county_pop_file)\n', (532, 549), False, 'import rasterio\n'), ((843, 875), 'rasterio.open', 'rasterio.open', (['spatial_dist_file'], {}), '(spatial_dist_file)\n', (856, 875), False, 'import rasterio\n'), ((1070, 1093), 'numpy.ones', 'np.ones', (['pop_dist.shape'], {}), '(pop_dist.shape)\n', (1077, 1093), True, 'import numpy as np\n'), ((1598, 1634), 'rasterio.open', 'rasterio.open', (['fout.name', '"""w"""'], {}), "(fout.name, 'w', **prf)\n", (1611, 1634), False, 'import rasterio\n')]
import os import math from pathlib import Path import clip import torch from PIL import Image import numpy as np import pandas as pd from common import common_path # Set the path to the photos # dataset_version = "lite" # Use "lite" or "full" # photos_path = Path("unsplash-dataset") / dataset_version / "photos" photos_path = os.path.join(common_path.project_dir, 'unsplash-dataset/lite/photos') # List all JPGs in the folder photos_files = list(Path(photos_path).glob("*.jpg")) # Print some statistics print(f"Photos found: {len(photos_files)}") # Load the open CLIP model device = "cuda" if torch.cuda.is_available() else "cpu" model, preprocess = clip.load("ViT-B/32", device=device) # Function that computes the feature vectors for a batch of images def compute_clip_features(photos_batch): # Load all the photos from the files photos = [Image.open(photo_file) for photo_file in photos_batch] # Preprocess all photos photos_preprocessed = torch.stack([preprocess(photo) for photo in photos]).to(device) with torch.no_grad(): # Encode the photos batch to compute the feature vectors and normalize them photos_features = model.encode_image(photos_preprocessed) photos_features /= photos_features.norm(dim=-1, keepdim=True) # Transfer the feature vectors back to the CPU and convert to numpy return photos_features.cpu().numpy() # Define the batch size so that it fits on your GPU. You can also do the processing on the CPU, but it will be slower. batch_size = 16 # Path where the feature vectors will be stored features_path = os.path.join(common_path.project_dir, 'unsplash-dataset/lite/features') # Compute how many batches are needed batches = math.ceil(len(photos_files) / batch_size) # Process each batch for i in range(batches): print(f"Processing batch {i + 1}/{batches}") batch_ids_path = os.path.join(features_path, f"{i:010d}.csv") batch_features_path = os.path.join(features_path, f"{i:010d}.npy") # Only do the processing if the batch wasn't processed yet if not os.path.exists(batch_features_path): try: # Select the photos for the current batch batch_files = photos_files[i * batch_size: (i + 1) * batch_size] # Compute the features and save to a numpy file batch_features = compute_clip_features(batch_files) np.save(batch_features_path, batch_features) # Save the photo IDs to a CSV file photo_ids = [photo_file.name.split(".")[0] for photo_file in batch_files] photo_ids_data = pd.DataFrame(photo_ids, columns=['photo_id']) photo_ids_data.to_csv(batch_ids_path, index=False) except: # Catch problems with the processing to make the process more robust print(f'Problem with batch {i}') # Load all numpy files features_list = [np.load(features_file) for features_file in sorted(Path(features_path).glob("*.npy"))] # Concatenate the features and store in a merged file features = np.concatenate(features_list) np.save(os.path.join(features_path, "features.npy"), features) # Load all the photo IDs photo_ids = pd.concat([pd.read_csv(ids_file) for ids_file in sorted(Path(features_path).glob("*.csv"))]) photo_ids.to_csv(os.path.join(features_path, "photo_ids.csv"), index=False)
[ "os.path.exists", "PIL.Image.open", "pandas.read_csv", "pathlib.Path", "os.path.join", "torch.cuda.is_available", "numpy.concatenate", "clip.load", "pandas.DataFrame", "torch.no_grad", "numpy.load", "numpy.save" ]
[((332, 401), 'os.path.join', 'os.path.join', (['common_path.project_dir', '"""unsplash-dataset/lite/photos"""'], {}), "(common_path.project_dir, 'unsplash-dataset/lite/photos')\n", (344, 401), False, 'import os\n'), ((659, 695), 'clip.load', 'clip.load', (['"""ViT-B/32"""'], {'device': 'device'}), "('ViT-B/32', device=device)\n", (668, 695), False, 'import clip\n'), ((1598, 1669), 'os.path.join', 'os.path.join', (['common_path.project_dir', '"""unsplash-dataset/lite/features"""'], {}), "(common_path.project_dir, 'unsplash-dataset/lite/features')\n", (1610, 1669), False, 'import os\n'), ((3041, 3070), 'numpy.concatenate', 'np.concatenate', (['features_list'], {}), '(features_list)\n', (3055, 3070), True, 'import numpy as np\n'), ((602, 627), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (625, 627), False, 'import torch\n'), ((1879, 1923), 'os.path.join', 'os.path.join', (['features_path', 'f"""{i:010d}.csv"""'], {}), "(features_path, f'{i:010d}.csv')\n", (1891, 1923), False, 'import os\n'), ((1950, 1994), 'os.path.join', 'os.path.join', (['features_path', 'f"""{i:010d}.npy"""'], {}), "(features_path, f'{i:010d}.npy')\n", (1962, 1994), False, 'import os\n'), ((2888, 2910), 'numpy.load', 'np.load', (['features_file'], {}), '(features_file)\n', (2895, 2910), True, 'import numpy as np\n'), ((3079, 3122), 'os.path.join', 'os.path.join', (['features_path', '"""features.npy"""'], {}), "(features_path, 'features.npy')\n", (3091, 3122), False, 'import os\n'), ((3282, 3326), 'os.path.join', 'os.path.join', (['features_path', '"""photo_ids.csv"""'], {}), "(features_path, 'photo_ids.csv')\n", (3294, 3326), False, 'import os\n'), ((861, 883), 'PIL.Image.open', 'Image.open', (['photo_file'], {}), '(photo_file)\n', (871, 883), False, 'from PIL import Image\n'), ((1045, 1060), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1058, 1060), False, 'import torch\n'), ((2070, 2105), 'os.path.exists', 'os.path.exists', (['batch_features_path'], {}), '(batch_features_path)\n', (2084, 2105), False, 'import os\n'), ((3183, 3204), 'pandas.read_csv', 'pd.read_csv', (['ids_file'], {}), '(ids_file)\n', (3194, 3204), True, 'import pandas as pd\n'), ((453, 470), 'pathlib.Path', 'Path', (['photos_path'], {}), '(photos_path)\n', (457, 470), False, 'from pathlib import Path\n'), ((2388, 2432), 'numpy.save', 'np.save', (['batch_features_path', 'batch_features'], {}), '(batch_features_path, batch_features)\n', (2395, 2432), True, 'import numpy as np\n'), ((2596, 2641), 'pandas.DataFrame', 'pd.DataFrame', (['photo_ids'], {'columns': "['photo_id']"}), "(photo_ids, columns=['photo_id'])\n", (2608, 2641), True, 'import pandas as pd\n'), ((2939, 2958), 'pathlib.Path', 'Path', (['features_path'], {}), '(features_path)\n', (2943, 2958), False, 'from pathlib import Path\n'), ((3228, 3247), 'pathlib.Path', 'Path', (['features_path'], {}), '(features_path)\n', (3232, 3247), False, 'from pathlib import Path\n')]
import numpy as np import datajoint as dj from treadmill_pipeline import project_database_prefix from ephys.utilities import ingestion, time_sync from ephys import get_schema_name schema = dj.schema(project_database_prefix + 'treadmill_pipeline') reference = dj.create_virtual_module('reference', get_schema_name('reference')) acquisition = dj.create_virtual_module('acquisition', get_schema_name('acquisition')) behavior = dj.create_virtual_module('behavior', get_schema_name('behavior')) @schema class TreadmillTracking(dj.Imported): definition = """ # session-level tracking data from the treadmill_pipeline(s) employed in the experiment -> acquisition.Session treadmill_tracking_time: datetime # start time of this treadmill_pipeline speed recording --- treadmill_tracking_name: varchar(40) # user-assign name of this treadmill_pipeline tracking (e.g. 27032019laserSess1) treadmill_timestamps: blob@ephys_store # (s) timestamps of the treadmill_pipeline speed samples """ class TreadmillSync(dj.Part): definition = """ -> master --- sync_master_clock: varchar(128) # name of the sync-master track_sync_data=null: blob@ephys_store # sync data (binary) track_time_zero=null: float # (s) the first time point of this tracking track_sync_timestamps=null: blob@ephys_store # (s) timestamps of sync data in tracking clock track_sync_master_timestamps=null: blob@ephys_store # (s) timestamps of sync data in master clock """ class Speed(dj.Part): definition = """ -> master treadmill_name: varchar(32) --- treadmill_speed: blob@ephys_store # (s) treadmill_pipeline speed at each timestamp """ key_source = acquisition.Session & acquisition.Recording # wait for recording to be ingested first before tracking def make(self, key): input_dir = ingestion.find_input_directory(key) if not input_dir: print(f'{input_dir} not found in this machine, skipping...') return rec_type, recordings = ingestion.get_recordings(input_dir) if rec_type in ('neuropixels', 'neurologger'): # if 'neuropixels' recording, check for OptiTrack's `motive` or `.csv` opti_list = ingestion.get_optitrack(input_dir) if not opti_list: raise FileNotFoundError('No OptiTrack "matmot.mtv" or ".csv" found') for opti in opti_list: if 'Format Version' not in opti.meta: raise NotImplementedError('Treadmill data ingest from type other than "optitrack.csv" not implemented') secondary_data = opti.secondary_data if 'Treadmill' not in secondary_data: raise KeyError('No "Treadmill" found in the secondary data of optitrack.csv') treadmill_key = dict(key, treadmill_tracking_time=opti.recording_time) self.insert1(dict(treadmill_key, treadmill_tracking_name=opti.tracking_name, # name of the session folder treadmill_timestamps=secondary_data['t'])) if hasattr(opti, 'sync_data'): self.TreadmillSync.insert1(dict(treadmill_key, sync_master_clock=opti.sync_data['master_name'], track_time_zero=secondary_data['t'][0], track_sync_timestamps=opti.sync_data['slave'], track_sync_master_timestamps=opti.sync_data['master'])) else: # data presynced with tracking-recording pair, # still need for a linear shift from session start to the recording this tracking is synced to self.TrackingSync.insert1(time_sync.create_tracking_sync_data( treadmill_key, np.array([secondary_data['t'][0], secondary_data['t'][-1]]))) self.Speed.insert1([dict(treadmill_key, treadmill_name=k, treadmill_speed=v['speed']) for k, v in secondary_data['Treadmill'].items()]) print(f'Insert {len(opti_list)} treadmill_pipeline tracking(s): {input_dir.stem}') else: raise NotImplementedError(f'Treadmill Tracking ingestion for recording type {rec_type} not implemented')
[ "ephys.utilities.ingestion.find_input_directory", "ephys.utilities.ingestion.get_optitrack", "numpy.array", "ephys.utilities.ingestion.get_recordings", "datajoint.schema", "ephys.get_schema_name" ]
[((192, 249), 'datajoint.schema', 'dj.schema', (["(project_database_prefix + 'treadmill_pipeline')"], {}), "(project_database_prefix + 'treadmill_pipeline')\n", (201, 249), True, 'import datajoint as dj\n'), ((301, 329), 'ephys.get_schema_name', 'get_schema_name', (['"""reference"""'], {}), "('reference')\n", (316, 329), False, 'from ephys import get_schema_name\n'), ((385, 415), 'ephys.get_schema_name', 'get_schema_name', (['"""acquisition"""'], {}), "('acquisition')\n", (400, 415), False, 'from ephys import get_schema_name\n'), ((465, 492), 'ephys.get_schema_name', 'get_schema_name', (['"""behavior"""'], {}), "('behavior')\n", (480, 492), False, 'from ephys import get_schema_name\n'), ((2041, 2076), 'ephys.utilities.ingestion.find_input_directory', 'ingestion.find_input_directory', (['key'], {}), '(key)\n', (2071, 2076), False, 'from ephys.utilities import ingestion, time_sync\n'), ((2227, 2262), 'ephys.utilities.ingestion.get_recordings', 'ingestion.get_recordings', (['input_dir'], {}), '(input_dir)\n', (2251, 2262), False, 'from ephys.utilities import ingestion, time_sync\n'), ((2415, 2449), 'ephys.utilities.ingestion.get_optitrack', 'ingestion.get_optitrack', (['input_dir'], {}), '(input_dir)\n', (2438, 2449), False, 'from ephys.utilities import ingestion, time_sync\n'), ((4133, 4192), 'numpy.array', 'np.array', (["[secondary_data['t'][0], secondary_data['t'][-1]]"], {}), "([secondary_data['t'][0], secondary_data['t'][-1]])\n", (4141, 4192), True, 'import numpy as np\n')]
"Test list input." # For support of python 2.5 from __future__ import with_statement import numpy as np from numpy.testing import assert_equal, assert_array_almost_equal import bottleneck as bn # --------------------------------------------------------------------------- # Check that functions can handle list input def lists(): "Iterator that yields lists to use for unit testing." ss = {} ss[1] = {'size': 4, 'shapes': [(4,)]} ss[2] = {'size': 6, 'shapes': [(1, 6), (2, 3)]} ss[3] = {'size': 6, 'shapes': [(1, 2, 3)]} ss[4] = {'size': 24, 'shapes': [(1, 2, 3, 4)]} # Unaccelerated for ndim in ss: size = ss[ndim]['size'] shapes = ss[ndim]['shapes'] a = np.arange(size) for shape in shapes: a = a.reshape(shape) yield a.tolist() def unit_maker(func, func0, args=tuple()): "Test that bn.xxx gives the same output as bn.slow.xxx for list input." msg = '\nfunc %s | input %s | shape %s\n' msg += '\nInput array:\n%s\n' for i, arr in enumerate(lists()): argsi = tuple([list(arr)] + list(args)) actual = func(*argsi) desired = func0(*argsi) tup = (func.__name__, 'a'+str(i), str(np.array(arr).shape), arr) err_msg = msg % tup assert_array_almost_equal(actual, desired, err_msg=err_msg) def test_nansum(): "Test nansum." yield unit_maker, bn.nansum, bn.slow.nansum def test_nanmax(): "Test nanmax." yield unit_maker, bn.nanmax, bn.slow.nanmax def test_nanargmin(): "Test nanargmin." yield unit_maker, bn.nanargmin, bn.slow.nanargmin def test_nanargmax(): "Test nanargmax." yield unit_maker, bn.nanargmax, bn.slow.nanargmax def test_nanmin(): "Test nanmin." yield unit_maker, bn.nanmin, bn.slow.nanmin def test_nanmean(): "Test nanmean." yield unit_maker, bn.nanmean, bn.slow.nanmean def test_nanstd(): "Test nanstd." yield unit_maker, bn.nanstd, bn.slow.nanstd def test_nanvar(): "Test nanvar." yield unit_maker, bn.nanvar, bn.slow.nanvar def test_median(): "Test median." yield unit_maker, bn.median, bn.slow.median def test_nanmedian(): "Test nanmedian." yield unit_maker, bn.nanmedian, bn.slow.nanmedian def test_rankdata(): "Test rankdata." yield unit_maker, bn.rankdata, bn.slow.rankdata def test_nanrankdata(): "Test nanrankdata." yield unit_maker, bn.nanrankdata, bn.slow.nanrankdata def test_partsort(): "Test partsort." yield unit_maker, bn.partsort, bn.slow.partsort, (2,) def test_argpartsort(): "Test argpartsort." yield unit_maker, bn.argpartsort, bn.slow.argpartsort, (2,) def test_ss(): "Test ss." yield unit_maker, bn.ss, bn.slow.ss def test_nn(): "Test nn." a = [[1, 2], [3, 4]] a0 = [1, 2] assert_equal(bn.nn(a, a0), bn.slow.nn(a, a0)) def test_anynan(): "Test anynan." yield unit_maker, bn.anynan, bn.slow.anynan def test_allnan(): "Test allnan." yield unit_maker, bn.allnan, bn.slow.allnan def test_move_sum(): "Test move_sum." yield unit_maker, bn.move_sum, bn.slow.move_sum, (2,) def test_move_nansum(): "Test move_nansum." yield unit_maker, bn.move_nansum, bn.slow.move_nansum, (2,) def test_move_mean(): "Test move_mean." yield unit_maker, bn.move_mean, bn.slow.move_mean, (2,) def test_move_median(): "Test move_median." yield unit_maker, bn.move_median, bn.slow.move_median, (2,) def test_move_nanmean(): "Test move_nanmean." yield unit_maker, bn.move_nanmean, bn.slow.move_nanmean, (2,) def test_move_std(): "Test move_std." yield unit_maker, bn.move_std, bn.slow.move_std, (2,) def test_move_nanstd(): "Test move_nanstd." yield unit_maker, bn.move_nanstd, bn.slow.move_nanstd, (2,) def test_move_min(): "Test move_min." yield unit_maker, bn.move_min, bn.slow.move_min, (2,) def test_move_max(): "Test move_max." yield unit_maker, bn.move_max, bn.slow.move_max, (2,) def test_move_nanmin(): "Test move_nanmin." yield unit_maker, bn.move_nanmin, bn.slow.move_nanmin, (2,) def test_move_nanmax(): "Test move_nanmax." yield unit_maker, bn.move_nanmax, bn.slow.move_nanmax, (2,)
[ "numpy.testing.assert_array_almost_equal", "bottleneck.slow.nn", "numpy.array", "numpy.arange", "bottleneck.nn" ]
[((717, 732), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (726, 732), True, 'import numpy as np\n'), ((1282, 1341), 'numpy.testing.assert_array_almost_equal', 'assert_array_almost_equal', (['actual', 'desired'], {'err_msg': 'err_msg'}), '(actual, desired, err_msg=err_msg)\n', (1307, 1341), False, 'from numpy.testing import assert_equal, assert_array_almost_equal\n'), ((2844, 2856), 'bottleneck.nn', 'bn.nn', (['a', 'a0'], {}), '(a, a0)\n', (2849, 2856), True, 'import bottleneck as bn\n'), ((2858, 2875), 'bottleneck.slow.nn', 'bn.slow.nn', (['a', 'a0'], {}), '(a, a0)\n', (2868, 2875), True, 'import bottleneck as bn\n'), ((1219, 1232), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (1227, 1232), True, 'import numpy as np\n')]
import os from functools import partial from multiprocessing import Pool from typing import Any, Callable, Dict, List, Optional import numpy as np import pandas as pd from tqdm import tqdm from src.dataset.utils.waveform_preprocessings import preprocess_strain def id_2_path( image_id: str, is_train: bool = True, data_dir: str = "../input/g2net-gravitational-wave-detection", ) -> str: """ modify from https://www.kaggle.com/ihelon/g2net-eda-and-modeling """ folder = "train" if is_train else "test" return "{}/{}/{}/{}/{}/{}.npy".format( data_dir, folder, image_id[0], image_id[1], image_id[2], image_id ) def path_2_id(path: str) -> str: return os.path.basename(path).replace(".npy", "") def add_dir(df: pd.DataFrame) -> pd.DataFrame: df["top_dir"] = df["id"].apply(lambda x: x[0]) df["bottom_dir"] = df["id"].apply(lambda x: x[:3]) return df def add_data_path( df: pd.DataFrame, is_train: bool = False, data_dir: str = "../input/g2net-gravitational-wave-detection", ) -> pd.DataFrame: df = add_dir(df=df) df["path"] = df["id"].apply( lambda x: id_2_path(image_id=x, is_train=is_train, data_dir=data_dir) ) return df def get_agg_feats( path: str, interp_psd: Optional[Callable] = None, psds: Optional[np.ndarray] = None, window: str = "tukey", fs: int = 2048, fband: List[int] = [10, 912], psd_cache_path_suffix: Optional[str] = None, T: float = 2.0, ) -> Dict[str, Any]: sample_data = np.load(path) data_id = path_2_id(path) if interp_psd is None: for i, strain in enumerate(sample_data): _, strain_bp = preprocess_strain( strain=strain, interp_psd=interp_psd, psd=psds[i], window=window, fs=fs, fband=fband, ) sample_data[i] = strain_bp mean = sample_data.mean(axis=-1) std = sample_data.std(axis=-1) minim = sample_data.min(axis=-1) maxim = sample_data.max(axis=-1) ene = (sample_data ** 2).sum(axis=-1) agg_dict = { "id": data_id, "mean_site0": mean[0], "mean_site1": mean[1], "mean_site2": mean[2], "std_site0": std[0], "std_site1": std[1], "std_site2": std[2], "min_site0": minim[0], "min_site1": minim[1], "min_site2": minim[2], "max_site0": maxim[0], "max_site1": maxim[1], "max_site2": maxim[2], "ene_site0": ene[0], "ene_site1": ene[1], "ene_site2": ene[2], } if psd_cache_path_suffix is not None: cache_path = path.replace(".npy", psd_cache_path_suffix) if os.path.exists(cache_path): psd = np.load(cache_path) psd_ranges = [10, 35, 350, 500, 912] psd_hz_begin = 0 for psd_hz_end in psd_ranges: psd_mean = psd[:, int(psd_hz_begin * T) : int(psd_hz_end * T)].mean( axis=-1 ) for site_id, psd_mean_for_site in enumerate(psd_mean): agg_dict[ f"psd_{psd_hz_begin}-{psd_hz_end}hz_site{site_id}" ] = psd_mean_for_site psd_hz_begin = psd_hz_end for site_id, psd_mean_for_site in enumerate(psd.mean(axis=-1)): agg_dict[f"psd_all-hz_site{site_id}"] = psd_mean_for_site return agg_dict def get_site_metrics( df: pd.DataFrame, interp_psd: Optional[Callable] = None, psds: Optional[np.ndarray] = None, window: str = "tukey", fs: int = 2048, fband: List[int] = [10, 912], psd_cache_path_suffix: Optional[str] = None, num_workers: int = 8, ): """ Compute for each id the metrics for each site. df: the complete df modify from https://www.kaggle.com/andradaolteanu/g2net-searching-the-sky-pytorch-effnet-w-meta """ func_ = partial( get_agg_feats, interp_psd=interp_psd, psds=psds, window=window, fs=fs, fband=fband, psd_cache_path_suffix=psd_cache_path_suffix, ) if num_workers > 1: with Pool(processes=num_workers) as pool: agg_dicts = list( tqdm( pool.imap(func_, df["path"].tolist()), total=len(df), ) ) else: agg_dicts = [] for ID, path in tqdm(zip(df["id"].values, df["path"].values)): # First extract the cronological info agg_dict = func_(path=path) agg_dicts.append(agg_dict) agg_df = pd.DataFrame(agg_dicts) df = pd.merge(df, agg_df, on="id") return df
[ "os.path.exists", "src.dataset.utils.waveform_preprocessings.preprocess_strain", "pandas.merge", "functools.partial", "os.path.basename", "multiprocessing.Pool", "pandas.DataFrame", "numpy.load" ]
[((1533, 1546), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (1540, 1546), True, 'import numpy as np\n'), ((3986, 4127), 'functools.partial', 'partial', (['get_agg_feats'], {'interp_psd': 'interp_psd', 'psds': 'psds', 'window': 'window', 'fs': 'fs', 'fband': 'fband', 'psd_cache_path_suffix': 'psd_cache_path_suffix'}), '(get_agg_feats, interp_psd=interp_psd, psds=psds, window=window, fs=\n fs, fband=fband, psd_cache_path_suffix=psd_cache_path_suffix)\n', (3993, 4127), False, 'from functools import partial\n'), ((4686, 4709), 'pandas.DataFrame', 'pd.DataFrame', (['agg_dicts'], {}), '(agg_dicts)\n', (4698, 4709), True, 'import pandas as pd\n'), ((4720, 4749), 'pandas.merge', 'pd.merge', (['df', 'agg_df'], {'on': '"""id"""'}), "(df, agg_df, on='id')\n", (4728, 4749), True, 'import pandas as pd\n'), ((2741, 2767), 'os.path.exists', 'os.path.exists', (['cache_path'], {}), '(cache_path)\n', (2755, 2767), False, 'import os\n'), ((702, 724), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (718, 724), False, 'import os\n'), ((1680, 1788), 'src.dataset.utils.waveform_preprocessings.preprocess_strain', 'preprocess_strain', ([], {'strain': 'strain', 'interp_psd': 'interp_psd', 'psd': 'psds[i]', 'window': 'window', 'fs': 'fs', 'fband': 'fband'}), '(strain=strain, interp_psd=interp_psd, psd=psds[i], window\n =window, fs=fs, fband=fband)\n', (1697, 1788), False, 'from src.dataset.utils.waveform_preprocessings import preprocess_strain\n'), ((2787, 2806), 'numpy.load', 'np.load', (['cache_path'], {}), '(cache_path)\n', (2794, 2806), True, 'import numpy as np\n'), ((4224, 4251), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'num_workers'}), '(processes=num_workers)\n', (4228, 4251), False, 'from multiprocessing import Pool\n')]
import unittest import shutil import tempfile import numpy as np # import pandas as pd # import pymc3 as pm # from pymc3 import summary # from sklearn.mixture import BayesianGaussianMixture as skBayesianGaussianMixture from sklearn.model_selection import train_test_split from pmlearn.exceptions import NotFittedError from pmlearn.mixture import DirichletProcessMixture class DirichletProcessMixtureTestCase(unittest.TestCase): def setUp(self): self.num_truncate = 3 self.num_components = 3 self.num_pred = 1 self.num_training_samples = 100 self.pi = np.array([0.35, 0.4, 0.25]) self.means = np.array([0, 5, 10]) self.sigmas = np.array([0.5, 0.5, 1.0]) self.components = np.random.randint(0, self.num_components, self.num_training_samples) X = np.random.normal(loc=self.means[self.components], scale=self.sigmas[self.components]) X.shape = (self.num_training_samples, 1) self.X_train, self.X_test = train_test_split(X, test_size=0.3) self.test_DPMM = DirichletProcessMixture() self.test_nuts_DPMM = DirichletProcessMixture() self.test_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.test_dir) # class DirichletProcessMixtureFitTestCase(DirichletProcessMixtureTestCase): # def test_advi_fit_returns_correct_model(self): # # This print statement ensures PyMC3 output won't overwrite the test name # print('') # self.test_DPMM.fit(self.X_train) # # self.assertEqual(self.num_pred, self.test_DPMM.num_pred) # self.assertEqual(self.num_components, self.test_DPMM.num_components) # self.assertEqual(self.num_truncate, self.test_DPMM.num_truncate) # # self.assertAlmostEqual(self.pi[0], # self.test_DPMM.summary['mean']['pi__0'], # 0) # self.assertAlmostEqual(self.pi[1], # self.test_DPMM.summary['mean']['pi__1'], # 0) # self.assertAlmostEqual(self.pi[2], # self.test_DPMM.summary['mean']['pi__2'], # 0) # # self.assertAlmostEqual( # self.means[0], # self.test_DPMM.summary['mean']['cluster_center_0__0'], # 0) # self.assertAlmostEqual( # self.means[1], # self.test_DPMM.summary['mean']['cluster_center_1__0'], # 0) # self.assertAlmostEqual( # self.means[2], # self.test_DPMM.summary['mean']['cluster_center_2__0'], # 0) # # self.assertAlmostEqual( # self.sigmas[0], # self.test_DPMM.summary['mean']['cluster_variance_0__0'], # 0) # self.assertAlmostEqual( # self.sigmas[1], # self.test_DPMM.summary['mean']['cluster_variance_1__0'], # 0) # self.assertAlmostEqual( # self.sigmas[2], # self.test_DPMM.summary['mean']['cluster_variance_2__0'], # 0) # # def test_nuts_fit_returns_correct_model(self): # # This print statement ensures PyMC3 output won't overwrite the test name # print('') # self.test_nuts_DPMM.fit(self.X_train, # inference_type='nuts', # inference_args={'draws': 1000, # 'chains': 2}) # # self.assertEqual(self.num_pred, self.test_nuts_DPMM.num_pred) # self.assertEqual(self.num_components, self.test_nuts_DPMM.num_components) # self.assertEqual(self.num_components, self.test_nuts_DPMM.num_truncate) # # self.assertAlmostEqual(self.pi[0], # self.test_nuts_DPMM.summary['mean']['pi__0'], # 0) # self.assertAlmostEqual(self.pi[1], # self.test_nuts_DPMM.summary['mean']['pi__1'], # 0) # self.assertAlmostEqual(self.pi[2], # self.test_nuts_DPMM.summary['mean']['pi__2'], # 0) # # self.assertAlmostEqual( # self.means[0], # self.test_nuts_DPMM.summary['mean']['cluster_center_0__0'], # 0) # self.assertAlmostEqual( # self.means[1], # self.test_nuts_DPMM.summary['mean']['cluster_center_1__0'], # 0) # self.assertAlmostEqual( # self.means[2], # self.test_nuts_DPMM.summary['mean']['cluster_center_2__0'], # 0) # # self.assertAlmostEqual( # self.sigmas[0], # self.test_nuts_DPMM.summary['mean']['cluster_variance_0__0'], # 0) # self.assertAlmostEqual( # self.sigmas[1], # self.test_nuts_DPMM.summary['mean']['cluster_variance_1__0'], # 0) # self.assertAlmostEqual( # self.sigmas[2], # self.test_nuts_DPMM.summary['mean']['cluster_variance_2__0'], # 0) # # class DirichletProcessMixturePredictTestCase(DirichletProcessMixtureTestCase): # def test_predict_returns_predictions(self): # print('') # self.test_DPMM.fit(self.X_train, self.y_train) # preds = self.test_DPMM.predict(self.X_test) # self.assertEqual(self.y_test.shape, preds.shape) # def test_predict_returns_mean_predictions_and_std(self): # print('') # self.test_DPMM.fit(self.X_train, self.y_train) # preds, stds = self.test_DPMM.predict(self.X_test, return_std=True) # self.assertEqual(self.y_test.shape, preds.shape) # self.assertEqual(self.y_test.shape, stds.shape) def test_predict_raises_error_if_not_fit(self): print('') with self.assertRaises(NotFittedError) as no_fit_error: test_DPMM = DirichletProcessMixture() test_DPMM.predict(self.X_train) expected = 'Run fit on the model before predict.' self.assertEqual(str(no_fit_error.exception), expected) # class DirichletProcessMixtureScoreTestCase(DirichletProcessMixtureTestCase): # def test_score_matches_sklearn_performance(self): # print('') # skDPMM = skBayesianGaussianMixture(n_components=3) # skDPMM.fit(self.X_train) # skDPMM_score = skDPMM.score(self.X_test) # # self.test_DPMM.fit(self.X_train) # test_DPMM_score = self.test_DPMM.score(self.X_test) # # self.assertAlmostEqual(skDPMM_score, test_DPMM_score, 0) # # # class DirichletProcessMixtureSaveAndLoadTestCase(DirichletProcessMixtureTestCase): # def test_save_and_load_work_correctly(self): # print('') # self.test_DPMM.fit(self.X_train) # score1 = self.test_DPMM.score(self.X_test) # self.test_DPMM.save(self.test_dir) # # DPMM2 = DirichletProcessMixture() # DPMM2.load(self.test_dir) # # self.assertEqual(self.test_DPMM.inference_type, DPMM2.inference_type) # self.assertEqual(self.test_DPMM.num_pred, DPMM2.num_pred) # self.assertEqual(self.test_DPMM.num_training_samples, # DPMM2.num_training_samples) # self.assertEqual(self.test_DPMM.num_truncate, DPMM2.num_truncate) # # pd.testing.assert_frame_equal(summary(self.test_DPMM.trace), # summary(DPMM2.trace)) # # score2 = DPMM2.score(self.X_test) # self.assertAlmostEqual(score1, score2, 0)
[ "numpy.random.normal", "sklearn.model_selection.train_test_split", "numpy.array", "numpy.random.randint", "tempfile.mkdtemp", "shutil.rmtree", "pmlearn.mixture.DirichletProcessMixture" ]
[((601, 628), 'numpy.array', 'np.array', (['[0.35, 0.4, 0.25]'], {}), '([0.35, 0.4, 0.25])\n', (609, 628), True, 'import numpy as np\n'), ((650, 670), 'numpy.array', 'np.array', (['[0, 5, 10]'], {}), '([0, 5, 10])\n', (658, 670), True, 'import numpy as np\n'), ((693, 718), 'numpy.array', 'np.array', (['[0.5, 0.5, 1.0]'], {}), '([0.5, 0.5, 1.0])\n', (701, 718), True, 'import numpy as np\n'), ((746, 814), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.num_components', 'self.num_training_samples'], {}), '(0, self.num_components, self.num_training_samples)\n', (763, 814), True, 'import numpy as np\n'), ((916, 1006), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self.means[self.components]', 'scale': 'self.sigmas[self.components]'}), '(loc=self.means[self.components], scale=self.sigmas[self.\n components])\n', (932, 1006), True, 'import numpy as np\n'), ((1117, 1151), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X'], {'test_size': '(0.3)'}), '(X, test_size=0.3)\n', (1133, 1151), False, 'from sklearn.model_selection import train_test_split\n'), ((1178, 1203), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (1201, 1203), False, 'from pmlearn.mixture import DirichletProcessMixture\n'), ((1234, 1259), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (1257, 1259), False, 'from pmlearn.mixture import DirichletProcessMixture\n'), ((1284, 1302), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1300, 1302), False, 'import tempfile\n'), ((1336, 1364), 'shutil.rmtree', 'shutil.rmtree', (['self.test_dir'], {}), '(self.test_dir)\n', (1349, 1364), False, 'import shutil\n'), ((6110, 6135), 'pmlearn.mixture.DirichletProcessMixture', 'DirichletProcessMixture', ([], {}), '()\n', (6133, 6135), False, 'from pmlearn.mixture import DirichletProcessMixture\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np from skimage import draw from skimage import measure from astropy.io import fits from astropy import units as u from astropy import wcs, coordinates from scipy.ndimage.filters import gaussian_filter def standard(X): """ standard : This function makes data ragbe between 0 and 1. Arguments: X (numoy array) : input data. -------- Returns: standard data. """ xmin = X.min() X = X-xmin xmax = X.max() X = X/xmax return X def fetch_data(image_file,model_file,do_standard=True,ignore_error=False): """ fetch_data : This function reads image and model. Arguments: image_file (string) : path to image file. model_file (string) : path to model file. do_standard (logical) (default=True) : if true, minimum/maximum value of image will be set to 0/1. -------- Returns: image, x coordinates, y coordinates """ with fits.open(image_file) as hdulist: data = hdulist[0].data header = hdulist[0].header lx = header['NAXIS1'] ly = header['NAXIS2'] coord_sys = wcs.WCS(header) model_file = model_file sources = np.loadtxt(model_file, dtype={'names': ('name', 'ra', 'dec', 'I'), 'formats': ('S10', 'f4', 'f4', 'f4')}) ra, dec = sources['ra'],sources['dec'] num_sources = len(ra) radec_coords = coordinates.SkyCoord(ra, dec, unit='deg', frame='fk5') coords_ar = np.vstack([radec_coords.ra*u.deg, radec_coords.dec*u.deg, np.zeros(num_sources), np.zeros(num_sources)]).T xy_coords = coord_sys.wcs_world2pix(coords_ar, 0) x_coords, y_coords = xy_coords[:,0], xy_coords[:,1] filt = (0<=x_coords) & (x_coords<lx) & (0<=y_coords) & (y_coords<ly) if ignore_error: x_coords, y_coords = x_coords[filt], y_coords[filt] else: assert np.sum(filt)==num_sources,'There are some sources out of images! The problem might be in coordinate conversion system or simulation!' if do_standard==True: data = standard(data) return np.moveaxis(data, 0, -1), x_coords, y_coords def fetch_data_3ch(image_file,model_file,do_standard=True): """ fetch_data_3ch : This function reads 3 images of 3 robust and model. Arguments: image_file (string) : path to robust 0 image file. model_file (string) : path to model file. do_standard (logical) (default=True) : if true, minimum/maximum value of image will be set to 0/1. -------- Returns: image, x coordinates, y coordinates """ data0, x_coords, y_coords = fetch_data(image_file,model_file,do_standard=do_standard) # lx,ly = data0[0,:,:,0].shape try: data1, x_coords, y_coords = fetch_data(image_file.replace('robust-0','robust-1'),model_file,do_standard=do_standard) except: assert 0,'Robust 1 does not exist.' try: data2, x_coords, y_coords = fetch_data(image_file.replace('robust-0','robust-2'),model_file,do_standard=do_standard) except: assert 0,'Robust 1 does not exist.' return np.concatenate((data0,data1,data2), axis=-1), x_coords, y_coords def cat2map(lx,ly,x_coords,y_coords): """ cat2map : This function converts a catalog to a 0/1 map which are representing background/point source. Arguments: lx (int): number of pixels of the image in first dimension. ly (int): number of pixels of the image in second dimension. x_coords (numpy array): list of the first dimension of point source positions. y_coords (numpy array): list of the second dimension of point source positions. -------- Returns: catalog image as nupmy array. """ cat = np.zeros((lx,ly)) for i,j in zip(x_coords.astype(int), y_coords.astype(int)): cat[j, i] = 1 return cat def magnifier(y,radius=15,value=1): """ magnifier (numpy array): This function magnifies any pixel with value one by a given value. Arguments: y : input 2D map. radius (int) (default=15) : radius of magnification. value (float) (default=True) : the value you want to use in magnified pixels. -------- Returns: image with magnified objects as numpy array. """ mag = np.zeros(y.shape) for i,j in np.argwhere(y==1): rr, cc = draw.circle(i, j, radius=radius, shape=mag.shape) mag[rr, cc] = value return mag def circle(y,radius=15): """ circle : This function add some circles around any pixel with value one. Arguments: y (numpy array): input 2D map. radius (int) (default=15): circle radius. -------- Returns: image with circles around objects. """ mag = np.zeros(y.shape) for i,j in np.argwhere(y==1): rr, cc = draw.circle_perimeter(i, j, radius=radius, shape=mag.shape) mag[rr, cc] = 1 return mag def horn_kernel(y,radius=10,step_height=1): """ horn_kernel : Horn shape kernel. Arguments: y (numpy array): input 2D map. radius (int) (default=15): effective radius of kernel. -------- Returns: kerneled image. """ mag = np.zeros(y.shape) for r in range(1,radius): for i,j in np.argwhere(y==1): rr, cc = draw.circle(i, j, radius=r, shape=mag.shape) mag[rr, cc] += 1.*step_height/radius return mag def gaussian_kernel(y,sigma=7): """ gaussian_kernel: Gaussian filter. Arguments: y (numpy array): input 2D map. sigma (float) (default=7): effective length of Gaussian smoothing. -------- Returns: kerneled image. """ return gaussian_filter(y, sigma) def ch_mkdir(directory): """ ch_mkdir : This function creates a directory if it does not exist. Arguments: directory (string): Path to the directory. -------- Returns: null. """ if not os.path.exists(directory): os.makedirs(directory) def the_print(text,style='bold',tc='gray',bgc='red'): """ prints table of formatted text format options """ colors = ['black','red','green','yellow','blue','purple','skyblue','gray'] if style == 'bold': style = 1 elif style == 'underlined': style = 4 else: style = 0 fg = 30+colors.index(tc) bg = 40+colors.index(bgc) form = ';'.join([str(style), str(fg), str(bg)]) print('\x1b[%sm %s \x1b[0m' % (form, text)) #def ps_extract(xp): # xp = xp-xp.min() # xp = xp/xp.max() # nb = [] # for trsh in np.linspace(0,0.2,200): # blobs = measure.label(xp>trsh) # nn = np.unique(blobs).shape[0] # nb.append(nn) # nb = np.array(nb) # nb = np.diff(nb) # trshs = np.linspace(0,0.2,200)[:-1] # thrsl = trshs[~((-5<nb) & (nb<5))] # if thrsl.shape[0]==0: # trsh = 0.1 # else: # trsh = thrsl[-1] #2: 15, 20 #3: 30,10 #4: 50, 10 # nnp = 0 # for tr in np.linspace(1,0,1000): # blobs = measure.label(xp>tr) # nn = np.unique(blobs).shape[0] # if nn-nnp>50: # break # nnp = nn # trsh = tr # blobs = measure.label(xp>trsh) # xl = [] # yl = [] # pl = [] # for v in np.unique(blobs)[1:]: # filt = blobs==v # pnt = np.round(np.mean(np.argwhere(filt),axis=0)).astype(int) # if filt.sum()>10: # xl.append(pnt[1]) # yl.append(pnt[0]) # pl.append(np.mean(xp[blobs==v])) # return np.array([xl,yl]).T,np.array(pl)
[ "skimage.draw.circle", "os.path.exists", "scipy.ndimage.filters.gaussian_filter", "os.makedirs", "astropy.coordinates.SkyCoord", "numpy.sum", "numpy.zeros", "numpy.argwhere", "skimage.draw.circle_perimeter", "numpy.concatenate", "astropy.io.fits.open", "numpy.moveaxis", "numpy.loadtxt", "astropy.wcs.WCS" ]
[((1351, 1460), 'numpy.loadtxt', 'np.loadtxt', (['model_file'], {'dtype': "{'names': ('name', 'ra', 'dec', 'I'), 'formats': ('S10', 'f4', 'f4', 'f4')}"}), "(model_file, dtype={'names': ('name', 'ra', 'dec', 'I'),\n 'formats': ('S10', 'f4', 'f4', 'f4')})\n", (1361, 1460), True, 'import numpy as np\n'), ((1583, 1637), 'astropy.coordinates.SkyCoord', 'coordinates.SkyCoord', (['ra', 'dec'], {'unit': '"""deg"""', 'frame': '"""fk5"""'}), "(ra, dec, unit='deg', frame='fk5')\n", (1603, 1637), False, 'from astropy import wcs, coordinates\n'), ((3975, 3993), 'numpy.zeros', 'np.zeros', (['(lx, ly)'], {}), '((lx, ly))\n', (3983, 3993), True, 'import numpy as np\n'), ((4536, 4553), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (4544, 4553), True, 'import numpy as np\n'), ((4569, 4588), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (4580, 4588), True, 'import numpy as np\n'), ((5014, 5031), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (5022, 5031), True, 'import numpy as np\n'), ((5047, 5066), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (5058, 5066), True, 'import numpy as np\n'), ((5471, 5488), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (5479, 5488), True, 'import numpy as np\n'), ((5986, 6011), 'scipy.ndimage.filters.gaussian_filter', 'gaussian_filter', (['y', 'sigma'], {}), '(y, sigma)\n', (6001, 6011), False, 'from scipy.ndimage.filters import gaussian_filter\n'), ((1102, 1123), 'astropy.io.fits.open', 'fits.open', (['image_file'], {}), '(image_file)\n', (1111, 1123), False, 'from astropy.io import fits\n'), ((1292, 1307), 'astropy.wcs.WCS', 'wcs.WCS', (['header'], {}), '(header)\n', (1299, 1307), False, 'from astropy import wcs, coordinates\n'), ((2283, 2307), 'numpy.moveaxis', 'np.moveaxis', (['data', '(0)', '(-1)'], {}), '(data, 0, -1)\n', (2294, 2307), True, 'import numpy as np\n'), ((3334, 3380), 'numpy.concatenate', 'np.concatenate', (['(data0, data1, data2)'], {'axis': '(-1)'}), '((data0, data1, data2), axis=-1)\n', (3348, 3380), True, 'import numpy as np\n'), ((4607, 4656), 'skimage.draw.circle', 'draw.circle', (['i', 'j'], {'radius': 'radius', 'shape': 'mag.shape'}), '(i, j, radius=radius, shape=mag.shape)\n', (4618, 4656), False, 'from skimage import draw\n'), ((5085, 5144), 'skimage.draw.circle_perimeter', 'draw.circle_perimeter', (['i', 'j'], {'radius': 'radius', 'shape': 'mag.shape'}), '(i, j, radius=radius, shape=mag.shape)\n', (5106, 5144), False, 'from skimage import draw\n'), ((5538, 5557), 'numpy.argwhere', 'np.argwhere', (['(y == 1)'], {}), '(y == 1)\n', (5549, 5557), True, 'import numpy as np\n'), ((6264, 6289), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (6278, 6289), False, 'import os\n'), ((6301, 6323), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (6312, 6323), False, 'import os\n'), ((2080, 2092), 'numpy.sum', 'np.sum', (['filt'], {}), '(filt)\n', (2086, 2092), True, 'import numpy as np\n'), ((5582, 5626), 'skimage.draw.circle', 'draw.circle', (['i', 'j'], {'radius': 'r', 'shape': 'mag.shape'}), '(i, j, radius=r, shape=mag.shape)\n', (5593, 5626), False, 'from skimage import draw\n'), ((1741, 1762), 'numpy.zeros', 'np.zeros', (['num_sources'], {}), '(num_sources)\n', (1749, 1762), True, 'import numpy as np\n'), ((1764, 1785), 'numpy.zeros', 'np.zeros', (['num_sources'], {}), '(num_sources)\n', (1772, 1785), True, 'import numpy as np\n')]
import os import cv2 from Segmentation import CombinedHist, get_histograms, HistQueue import matplotlib.pyplot as plt import numpy as np listofFiles = os.listdir('generated_frames') # change the size of queue accordingly queue_of_hists = HistQueue.HistQueue(25) x = [] y_r = [] y_g = [] y_b = [] def compare(current_hist, frame_no): avg_histr = queue_of_hists.getAverageHist() red_result = cv2.compareHist(current_hist.getRedHistr(), avg_histr.getRedHistr(), 0) green_result = cv2.compareHist(current_hist.getGreenHistr(), avg_histr.getGreenHistr(), 0) blue_result = cv2.compareHist(current_hist.getBlueHistr(), avg_histr.getBlueHistr(), 0) x.append(i) y_r.append(red_result) y_g.append(green_result) y_b.append(blue_result) # print(red_result) for i in range(0, 4000): blue_histr, green_histr, red_histr = get_histograms.get_histograms('generated_frames/frame' + str(i) + ".jpg") hist_of_image = CombinedHist.CombinedHist(blue_histr, green_histr, red_histr) compare(hist_of_image, i) queue_of_hists.insert_histr(hist_of_image) print("frame" + str(i) + ".jpg") fig = plt.figure(figsize=(18, 5)) y = np.add(np.add(y_r, y_g), y_b) / 3 value = np.percentile(y, 5) median = np.median(y) minimum = np.amin(y) y_sorted = np.sort(y) getting_index = y_sorted[8] print("quartile" + str(value)) print("median" + str(median)) plt.plot(x, y, color='k') plt.axhline(y=value, color='r', linestyle='-') plt.xticks(np.arange(min(x), max(x) + 1, 100.0)) plt.show()
[ "numpy.median", "os.listdir", "numpy.amin", "Segmentation.CombinedHist.CombinedHist", "numpy.add", "numpy.sort", "matplotlib.pyplot.plot", "matplotlib.pyplot.axhline", "matplotlib.pyplot.figure", "Segmentation.HistQueue.HistQueue", "numpy.percentile", "matplotlib.pyplot.show" ]
[((152, 182), 'os.listdir', 'os.listdir', (['"""generated_frames"""'], {}), "('generated_frames')\n", (162, 182), False, 'import os\n'), ((239, 262), 'Segmentation.HistQueue.HistQueue', 'HistQueue.HistQueue', (['(25)'], {}), '(25)\n', (258, 262), False, 'from Segmentation import CombinedHist, get_histograms, HistQueue\n'), ((1131, 1158), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 5)'}), '(figsize=(18, 5))\n', (1141, 1158), True, 'import matplotlib.pyplot as plt\n'), ((1206, 1225), 'numpy.percentile', 'np.percentile', (['y', '(5)'], {}), '(y, 5)\n', (1219, 1225), True, 'import numpy as np\n'), ((1236, 1248), 'numpy.median', 'np.median', (['y'], {}), '(y)\n', (1245, 1248), True, 'import numpy as np\n'), ((1259, 1269), 'numpy.amin', 'np.amin', (['y'], {}), '(y)\n', (1266, 1269), True, 'import numpy as np\n'), ((1281, 1291), 'numpy.sort', 'np.sort', (['y'], {}), '(y)\n', (1288, 1291), True, 'import numpy as np\n'), ((1381, 1406), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'color': '"""k"""'}), "(x, y, color='k')\n", (1389, 1406), True, 'import matplotlib.pyplot as plt\n'), ((1407, 1453), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': 'value', 'color': '"""r"""', 'linestyle': '"""-"""'}), "(y=value, color='r', linestyle='-')\n", (1418, 1453), True, 'import matplotlib.pyplot as plt\n'), ((1503, 1513), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1511, 1513), True, 'import matplotlib.pyplot as plt\n'), ((948, 1009), 'Segmentation.CombinedHist.CombinedHist', 'CombinedHist.CombinedHist', (['blue_histr', 'green_histr', 'red_histr'], {}), '(blue_histr, green_histr, red_histr)\n', (973, 1009), False, 'from Segmentation import CombinedHist, get_histograms, HistQueue\n'), ((1171, 1187), 'numpy.add', 'np.add', (['y_r', 'y_g'], {}), '(y_r, y_g)\n', (1177, 1187), True, 'import numpy as np\n')]
#!/usr/bin/env python # vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 et tw=80 : # # Extract and save extended object catalogs from the specified data and # uncertainty images. This version of the script jointly analyzes all # images from a specific AOR/channel to enable more sophisticated # analysis. # # <NAME> # Created: 2021-02-02 # Last modified: 2021-08-24 #-------------------------------------------------------------------------- #************************************************************************** #-------------------------------------------------------------------------- ## Logging setup: import logging #logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) #logger.setLevel(logging.DEBUG) logger.setLevel(logging.INFO) ## Current version: __version__ = "0.3.5" ## Python version-agnostic module reloading: try: reload # Python 2.7 except NameError: try: from importlib import reload # Python 3.4+ except ImportError: from imp import reload # Python 3.0 - 3.3 ## Modules: import argparse import shutil #import resource #import signal import glob #import gc import os import sys import time import numpy as np #from numpy.lib.recfunctions import append_fields #import datetime as dt #from dateutil import parser as dtp #from functools import partial #from collections import OrderedDict #from collections.abc import Iterable #import multiprocessing as mp #np.set_printoptions(suppress=True, linewidth=160) _have_np_vers = float('.'.join(np.__version__.split('.')[:2])) ##--------------------------------------------------------------------------## ## Disable buffering on stdout/stderr: class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) ##--------------------------------------------------------------------------## ## Spitzer pipeline filesystem helpers: try: import spitz_fs_helpers reload(spitz_fs_helpers) except ImportError: logger.error("failed to import spitz_fs_helpers module!") sys.exit(1) sfh = spitz_fs_helpers ## Spitzer pipeline cross-correlation: try: import spitz_xcorr_stacking reload(spitz_xcorr_stacking) except ImportError: logger.error("failed to import spitz_xcor_stacking module!") sys.exit(1) sxc = spitz_xcorr_stacking.SpitzerXCorr() ## Catalog pruning helpers: try: import catalog_tools reload(catalog_tools) except ImportError: logger.error("failed to import catalog_tools module!") sys.exit(1) xcp = catalog_tools.XCorrPruner() ## Spitzer star detection routine: try: import spitz_extract reload(spitz_extract) spf = spitz_extract.SpitzFind() except ImportError: logger.error("spitz_extract module not found!") sys.exit(1) ## Hybrid stack+individual position calculator: try: import spitz_stack_astrom reload(spitz_stack_astrom) ha = spitz_stack_astrom.HybridAstrom() except ImportError: logger.error("failed to import spitz_stack_astrom module!") sys.exit(1) ## HORIZONS ephemeris tools: try: import jpl_eph_helpers reload(jpl_eph_helpers) except ImportError: logger.error("failed to import jpl_eph_helpers module!") sys.exit(1) eee = jpl_eph_helpers.EphTool() ##--------------------------------------------------------------------------## ## Fast FITS I/O: try: import fitsio except ImportError: logger.error("fitsio module not found! Install and retry.") sys.stderr.write("\nError: fitsio module not found!\n") sys.exit(1) ## Save FITS image with clobber (fitsio): def qsave(iname, idata, header=None, **kwargs): this_func = sys._getframe().f_code.co_name parent_func = sys._getframe(1).f_code.co_name sys.stderr.write("Writing to '%s' ... " % iname) fitsio.write(iname, idata, clobber=True, header=header, **kwargs) sys.stderr.write("done.\n") ##--------------------------------------------------------------------------## ##------------------ Parse Command Line ----------------## ##--------------------------------------------------------------------------## ## Dividers: halfdiv = '-' * 40 fulldiv = '-' * 80 ## Parse arguments and run script: class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ## Enable raw text AND display of defaults: class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass ## Parse the command line: if __name__ == '__main__': # ------------------------------------------------------------------ prog_name = os.path.basename(__file__) descr_txt = """ Extract catalogs from the listed Spitzer data/uncertainty images. Version: %s """ % __version__ parser = MyParser(prog=prog_name, description=descr_txt) #formatter_class=argparse.RawTextHelpFormatter) # ------------------------------------------------------------------ parser.set_defaults(imtype=None) #'cbcd') #'clean') #parser.set_defaults(sigthresh=3.0) parser.set_defaults(sigthresh=2.0) parser.set_defaults(skip_existing=True) parser.set_defaults(save_registered=True) #parser.set_defaults(save_reg_subdir=None) # ------------------------------------------------------------------ #parser.add_argument('firstpos', help='first positional argument') #parser.add_argument('-w', '--whatever', required=False, default=5.0, # help='some option with default [def: %(default)s]', type=float) # ------------------------------------------------------------------ # ------------------------------------------------------------------ iogroup = parser.add_argument_group('File I/O') iogroup.add_argument('--overwrite', required=False, dest='skip_existing', action='store_false', help='overwrite existing catalogs') #iogroup.add_argument('-E', '--ephem_data', default=None, required=True, # help='CSV file with SST ephemeris data', type=str) iogroup.add_argument('-I', '--input_folder', default=None, required=True, help='where to find input images', type=str) iogroup.add_argument('-O', '--output_folder', default=None, required=False, help='where to save extended catalog outputs', type=str) iogroup.add_argument('-W', '--walk', default=False, action='store_true', help='recursively walk subfolders to find CBCD images') imtype = iogroup.add_mutually_exclusive_group() #imtype.add_argument('--cbcd', required=False, action='store_const', # dest='imtype', const='cbcd', help='use cbcd images') imtype.add_argument('--hcfix', required=False, action='store_const', dest='imtype', const='hcfix', help='use hcfix images') imtype.add_argument('--clean', required=False, action='store_const', dest='imtype', const='clean', help='use clean images') imtype.add_argument('--nudge', required=False, action='store_const', dest='imtype', const='nudge', help='use nudge images') #iogroup.add_argument('-R', '--ref_image', default=None, required=True, # help='KELT image with WCS') # ------------------------------------------------------------------ # ------------------------------------------------------------------ # Miscellany: miscgroup = parser.add_argument_group('Miscellany') miscgroup.add_argument('--debug', dest='debug', default=False, help='Enable extra debugging messages', action='store_true') miscgroup.add_argument('-q', '--quiet', action='count', default=0, help='less progress/status reporting') miscgroup.add_argument('-v', '--verbose', action='count', default=0, help='more progress/status reporting') # ------------------------------------------------------------------ context = parser.parse_args() context.vlevel = 99 if context.debug else (context.verbose-context.quiet) context.prog_name = prog_name # Unless otherwise specified, output goes into input folder: if not context.output_folder: context.output_folder = context.input_folder # Ensure an image type is selected: if not context.imtype: sys.stderr.write("\nNo image type selected!\n\n") sys.exit(1) ## Use imtype-specific folder for registered file output: #if not context.save_reg_subdir: # context.save_reg_subdir = 'aligned_%s' % context.imtype ##--------------------------------------------------------------------------## ##------------------ Make Input Image List ----------------## ##--------------------------------------------------------------------------## tstart = time.time() sys.stderr.write("Listing %s frames ... " % context.imtype) #im_wildpath = 'SPITZ*%s.fits' % context.imtype #im_wildcard = os.path.join(context.input_folder, 'SPIT*' #_img_types = ['cbcd', 'clean', 'cbunc'] #_type_suff = dict([(x, x+'.fits') for x in _im_types]) #img_list = {} #for imsuff in suffixes: # wpath = '%s/SPITZ*%s.fits' % (context.input_folder, imsuff) # img_list[imsuff] = sorted(glob.glob(os.path.join(context. #img_files = sorted(glob.glob(os.path.join(context.input_folder, im_wildpath))) if context.walk: img_files = sfh.get_files_walk(context.input_folder, flavor=context.imtype) else: img_files = sfh.get_files_single(context.input_folder, flavor=context.imtype) sys.stderr.write("done.\n") ## Abort in case of no input: if not img_files: sys.stderr.write("No input (%s) files found in folder:\n" % context.imtype) sys.stderr.write("--> %s\n\n" % context.input_folder) sys.exit(1) n_images = len(img_files) ## List of uncertainty frames (warn if any missing): #unc_files = [x.replace(context.imtype, 'cbunc') for x in img_files] #sys.stderr.write("Checking error-images ... ") #have_unc = [os.path.isfile(x) for x in unc_files] #if not all(have_unc): # sys.stderr.write("WARNING: some uncertainty frames missing!\n") #else: # sys.stderr.write("done.\n") ##--------------------------------------------------------------------------## ##------------------ Load SST Ephemeris Data ----------------## ##--------------------------------------------------------------------------## ### Ephemeris data file must exist: #if not context.ephem_data: # logger.error("context.ephem_data not set?!?!") # sys.exit(1) #if not os.path.isfile(context.ephem_data): # logger.error("Ephemeris file not found: %s" % context.ephem_data) # sys.exit(1) # ### Load ephemeris data: #eee.load(context.ephem_data) ##--------------------------------------------------------------------------## ##------------------ Unique AOR/Channel Combos ----------------## ##--------------------------------------------------------------------------## unique_tags = sorted(list(set([sfh.get_irac_aor_tag(x) for x in img_files]))) images_by_tag = {x:[] for x in unique_tags} for ii in img_files: images_by_tag[sfh.get_irac_aor_tag(ii)].append(ii) ##--------------------------------------------------------------------------## ##------------------ Diagnostic Region Files ----------------## ##--------------------------------------------------------------------------## def regify_excat_pix(data, rpath, win=False, rr=2.0): colnames = ('wx', 'wy') if win else ('x', 'y') xpix, ypix = [data[x] for x in colnames] with open(rpath, 'w') as rfile: for xx,yy in zip(xpix, ypix): rfile.write("image; circle(%8.3f, %8.3f, %8.3f)\n" % (xx, yy, rr)) return ##--------------------------------------------------------------------------## ##------------------ ExtendedCatalog Ephem Format ----------------## ##--------------------------------------------------------------------------## #def reformat_ephem(edata): ##--------------------------------------------------------------------------## ##------------------ Stack/Image Comparison ----------------## ##--------------------------------------------------------------------------## #def xcheck(idata, sdata): # nstack = len(sdata) # nimage = len(idata) # sys.stderr.write("nstack: %d\n" % nstack) # sys.stderr.write("nimage: %d\n" % nimage) # return ##--------------------------------------------------------------------------## ##------------------ Process All Images ----------------## ##--------------------------------------------------------------------------## ntodo = 0 nproc = 0 ntotal = len(img_files) min_sobj = 10 # bark if fewer than this many found in stack skip_stuff = False #context.save_registered = False #context.skip_existing = False ## Reduce bright pixel threshold: #sxc.set_bp_thresh(10.0) #sxc.set_bp_thresh(5.0) sxc.set_bp_thresh(10.0) #sxc.set_vlevel(10) sxc.set_roi_rfrac(0.90) sxc.set_roi_rfrac(2.00) #sys.exit(0) #for aor_tag,tag_files in images_by_tag.items(): for aor_tag in unique_tags: sys.stderr.write("\n\nProcessing images from %s ...\n" % aor_tag) tag_files = images_by_tag[aor_tag] n_tagged = len(tag_files) if n_tagged < 2: sys.stderr.write("WARNING: only %d images with tag %s\n" % (n_tagged, aor_tag)) sys.stderr.write("This case is not currently handled ...\n") sys.exit(1) # File/folder paths: aor_dir = os.path.dirname(tag_files[0]) stack_ibase = '%s_%s_stack.fits' % (aor_tag, context.imtype) stack_cbase = '%s_%s_stack.fcat' % (aor_tag, context.imtype) medze_ibase = '%s_%s_medze.fits' % (aor_tag, context.imtype) stack_ipath = os.path.join(aor_dir, stack_ibase) stack_cpath = os.path.join(aor_dir, stack_cbase) medze_ipath = os.path.join(aor_dir, medze_ibase) #sys.stderr.write("stack_ibase: %s\n" % stack_ibase) #sys.stderr.write("As of this point ...\n") #sys.stderr.write("sxc._roi_rfrac: %.5f\n" % sxc._roi_rfrac) sys.stderr.write("Cross-correlating and stacking ... ") result = sxc.shift_and_stack(tag_files) sys.stderr.write("done.\n") sxc.save_istack(stack_ipath) #sys.exit(0) #istack = sxc.get_stacked() #qsave(stack_ipath, istack) # Dump registered data to disk: if context.save_registered: save_reg_subdir = 'aligned_%s_%s' % (aor_tag, context.imtype) sys.stderr.write("Saving registered frames for inspection ...\n") #reg_dir = os.path.join(aor_dir, context.save_reg_subdir) reg_dir = os.path.join(aor_dir, save_reg_subdir) if os.path.isdir(reg_dir): shutil.rmtree(reg_dir) os.mkdir(reg_dir) sxc.dump_registered_images(reg_dir) sxc.dump_bright_pixel_masks(reg_dir) sys.stderr.write("\n") # Extract stars from stacked image: spf.use_images(ipath=stack_ipath) stack_cat = spf.find_stars(context.sigthresh) sdata = stack_cat.get_catalog() nsobj = len(sdata) sys.stderr.write(" \nFound %d sources in stacked image.\n\n" % nsobj) if (nsobj < min_sobj): sys.stderr.write("Fewer than %d objects found in stack ... \n" % min_sobj) sys.stderr.write("Found %d objects.\n\n" % nsobj) sys.stderr.write("--> %s\n\n" % stack_ipath) sys.exit(1) stack_cat.save_as_fits(stack_cpath, overwrite=True) # region file for diagnostics: stack_rfile = stack_ipath + '.reg' regify_excat_pix(sdata, stack_rfile, win=True) # Make/save 'medianize' stack for comparison: sxc.make_mstack() sxc.save_mstack(medze_ipath) # Set up pruning system: xshifts, yshifts = sxc.get_stackcat_offsets() xcp.set_master_catalog(sdata) xcp.set_image_offsets(xshifts, yshifts) # Set up hybrid astrometry system: ha.set_stack_excat(stack_cat) # catalog of detections ha.set_xcorr_metadata(sxc) # pixel offsets by image ## Stop here for now ... #if skip_stuff: # continue # process individual files with cross-correlation help: for ii,img_ipath in enumerate(tag_files, 1): sys.stderr.write("%s\n" % fulldiv) unc_ipath = img_ipath.replace(context.imtype, 'cbunc') if not os.path.isfile(unc_ipath): sys.stderr.write("WARNING: file not found:\n--> %s\n" % unc_ipath) continue img_ibase = os.path.basename(img_ipath) #cat_ibase = img_ibase.replace(context.imtype, 'fcat') cat_fbase = img_ibase + '.fcat' cat_pbase = img_ibase + '.pcat' cat_mbase = img_ibase + '.mcat' ### FIXME ### ### context.output_folder is not appropriate for walk mode ... save_dir = context.output_folder # NOT FOR WALK MODE save_dir = os.path.dirname(img_ipath) cat_fpath = os.path.join(save_dir, cat_fbase) cat_ppath = os.path.join(save_dir, cat_pbase) cat_mpath = os.path.join(save_dir, cat_mbase) ### FIXME ### sys.stderr.write("Catalog %s ... " % cat_fpath) if context.skip_existing: if os.path.isfile(cat_mpath): sys.stderr.write("exists! Skipping ... \n") continue nproc += 1 sys.stderr.write("not found ... creating ...\n") spf.use_images(ipath=img_ipath, upath=unc_ipath) result = spf.find_stars(context.sigthresh) ## FIXME: this just grabs the ephemeris from the header content ## of the first ExtendedCatalog produced. This should be obtained ## separately to make things easier to follow (and to eliminate ## the need to pre-modify the image headers ...) eph_data = eee.eph_from_header(result.get_header()) result.set_ephem(eph_data) result.save_as_fits(cat_fpath, overwrite=True) nfound = len(result.get_catalog()) frame_rfile = img_ipath + '.reg' regify_excat_pix(result.get_catalog(), frame_rfile, win=True) # prune sources not detected in stacked frame: pruned = xcp.prune_spurious(result.get_catalog(), img_ipath) npruned = len(pruned) sys.stderr.write("nfound: %d, npruned: %d\n" % (nfound, npruned)) if (len(pruned) < 5): sys.stderr.write("BARKBARKBARK\n") sys.exit(1) result.set_catalog(pruned) result.save_as_fits(cat_ppath, overwrite=True) # build and save hybrid catalog: mcat = ha.make_hybrid_excat(result) mcat.set_ephem(eph_data) mcat.save_as_fits(cat_mpath, overwrite=True) mxcat_rfile = img_ipath + '.mcat.reg' #regify_excat_pix(mcat.get_catalog(), mxcat_rfile, win=True) # stop early if requested: if (ntodo > 0) and (nproc >= ntodo): break #break #sys.exit(0) if (ntodo > 0) and (nproc >= ntodo): break tstop = time.time() ttook = tstop - tstart sys.stderr.write("Extraction completed in %.3f seconds.\n" % ttook) #import astropy.io.fits as pf # #imra = np.array([hh['CRVAL1'] for hh in sxc._im_hdrs]) #imde = np.array([hh['CRVAL2'] for hh in sxc._im_hdrs]) # ##sys.stderr.write("\n\n\n") ##sys.stderr.write("sxc.shift_and_stack(tag_files)\n") ##result = sxc.shift_and_stack(tag_files) #sys.exit(0) # #layers = sxc.pad_and_shift(sxc._im_data, sxc._x_shifts, sxc._y_shifts) #tstack = sxc.dumb_stack(layers) #pf.writeto('tstack.fits', tstack, overwrite=True) # #tdir = 'zzz' #if not os.path.isdir(tdir): # os.mkdir(tdir) # ##tag_bases = [os.path.basename(x) for x in tag_files] ##for ibase,idata in zip(tag_bases, layers): ## tsave = os.path.join(tdir, 'r' + ibase) ## sys.stderr.write("Saving %s ... \n" % tsave) ## pf.writeto(tsave, idata, overwrite=True) # #sys.stderr.write("\n\n\n") #sys.stderr.write("visual inspection with:\n") #sys.stderr.write("flztfs %s\n" % ' '.join(tag_files)) ##--------------------------------------------------------------------------## ###################################################################### # CHANGELOG (07_spitzer_aor_extraction.py): #--------------------------------------------------------------------- # # 2021-02-02: # -- Increased __version__ to 0.1.0. # -- First created 07_spitzer_aor_extraction.py. #
[ "logging.getLogger", "sys.exit", "jpl_eph_helpers.EphTool", "sys._getframe", "os.path.isdir", "os.mkdir", "spitz_extract.SpitzFind", "imp.reload", "os.path.isfile", "sys.stderr.write", "catalog_tools.XCorrPruner", "os.path.dirname", "time.time", "logging.basicConfig", "numpy.__version__.split", "spitz_stack_astrom.HybridAstrom", "fitsio.write", "os.path.join", "spitz_xcorr_stacking.SpitzerXCorr", "os.path.basename", "shutil.rmtree" ]
[((672, 711), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (691, 711), False, 'import logging\n'), ((721, 748), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (738, 748), False, 'import logging\n'), ((2585, 2620), 'spitz_xcorr_stacking.SpitzerXCorr', 'spitz_xcorr_stacking.SpitzerXCorr', ([], {}), '()\n', (2618, 2620), False, 'import spitz_xcorr_stacking\n'), ((2807, 2834), 'catalog_tools.XCorrPruner', 'catalog_tools.XCorrPruner', ([], {}), '()\n', (2832, 2834), False, 'import catalog_tools\n'), ((3502, 3527), 'jpl_eph_helpers.EphTool', 'jpl_eph_helpers.EphTool', ([], {}), '()\n', (3525, 3527), False, 'import jpl_eph_helpers\n'), ((9088, 9099), 'time.time', 'time.time', ([], {}), '()\n', (9097, 9099), False, 'import time\n'), ((9100, 9159), 'sys.stderr.write', 'sys.stderr.write', (["('Listing %s frames ... ' % context.imtype)"], {}), "('Listing %s frames ... ' % context.imtype)\n", (9116, 9159), False, 'import sys\n'), ((9798, 9825), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (9814, 9825), False, 'import sys\n'), ((19163, 19174), 'time.time', 'time.time', ([], {}), '()\n', (19172, 19174), False, 'import time\n'), ((19198, 19265), 'sys.stderr.write', 'sys.stderr.write', (["('Extraction completed in %.3f seconds.\\n' % ttook)"], {}), "('Extraction completed in %.3f seconds.\\n' % ttook)\n", (19214, 19265), False, 'import sys\n'), ((2222, 2246), 'imp.reload', 'reload', (['spitz_fs_helpers'], {}), '(spitz_fs_helpers)\n', (2228, 2246), False, 'from imp import reload\n'), ((2449, 2477), 'imp.reload', 'reload', (['spitz_xcorr_stacking'], {}), '(spitz_xcorr_stacking)\n', (2455, 2477), False, 'from imp import reload\n'), ((2684, 2705), 'imp.reload', 'reload', (['catalog_tools'], {}), '(catalog_tools)\n', (2690, 2705), False, 'from imp import reload\n'), ((2905, 2926), 'imp.reload', 'reload', (['spitz_extract'], {}), '(spitz_extract)\n', (2911, 2926), False, 'from imp import reload\n'), ((2937, 2962), 'spitz_extract.SpitzFind', 'spitz_extract.SpitzFind', ([], {}), '()\n', (2960, 2962), False, 'import spitz_extract\n'), ((3139, 3165), 'imp.reload', 'reload', (['spitz_stack_astrom'], {}), '(spitz_stack_astrom)\n', (3145, 3165), False, 'from imp import reload\n'), ((3175, 3208), 'spitz_stack_astrom.HybridAstrom', 'spitz_stack_astrom.HybridAstrom', ([], {}), '()\n', (3206, 3208), False, 'import spitz_stack_astrom\n'), ((3375, 3398), 'imp.reload', 'reload', (['jpl_eph_helpers'], {}), '(jpl_eph_helpers)\n', (3381, 3398), False, 'from imp import reload\n'), ((4002, 4050), 'sys.stderr.write', 'sys.stderr.write', (['("Writing to \'%s\' ... " % iname)'], {}), '("Writing to \'%s\' ... " % iname)\n', (4018, 4050), False, 'import sys\n'), ((4055, 4120), 'fitsio.write', 'fitsio.write', (['iname', 'idata'], {'clobber': '(True)', 'header': 'header'}), '(iname, idata, clobber=True, header=header, **kwargs)\n', (4067, 4120), False, 'import fitsio\n'), ((4125, 4152), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (4141, 4152), False, 'import sys\n'), ((4970, 4996), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (4986, 4996), False, 'import os\n'), ((9879, 9954), 'sys.stderr.write', 'sys.stderr.write', (["('No input (%s) files found in folder:\\n' % context.imtype)"], {}), "('No input (%s) files found in folder:\\n' % context.imtype)\n", (9895, 9954), False, 'import sys\n'), ((9959, 10012), 'sys.stderr.write', 'sys.stderr.write', (["('--> %s\\n\\n' % context.input_folder)"], {}), "('--> %s\\n\\n' % context.input_folder)\n", (9975, 10012), False, 'import sys\n'), ((10017, 10028), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10025, 10028), False, 'import sys\n'), ((13359, 13425), 'sys.stderr.write', 'sys.stderr.write', (['("""\n\nProcessing images from %s ...\n""" % aor_tag)'], {}), '("""\n\nProcessing images from %s ...\n""" % aor_tag)\n', (13375, 13425), False, 'import sys\n'), ((13749, 13778), 'os.path.dirname', 'os.path.dirname', (['tag_files[0]'], {}), '(tag_files[0])\n', (13764, 13778), False, 'import os\n'), ((13992, 14026), 'os.path.join', 'os.path.join', (['aor_dir', 'stack_ibase'], {}), '(aor_dir, stack_ibase)\n', (14004, 14026), False, 'import os\n'), ((14045, 14079), 'os.path.join', 'os.path.join', (['aor_dir', 'stack_cbase'], {}), '(aor_dir, stack_cbase)\n', (14057, 14079), False, 'import os\n'), ((14098, 14132), 'os.path.join', 'os.path.join', (['aor_dir', 'medze_ibase'], {}), '(aor_dir, medze_ibase)\n', (14110, 14132), False, 'import os\n'), ((14309, 14364), 'sys.stderr.write', 'sys.stderr.write', (['"""Cross-correlating and stacking ... """'], {}), "('Cross-correlating and stacking ... ')\n", (14325, 14364), False, 'import sys\n'), ((14413, 14440), 'sys.stderr.write', 'sys.stderr.write', (['"""done.\n"""'], {}), "('done.\\n')\n", (14429, 14440), False, 'import sys\n'), ((15299, 15369), 'sys.stderr.write', 'sys.stderr.write', (['(""" \nFound %d sources in stacked image.\n\n""" % nsobj)'], {}), '(""" \nFound %d sources in stacked image.\n\n""" % nsobj)\n', (15315, 15369), False, 'import sys\n'), ((2333, 2344), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2341, 2344), False, 'import sys\n'), ((2567, 2578), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2575, 2578), False, 'import sys\n'), ((2789, 2800), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2797, 2800), False, 'import sys\n'), ((3039, 3050), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3047, 3050), False, 'import sys\n'), ((3297, 3308), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3305, 3308), False, 'import sys\n'), ((3484, 3495), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3492, 3495), False, 'import sys\n'), ((3738, 3795), 'sys.stderr.write', 'sys.stderr.write', (['"""\nError: fitsio module not found!\n"""'], {}), '("""\nError: fitsio module not found!\n""")\n', (3754, 3795), False, 'import sys\n'), ((3798, 3809), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3806, 3809), False, 'import sys\n'), ((4558, 4599), 'sys.stderr.write', 'sys.stderr.write', (["('error: %s\\n' % message)"], {}), "('error: %s\\n' % message)\n", (4574, 4599), False, 'import sys\n'), ((4634, 4645), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (4642, 4645), False, 'import sys\n'), ((8604, 8654), 'sys.stderr.write', 'sys.stderr.write', (['"""\nNo image type selected!\n\n"""'], {}), '("""\nNo image type selected!\n\n""")\n', (8620, 8654), False, 'import sys\n'), ((8662, 8673), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (8670, 8673), False, 'import sys\n'), ((13524, 13603), 'sys.stderr.write', 'sys.stderr.write', (["('WARNING: only %d images with tag %s\\n' % (n_tagged, aor_tag))"], {}), "('WARNING: only %d images with tag %s\\n' % (n_tagged, aor_tag))\n", (13540, 13603), False, 'import sys\n'), ((13628, 13688), 'sys.stderr.write', 'sys.stderr.write', (['"""This case is not currently handled ...\n"""'], {}), "('This case is not currently handled ...\\n')\n", (13644, 13688), False, 'import sys\n'), ((13697, 13708), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13705, 13708), False, 'import sys\n'), ((14702, 14767), 'sys.stderr.write', 'sys.stderr.write', (['"""Saving registered frames for inspection ...\n"""'], {}), "('Saving registered frames for inspection ...\\n')\n", (14718, 14767), False, 'import sys\n'), ((14852, 14890), 'os.path.join', 'os.path.join', (['aor_dir', 'save_reg_subdir'], {}), '(aor_dir, save_reg_subdir)\n', (14864, 14890), False, 'import os\n'), ((14902, 14924), 'os.path.isdir', 'os.path.isdir', (['reg_dir'], {}), '(reg_dir)\n', (14915, 14924), False, 'import os\n'), ((14969, 14986), 'os.mkdir', 'os.mkdir', (['reg_dir'], {}), '(reg_dir)\n', (14977, 14986), False, 'import os\n'), ((15084, 15106), 'sys.stderr.write', 'sys.stderr.write', (['"""\n"""'], {}), "('\\n')\n", (15100, 15106), False, 'import sys\n'), ((15404, 15478), 'sys.stderr.write', 'sys.stderr.write', (["('Fewer than %d objects found in stack ... \\n' % min_sobj)"], {}), "('Fewer than %d objects found in stack ... \\n' % min_sobj)\n", (15420, 15478), False, 'import sys\n'), ((15487, 15536), 'sys.stderr.write', 'sys.stderr.write', (["('Found %d objects.\\n\\n' % nsobj)"], {}), "('Found %d objects.\\n\\n' % nsobj)\n", (15503, 15536), False, 'import sys\n'), ((15545, 15589), 'sys.stderr.write', 'sys.stderr.write', (["('--> %s\\n\\n' % stack_ipath)"], {}), "('--> %s\\n\\n' % stack_ipath)\n", (15561, 15589), False, 'import sys\n'), ((15598, 15609), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (15606, 15609), False, 'import sys\n'), ((16412, 16446), 'sys.stderr.write', 'sys.stderr.write', (["('%s\\n' % fulldiv)"], {}), "('%s\\n' % fulldiv)\n", (16428, 16446), False, 'import sys\n'), ((16672, 16699), 'os.path.basename', 'os.path.basename', (['img_ipath'], {}), '(img_ipath)\n', (16688, 16699), False, 'import os\n'), ((17060, 17086), 'os.path.dirname', 'os.path.dirname', (['img_ipath'], {}), '(img_ipath)\n', (17075, 17086), False, 'import os\n'), ((17107, 17140), 'os.path.join', 'os.path.join', (['save_dir', 'cat_fbase'], {}), '(save_dir, cat_fbase)\n', (17119, 17140), False, 'import os\n'), ((17161, 17194), 'os.path.join', 'os.path.join', (['save_dir', 'cat_pbase'], {}), '(save_dir, cat_pbase)\n', (17173, 17194), False, 'import os\n'), ((17215, 17248), 'os.path.join', 'os.path.join', (['save_dir', 'cat_mbase'], {}), '(save_dir, cat_mbase)\n', (17227, 17248), False, 'import os\n'), ((17280, 17327), 'sys.stderr.write', 'sys.stderr.write', (["('Catalog %s ... ' % cat_fpath)"], {}), "('Catalog %s ... ' % cat_fpath)\n", (17296, 17327), False, 'import sys\n'), ((17517, 17565), 'sys.stderr.write', 'sys.stderr.write', (['"""not found ... creating ...\n"""'], {}), "('not found ... creating ...\\n')\n", (17533, 17565), False, 'import sys\n'), ((18419, 18484), 'sys.stderr.write', 'sys.stderr.write', (["('nfound: %d, npruned: %d\\n' % (nfound, npruned))"], {}), "('nfound: %d, npruned: %d\\n' % (nfound, npruned))\n", (18435, 18484), False, 'import sys\n'), ((1599, 1624), 'numpy.__version__.split', 'np.__version__.split', (['"""."""'], {}), "('.')\n", (1619, 1624), True, 'import numpy as np\n'), ((3917, 3932), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (3930, 3932), False, 'import sys\n'), ((3966, 3982), 'sys._getframe', 'sys._getframe', (['(1)'], {}), '(1)\n', (3979, 3982), False, 'import sys\n'), ((14938, 14960), 'shutil.rmtree', 'shutil.rmtree', (['reg_dir'], {}), '(reg_dir)\n', (14951, 14960), False, 'import shutil\n'), ((16525, 16550), 'os.path.isfile', 'os.path.isfile', (['unc_ipath'], {}), '(unc_ipath)\n', (16539, 16550), False, 'import os\n'), ((16564, 16632), 'sys.stderr.write', 'sys.stderr.write', (['("""WARNING: file not found:\n--> %s\n""" % unc_ipath)'], {}), '("""WARNING: file not found:\n--> %s\n""" % unc_ipath)\n', (16580, 16632), False, 'import sys\n'), ((17377, 17402), 'os.path.isfile', 'os.path.isfile', (['cat_mpath'], {}), '(cat_mpath)\n', (17391, 17402), False, 'import os\n'), ((18527, 18561), 'sys.stderr.write', 'sys.stderr.write', (['"""BARKBARKBARK\n"""'], {}), "('BARKBARKBARK\\n')\n", (18543, 18561), False, 'import sys\n'), ((18574, 18585), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (18582, 18585), False, 'import sys\n'), ((17420, 17464), 'sys.stderr.write', 'sys.stderr.write', (['"""exists! Skipping ... \n"""'], {}), "('exists! Skipping ... \\n')\n", (17436, 17464), False, 'import sys\n')]
# Copyright 2020 Toyota Research Institute. All rights reserved. """ Geometry utilities """ import numpy as np def invert_pose_numpy(T): """ 'Invert' 4x4 extrinsic matrix Parameters ---------- T: 4x4 matrix (world to camera) Returns ------- 4x4 matrix (camera to world) """ Tc = np.copy(T) R, t = Tc[:3, :3], Tc[:3, 3] Tc[:3, :3], Tc[:3, 3] = R.T, - np.matmul(R.T, t) return Tc
[ "numpy.copy", "numpy.matmul" ]
[((326, 336), 'numpy.copy', 'np.copy', (['T'], {}), '(T)\n', (333, 336), True, 'import numpy as np\n'), ((405, 422), 'numpy.matmul', 'np.matmul', (['R.T', 't'], {}), '(R.T, t)\n', (414, 422), True, 'import numpy as np\n')]
import numpy as np from tests.test_utils import run_track_tests from mirdata import annotations from mirdata.datasets import tonas TEST_DATA_HOME = "tests/resources/mir_datasets/tonas" def test_track(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) track = dataset.track(default_trackid) expected_attributes = { "singer": "<NAME>", "style": "Debla", "title": "<NAME>", "tuning_frequency": 451.0654725341684, "f0_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.f0.Corrected", "notes_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.notes.Corrected", "audio_path": "tests/resources/mir_datasets/tonas/Deblas/01-D_AMairena.wav", "track_id": "01-D_AMairena", } expected_property_types = { "f0": annotations.F0Data, "f0_automatic": annotations.F0Data, "f0_corrected": annotations.F0Data, "notes": annotations.NoteData, "audio": tuple, "singer": str, "style": str, "title": str, "tuning_frequency": float, } run_track_tests(track, expected_attributes, expected_property_types) def test_to_jams(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) track = dataset.track(default_trackid) jam = track.to_jams() # Validate cante100 jam schema assert jam.validate() # Validate melody f0 = jam.search(namespace="pitch_contour")[0]["data"] assert [note.time for note in f0] == [0.197, 0.209, 0.221, 0.232] assert [note.duration for note in f0] == [0.0, 0.0, 0.0, 0.0] assert [note.value for note in f0] == [ {"index": 0, "frequency": 0.0, "voiced": False}, {"index": 0, "frequency": 379.299, "voiced": True}, {"index": 0, "frequency": 379.299, "voiced": True}, {"index": 0, "frequency": 379.299, "voiced": True}, ] print([note.confidence for note in f0]) assert [note.confidence for note in f0] == [3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05] # Validate note transciption notes = jam.search(namespace="note_hz")[0]["data"] assert [note.time for note in notes] == [ 0.216667, 0.65, 2.183333, 2.566667, ] assert [note.duration for note in notes] == [ 0.433333, 1.016667, 0.3833329999999999, 0.3333330000000001, ] assert [note.value for note in notes] == [ 388.8382625732775, 411.9597888711769, 388.8382625732775, 411.9597888711769, ] assert [note.confidence for note in notes] == [None, None, None, None] def test_load_melody(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) track = dataset.track(default_trackid) f0_path = track.f0_path f0_data_corrected = tonas.load_f0(f0_path, True) f0_data_automatic = tonas.load_f0(f0_path, False) # check types assert type(f0_data_corrected) == annotations.F0Data assert type(f0_data_corrected.times) is np.ndarray assert type(f0_data_corrected.frequencies) is np.ndarray assert type(f0_data_corrected.voicing) is np.ndarray assert type(f0_data_corrected._confidence) is np.ndarray assert type(f0_data_automatic) == annotations.F0Data assert type(f0_data_automatic.times) is np.ndarray assert type(f0_data_automatic.frequencies) is np.ndarray assert type(f0_data_corrected.voicing) is np.ndarray assert type(f0_data_automatic._confidence) is np.ndarray # check values assert np.array_equal( f0_data_corrected.times, np.array([0.197, 0.209, 0.221, 0.232]), ) assert np.array_equal( f0_data_corrected.frequencies, np.array([0.000, 379.299, 379.299, 379.299]) ) assert np.array_equal( f0_data_corrected.voicing, np.array([0.0, 1.0, 1.0, 1.0]), ) assert np.array_equal( f0_data_corrected._confidence, np.array([3.090e-06, 0.00000286, 0.00000715, 0.00001545]), ) # check values assert np.array_equal( f0_data_automatic.times, np.array([0.197, 0.209, 0.221, 0.232]), ) assert np.array_equal( f0_data_automatic.frequencies, np.array( [ 0.000, 0.000, 143.918, 143.918, ] ), ) assert np.array_equal( f0_data_automatic.voicing, np.array([0.0, 0.0, 1.0, 1.0]), ) assert np.array_equal( f0_data_automatic._confidence, np.array([3.090e-06, 2.860e-06, 0.00000715, 0.00001545]), ) def test_load_notes(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) track = dataset.track(default_trackid) notes_path = track.notes_path notes_data = tonas.load_notes(notes_path) tuning_frequency = tonas._load_tuning_frequency(notes_path) # check types assert type(notes_data) == annotations.NoteData assert type(notes_data.intervals) is np.ndarray assert type(notes_data.pitches) is np.ndarray assert type(notes_data.confidence) is np.ndarray assert type(tuning_frequency) is float # check tuning frequency assert tuning_frequency == 451.0654725341684 # check values assert np.array_equal( notes_data.intervals[:, 0], np.array([0.216667, 0.65, 2.183333, 2.566667]) ) assert np.array_equal( notes_data.intervals[:, 1], np.array([0.65, 1.666667, 2.566666, 2.9]) ) assert np.array_equal( notes_data.pitches, np.array( [388.8382625732775, 411.9597888711769, 388.8382625732775, 411.9597888711769] ), ) assert np.array_equal( notes_data.confidence, np.array( [ 0.018007, 0.010794, 0.00698, 0.03265, ] ), ) def test_load_audio(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) track = dataset.track(default_trackid) audio_path = track.audio_path audio, sr = tonas.load_audio(audio_path) assert sr == 44100 assert type(audio) is np.ndarray def test_metadata(): default_trackid = "01-D_AMairena" dataset = tonas.Dataset(TEST_DATA_HOME) metadata = dataset._metadata assert metadata[default_trackid] == { "title": "En el barrio de Triana", "style": "Debla", "singer": "<NAME>", }
[ "mirdata.datasets.tonas.Dataset", "mirdata.datasets.tonas.load_audio", "mirdata.datasets.tonas._load_tuning_frequency", "mirdata.datasets.tonas.load_f0", "numpy.array", "tests.test_utils.run_track_tests", "mirdata.datasets.tonas.load_notes" ]
[((260, 289), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (273, 289), False, 'from mirdata.datasets import tonas\n'), ((1137, 1205), 'tests.test_utils.run_track_tests', 'run_track_tests', (['track', 'expected_attributes', 'expected_property_types'], {}), '(track, expected_attributes, expected_property_types)\n', (1152, 1205), False, 'from tests.test_utils import run_track_tests\n'), ((1280, 1309), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (1293, 1309), False, 'from mirdata.datasets import tonas\n'), ((2749, 2778), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (2762, 2778), False, 'from mirdata.datasets import tonas\n'), ((2874, 2902), 'mirdata.datasets.tonas.load_f0', 'tonas.load_f0', (['f0_path', '(True)'], {}), '(f0_path, True)\n', (2887, 2902), False, 'from mirdata.datasets import tonas\n'), ((2927, 2956), 'mirdata.datasets.tonas.load_f0', 'tonas.load_f0', (['f0_path', '(False)'], {}), '(f0_path, False)\n', (2940, 2956), False, 'from mirdata.datasets import tonas\n'), ((4739, 4768), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (4752, 4768), False, 'from mirdata.datasets import tonas\n'), ((4863, 4891), 'mirdata.datasets.tonas.load_notes', 'tonas.load_notes', (['notes_path'], {}), '(notes_path)\n', (4879, 4891), False, 'from mirdata.datasets import tonas\n'), ((4915, 4955), 'mirdata.datasets.tonas._load_tuning_frequency', 'tonas._load_tuning_frequency', (['notes_path'], {}), '(notes_path)\n', (4943, 4955), False, 'from mirdata.datasets import tonas\n'), ((6030, 6059), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (6043, 6059), False, 'from mirdata.datasets import tonas\n'), ((6153, 6181), 'mirdata.datasets.tonas.load_audio', 'tonas.load_audio', (['audio_path'], {}), '(audio_path)\n', (6169, 6181), False, 'from mirdata.datasets import tonas\n'), ((6317, 6346), 'mirdata.datasets.tonas.Dataset', 'tonas.Dataset', (['TEST_DATA_HOME'], {}), '(TEST_DATA_HOME)\n', (6330, 6346), False, 'from mirdata.datasets import tonas\n'), ((3647, 3685), 'numpy.array', 'np.array', (['[0.197, 0.209, 0.221, 0.232]'], {}), '([0.197, 0.209, 0.221, 0.232])\n', (3655, 3685), True, 'import numpy as np\n'), ((3759, 3801), 'numpy.array', 'np.array', (['[0.0, 379.299, 379.299, 379.299]'], {}), '([0.0, 379.299, 379.299, 379.299])\n', (3767, 3801), True, 'import numpy as np\n'), ((3880, 3910), 'numpy.array', 'np.array', (['[0.0, 1.0, 1.0, 1.0]'], {}), '([0.0, 1.0, 1.0, 1.0])\n', (3888, 3910), True, 'import numpy as np\n'), ((3992, 4043), 'numpy.array', 'np.array', (['[3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05]'], {}), '([3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05])\n', (4000, 4043), True, 'import numpy as np\n'), ((4145, 4183), 'numpy.array', 'np.array', (['[0.197, 0.209, 0.221, 0.232]'], {}), '([0.197, 0.209, 0.221, 0.232])\n', (4153, 4183), True, 'import numpy as np\n'), ((4265, 4303), 'numpy.array', 'np.array', (['[0.0, 0.0, 143.918, 143.918]'], {}), '([0.0, 0.0, 143.918, 143.918])\n', (4273, 4303), True, 'import numpy as np\n'), ((4486, 4516), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0, 1.0]'], {}), '([0.0, 0.0, 1.0, 1.0])\n', (4494, 4516), True, 'import numpy as np\n'), ((4598, 4649), 'numpy.array', 'np.array', (['[3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05]'], {}), '([3.09e-06, 2.86e-06, 7.15e-06, 1.545e-05])\n', (4606, 4649), True, 'import numpy as np\n'), ((5387, 5433), 'numpy.array', 'np.array', (['[0.216667, 0.65, 2.183333, 2.566667]'], {}), '([0.216667, 0.65, 2.183333, 2.566667])\n', (5395, 5433), True, 'import numpy as np\n'), ((5503, 5544), 'numpy.array', 'np.array', (['[0.65, 1.666667, 2.566666, 2.9]'], {}), '([0.65, 1.666667, 2.566666, 2.9])\n', (5511, 5544), True, 'import numpy as np\n'), ((5614, 5705), 'numpy.array', 'np.array', (['[388.8382625732775, 411.9597888711769, 388.8382625732775, 411.9597888711769]'], {}), '([388.8382625732775, 411.9597888711769, 388.8382625732775, \n 411.9597888711769])\n', (5622, 5705), True, 'import numpy as np\n'), ((5796, 5844), 'numpy.array', 'np.array', (['[0.018007, 0.010794, 0.00698, 0.03265]'], {}), '([0.018007, 0.010794, 0.00698, 0.03265])\n', (5804, 5844), True, 'import numpy as np\n')]
import argparse import csv import matplotlib import matplotlib.ticker as tck import matplotlib.pyplot as plt import numpy as np # Matplotlib export settings matplotlib.use('pgf') import matplotlib.pyplot as plt matplotlib.rcParams.update({ 'pgf.texsystem': 'pdflatex', 'font.size': 10, 'font.family': 'serif', # use serif/main font for text elements 'text.usetex': True, # use inline math for ticks 'pgf.rcfonts': False # don't setup fonts from rc parameters }) # Main function def main(args): C_zero = 7.5240e-03 * 1e-6 # Farads/km C_pos = 1.2027e-02 * 1e-6 # Farads/km G_zero = 2.0000e-08 # Mhos/km G_pos = 2.0000e-08 # Mhos/km length = 300 # km FREQ_INDEX = 0 R_ZERO_INDEX = 1 L_ZERO_INDEX = 2 R_POS_INDEX = 3 L_POS_INDEX = 4 MAGNITUDE_INDEX = 0 PHASE_INDEX = 1 # prepopulate data with a list of five empty lists data = [[] for i in range(5)] # Read in PSCAD .CSV data print('*** Opening assignment 4 CSV data file...') with open('data_assign04.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 # Read in row data for row in csv_reader: if line_count == 0: print('Column names are: ' + ', '.join(row)) line_count += 1 else: data[FREQ_INDEX].append(float(row[0])) data[R_ZERO_INDEX].append(float(row[1])) # Ohms/km data[L_ZERO_INDEX].append(float(row[2]) * 1e-3) # Henries/km data[R_POS_INDEX].append(float(row[3])) # Ohms/km data[L_POS_INDEX].append(float(row[4]) * 1e-3) # Henries/km line_count += 1 # Figure out when break switched print('Processed ' + str(line_count) + ' lines.') num_data_points = len(data[FREQ_INDEX]) # Prepare values for Z(w) magnitude and phase impedance_zero = [[],[]] impedance_pos = [[],[]] for index in range(num_data_points): omega = 2*np.pi*data[FREQ_INDEX][index] impedance_zero_val = np.sqrt((data[R_ZERO_INDEX][index] + (1j*omega*data[L_ZERO_INDEX][index]))/(G_zero + (1j*omega*C_zero))) impedance_pos_val = np.sqrt((data[R_POS_INDEX][index] + (1j*omega*data[L_POS_INDEX][index])) /(G_pos + (1j*omega*C_pos))) # print("F: " + str(data[FREQ_INDEX][index])) # print("Omega: " + str(omega)) # print("R_0: " + str(data[R_ZERO_INDEX][index])) # print("L_0: " + str(data[L_ZERO_INDEX][index])) # print("C_0: " + str(C_zero)) # print("G_0: " + str(G_zero)) # print("R_+: " + str(data[R_POS_INDEX][index])) # print("L_+: " + str(data[L_POS_INDEX][index])) # print("C_+: " + str(C_pos)) # print("G_+: " + str(G_pos)) # print("Zc_0: " + str(impedance_zero_val)) # print("Zc_0 mag: " + str(np.absolute(impedance_zero_val))) # print("Zc_+: " + str(impedance_pos_val)) # print("Zc_+ mag: " + str(np.absolute(impedance_pos_val))) impedance_zero[MAGNITUDE_INDEX].append(np.absolute(impedance_zero_val)) impedance_zero[PHASE_INDEX].append(np.angle(impedance_zero_val)) impedance_pos[MAGNITUDE_INDEX].append(np.absolute(impedance_pos_val)) impedance_pos[PHASE_INDEX].append(np.angle(impedance_pos_val)) print("\r\n") # Prepare values for propagation function magnitude and phase as well # Prepare values for attenuation alpha(w) (nepers/km) # Prepare values for phase displacement beta(w) (radians/km) # Prepare values for propagation speed a(w) (km/s) propagation_zero = [[],[]] propagation_pos = [[],[]] attenuation_zero = [] attenuation_pos = [] phase_zero = [] phase_pos = [] propagation_speed_zero = [] propagation_speed_pos = [] for index in range(num_data_points): omega = 2*np.pi*data[FREQ_INDEX][index] gamma_zero = np.sqrt((data[R_ZERO_INDEX][index] + 1j*omega*data[L_ZERO_INDEX][index])*(G_zero + 1j*omega*C_zero)) gamma_pos = np.sqrt((data[R_POS_INDEX][index] + 1j*omega*data[L_POS_INDEX][index])*(G_pos + 1j*omega*C_pos)) # propagation function magnitude and phase propagation_zero[MAGNITUDE_INDEX].append(np.absolute(np.exp(-1*gamma_zero*length))) propagation_zero[PHASE_INDEX].append(-np.imag(gamma_zero)*length) propagation_pos[MAGNITUDE_INDEX].append(np.absolute(np.exp(-1*gamma_pos*length))) propagation_pos[PHASE_INDEX].append(-np.imag(gamma_pos)*length) # attenuation (real component of gamma) (nepers/km) attenuation_zero.append(np.real(gamma_zero)) attenuation_pos.append(np.real(gamma_pos)) # phase displacement (imaginary component of gamma) (radians/km) phase_zero.append(np.imag(gamma_zero)) phase_pos.append(np.imag(gamma_pos)) # propagation speed (omega/phase_displacement) (km/s) propagation_speed_zero.append(omega/phase_zero[-1]) propagation_speed_pos.append(omega/phase_pos[-1]) # propagation_speed_zero.append(1/np.sqrt(data[L_ZERO_INDEX][index]*C_zero)) # propagation_speed_pos.append(1/np.sqrt(data[L_POS_INDEX][index]*C_pos)) # Plots for publication legend_font_size = 6 # Plot Z(w) magnitude and phase fig, ax = plt.subplots(2) ax[0].plot(data[FREQ_INDEX], impedance_zero[MAGNITUDE_INDEX], color='b', label='zero sequence') ax[0].plot(data[FREQ_INDEX], impedance_pos[MAGNITUDE_INDEX], color='g', label='positive sequence') ax[0].set(xlabel='Frequency $Hz$', ylabel='Magnitude ($\Omega/km$)', title='$Z_c$ - Magnitude vs. Frequency') ax[0].grid() ax[0].set_xscale('log') ax[0].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) ax[1].plot(data[FREQ_INDEX], impedance_zero[PHASE_INDEX], color='b', label='zero sequence') ax[1].plot(data[FREQ_INDEX], impedance_pos[PHASE_INDEX], color='g', label='positive sequence') ax[1].yaxis.set_major_formatter(tck.FormatStrFormatter('%1.1f $\pi$')) ax[1].yaxis.set_major_locator(tck.MultipleLocator(base=1/5)) ax[1].set(xlabel='Frequency $Hz$', ylabel='Phase ($rad$)', title='$Z_c$ - Phase vs. Frequency') ax[1].grid() ax[1].set_xscale('log') ax[1].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,8) fig.tight_layout() fig.savefig('zc_magnitude_phase_plots.pgf') fig.savefig('zc_magnitude_phase_plots.png') # Plot propagation function magnitude and phase fig, ax = plt.subplots(2) ax[0].plot(data[FREQ_INDEX], propagation_zero[MAGNITUDE_INDEX], color='b', label='zero sequence') ax[0].plot(data[FREQ_INDEX], propagation_pos[MAGNITUDE_INDEX], color='g', label='positive sequence') ax[0].set(xlabel='Frequency $Hz$', ylabel=r'Magnitude $\left|e^{-\gamma{}l}\right|$', title='$e^{-\gamma{}l}$ - Magnitude vs. Frequency') ax[0].grid() ax[0].set_xscale('log') ax[0].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) ax[1].plot(data[FREQ_INDEX], propagation_zero[PHASE_INDEX], color='b', label='zero sequence') ax[1].plot(data[FREQ_INDEX], propagation_pos[PHASE_INDEX], color='g', label='positive sequence') ax[1].set(xlabel='Frequency $Hz$', ylabel=r'Phase $\phi{}=\beta{}l=\omega{}\tau$ ($rad$)', title='$e^{-\gamma{}l}$ - Phase vs. Frequency') ax[1].grid() ax[1].set_xscale('log') ax[1].legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,8) fig.tight_layout() fig.savefig('prop_magnitude_phase_plots.pgf') fig.savefig('prop_magnitude_phase_plots.png') # Plot propagation function magnitude and phase (no long for frequency) fig, ax = plt.subplots(1) ax.plot(data[FREQ_INDEX], propagation_zero[PHASE_INDEX], color='b', label='zero sequence') ax.plot(data[FREQ_INDEX], propagation_pos[PHASE_INDEX], color='g', label='positive sequence') ax.set(xlabel='Frequency $Hz$', ylabel=r'Phase $\phi{}=\beta{}l=\omega{}\tau$ ($rad$)', title='$e^{-\gamma{}l}$ - Phase vs. Frequency') ax.grid() ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,3.5) fig.tight_layout() fig.savefig('prop_phase_plot_nolog.pgf') fig.savefig('prop_phase_plot_nolog.png') # Plot attenuation (real component of gamma) (nepers/km) fig, ax = plt.subplots() ax.plot(data[FREQ_INDEX], attenuation_zero, color='b', label='zero sequence') ax.plot(data[FREQ_INDEX], attenuation_pos, color='g', label='positive sequence') ax.set(xlabel='Frequency $Hz$', ylabel=r'Attenuation $\alpha{}(\omega)$ $(nepers/km)$', title=r'Attenuation $\alpha{}(\omega)$ vs. Frequency') ax.grid() ax.set_xscale('log') ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,3.5) fig.tight_layout() fig.savefig('attenuation_plots.pgf') fig.savefig('attenuation_plots.png') # Plot phase displacement beta(w) (radians/km) fig, ax = plt.subplots() ax.plot(data[FREQ_INDEX], phase_zero, color='b', label='zero sequence') ax.plot(data[FREQ_INDEX], phase_pos, color='g', label='positive sequence') ax.set(xlabel='Frequency $Hz$', ylabel=r'Phase Displacement $\beta{}(\omega)$ $(rad/km)$', title=r'Phase Displacement $\beta{}(\omega)$ vs. Frequency') ax.grid() ax.set_xscale('log') ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,3.5) fig.tight_layout() fig.savefig('phase_displacement_plots.pgf') fig.savefig('phase_displacement_plots.png') # Plot propagation speed a(w) (km/s) fig, ax = plt.subplots() ax.plot(data[FREQ_INDEX], propagation_speed_zero, color='b', label='zero sequence') ax.plot(data[FREQ_INDEX], propagation_speed_pos, color='g', label='positive sequence') ax.set(xlabel='Frequency $Hz$', ylabel=r'Propagation Speed $a(\omega)$ $(km/s)$', title=r'Propagation Speed $a(\omega)$ vs. Frequency') ax.grid() ax.set_xscale('log') ax.legend(loc='best', prop={'size':legend_font_size}, fancybox=True, shadow=True) fig.set_size_inches(6.5,3.5) fig.tight_layout() fig.savefig('propagation_speed_plots.pgf') fig.savefig('propagation_speed_plots.png') if __name__ == '__main__': # the following sets up the argument parser for the program parser = argparse.ArgumentParser(description='Assignment 4 solution generator') args = parser.parse_args() main(args)
[ "numpy.sqrt", "argparse.ArgumentParser", "matplotlib.rcParams.update", "matplotlib.use", "matplotlib.ticker.MultipleLocator", "numpy.absolute", "numpy.imag", "numpy.angle", "numpy.exp", "numpy.real", "matplotlib.ticker.FormatStrFormatter", "csv.reader", "matplotlib.pyplot.subplots" ]
[((160, 181), 'matplotlib.use', 'matplotlib.use', (['"""pgf"""'], {}), "('pgf')\n", (174, 181), False, 'import matplotlib\n'), ((214, 359), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'pgf.texsystem': 'pdflatex', 'font.size': 10, 'font.family': 'serif',\n 'text.usetex': True, 'pgf.rcfonts': False}"], {}), "({'pgf.texsystem': 'pdflatex', 'font.size': 10,\n 'font.family': 'serif', 'text.usetex': True, 'pgf.rcfonts': False})\n", (240, 359), False, 'import matplotlib\n'), ((5331, 5346), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (5343, 5346), True, 'import matplotlib.pyplot as plt\n'), ((6585, 6600), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (6597, 6600), True, 'import matplotlib.pyplot as plt\n'), ((7805, 7820), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (7817, 7820), True, 'import matplotlib.pyplot as plt\n'), ((8476, 8490), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8488, 8490), True, 'import matplotlib.pyplot as plt\n'), ((9134, 9148), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9146, 9148), True, 'import matplotlib.pyplot as plt\n'), ((9793, 9807), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9805, 9807), True, 'import matplotlib.pyplot as plt\n'), ((10507, 10577), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Assignment 4 solution generator"""'}), "(description='Assignment 4 solution generator')\n", (10530, 10577), False, 'import argparse\n'), ((1094, 1129), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (1104, 1129), False, 'import csv\n'), ((2097, 2216), 'numpy.sqrt', 'np.sqrt', (['((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][index]) / (\n G_zero + 1.0j * omega * C_zero))'], {}), '((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][\n index]) / (G_zero + 1.0j * omega * C_zero))\n', (2104, 2216), True, 'import numpy as np\n'), ((2231, 2346), 'numpy.sqrt', 'np.sqrt', (['((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]) / (\n G_pos + 1.0j * omega * C_pos))'], {}), '((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]\n ) / (G_pos + 1.0j * omega * C_pos))\n', (2238, 2346), True, 'import numpy as np\n'), ((3954, 4073), 'numpy.sqrt', 'np.sqrt', (['((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][index]) * (\n G_zero + 1.0j * omega * C_zero))'], {}), '((data[R_ZERO_INDEX][index] + 1.0j * omega * data[L_ZERO_INDEX][\n index]) * (G_zero + 1.0j * omega * C_zero))\n', (3961, 4073), True, 'import numpy as np\n'), ((4075, 4190), 'numpy.sqrt', 'np.sqrt', (['((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]) * (\n G_pos + 1.0j * omega * C_pos))'], {}), '((data[R_POS_INDEX][index] + 1.0j * omega * data[L_POS_INDEX][index]\n ) * (G_pos + 1.0j * omega * C_pos))\n', (4082, 4190), True, 'import numpy as np\n'), ((6030, 6068), 'matplotlib.ticker.FormatStrFormatter', 'tck.FormatStrFormatter', (['"""%1.1f $\\\\pi$"""'], {}), "('%1.1f $\\\\pi$')\n", (6052, 6068), True, 'import matplotlib.ticker as tck\n'), ((6103, 6134), 'matplotlib.ticker.MultipleLocator', 'tck.MultipleLocator', ([], {'base': '(1 / 5)'}), '(base=1 / 5)\n', (6122, 6134), True, 'import matplotlib.ticker as tck\n'), ((3100, 3131), 'numpy.absolute', 'np.absolute', (['impedance_zero_val'], {}), '(impedance_zero_val)\n', (3111, 3131), True, 'import numpy as np\n'), ((3176, 3204), 'numpy.angle', 'np.angle', (['impedance_zero_val'], {}), '(impedance_zero_val)\n', (3184, 3204), True, 'import numpy as np\n'), ((3252, 3282), 'numpy.absolute', 'np.absolute', (['impedance_pos_val'], {}), '(impedance_pos_val)\n', (3263, 3282), True, 'import numpy as np\n'), ((3326, 3353), 'numpy.angle', 'np.angle', (['impedance_pos_val'], {}), '(impedance_pos_val)\n', (3334, 3353), True, 'import numpy as np\n'), ((4643, 4662), 'numpy.real', 'np.real', (['gamma_zero'], {}), '(gamma_zero)\n', (4650, 4662), True, 'import numpy as np\n'), ((4695, 4713), 'numpy.real', 'np.real', (['gamma_pos'], {}), '(gamma_pos)\n', (4702, 4713), True, 'import numpy as np\n'), ((4814, 4833), 'numpy.imag', 'np.imag', (['gamma_zero'], {}), '(gamma_zero)\n', (4821, 4833), True, 'import numpy as np\n'), ((4860, 4878), 'numpy.imag', 'np.imag', (['gamma_pos'], {}), '(gamma_pos)\n', (4867, 4878), True, 'import numpy as np\n'), ((4284, 4316), 'numpy.exp', 'np.exp', (['(-1 * gamma_zero * length)'], {}), '(-1 * gamma_zero * length)\n', (4290, 4316), True, 'import numpy as np\n'), ((4449, 4480), 'numpy.exp', 'np.exp', (['(-1 * gamma_pos * length)'], {}), '(-1 * gamma_pos * length)\n', (4455, 4480), True, 'import numpy as np\n'), ((4361, 4380), 'numpy.imag', 'np.imag', (['gamma_zero'], {}), '(gamma_zero)\n', (4368, 4380), True, 'import numpy as np\n'), ((4524, 4542), 'numpy.imag', 'np.imag', (['gamma_pos'], {}), '(gamma_pos)\n', (4531, 4542), True, 'import numpy as np\n')]
import unittest from cosymlib import file_io from numpy import testing from cosymlib.molecule.geometry import Geometry import os data_dir = os.path.join(os.path.dirname(__file__), 'data') class TestSymgroupFchk(unittest.TestCase): def setUp(self): self._structure = file_io.read_generic_structure_file(data_dir + '/wfnsym/tih4_5d.fchk') self._geometry = self._structure.geometry def test_symmetry_measure(self): # print(self._structure.geometry) measure = self._geometry.get_symmetry_measure('C3', central_atom=1) self.assertAlmostEqual(measure, 0) class TestSymgroupCycles(unittest.TestCase): def setUp(self): self._geometry = Geometry(positions=[[ 0.506643354, -1.227657970, 0.000000000], [ 1.303068499, 0.000000000, 0.000000000], [ 0.506643354, 1.227657970, 0.000000000], [-0.926250976, 0.939345948, 0.000000000], [-0.926250976, -0.939345948, 0.000000000]], # name='test', symbols=['C', 'C', 'C', 'C', 'C'], connectivity_thresh=1.5, ) def test_symmetry_measure(self): measure = self._geometry.get_symmetry_measure('C5') self.assertAlmostEqual(measure, 0.8247502, places=6) measure = self._geometry.get_symmetry_measure('C2') self.assertAlmostEqual(measure, 0.0, places=6) measure = self._geometry.get_symmetry_measure('C3') self.assertAlmostEqual(measure, 33.482451, places=6) #def test_symmetry_measure_permutation(self): # measure = self._geometry.get_symmetry_measure('C5', fix_permutation=True) # self.assertAlmostEqual(measure, 0.8247502, places=6) def test_symmetry_nearest(self): nearest = self._geometry.get_symmetry_nearest_structure('C5').get_positions() # print(nearest) reference = [[ 4.05078542e-01, -1.24670356e+00, 0.00000000e+00], [ 1.31086170e+00, -1.33226763e-16, 0.00000000e+00], [ 4.05078542e-01, 1.24670356e+00, 0.00000000e+00], [-1.06050939e+00, 7.70505174e-01, 0.00000000e+00], [-1.06050939e+00, -7.70505174e-01, 0.00000000e+00]] testing.assert_array_almost_equal(nearest, reference, decimal=6)
[ "os.path.dirname", "numpy.testing.assert_array_almost_equal", "cosymlib.molecule.geometry.Geometry", "cosymlib.file_io.read_generic_structure_file" ]
[((155, 180), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (170, 180), False, 'import os\n'), ((283, 353), 'cosymlib.file_io.read_generic_structure_file', 'file_io.read_generic_structure_file', (["(data_dir + '/wfnsym/tih4_5d.fchk')"], {}), "(data_dir + '/wfnsym/tih4_5d.fchk')\n", (318, 353), False, 'from cosymlib import file_io\n'), ((697, 950), 'cosymlib.molecule.geometry.Geometry', 'Geometry', ([], {'positions': '[[0.506643354, -1.22765797, 0.0], [1.303068499, 0.0, 0.0], [0.506643354, \n 1.22765797, 0.0], [-0.926250976, 0.939345948, 0.0], [-0.926250976, -\n 0.939345948, 0.0]]', 'symbols': "['C', 'C', 'C', 'C', 'C']", 'connectivity_thresh': '(1.5)'}), "(positions=[[0.506643354, -1.22765797, 0.0], [1.303068499, 0.0, 0.0\n ], [0.506643354, 1.22765797, 0.0], [-0.926250976, 0.939345948, 0.0], [-\n 0.926250976, -0.939345948, 0.0]], symbols=['C', 'C', 'C', 'C', 'C'],\n connectivity_thresh=1.5)\n", (705, 950), False, 'from cosymlib.molecule.geometry import Geometry\n'), ((2444, 2508), 'numpy.testing.assert_array_almost_equal', 'testing.assert_array_almost_equal', (['nearest', 'reference'], {'decimal': '(6)'}), '(nearest, reference, decimal=6)\n', (2477, 2508), False, 'from numpy import testing\n')]
import matplotlib.pyplot as plt import numpy as np def plot_chains(chain, fileout=None, tracers=0, labels=None, delay=0, ymax=200000, thin=100, num_xticks=7, truths=None): if chain.ndim < 3: print("You must include a multiple chains") return n_chains, length, n_var = chain.shape print(n_chains, length, n_var) if (labels is not None) and (len(labels) != n_var): print("You must provide the correct number of variable labels.") return if (truths is not None) and (len(truths) != n_var): print("You must provide the correct number of truths.") return fig, ax = plt.subplots(int(n_var/2) + n_var%2, 2, figsize=(8, 0.8*n_var)) plt.subplots_adjust(left=0.09, bottom=0.07, right=0.96, top=0.96, hspace=0) color = np.empty(n_chains, dtype=str) color[:] = 'k' alpha = 0.01 * np.ones(n_chains) zorder = np.ones(n_chains) if tracers > 0: idx = np.random.choice(n_chains, tracers, replace=False) color[idx] = 'r' alpha[idx] = 1.0 zorder[idx] = 2.0 for i in range(n_var): ix = int(i/2) iy = i%2 for j in range(n_chains): xvals = (np.arange(length)*thin - delay) / 1000.0 ax[ix,iy].plot(xvals, chain[j,:,i], color=color[j], alpha=alpha[j], rasterized=True, zorder=zorder[j]) if ymax is None: ymax = (length*thin-delay) ax[ix,iy].set_xlim(-delay/1000.0, ymax/1000.0) ax[ix,iy].set_xticks(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks)) ax[ix,iy].set_xticklabels([]) # Add y-axis labels if provided by use if labels is not None: ax[ix,iy].set_ylabel(labels[i]) if delay != 0: ax[ix,iy].axvline(0, color='k', linestyle='dashed', linewidth=2.0, zorder=9) if truths is not None: ax[ix,iy].axhline(truths[i], color='C0', linestyle='dashed', linewidth=2.0, zorder=10) # plt.tight_layout() ax[-1,0].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U')) ax[-1,1].set_xticklabels(np.linspace(-delay/1000.0,ymax/1000.0,num_xticks).astype('i8').astype('U')) ax[-1,0].set_xlabel(r'Steps ($\times$1000)') ax[-1,1].set_xlabel(r'Steps ($\times$1000)') if fileout is None: plt.show() else: plt.savefig(fileout, rasterized=True) return # from dart_board import plotting # import numpy as np # import pickle # chains = pickle.load(open("../data/HMXB_chain.obj", "rb")) # plotting.plot_chains(chains)
[ "matplotlib.pyplot.savefig", "numpy.ones", "numpy.arange", "numpy.random.choice", "numpy.linspace", "numpy.empty", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.show" ]
[((708, 783), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.09)', 'bottom': '(0.07)', 'right': '(0.96)', 'top': '(0.96)', 'hspace': '(0)'}), '(left=0.09, bottom=0.07, right=0.96, top=0.96, hspace=0)\n', (727, 783), True, 'import matplotlib.pyplot as plt\n'), ((798, 827), 'numpy.empty', 'np.empty', (['n_chains'], {'dtype': 'str'}), '(n_chains, dtype=str)\n', (806, 827), True, 'import numpy as np\n'), ((897, 914), 'numpy.ones', 'np.ones', (['n_chains'], {}), '(n_chains)\n', (904, 914), True, 'import numpy as np\n'), ((866, 883), 'numpy.ones', 'np.ones', (['n_chains'], {}), '(n_chains)\n', (873, 883), True, 'import numpy as np\n'), ((949, 999), 'numpy.random.choice', 'np.random.choice', (['n_chains', 'tracers'], {'replace': '(False)'}), '(n_chains, tracers, replace=False)\n', (965, 999), True, 'import numpy as np\n'), ((2285, 2295), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2293, 2295), True, 'import matplotlib.pyplot as plt\n'), ((2314, 2351), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fileout'], {'rasterized': '(True)'}), '(fileout, rasterized=True)\n', (2325, 2351), True, 'import matplotlib.pyplot as plt\n'), ((1494, 1549), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (1505, 1549), True, 'import numpy as np\n'), ((1200, 1217), 'numpy.arange', 'np.arange', (['length'], {}), '(length)\n', (1209, 1217), True, 'import numpy as np\n'), ((1972, 2027), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (1983, 2027), True, 'import numpy as np\n'), ((2077, 2132), 'numpy.linspace', 'np.linspace', (['(-delay / 1000.0)', '(ymax / 1000.0)', 'num_xticks'], {}), '(-delay / 1000.0, ymax / 1000.0, num_xticks)\n', (2088, 2132), True, 'import numpy as np\n')]
## ## Evaluation Script ## import numpy as np import time from sample_model import Model from data_loader import data_loader from generator import Generator def evaluate(label_indices = {'brick': 0, 'ball': 1, 'cylinder': 2}, channel_means = np.array([147.12697, 160.21092, 167.70029]), data_path = '../data', minibatch_size = 32, num_batches_to_test = 10, checkpoint_dir = 'tf_data/sample_model'): print("1. Loading data") data = data_loader(label_indices = label_indices, channel_means = channel_means, train_test_split = 0.5, data_path = data_path) print("2. Instantiating the model") M = Model(mode = 'test') #Evaluate on test images: GT = Generator(data.test.X, data.test.y, minibatch_size = minibatch_size) num_correct = 0 num_total = 0 print("3. Evaluating on test images") for i in range(num_batches_to_test): GT.generate() yhat = M.predict(X = GT.X, checkpoint_dir = checkpoint_dir) correct_predictions = (np.argmax(yhat, axis = 1) == np.argmax(GT.y, axis = 1)) num_correct += np.sum(correct_predictions) num_total += len(correct_predictions) accuracy = round(num_correct/num_total,4) return accuracy def calculate_score(accuracy): score = 0 if accuracy >= 0.92: score = 10 elif accuracy >= 0.9: score = 9 elif accuracy >= 0.85: score = 8 elif accuracy >= 0.8: score = 7 elif accuracy >= 0.75: score = 6 elif accuracy >= 0.70: score = 5 else: score = 4 return score if __name__ == '__main__': program_start = time.time() accuracy = evaluate() score = calculate_score(accuracy) program_end = time.time() total_time = round(program_end - program_start,2) print() print("Execution time (seconds) = ", total_time) print('Accuracy = ' + str(accuracy)) print("Score = ", score) print()
[ "generator.Generator", "sample_model.Model", "data_loader.data_loader", "numpy.argmax", "numpy.array", "numpy.sum", "time.time" ]
[((258, 301), 'numpy.array', 'np.array', (['[147.12697, 160.21092, 167.70029]'], {}), '([147.12697, 160.21092, 167.70029])\n', (266, 301), True, 'import numpy as np\n'), ((513, 629), 'data_loader.data_loader', 'data_loader', ([], {'label_indices': 'label_indices', 'channel_means': 'channel_means', 'train_test_split': '(0.5)', 'data_path': 'data_path'}), '(label_indices=label_indices, channel_means=channel_means,\n train_test_split=0.5, data_path=data_path)\n', (524, 629), False, 'from data_loader import data_loader\n'), ((745, 763), 'sample_model.Model', 'Model', ([], {'mode': '"""test"""'}), "(mode='test')\n", (750, 763), False, 'from sample_model import Model\n'), ((806, 872), 'generator.Generator', 'Generator', (['data.test.X', 'data.test.y'], {'minibatch_size': 'minibatch_size'}), '(data.test.X, data.test.y, minibatch_size=minibatch_size)\n', (815, 872), False, 'from generator import Generator\n'), ((1755, 1766), 'time.time', 'time.time', ([], {}), '()\n', (1764, 1766), False, 'import time\n'), ((1849, 1860), 'time.time', 'time.time', ([], {}), '()\n', (1858, 1860), False, 'import time\n'), ((1206, 1233), 'numpy.sum', 'np.sum', (['correct_predictions'], {}), '(correct_predictions)\n', (1212, 1233), True, 'import numpy as np\n'), ((1127, 1150), 'numpy.argmax', 'np.argmax', (['yhat'], {'axis': '(1)'}), '(yhat, axis=1)\n', (1136, 1150), True, 'import numpy as np\n'), ((1156, 1179), 'numpy.argmax', 'np.argmax', (['GT.y'], {'axis': '(1)'}), '(GT.y, axis=1)\n', (1165, 1179), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import distance from matplotlib import style from clustering_algorithms.affinity_propagation import AffinityPropagation from clustering_algorithms.custom_k_means import KMeans from clustering_algorithms.custom_mean_shift import MeanShift from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition from clustering_algorithms.dbscan import DbScan from prepare_data.format_sequences import format_sequences_from_student from utils.e_mine import e_mine_find_common_scanpath from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, \ needleman_wunsch_with_penalty import numpy as np # def initialize_2D_number_data_and_plot_them(): # number_data = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11], [8, 2], [10, 2], [9, 3]]) # # plot data # plt.scatter(number_data[:, 0], number_data[:, 1]) # plt.show() # return number_data # # # def test_k_means_with_numbers_then_plot_results(): # clf = KMeans(k=3) # clf.fit(number_data) # # for centroid in clf.centroids: # plt.scatter(clf.centroids[centroid][0], clf.centroids[centroid][1], # marker="o", color="k", s=150, linewidths=5) # # for classification in clf.classifications: # color = colors[classification] # for featureset in clf.classifications[classification]: # plt.scatter(featureset[0], featureset[1], marker="x", color=color, # s=150, linewidths=5) # plt.show() # # # def test_mean_shift_with_numbers_then_plot_results(): # clf_ms = MeanShift() # clf_ms.fit(number_data) # plt.scatter(number_data[:, 0], number_data[:, 1], s=150) # centroids = clf_ms.centroids # for c in centroids: # plt.scatter(centroids[c][0], centroids[c][1], color='k', marker="*", s=150) # plt.show() def initialize_string_sequences(student_name): # print(format_sequences_from_student(student_name)) return format_sequences_from_student(student_name) # return ["ACCAEF", "ACCEF", "AACF", "CCCEF", "CCAACCF", "CCACF"] def print_description(): print("***************************************************") print("NAME OF ALGORITHM") print("- *CLUSTER REPRESENTER* [CLUSTER MEMBER, CLUSTER MEMBER, CLUSTER MEMBER]") print("***************************************************") def test_and_print_results_string_k_means_with_levenshtein_distance(): kmeans_alg = KMeans(k=3, distance_function=distance.levenshtein, find_average_function=e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar) kmeans_alg.fit(string_data) print_k_means_results(kmeans_alg, "Levenshtein") def test_and_print_results_string_k_means_with_needleman_wunsch_distance(): kmeans_alg = KMeans(k=3, distance_function=needleman_wunsch, find_average_function=e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar) kmeans_alg.fit(string_data) print_k_means_results(kmeans_alg, "Needleman-Wunsch") def test_and_print_results_string_k_means_with_needleman_wunsch_distance_with_extra_penalty_points(): kmeans_alg = KMeans(k=3, distance_function=needleman_wunsch_with_penalty, find_average_function=e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar) kmeans_alg.fit(string_data) print_k_means_results(kmeans_alg, "Needleman-Wunsch with additional penalty") def print_k_means_results(kmeans_alg, distance_algorithm): centroid_cluster_map_kmeans = {} for i in range(0, len(kmeans_alg.centroids)): centroid_cluster_map_kmeans[kmeans_alg.centroids[i]] = kmeans_alg.classifications[i] print() print("K Means string edition with %s distance algorithm" % distance_algorithm) for centroid in centroid_cluster_map_kmeans: print(" - *%s* %s" % (centroid, centroid_cluster_map_kmeans[centroid])) def test_and_print_results_string_mean_shift_with_levenshtein_distance(): mean_shift_string_edition = MeanShiftStringEdition() mean_shift_string_edition.fit(string_data) print_mean_shift_results(mean_shift_string_edition, "Levenshtein") def test_and_print_results_string_mean_shift_with_needleman_wunsch_distance(): mean_shift_string_edition = MeanShiftStringEdition(distance_function=needleman_wunsch) mean_shift_string_edition.fit(string_data) print_mean_shift_results(mean_shift_string_edition, "Needleman-Wunsch") def test_and_print_results_string_mean_shift_with_needleman_wunsch_distance_with_extra_penalty_points(): mean_shift_string_edition = MeanShiftStringEdition(distance_function=needleman_wunsch_with_penalty) mean_shift_string_edition.fit(string_data) print_mean_shift_results(mean_shift_string_edition, "Needleman-Wunsch with additional penalty") def print_mean_shift_results(mean_shift_string_edition, distance_algorithm): print() print("Mean Shift string edition with %s distance algorithm" % distance_algorithm) for centroid in mean_shift_string_edition.centroids: print(" - *%s*" % mean_shift_string_edition.centroids[centroid]) def test_and_print_results_string_affinity_propagation_with_levenstein_distance(): data_as_array = np.asarray(string_data) lev_similarity_scores = -1 * np.array( [[distance.levenshtein(w1, w2) for w1 in data_as_array] for w2 in data_as_array]) affinity_propagation_alg = AffinityPropagation() affinity_propagation_alg.fit(lev_similarity_scores) print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Levenshtein") def test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance(): data_as_array = np.asarray(string_data) lev_similarity_scores = -1 * np.array( [[needleman_wunsch(w1, w2) for w1 in data_as_array] for w2 in data_as_array]) affinity_propagation_alg = AffinityPropagation() affinity_propagation_alg.fit(lev_similarity_scores) print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Needleman-Wunsch") def test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance_with_extra_penalty_points(): data_as_array = np.asarray(string_data) lev_similarity_scores = -1 * np.array( [[needleman_wunsch_with_penalty(w1, w2) for w1 in data_as_array] for w2 in data_as_array]) affinity_propagation_alg = AffinityPropagation() affinity_propagation_alg.fit(lev_similarity_scores) print_affinity_propagation_results(affinity_propagation_alg, data_as_array, "Needleman-Wunsch with additional penalty") def print_affinity_propagation_results(affinity_propagation_alg, data_as_array, distance_algorithm): print() print('Affinity Propagation with %s distance algorithm' % distance_algorithm) exemplar_features_map = affinity_propagation_alg.get_exemplars_and_their_features(data_as_array) for exemplar in exemplar_features_map: print(" - *%s* %s" % (exemplar, exemplar_features_map[exemplar])) def test_and_print_results_string_db_scan_with_levenstein_distance(): def lev_metric(x, y): i, j = int(x[0]), int(y[0]) # extract indices return distance.levenshtein(string_data[i], string_data[j]) db_scan = DbScan() db_scan.fit(lev_metric, string_data) print_db_scan_results(db_scan, "Levenshtein") def test_and_print_results_string_db_scan_with_needleman_wunsch_distance(): def lev_metric(x, y): i, j = int(x[0]), int(y[0]) # extract indices return needleman_wunsch(string_data[i], string_data[j]) db_scan = DbScan() db_scan.fit(lev_metric, string_data) print_db_scan_results(db_scan, "Needleman-Wunsch") def test_and_print_results_string_db_scan_with_needleman_wunsch_distance_with_extra_penalty_points(): def lev_metric(x, y): i, j = int(x[0]), int(y[0]) # extract indices return needleman_wunsch_with_penalty(string_data[i], string_data[j]) db_scan = DbScan() db_scan.fit(lev_metric, string_data) print_db_scan_results(db_scan, "Needleman-Wunsch with additional penalty") def print_db_scan_results(db_scan, distance_algorithm): print() print('DB Scan with %s distance algorithm' % distance_algorithm) for cluster in db_scan.get_clusters(): cluster_representer = e_mine_find_common_scanpath(db_scan.get_clusters()[cluster]) print(" - *%s* %s" % (cluster_representer, db_scan.get_clusters()[cluster])) ''' 1# Initialize number collection and plot style ''' # style.use('ggplot') # number_data = initialize_2D_number_data_and_plot_them() # colors = 10 * ["g", "r", "c", "b", "k"] ''' Test classification algorithms with numbers ''' # test_k_means_with_numbers_then_plot_results() # test_mean_shift_with_numbers_then_plot_results() ''' 2# Initialize string collection and print description on printed form ''' student_name = "student_1" string_data = initialize_string_sequences(student_name) print_description() ''' Test classification algorithms with strings ''' test_and_print_results_string_k_means_with_levenshtein_distance() test_and_print_results_string_k_means_with_needleman_wunsch_distance() test_and_print_results_string_k_means_with_needleman_wunsch_distance_with_extra_penalty_points() test_and_print_results_string_mean_shift_with_levenshtein_distance() test_and_print_results_string_mean_shift_with_needleman_wunsch_distance() test_and_print_results_string_mean_shift_with_needleman_wunsch_distance_with_extra_penalty_points() test_and_print_results_string_affinity_propagation_with_levenstein_distance() test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance() test_and_print_results_string_affinity_propagation_with_needleman_wunsch_distance_with_extra_penalty_points() test_and_print_results_string_db_scan_with_levenstein_distance() test_and_print_results_string_db_scan_with_needleman_wunsch_distance() test_and_print_results_string_db_scan_with_needleman_wunsch_distance_with_extra_penalty_points()
[ "utils.string_compare_algorithm.needleman_wunsch_with_penalty", "prepare_data.format_sequences.format_sequences_from_student", "numpy.asarray", "clustering_algorithms.affinity_propagation.AffinityPropagation", "clustering_algorithms.custom_k_means.KMeans", "distance.levenshtein", "clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition", "utils.string_compare_algorithm.needleman_wunsch", "clustering_algorithms.dbscan.DbScan" ]
[((2032, 2075), 'prepare_data.format_sequences.format_sequences_from_student', 'format_sequences_from_student', (['student_name'], {}), '(student_name)\n', (2061, 2075), False, 'from prepare_data.format_sequences import format_sequences_from_student\n'), ((2510, 2664), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'distance.levenshtein', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=distance.levenshtein, find_average_function=\n e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar)\n', (2516, 2664), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((2864, 3014), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'needleman_wunsch', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=needleman_wunsch, find_average_function=\n e_mine_find_common_scanpath, check_is_optimized_function=is_string_similar)\n', (2870, 3014), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((3245, 3411), 'clustering_algorithms.custom_k_means.KMeans', 'KMeans', ([], {'k': '(3)', 'distance_function': 'needleman_wunsch_with_penalty', 'find_average_function': 'e_mine_find_common_scanpath', 'check_is_optimized_function': 'is_string_similar'}), '(k=3, distance_function=needleman_wunsch_with_penalty,\n find_average_function=e_mine_find_common_scanpath,\n check_is_optimized_function=is_string_similar)\n', (3251, 3411), False, 'from clustering_algorithms.custom_k_means import KMeans\n'), ((4140, 4164), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {}), '()\n', (4162, 4164), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((4397, 4455), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {'distance_function': 'needleman_wunsch'}), '(distance_function=needleman_wunsch)\n', (4419, 4455), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((4719, 4790), 'clustering_algorithms.custom_mean_shift_string_edition.MeanShiftStringEdition', 'MeanShiftStringEdition', ([], {'distance_function': 'needleman_wunsch_with_penalty'}), '(distance_function=needleman_wunsch_with_penalty)\n', (4741, 4790), False, 'from clustering_algorithms.custom_mean_shift_string_edition import MeanShiftStringEdition\n'), ((5352, 5375), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (5362, 5375), True, 'import numpy as np\n'), ((5540, 5561), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (5559, 5561), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((5825, 5848), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (5835, 5848), True, 'import numpy as np\n'), ((6009, 6030), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (6028, 6030), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((6325, 6348), 'numpy.asarray', 'np.asarray', (['string_data'], {}), '(string_data)\n', (6335, 6348), True, 'import numpy as np\n'), ((6522, 6543), 'clustering_algorithms.affinity_propagation.AffinityPropagation', 'AffinityPropagation', ([], {}), '()\n', (6541, 6543), False, 'from clustering_algorithms.affinity_propagation import AffinityPropagation\n'), ((7376, 7384), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (7382, 7384), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((7714, 7722), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (7720, 7722), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((8096, 8104), 'clustering_algorithms.dbscan.DbScan', 'DbScan', ([], {}), '()\n', (8102, 8104), False, 'from clustering_algorithms.dbscan import DbScan\n'), ((7308, 7360), 'distance.levenshtein', 'distance.levenshtein', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (7328, 7360), False, 'import distance\n'), ((7650, 7698), 'utils.string_compare_algorithm.needleman_wunsch', 'needleman_wunsch', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (7666, 7698), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((8019, 8080), 'utils.string_compare_algorithm.needleman_wunsch_with_penalty', 'needleman_wunsch_with_penalty', (['string_data[i]', 'string_data[j]'], {}), '(string_data[i], string_data[j])\n', (8048, 8080), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((5429, 5457), 'distance.levenshtein', 'distance.levenshtein', (['w1', 'w2'], {}), '(w1, w2)\n', (5449, 5457), False, 'import distance\n'), ((5902, 5926), 'utils.string_compare_algorithm.needleman_wunsch', 'needleman_wunsch', (['w1', 'w2'], {}), '(w1, w2)\n', (5918, 5926), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n'), ((6402, 6439), 'utils.string_compare_algorithm.needleman_wunsch_with_penalty', 'needleman_wunsch_with_penalty', (['w1', 'w2'], {}), '(w1, w2)\n', (6431, 6439), False, 'from utils.string_compare_algorithm import levenstein_sequence_similarity, is_string_similar, needleman_wunsch, needleman_wunsch_with_penalty\n')]
# !/usr/bin/env python # -*- coding: utf-8 -*- """Conversion between single-channel integer value to 3-channels color image. Mostly used for semantic segmentation. """ from __future__ import annotations import numpy as np import torch from multipledispatch import dispatch from torch import Tensor from onevision.cv.core import get_num_channels from onevision.cv.core import to_channel_first from onevision.type import TensorOrArray __all__ = [ "integer_to_color", "is_color_image", ] # MARK: - Functional def _integer_to_color(image: np.ndarray, colors: list) -> np.ndarray: """Convert the integer-encoded image to color image. Fill an image with labels' colors. Args: image (np.ndarray): An image in either one-hot or integer. colors (list): List of all colors. Returns: color (np.ndarray): Colored image. """ if len(colors) <= 0: raise ValueError(f"No colors are provided.") # NOTE: Convert to channel-first image = to_channel_first(image) # NOTE: Squeeze dims to 2 if image.ndim == 3: image = np.squeeze(image) # NOTE: Draw color r = np.zeros_like(image).astype(np.uint8) g = np.zeros_like(image).astype(np.uint8) b = np.zeros_like(image).astype(np.uint8) for l in range(0, len(colors)): idx = image == l r[idx] = colors[l][0] g[idx] = colors[l][1] b[idx] = colors[l][2] rgb = np.stack([r, g, b], axis=0) return rgb @dispatch(Tensor, list) def integer_to_color(image: Tensor, colors: list) -> Tensor: mask_np = image.numpy() mask_np = integer_to_color(mask_np, colors) color = torch.from_numpy(mask_np) return color @dispatch(np.ndarray, list) def integer_to_color(image: np.ndarray, colors: list) -> np.ndarray: # [C, H, W] if image.ndim == 3: return _integer_to_color(image, colors) # [B, C, H, W] if image.ndim == 4: colors = [_integer_to_color(i, colors) for i in image] colors = np.stack(colors).astype(np.uint8) return colors raise ValueError(f"`image.ndim` must be 3 or 4. But got: {image.ndim}.") def is_color_image(image: TensorOrArray) -> bool: """Check if the given image is color encoded.""" if get_num_channels(image) in [3, 4]: return True return False
[ "torch.from_numpy", "numpy.squeeze", "numpy.stack", "multipledispatch.dispatch", "onevision.cv.core.to_channel_first", "numpy.zeros_like", "onevision.cv.core.get_num_channels" ]
[((1527, 1549), 'multipledispatch.dispatch', 'dispatch', (['Tensor', 'list'], {}), '(Tensor, list)\n', (1535, 1549), False, 'from multipledispatch import dispatch\n'), ((1747, 1773), 'multipledispatch.dispatch', 'dispatch', (['np.ndarray', 'list'], {}), '(np.ndarray, list)\n', (1755, 1773), False, 'from multipledispatch import dispatch\n'), ((1037, 1060), 'onevision.cv.core.to_channel_first', 'to_channel_first', (['image'], {}), '(image)\n', (1053, 1060), False, 'from onevision.cv.core import to_channel_first\n'), ((1481, 1508), 'numpy.stack', 'np.stack', (['[r, g, b]'], {'axis': '(0)'}), '([r, g, b], axis=0)\n', (1489, 1508), True, 'import numpy as np\n'), ((1701, 1726), 'torch.from_numpy', 'torch.from_numpy', (['mask_np'], {}), '(mask_np)\n', (1717, 1726), False, 'import torch\n'), ((1136, 1153), 'numpy.squeeze', 'np.squeeze', (['image'], {}), '(image)\n', (1146, 1153), True, 'import numpy as np\n'), ((2309, 2332), 'onevision.cv.core.get_num_channels', 'get_num_channels', (['image'], {}), '(image)\n', (2325, 2332), False, 'from onevision.cv.core import get_num_channels\n'), ((1190, 1210), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1203, 1210), True, 'import numpy as np\n'), ((1236, 1256), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1249, 1256), True, 'import numpy as np\n'), ((1282, 1302), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1295, 1302), True, 'import numpy as np\n'), ((2059, 2075), 'numpy.stack', 'np.stack', (['colors'], {}), '(colors)\n', (2067, 2075), True, 'import numpy as np\n')]
#!/usr/bin/env python import sys from os.path import exists import numpy as np import pylab import scipy.interpolate def read_fortran(filename): """ Reads Fortran style binary data and returns a numpy array. """ with open(filename, 'rb') as f: # read size of record f.seek(0) n = np.fromfile(f, dtype='int32', count=1)[0] # read contents of record f.seek(4) v = np.fromfile(f, dtype='float32') return v[:-1] def mesh2grid(v, x, z): """ Interpolates from an unstructured coordinates (mesh) to a structured coordinates (grid) """ lx = x.max() - x.min() lz = z.max() - z.min() nn = v.size mesh = _stack(x, z) nx = np.around(np.sqrt(nn*lx/lz)) nz = np.around(np.sqrt(nn*lz/lx)) dx = lx/nx dz = lz/nz # construct structured grid x = np.linspace(x.min(), x.max(), nx) z = np.linspace(z.min(), z.max(), nz) X, Z = np.meshgrid(x, z) grid = _stack(X.flatten(), Z.flatten()) # interpolate to structured grid V = scipy.interpolate.griddata(mesh, v, grid, 'linear') # workaround edge issues if np.any(np.isnan(V)): W = scipy.interpolate.griddata(mesh, v, grid, 'nearest') for i in np.where(np.isnan(V)): V[i] = W[i] return np.reshape(V, (int(nz), int(nx))), x, z def _stack(*args): return np.column_stack(args) if __name__ == '__main__': """ Plots data on 2-D unstructured mesh Modified from a script for specfem2d: http://tigress-web.princeton.edu/~rmodrak/visualize/plot2d Can be used to plot models or kernels created by inv.cu SYNTAX plot_model.py folder_name component_name||file_name (time_step) e.g. ./plot_model.py output vx 1000 ./plot_model.py output proc001000_vx.bin ./plot_model.py example/model/checker vs """ istr = '' if len(sys.argv) > 3: istr = str(sys.argv[3]) while len(istr) < 6: istr = '0' + istr else: istr = '000000' # parse command line arguments x_coords_file = '%s/proc000000_x.bin' % sys.argv[1] z_coords_file = '%s/proc000000_z.bin' % sys.argv[1] # check that files actually exist assert exists(x_coords_file) assert exists(z_coords_file) database_file = "%s/%s" % (sys.argv[1], sys.argv[2]) if not exists(database_file): database_file = "%s/%s.bin" % (sys.argv[1], sys.argv[2]) if not exists(database_file): database_file = "%s/proc%s_%s.bin" % (sys.argv[1], istr, sys.argv[2]) assert exists(database_file) # read mesh coordinates #try: if True: x = read_fortran(x_coords_file) z = read_fortran(z_coords_file) #except: # raise Exception('Error reading mesh coordinates.') # read database file try: v = read_fortran(database_file) except: raise Exception('Error reading database file: %s' % database_file) # check mesh dimensions assert x.shape == z.shape == v.shape, 'Inconsistent mesh dimensions.' # interpolate to uniform rectangular grid V, X, Z = mesh2grid(v, x, z) # display figure pylab.pcolor(X, Z, V) locs = np.arange(X.min(), X.max() + 1, (X.max() - X.min()) / 5) pylab.xticks(locs, map(lambda x: "%g" % x, locs / 1e3)) locs = np.arange(Z.min(), Z.max() + 1, (Z.max() - Z.min()) / 5) pylab.yticks(locs, map(lambda x: "%g" % x, locs / 1e3)) pylab.colorbar() pylab.xlabel('x / km') pylab.ylabel('z / km') pylab.gca().invert_yaxis() pylab.show()
[ "os.path.exists", "numpy.fromfile", "numpy.sqrt", "pylab.gca", "pylab.xlabel", "numpy.column_stack", "pylab.colorbar", "numpy.isnan", "numpy.meshgrid", "pylab.pcolor", "pylab.ylabel", "pylab.show" ]
[((849, 866), 'numpy.meshgrid', 'np.meshgrid', (['x', 'z'], {}), '(x, z)\n', (860, 866), True, 'import numpy as np\n'), ((1239, 1260), 'numpy.column_stack', 'np.column_stack', (['args'], {}), '(args)\n', (1254, 1260), True, 'import numpy as np\n'), ((2029, 2050), 'os.path.exists', 'exists', (['x_coords_file'], {}), '(x_coords_file)\n', (2035, 2050), False, 'from os.path import exists\n'), ((2059, 2080), 'os.path.exists', 'exists', (['z_coords_file'], {}), '(z_coords_file)\n', (2065, 2080), False, 'from os.path import exists\n'), ((2338, 2359), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2344, 2359), False, 'from os.path import exists\n'), ((2871, 2892), 'pylab.pcolor', 'pylab.pcolor', (['X', 'Z', 'V'], {}), '(X, Z, V)\n', (2883, 2892), False, 'import pylab\n'), ((3138, 3154), 'pylab.colorbar', 'pylab.colorbar', ([], {}), '()\n', (3152, 3154), False, 'import pylab\n'), ((3156, 3178), 'pylab.xlabel', 'pylab.xlabel', (['"""x / km"""'], {}), "('x / km')\n", (3168, 3178), False, 'import pylab\n'), ((3180, 3202), 'pylab.ylabel', 'pylab.ylabel', (['"""z / km"""'], {}), "('z / km')\n", (3192, 3202), False, 'import pylab\n'), ((3232, 3244), 'pylab.show', 'pylab.show', ([], {}), '()\n', (3242, 3244), False, 'import pylab\n'), ((382, 413), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': '"""float32"""'}), "(f, dtype='float32')\n", (393, 413), True, 'import numpy as np\n'), ((655, 676), 'numpy.sqrt', 'np.sqrt', (['(nn * lx / lz)'], {}), '(nn * lx / lz)\n', (662, 676), True, 'import numpy as np\n'), ((690, 711), 'numpy.sqrt', 'np.sqrt', (['(nn * lz / lx)'], {}), '(nn * lz / lx)\n', (697, 711), True, 'import numpy as np\n'), ((1038, 1049), 'numpy.isnan', 'np.isnan', (['V'], {}), '(V)\n', (1046, 1049), True, 'import numpy as np\n'), ((2144, 2165), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2150, 2165), False, 'from os.path import exists\n'), ((2234, 2255), 'os.path.exists', 'exists', (['database_file'], {}), '(database_file)\n', (2240, 2255), False, 'from os.path import exists\n'), ((293, 331), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': '"""int32"""', 'count': '(1)'}), "(f, dtype='int32', count=1)\n", (304, 331), True, 'import numpy as np\n'), ((1131, 1142), 'numpy.isnan', 'np.isnan', (['V'], {}), '(V)\n', (1139, 1142), True, 'import numpy as np\n'), ((3204, 3215), 'pylab.gca', 'pylab.gca', ([], {}), '()\n', (3213, 3215), False, 'import pylab\n')]
# with the TRACKBAR gui component # we can perform some action my moving cursor import cv2 import numpy as np def funk(): # create one funciton # Now we are not adding any action in it . # just pass pass def main(): img1 = np.zeros((512,512,3) , np.uint8) # create a imgae of size 512 x512 windowName = 'openCV BGR color Palette' # give the name to window which will appear after the execution ofthis program cv2.namedWindow(windowName) # putting it (name) into the command # create just labels # make a Trackbar (we can scroll and change the color manually upto range 0 -255) # just create scroll label cv2.createTrackbar('B',windowName , 0 , 255 , funk) cv2.createTrackbar('G',windowName , 0 , 255 , funk) cv2.createTrackbar('R',windowName , 0 , 255 , funk) while(True): cv2.imshow(windowName , img1) # display the image on the window which we have created earlier #exit from the loop if cv2.waitKey(20)>0: # enter the any key to close the window break # put/ decide the colors on the labels corresponding windowNmae # when scroll will move then track position will also be changed ., so corresponding to that position these below commands will perform some action blue = cv2.getTrackbarPos('B' , windowName) green = cv2.getTrackbarPos('R' , windowName) red = cv2. getTrackbarPos('G' , windowName) img1[:]= [blue ,green , red] # correspoding to cordinates this image will be shown print(blue , green , red) cv2.destroyAllWindows() if __name__ == "__main__": main()
[ "cv2.imshow", "numpy.zeros", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.getTrackbarPos", "cv2.createTrackbar", "cv2.namedWindow" ]
[((250, 283), 'numpy.zeros', 'np.zeros', (['(512, 512, 3)', 'np.uint8'], {}), '((512, 512, 3), np.uint8)\n', (258, 283), True, 'import numpy as np\n'), ((451, 478), 'cv2.namedWindow', 'cv2.namedWindow', (['windowName'], {}), '(windowName)\n', (466, 478), False, 'import cv2\n'), ((673, 722), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""B"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('B', windowName, 0, 255, funk)\n", (691, 722), False, 'import cv2\n'), ((733, 782), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""G"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('G', windowName, 0, 255, funk)\n", (751, 782), False, 'import cv2\n'), ((790, 839), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""R"""', 'windowName', '(0)', '(255)', 'funk'], {}), "('R', windowName, 0, 255, funk)\n", (808, 839), False, 'import cv2\n'), ((1636, 1659), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1657, 1659), False, 'import cv2\n'), ((871, 899), 'cv2.imshow', 'cv2.imshow', (['windowName', 'img1'], {}), '(windowName, img1)\n', (881, 899), False, 'import cv2\n'), ((1338, 1373), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""B"""', 'windowName'], {}), "('B', windowName)\n", (1356, 1373), False, 'import cv2\n'), ((1398, 1433), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""R"""', 'windowName'], {}), "('R', windowName)\n", (1416, 1433), False, 'import cv2\n'), ((1450, 1485), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""G"""', 'windowName'], {}), "('G', windowName)\n", (1468, 1485), False, 'import cv2\n'), ((1007, 1022), 'cv2.waitKey', 'cv2.waitKey', (['(20)'], {}), '(20)\n', (1018, 1022), False, 'import cv2\n')]
from configs import cfg from src.utils.record_log import _logger import numpy as np import tensorflow as tf import scipy.stats as stats class Evaluator(object): def __init__(self, model): self.model = model self.global_step = model.global_step ## ---- summary---- self.build_summary() self.writer = tf.summary.FileWriter(cfg.summary_dir) def get_evaluation(self, sess, dataset_obj, global_step=None): _logger.add() _logger.add('getting evaluation result for %s' % dataset_obj.data_type) logits_list, loss_list = [], [] target_score_list, predicted_score_list = [], [] for sample_batch, _, _, _ in dataset_obj.generate_batch_sample_iter(): feed_dict = self.model.get_feed_dict(sample_batch, 'dev') logits, loss, predicted_score = sess.run([self.model.logits, self.model.loss, self.model.predicted_score], feed_dict) logits_list.append(np.argmax(logits, -1)) loss_list.append(loss) predicted_score_list.append(predicted_score) for sample in sample_batch: target_score_list.append(sample['relatedness_score']) logits_array = np.concatenate(logits_list, 0) loss_value = np.mean(loss_list) target_scores = np.array(target_score_list) predicted_scores = np.concatenate(predicted_score_list, 0) # pearson, spearman, mse pearson_value = stats.pearsonr(target_scores, predicted_scores)[0] spearman_value = stats.spearmanr(target_scores, predicted_scores)[0] mse_value = np.mean((target_scores - predicted_scores) ** 2) # todo: analysis # analysis_save_dir = cfg.mkdir(cfg.answer_dir, 'gs_%d' % global_step or 0) # OutputAnalysis.do_analysis(dataset_obj, logits_array, accu_array, analysis_save_dir, # cfg.fine_grained) if global_step is not None: if dataset_obj.data_type == 'train': summary_feed_dict = { self.train_loss: loss_value, self.train_pearson: pearson_value, self.train_spearman: spearman_value, self.train_mse: mse_value, } summary = sess.run(self.train_summaries, summary_feed_dict) self.writer.add_summary(summary, global_step) elif dataset_obj.data_type == 'dev': summary_feed_dict = { self.dev_loss: loss_value, self.dev_pearson: pearson_value, self.dev_spearman: spearman_value, self.dev_mse: mse_value, } summary = sess.run(self.dev_summaries, summary_feed_dict) self.writer.add_summary(summary, global_step) else: summary_feed_dict = { self.test_loss: loss_value, self.test_pearson: pearson_value, self.test_spearman: spearman_value, self.test_mse: mse_value, } summary = sess.run(self.test_summaries, summary_feed_dict) self.writer.add_summary(summary, global_step) return loss_value, (pearson_value, spearman_value, mse_value) # --- internal use ------ def build_summary(self): with tf.name_scope('train_summaries'): self.train_loss = tf.placeholder(tf.float32, [], 'train_loss') self.train_pearson = tf.placeholder(tf.float32, [], 'train_pearson') self.train_spearman = tf.placeholder(tf.float32, [], 'train_spearman') self.train_mse = tf.placeholder(tf.float32, [], 'train_mse') tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_loss', self.train_loss)) tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_pearson', self.train_pearson)) tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_spearman', self.train_spearman)) tf.add_to_collection('train_summaries_collection', tf.summary.scalar('train_mse', self.train_mse)) self.train_summaries = tf.summary.merge_all('train_summaries_collection') with tf.name_scope('dev_summaries'): self.dev_loss = tf.placeholder(tf.float32, [], 'dev_loss') self.dev_pearson = tf.placeholder(tf.float32, [], 'dev_pearson') self.dev_spearman = tf.placeholder(tf.float32, [], 'dev_spearman') self.dev_mse = tf.placeholder(tf.float32, [], 'dev_mse') tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_loss',self.dev_loss)) tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_pearson', self.dev_pearson)) tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_spearman', self.dev_spearman)) tf.add_to_collection('dev_summaries_collection', tf.summary.scalar('dev_mse', self.dev_mse)) self.dev_summaries = tf.summary.merge_all('dev_summaries_collection') with tf.name_scope('test_summaries'): self.test_loss = tf.placeholder(tf.float32, [], 'test_loss') self.test_pearson = tf.placeholder(tf.float32, [], 'test_pearson') self.test_spearman = tf.placeholder(tf.float32, [], 'test_spearman') self.test_mse = tf.placeholder(tf.float32, [], 'test_mse') tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_loss',self.test_loss)) tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_pearson', self.test_pearson)) tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_spearman', self.test_spearman)) tf.add_to_collection('test_summaries_collection', tf.summary.scalar('test_mse', self.test_mse)) self.test_summaries = tf.summary.merge_all('test_summaries_collection')
[ "src.utils.record_log._logger.add", "numpy.mean", "tensorflow.summary.merge_all", "tensorflow.placeholder", "numpy.argmax", "tensorflow.summary.scalar", "numpy.array", "tensorflow.name_scope", "numpy.concatenate", "scipy.stats.pearsonr", "scipy.stats.spearmanr", "tensorflow.summary.FileWriter" ]
[((346, 384), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['cfg.summary_dir'], {}), '(cfg.summary_dir)\n', (367, 384), True, 'import tensorflow as tf\n'), ((461, 474), 'src.utils.record_log._logger.add', '_logger.add', ([], {}), '()\n', (472, 474), False, 'from src.utils.record_log import _logger\n'), ((483, 554), 'src.utils.record_log._logger.add', '_logger.add', (["('getting evaluation result for %s' % dataset_obj.data_type)"], {}), "('getting evaluation result for %s' % dataset_obj.data_type)\n", (494, 554), False, 'from src.utils.record_log import _logger\n'), ((1256, 1286), 'numpy.concatenate', 'np.concatenate', (['logits_list', '(0)'], {}), '(logits_list, 0)\n', (1270, 1286), True, 'import numpy as np\n'), ((1308, 1326), 'numpy.mean', 'np.mean', (['loss_list'], {}), '(loss_list)\n', (1315, 1326), True, 'import numpy as np\n'), ((1351, 1378), 'numpy.array', 'np.array', (['target_score_list'], {}), '(target_score_list)\n', (1359, 1378), True, 'import numpy as np\n'), ((1406, 1445), 'numpy.concatenate', 'np.concatenate', (['predicted_score_list', '(0)'], {}), '(predicted_score_list, 0)\n', (1420, 1445), True, 'import numpy as np\n'), ((1651, 1699), 'numpy.mean', 'np.mean', (['((target_scores - predicted_scores) ** 2)'], {}), '((target_scores - predicted_scores) ** 2)\n', (1658, 1699), True, 'import numpy as np\n'), ((1503, 1550), 'scipy.stats.pearsonr', 'stats.pearsonr', (['target_scores', 'predicted_scores'], {}), '(target_scores, predicted_scores)\n', (1517, 1550), True, 'import scipy.stats as stats\n'), ((1579, 1627), 'scipy.stats.spearmanr', 'stats.spearmanr', (['target_scores', 'predicted_scores'], {}), '(target_scores, predicted_scores)\n', (1594, 1627), True, 'import scipy.stats as stats\n'), ((3449, 3481), 'tensorflow.name_scope', 'tf.name_scope', (['"""train_summaries"""'], {}), "('train_summaries')\n", (3462, 3481), True, 'import tensorflow as tf\n'), ((3513, 3557), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_loss"""'], {}), "(tf.float32, [], 'train_loss')\n", (3527, 3557), True, 'import tensorflow as tf\n'), ((3591, 3638), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_pearson"""'], {}), "(tf.float32, [], 'train_pearson')\n", (3605, 3638), True, 'import tensorflow as tf\n'), ((3673, 3721), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_spearman"""'], {}), "(tf.float32, [], 'train_spearman')\n", (3687, 3721), True, 'import tensorflow as tf\n'), ((3751, 3794), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""train_mse"""'], {}), "(tf.float32, [], 'train_mse')\n", (3765, 3794), True, 'import tensorflow as tf\n'), ((4294, 4344), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""train_summaries_collection"""'], {}), "('train_summaries_collection')\n", (4314, 4344), True, 'import tensorflow as tf\n'), ((4359, 4389), 'tensorflow.name_scope', 'tf.name_scope', (['"""dev_summaries"""'], {}), "('dev_summaries')\n", (4372, 4389), True, 'import tensorflow as tf\n'), ((4419, 4461), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_loss"""'], {}), "(tf.float32, [], 'dev_loss')\n", (4433, 4461), True, 'import tensorflow as tf\n'), ((4493, 4538), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_pearson"""'], {}), "(tf.float32, [], 'dev_pearson')\n", (4507, 4538), True, 'import tensorflow as tf\n'), ((4571, 4617), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_spearman"""'], {}), "(tf.float32, [], 'dev_spearman')\n", (4585, 4617), True, 'import tensorflow as tf\n'), ((4645, 4686), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""dev_mse"""'], {}), "(tf.float32, [], 'dev_mse')\n", (4659, 4686), True, 'import tensorflow as tf\n'), ((5159, 5207), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""dev_summaries_collection"""'], {}), "('dev_summaries_collection')\n", (5179, 5207), True, 'import tensorflow as tf\n'), ((5222, 5253), 'tensorflow.name_scope', 'tf.name_scope', (['"""test_summaries"""'], {}), "('test_summaries')\n", (5235, 5253), True, 'import tensorflow as tf\n'), ((5284, 5327), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_loss"""'], {}), "(tf.float32, [], 'test_loss')\n", (5298, 5327), True, 'import tensorflow as tf\n'), ((5360, 5406), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_pearson"""'], {}), "(tf.float32, [], 'test_pearson')\n", (5374, 5406), True, 'import tensorflow as tf\n'), ((5440, 5487), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_spearman"""'], {}), "(tf.float32, [], 'test_spearman')\n", (5454, 5487), True, 'import tensorflow as tf\n'), ((5516, 5558), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]', '"""test_mse"""'], {}), "(tf.float32, [], 'test_mse')\n", (5530, 5558), True, 'import tensorflow as tf\n'), ((6044, 6093), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', (['"""test_summaries_collection"""'], {}), "('test_summaries_collection')\n", (6064, 6093), True, 'import tensorflow as tf\n'), ((1006, 1027), 'numpy.argmax', 'np.argmax', (['logits', '(-1)'], {}), '(logits, -1)\n', (1015, 1027), True, 'import numpy as np\n'), ((3858, 3906), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_loss"""', 'self.train_loss'], {}), "('train_loss', self.train_loss)\n", (3875, 3906), True, 'import tensorflow as tf\n'), ((3971, 4025), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_pearson"""', 'self.train_pearson'], {}), "('train_pearson', self.train_pearson)\n", (3988, 4025), True, 'import tensorflow as tf\n'), ((4090, 4146), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_spearman"""', 'self.train_spearman'], {}), "('train_spearman', self.train_spearman)\n", (4107, 4146), True, 'import tensorflow as tf\n'), ((4211, 4257), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train_mse"""', 'self.train_mse'], {}), "('train_mse', self.train_mse)\n", (4228, 4257), True, 'import tensorflow as tf\n'), ((4748, 4792), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_loss"""', 'self.dev_loss'], {}), "('dev_loss', self.dev_loss)\n", (4765, 4792), True, 'import tensorflow as tf\n'), ((4854, 4904), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_pearson"""', 'self.dev_pearson'], {}), "('dev_pearson', self.dev_pearson)\n", (4871, 4904), True, 'import tensorflow as tf\n'), ((4967, 5019), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_spearman"""', 'self.dev_spearman'], {}), "('dev_spearman', self.dev_spearman)\n", (4984, 5019), True, 'import tensorflow as tf\n'), ((5082, 5124), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""dev_mse"""', 'self.dev_mse'], {}), "('dev_mse', self.dev_mse)\n", (5099, 5124), True, 'import tensorflow as tf\n'), ((5621, 5667), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_loss"""', 'self.test_loss'], {}), "('test_loss', self.test_loss)\n", (5638, 5667), True, 'import tensorflow as tf\n'), ((5730, 5782), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_pearson"""', 'self.test_pearson'], {}), "('test_pearson', self.test_pearson)\n", (5747, 5782), True, 'import tensorflow as tf\n'), ((5846, 5900), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_spearman"""', 'self.test_spearman'], {}), "('test_spearman', self.test_spearman)\n", (5863, 5900), True, 'import tensorflow as tf\n'), ((5964, 6008), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""test_mse"""', 'self.test_mse'], {}), "('test_mse', self.test_mse)\n", (5981, 6008), True, 'import tensorflow as tf\n')]
#coding=utf-8 import matplotlib matplotlib.use("Agg") import tensorflow as tf import argparse import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D,MaxPooling2D,UpSampling2D,BatchNormalization,Reshape,Permute,Activation from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.callbacks import ModelCheckpoint from sklearn.preprocessing import LabelEncoder from PIL import Image import matplotlib.pyplot as plt import cv2 import random import os from tqdm import tqdm seed = 7 np.random.seed(seed) #设置图像大小 img_w = 32 img_h = 32 #分类 n_label=6 classes=[0.0,17.0,34.0,51.0,68.0,255.0] labelencoder = LabelEncoder() labelencoder.fit(classes) #训练批次和每次数据量 EPOCHS = 5 BS = 32 #图像最大值 divisor=255.0 #图像根路径 filepath ='C:\\Users\Administrator\Desktop\Project\src\\' #读取图片 def load_img(path, grayscale=False): if grayscale: img = cv2.imread(path,cv2.IMREAD_GRAYSCALE) else: img = cv2.imread(path) img = np.array(img,dtype="float") / divisor return img #获取训练数据和测试数据地址 def get_train_val(val_rate = 0.25): train_url = [] train_set = [] val_set = [] for pic in os.listdir(filepath + 'train'): train_url.append(pic) random.shuffle(train_url) total_num = len(train_url) val_num = int(val_rate * total_num) for i in range(len(train_url)): if i < val_num: val_set.append(train_url[i]) else: train_set.append(train_url[i]) return train_set,val_set # 生成训练数据 def generateData(batch_size,data=[]): while True: train_data = [] train_label = [] batch = 0 for i in (range(len(data))): url = data[i] batch += 1 img = load_img(filepath + 'train/' + url) img = img_to_array(img) train_data.append(img) label = load_img(filepath + 'label/' + url, grayscale=True) label = img_to_array(label).reshape((img_w * img_h,)) train_label.append(label) if batch % batch_size==0: train_data = np.array(train_data) train_label = np.array(train_label).flatten() #拍平 train_label = labelencoder.transform(train_label) train_label = to_categorical(train_label, num_classes=n_label) #编码输出便签 train_label = train_label.reshape((batch_size,img_w,img_h,n_label)) yield (train_data,train_label) train_data = [] train_label = [] batch = 0 #生成测试的数据 def generateValidData(batch_size,data=[]): while True: valid_data = [] valid_label = [] batch = 0 for i in (range(len(data))): url = data[i] batch += 1 img = load_img(filepath + 'train/' + url) img = img_to_array(img) valid_data.append(img) label = load_img(filepath + 'label/' + url, grayscale=True) label = img_to_array(label).reshape((img_w * img_h,)) valid_label.append(label) if batch % batch_size==0: valid_data = np.array(valid_data) valid_label = np.array(valid_label).flatten() valid_label = labelencoder.transform(valid_label) valid_label = to_categorical(valid_label, num_classes=n_label) valid_label = valid_label.reshape((batch_size,img_w,img_h,n_label)) yield (valid_data,valid_label) valid_data = [] valid_label = [] batch = 0 #定义模型-网络模型 def SegNet(): model = Sequential() #encoder model.add(Conv2D(64,(3,3),strides=(1,1),input_shape=(img_w,img_h,3),padding='same',activation='relu',data_format='channels_last')) model.add(BatchNormalization()) model.add(Conv2D(64,(3,3),strides=(1,1),padding='same',activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) #(128,128) model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2,2))) #(64,64) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) #(32,32) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) #(16,16) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) #(8,8) #decoder model.add(UpSampling2D(size=(2,2))) #(16,16) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(UpSampling2D(size=(2, 2))) #(32,32) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(512, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(UpSampling2D(size=(2, 2))) #(64,64) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(UpSampling2D(size=(2, 2))) #(128,128) model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(UpSampling2D(size=(2, 2))) #(256,256) model.add(Conv2D(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h,3), padding='same', activation='relu',data_format='channels_last')) model.add(BatchNormalization()) model.add(Conv2D(64, (3, 3), strides=(1, 1), padding='same', activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(n_label, (1, 1), strides=(1, 1), padding='same')) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy']) model.summary() return model #开始训练 def train(args): model = SegNet() modelcheck = ModelCheckpoint(args['model'],monitor='val_acc',save_best_only=True,mode='max') callable = [modelcheck,tf.keras.callbacks.TensorBoard(log_dir='.')] train_set,val_set = get_train_val() train_numb = len(train_set) valid_numb = len(val_set) print ("the number of train data is",train_numb) print ("the number of val data is",valid_numb) H = model.fit(x=generateData(BS,train_set),steps_per_epoch=(train_numb//BS),epochs=EPOCHS,verbose=2, validation_data=generateValidData(BS,val_set),validation_steps=(valid_numb//BS),callbacks=callable) # plot the training loss and accuracy plt.style.use("ggplot") plt.figure() N = EPOCHS plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["acc"], label="train_acc") plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc") plt.title("Training Loss and Accuracy on SegNet Satellite Seg") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="lower left") plt.savefig(args["plot"]) #获取参数 def args_parse(): # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-a", "--augment", help="using data augment or not", action="store_true", default=False) ap.add_argument("-m", "--model", required=False,default="segnet.h5", help="path to output model") ap.add_argument("-p", "--plot", type=str, default="plot.png", help="path to output accuracy/loss plot") args = vars(ap.parse_args()) return args #运行程序 if __name__=='__main__': args = args_parse() train(args) print("完成") #predict()
[ "sklearn.preprocessing.LabelEncoder", "matplotlib.pyplot.ylabel", "tensorflow.keras.layers.BatchNormalization", "numpy.array", "numpy.arange", "os.listdir", "tensorflow.keras.layers.Conv2D", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.style.use", "numpy.random.seed", "tensorflow.keras.preprocessing.image.img_to_array", "tensorflow.keras.models.Sequential", "tensorflow.keras.utils.to_categorical", "matplotlib.pyplot.savefig", "random.shuffle", "tensorflow.keras.layers.UpSampling2D", "tensorflow.keras.callbacks.TensorBoard", "matplotlib.use", "matplotlib.pyplot.title", "cv2.imread", "matplotlib.pyplot.legend", "tensorflow.keras.layers.MaxPooling2D", "matplotlib.pyplot.figure", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.Activation" ]
[((34, 55), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (48, 55), False, 'import matplotlib\n'), ((650, 670), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (664, 670), True, 'import numpy as np\n'), ((785, 799), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (797, 799), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((1318, 1348), 'os.listdir', 'os.listdir', (["(filepath + 'train')"], {}), "(filepath + 'train')\n", (1328, 1348), False, 'import os\n'), ((1386, 1411), 'random.shuffle', 'random.shuffle', (['train_url'], {}), '(train_url)\n', (1400, 1411), False, 'import random\n'), ((3970, 3982), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3980, 3982), False, 'from tensorflow.keras.models import Sequential\n'), ((8382, 8469), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (["args['model']"], {'monitor': '"""val_acc"""', 'save_best_only': '(True)', 'mode': '"""max"""'}), "(args['model'], monitor='val_acc', save_best_only=True, mode\n ='max')\n", (8397, 8469), False, 'from tensorflow.keras.callbacks import ModelCheckpoint\n'), ((9031, 9054), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (9044, 9054), True, 'import matplotlib.pyplot as plt\n'), ((9060, 9072), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9070, 9072), True, 'import matplotlib.pyplot as plt\n'), ((9374, 9437), 'matplotlib.pyplot.title', 'plt.title', (['"""Training Loss and Accuracy on SegNet Satellite Seg"""'], {}), "('Training Loss and Accuracy on SegNet Satellite Seg')\n", (9383, 9437), True, 'import matplotlib.pyplot as plt\n'), ((9443, 9464), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (9453, 9464), True, 'import matplotlib.pyplot as plt\n'), ((9470, 9497), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss/Accuracy"""'], {}), "('Loss/Accuracy')\n", (9480, 9497), True, 'import matplotlib.pyplot as plt\n'), ((9503, 9531), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""'}), "(loc='lower left')\n", (9513, 9531), True, 'import matplotlib.pyplot as plt\n'), ((9537, 9562), 'matplotlib.pyplot.savefig', 'plt.savefig', (["args['plot']"], {}), "(args['plot'])\n", (9548, 9562), True, 'import matplotlib.pyplot as plt\n'), ((9661, 9686), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9684, 9686), False, 'import argparse\n'), ((1034, 1072), 'cv2.imread', 'cv2.imread', (['path', 'cv2.IMREAD_GRAYSCALE'], {}), '(path, cv2.IMREAD_GRAYSCALE)\n', (1044, 1072), False, 'import cv2\n'), ((1098, 1114), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1108, 1114), False, 'import cv2\n'), ((4016, 4150), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'input_shape': '(img_w, img_h, 3)', 'padding': '"""same"""', 'activation': '"""relu"""', 'data_format': '"""channels_last"""'}), "(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding=\n 'same', activation='relu', data_format='channels_last')\n", (4022, 4150), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4152, 4172), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4170, 4172), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4191, 4260), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(64, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4197, 4260), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4273, 4293), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4291, 4293), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4312, 4342), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4324, 4342), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4378, 4448), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4384, 4448), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4467, 4487), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4485, 4487), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4506, 4576), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4512, 4576), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4595, 4615), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4613, 4615), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4634, 4664), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4646, 4664), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4696, 4766), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4702, 4766), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4785, 4805), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4803, 4805), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4824, 4894), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4830, 4894), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4913, 4933), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4931, 4933), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((4952, 5022), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (4958, 5022), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5041, 5061), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5059, 5061), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5080, 5110), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5092, 5110), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5145, 5215), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5151, 5215), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5234, 5254), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5252, 5254), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5273, 5343), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5279, 5343), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5362, 5382), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5380, 5382), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5401, 5471), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5407, 5471), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5490, 5510), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5508, 5510), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5529, 5559), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5541, 5559), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5594, 5664), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5600, 5664), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5683, 5703), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5701, 5703), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5722, 5792), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5728, 5792), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5811, 5831), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5829, 5831), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5850, 5920), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (5856, 5920), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5939, 5959), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (5957, 5959), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((5978, 6008), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (5990, 6008), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6057, 6082), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6069, 6082), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6116, 6186), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6122, 6186), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6205, 6225), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6223, 6225), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6244, 6314), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6250, 6314), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6333, 6353), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6351, 6353), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6372, 6442), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6378, 6442), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6461, 6481), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6479, 6481), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6500, 6525), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6512, 6525), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6560, 6630), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6566, 6630), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6649, 6669), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6667, 6669), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6688, 6758), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6694, 6758), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6777, 6797), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6795, 6797), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6816, 6886), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(512)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(512, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (6822, 6886), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6905, 6925), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6923, 6925), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((6944, 6969), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (6956, 6969), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7004, 7074), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7010, 7074), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7093, 7113), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7111, 7113), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7132, 7202), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7138, 7202), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7221, 7241), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7239, 7241), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7260, 7330), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(256)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(256, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7266, 7330), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7349, 7369), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7367, 7369), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7388, 7413), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (7400, 7413), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7450, 7520), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7456, 7520), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7539, 7559), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7557, 7559), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7578, 7648), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(128, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7584, 7648), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7667, 7687), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7685, 7687), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7706, 7731), 'tensorflow.keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (7718, 7731), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7768, 7902), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'input_shape': '(img_w, img_h, 3)', 'padding': '"""same"""', 'activation': '"""relu"""', 'data_format': '"""channels_last"""'}), "(64, (3, 3), strides=(1, 1), input_shape=(img_w, img_h, 3), padding=\n 'same', activation='relu', data_format='channels_last')\n", (7774, 7902), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7912, 7932), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (7930, 7932), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((7951, 8020), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(64, (3, 3), strides=(1, 1), padding='same', activation='relu')\n", (7957, 8020), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8039, 8059), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (8057, 8059), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8078, 8133), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['n_label', '(1, 1)'], {'strides': '(1, 1)', 'padding': '"""same"""'}), "(n_label, (1, 1), strides=(1, 1), padding='same')\n", (8084, 8133), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8152, 8173), 'tensorflow.keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (8162, 8173), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Reshape, Permute, Activation\n'), ((8490, 8533), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': '"""."""'}), "(log_dir='.')\n", (8520, 8533), True, 'import tensorflow as tf\n'), ((9103, 9118), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9112, 9118), True, 'import numpy as np\n'), ((9173, 9188), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9182, 9188), True, 'import numpy as np\n'), ((9245, 9260), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9254, 9260), True, 'import numpy as np\n'), ((9313, 9328), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (9322, 9328), True, 'import numpy as np\n'), ((1130, 1158), 'numpy.array', 'np.array', (['img'], {'dtype': '"""float"""'}), "(img, dtype='float')\n", (1138, 1158), True, 'import numpy as np\n'), ((1990, 2007), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (2002, 2007), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((3128, 3145), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (3140, 3145), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((2300, 2320), 'numpy.array', 'np.array', (['train_data'], {}), '(train_data)\n', (2308, 2320), True, 'import numpy as np\n'), ((2495, 2543), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['train_label'], {'num_classes': 'n_label'}), '(train_label, num_classes=n_label)\n', (2509, 2543), False, 'from tensorflow.keras.utils import to_categorical\n'), ((3440, 3460), 'numpy.array', 'np.array', (['valid_data'], {}), '(valid_data)\n', (3448, 3460), True, 'import numpy as np\n'), ((3628, 3676), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['valid_label'], {'num_classes': 'n_label'}), '(valid_label, num_classes=n_label)\n', (3642, 3676), False, 'from tensorflow.keras.utils import to_categorical\n'), ((2141, 2160), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['label'], {}), '(label)\n', (2153, 2160), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((3280, 3299), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['label'], {}), '(label)\n', (3292, 3299), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((2354, 2375), 'numpy.array', 'np.array', (['train_label'], {}), '(train_label)\n', (2362, 2375), True, 'import numpy as np\n'), ((3494, 3515), 'numpy.array', 'np.array', (['valid_label'], {}), '(valid_label)\n', (3502, 3515), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import math from typing import Tuple, Union import numpy as np from .cutting_plane import CUTStatus Arr = Union[np.ndarray] class ell_stable: """Ellipsoid Search Space ell_stable = {x | (x − xc)' Q^−1 (x − xc) ​≤ κ} Returns: [type] -- [description] """ # __slots__ = ('_n', '_c1', '_kappa', '_rho', '_sigma', '_delta', '_tsq', # '_xc', '_Q', 'use_parallel_cut', 'no_defer_trick') def __init__(self, val: Union[Arr, float], x: Arr): """Construct a new ell_stable object Arguments: val (Union[Arr, float]): [description] x (Arr): [description] """ self.use_parallel_cut = True self.no_defer_trick = False self._n = n = len(x) self._nSq = float(n * n) self._nPlus1 = float(n + 1) self._nMinus1 = float(n - 1) self._halfN = float(n) / 2.0 self._halfNplus1 = self._nPlus1 / 2.0 self._halfNminus1 = self._nMinus1 / 2.0 self._c1 = self._nSq / (self._nSq - 1) self._c2 = 2.0 / self._nPlus1 self._c3 = float(n) / self._nPlus1 self._xc = x self._kappa = 1.0 if np.isscalar(val): self._Q = np.eye(n) if self.no_defer_trick: self._Q *= val else: self._kappa = val else: self._Q = np.diag(val) def copy(self): """[summary] Returns: ell_stable: [description] """ E = ell_stable(self._kappa, self.xc) E._Q = self._Q.copy() # E._c1 = self._c1 E.use_parallel_cut = self.use_parallel_cut E.no_defer_trick = self.no_defer_trick return E @property def xc(self): """copy the whole array anyway Returns: [type]: [description] """ return self._xc @xc.setter def xc(self, x: Arr): """Set the xc object Arguments: x ([type]): [description] """ self._xc = x # @property # def use_parallel_cut(self) -> bool: # """[summary] # Returns: # bool: [description] # """ # return self._use_parallel_cut # @use_parallel_cut.setter # def use_parallel_cut(self, b: bool): # """[summary] # Arguments: # b (bool): [description] # """ # self._use_parallel_cut = b # Reference: Gill, Murray, and Wright, "Practical Optimization", p43. # Author: <NAME> (<EMAIL>) def update(self, cut) -> Tuple[int, float]: g, beta = cut # calculate inv(L)*g: (n-1)*n/2 multiplications invLg = g.copy() # initially for i in range(1, self._n): for j in range(i): self._Q[i, j] = self._Q[j, i] * invLg[j] # keep for rank-one update invLg[i] -= self._Q[i, j] # calculate inv(D)*inv(L)*g: n invDinvLg = invLg.copy() # initially for i in range(self._n): invDinvLg[i] *= self._Q[i, i] # calculate omega: n gQg = invDinvLg * invLg omega = sum(gQg) self._tsq = self._kappa * omega status = self._calc_ll(beta) if status != CUTStatus.success: return status, self._tsq # calculate Q*g = inv(L')*inv(D)*inv(L)*g : (n-1)*n/2 Qg = invDinvLg.copy() # initially for i in range(self._n - 1, 0, -1): for j in range(i, self._n): Qg[i - 1] -= self._Q[i, j] * Qg[j] # ??? # calculate xc: n self._xc -= (self._rho / omega) * Qg # rank-one update: 3*n + (n-1)*n/2 # r = self._sigma / omega mu = self._sigma / (1.0 - self._sigma) oldt = omega / mu # initially m = self._n - 1 for j in range(m): # p=sqrt(k)*vv(j) # p = invLg[j] # mup = mu * p t = oldt + gQg[j] # self._Q[j, j] /= t # update invD beta2 = invDinvLg[j] / t self._Q[j, j] *= oldt / t # update invD for k in range(j + 1, self._n): # v(k) -= p * self._Q[j, k] self._Q[j, k] += beta2 * self._Q[k, j] oldt = t # p = invLg(n1) # mup = mu * p t = oldt + gQg[m] self._Q[m, m] *= oldt / t # update invD self._kappa *= self._delta # if (self.no_defer_trick) # { # self._Q *= self._kappa # self._kappa = 1. # } return status, self._tsq def _calc_ll(self, beta) -> CUTStatus: """parallel or deep cut Arguments: beta ([type]): [description] Returns: int: [description] """ if np.isscalar(beta): return self._calc_dc(beta) if len(beta) < 2: # unlikely return self._calc_dc(beta[0]) return self._calc_ll_core(beta[0], beta[1]) def _calc_ll_core(self, b0: float, b1: float) -> CUTStatus: """Calculate new ellipsoid under Parallel Cut g' (x − xc​) + β0 ​≤ 0 g' (x − xc​) + β1 ​≥ 0 Arguments: b0 (float): [description] b1 (float): [description] Returns: int: [description] """ b1sqn = b1 * (b1 / self._tsq) t1n = 1 - b1sqn if t1n < 0 or not self.use_parallel_cut: return self._calc_dc(b0) bdiff = b1 - b0 if bdiff < 0: return CUTStatus.nosoln # no sol'n if b0 == 0: self._calc_ll_cc(b1, b1sqn) return CUTStatus.success b0b1n = b0 * (b1 / self._tsq) if self._n * b0b1n < -1: # unlikely return CUTStatus.noeffect # no effect # parallel cut t0n = 1.0 - b0 * (b0 / self._tsq) # t1 = self._tsq - b1sq bsum = b0 + b1 bsumn = bsum / self._tsq bav = bsum / 2.0 tempn = self._halfN * bsumn * bdiff xi = math.sqrt(t0n * t1n + tempn * tempn) self._sigma = self._c3 + (1.0 - b0b1n - xi) / (bsumn * bav * self._nPlus1) self._rho = self._sigma * bav self._delta = self._c1 * ((t0n + t1n) / 2 + xi / self._n) return CUTStatus.success def _calc_ll_cc(self, b1: float, b1sqn: float): """Calculate new ellipsoid under Parallel Cut, one of them is central g' (x − xc​) ​≤ 0 g' (x − xc​) + β1 ​≥ 0 Arguments: b1 (float): [description] b1sq (float): [description] """ n = self._n xi = math.sqrt(1 - b1sqn + (self._halfN * b1sqn) ** 2) self._sigma = self._c3 + self._c2 * (1.0 - xi) / b1sqn self._rho = self._sigma * b1 / 2.0 self._delta = self._c1 * (1.0 - b1sqn / 2.0 + xi / n) def _calc_dc(self, beta: float) -> CUTStatus: """Calculate new ellipsoid under Deep Cut g' (x − xc​) + β ​≤ 0 Arguments: beta (float): [description] Returns: int: [description] """ try: tau = math.sqrt(self._tsq) except ValueError: print("Warning: tsq is negative: {}".format(self._tsq)) self._tsq = 0.0 tau = 0.0 bdiff = tau - beta if bdiff < 0.0: return CUTStatus.nosoln # no sol'n if beta == 0.0: self._calc_cc(tau) return CUTStatus.success n = self._n gamma = tau + n * beta if gamma < 0.0: return CUTStatus.noeffect # no effect, unlikely self._mu = (bdiff / gamma) * self._halfNminus1 self._rho = gamma / self._nPlus1 self._sigma = 2.0 * self._rho / (tau + beta) self._delta = self._c1 * (1.0 - beta * (beta / self._tsq)) return CUTStatus.success def _calc_cc(self, tau: float): """Calculate new ellipsoid under Central Cut Arguments: tau (float): [description] """ self._mu = self._halfNminus1 self._sigma = self._c2 self._rho = tau / self._nPlus1 self._delta = self._c1
[ "numpy.eye", "math.sqrt", "numpy.isscalar", "numpy.diag" ]
[((1213, 1229), 'numpy.isscalar', 'np.isscalar', (['val'], {}), '(val)\n', (1224, 1229), True, 'import numpy as np\n'), ((4841, 4858), 'numpy.isscalar', 'np.isscalar', (['beta'], {}), '(beta)\n', (4852, 4858), True, 'import numpy as np\n'), ((6096, 6132), 'math.sqrt', 'math.sqrt', (['(t0n * t1n + tempn * tempn)'], {}), '(t0n * t1n + tempn * tempn)\n', (6105, 6132), False, 'import math\n'), ((6701, 6750), 'math.sqrt', 'math.sqrt', (['(1 - b1sqn + (self._halfN * b1sqn) ** 2)'], {}), '(1 - b1sqn + (self._halfN * b1sqn) ** 2)\n', (6710, 6750), False, 'import math\n'), ((1253, 1262), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (1259, 1262), True, 'import numpy as np\n'), ((1418, 1430), 'numpy.diag', 'np.diag', (['val'], {}), '(val)\n', (1425, 1430), True, 'import numpy as np\n'), ((7211, 7231), 'math.sqrt', 'math.sqrt', (['self._tsq'], {}), '(self._tsq)\n', (7220, 7231), False, 'import math\n')]
from .. import global_vars as g from ..window import Window import numpy as np from ..roi import makeROI class TestSettings(): def test_random_roi_color(self): initial = g.settings['roi_color'] g.settings['roi_color'] = 'random' w1 = Window(np.random.random([10, 10, 10])) roi1 = makeROI('rectangle', [[1, 1], [3, 3]]) roi2 = makeROI('rectangle', [[2, 2], [3, 3]]) assert roi1.pen.color().name() != roi2.pen.color().name(), 'Random ROI color is the same. This could be a random chance. Run repeatedly.' g.settings['roi_color'] = '#00ff00' roi3 = makeROI('rectangle', [[3, 3], [3, 3]]) assert roi3.pen.color().name() == "#00ff00", 'ROI color set. all rois are same color' g.settings['roi_color'] = initial def test_multitrace(self): initial = g.settings['multipleTraceWindows'] g.settings['multipleTraceWindows'] = False w1 = Window(np.random.random([10, 10, 10])) roi1 = makeROI('rectangle', [[1, 1], [3, 3]]) roi1.plot() roi2 = makeROI('rectangle', [[2, 2], [3, 3]]) roi2.plot() assert roi1.traceWindow == roi2.traceWindow, 'Traces not plotted together.' g.settings['multipleTraceWindows'] = True roi3 = makeROI('rectangle', [[3, 3], [3, 3]]) roi3.plot() assert roi3.traceWindow != roi1.traceWindow, 'Multiple trace windows' g.settings['multipleTraceWindows'] = initial
[ "numpy.random.random" ]
[((250, 280), 'numpy.random.random', 'np.random.random', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (266, 280), True, 'import numpy as np\n'), ((868, 898), 'numpy.random.random', 'np.random.random', (['[10, 10, 10]'], {}), '([10, 10, 10])\n', (884, 898), True, 'import numpy as np\n')]
""" NCL_bar_2.py =============== This script illustrates the following concepts: - Drawing bars instead of curves in an XY plot - Changing the aspect ratio of a bar plot - Drawing filled bars up or down based on a Y reference value - Setting the minimum/maximum value of the Y axis in a bar plot - Using named colors to indicate a fill color - Creating array of dates to use as x-axis tick labels - Creating a main title See following URLs to see the reproduced NCL plot & script: - Original NCL script: https://www.ncl.ucar.edu/Applications/Scripts/bar_2.ncl - Original NCL plot: https://www.ncl.ucar.edu/Applications/Images/bar_2_lg.png """ import geocat.datafiles as gdf import matplotlib.pyplot as plt ############################################################################### # Import packages: import numpy as np import xarray as xr from geocat.viz import util as gvutil ############################################################################### # Read in data: # Open a netCDF data file using xarray default engine and load the data into xarrays ds = xr.open_dataset(gdf.get("netcdf_files/soi.nc")) dsoik = ds.DSOI_KET date = ds.date num_months = np.shape(date)[0] # Dates in the file are represented by year and month (YYYYMM) # representing them fractionally will make ploting the data easier # This produces the same results as NCL's yyyymm_to_yyyyfrac() function date_frac = np.empty_like(date) for n in np.arange(0, num_months, 1): yyyy = int(date[n] / 100) mon = (date[n] / 100 - yyyy) * 100 date_frac[n] = yyyy + (mon - 1) / 12 ############################################################################### # Plot # Generate figure (set its size (width, height) in inches) and axes plt.figure(figsize=(12, 6)) ax = plt.axes() # Create a list of colors based on the color bar values colors = ['red' if (value > 0) else 'blue' for value in dsoik[::8]] plt.bar(date_frac[::8], dsoik[::8], align='edge', edgecolor='black', color=colors, width=8 / 12, linewidth=.6) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax, x_minor_per_major=4, y_minor_per_major=5, labelsize=20) # Use geocat.viz.util convenience function to set axes parameters gvutil.set_axes_limits_and_ticks(ax, ylim=(-3, 3), yticks=np.linspace(-3, 3, 7), yticklabels=np.linspace(-3, 3, 7), xlim=(date_frac[40], date_frac[-16]), xticks=np.linspace(1900, 1980, 5)) # Use geocat.viz.util convenience function to set titles and labels gvutil.set_titles_and_labels(ax, maintitle="Darwin Southern Oscillation Index", ylabel='Anomalies', maintitlefontsize=28, labelfontsize=20) plt.show()
[ "geocat.datafiles.get", "geocat.viz.util.add_major_minor_ticks", "matplotlib.pyplot.figure", "matplotlib.pyplot.bar", "matplotlib.pyplot.axes", "numpy.empty_like", "numpy.linspace", "numpy.shape", "geocat.viz.util.set_titles_and_labels", "numpy.arange", "matplotlib.pyplot.show" ]
[((1430, 1449), 'numpy.empty_like', 'np.empty_like', (['date'], {}), '(date)\n', (1443, 1449), True, 'import numpy as np\n'), ((1459, 1486), 'numpy.arange', 'np.arange', (['(0)', 'num_months', '(1)'], {}), '(0, num_months, 1)\n', (1468, 1486), True, 'import numpy as np\n'), ((1755, 1782), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (1765, 1782), True, 'import matplotlib.pyplot as plt\n'), ((1788, 1798), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (1796, 1798), True, 'import matplotlib.pyplot as plt\n'), ((1924, 2040), 'matplotlib.pyplot.bar', 'plt.bar', (['date_frac[::8]', 'dsoik[::8]'], {'align': '"""edge"""', 'edgecolor': '"""black"""', 'color': 'colors', 'width': '(8 / 12)', 'linewidth': '(0.6)'}), "(date_frac[::8], dsoik[::8], align='edge', edgecolor='black', color=\n colors, width=8 / 12, linewidth=0.6)\n", (1931, 2040), True, 'import matplotlib.pyplot as plt\n'), ((2161, 2253), 'geocat.viz.util.add_major_minor_ticks', 'gvutil.add_major_minor_ticks', (['ax'], {'x_minor_per_major': '(4)', 'y_minor_per_major': '(5)', 'labelsize': '(20)'}), '(ax, x_minor_per_major=4, y_minor_per_major=5,\n labelsize=20)\n', (2189, 2253), True, 'from geocat.viz import util as gvutil\n'), ((2827, 2975), 'geocat.viz.util.set_titles_and_labels', 'gvutil.set_titles_and_labels', (['ax'], {'maintitle': '"""Darwin Southern Oscillation Index"""', 'ylabel': '"""Anomalies"""', 'maintitlefontsize': '(28)', 'labelfontsize': '(20)'}), "(ax, maintitle=\n 'Darwin Southern Oscillation Index', ylabel='Anomalies',\n maintitlefontsize=28, labelfontsize=20)\n", (2855, 2975), True, 'from geocat.viz import util as gvutil\n'), ((3084, 3094), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3092, 3094), True, 'import matplotlib.pyplot as plt\n'), ((1117, 1147), 'geocat.datafiles.get', 'gdf.get', (['"""netcdf_files/soi.nc"""'], {}), "('netcdf_files/soi.nc')\n", (1124, 1147), True, 'import geocat.datafiles as gdf\n'), ((1197, 1211), 'numpy.shape', 'np.shape', (['date'], {}), '(date)\n', (1205, 1211), True, 'import numpy as np\n'), ((2528, 2549), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (2539, 2549), True, 'import numpy as np\n'), ((2596, 2617), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(7)'], {}), '(-3, 3, 7)\n', (2607, 2617), True, 'import numpy as np\n'), ((2730, 2756), 'numpy.linspace', 'np.linspace', (['(1900)', '(1980)', '(5)'], {}), '(1900, 1980, 5)\n', (2741, 2756), True, 'import numpy as np\n')]
import os.path import numpy as np import pickle from .common import Benchmark from refnx.analysis import CurveFitter, Objective, Parameter import refnx.reflect from refnx.reflect._creflect import abeles as c_abeles from refnx.reflect._reflect import abeles from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity from refnx.dataset import ReflectDataset as RD class Abeles(Benchmark): def setup(self): self.q = np.linspace(0.005, 0.5, 50000) self.layers = np.array([[0, 2.07, 0, 3], [50, 3.47, 0.0001, 4], [200, -0.5, 1e-5, 5], [50, 1, 0, 3], [0, 6.36, 0, 3]]) self.repeat = 20 self.number = 10 def time_cabeles(self): c_abeles(self.q, self.layers) def time_abeles(self): abeles(self.q, self.layers) def time_reflectivity_constant_dq_q(self): reflectivity(self.q, self.layers) def time_reflectivity_pointwise_dq(self): reflectivity(self.q, self.layers, dq=0.05 * self.q) class Reflect(Benchmark): timeout = 120. # repeat = 2 def setup(self): pth = os.path.dirname(os.path.abspath(refnx.reflect.__file__)) e361 = RD(os.path.join(pth, 'test', 'e361r.txt')) sio2 = SLD(3.47, name='SiO2') si = SLD(2.07, name='Si') d2o = SLD(6.36, name='D2O') polymer = SLD(1, name='polymer') # e361 is an older dataset, but well characterised structure361 = si | sio2(10, 4) | polymer(200, 3) | d2o(0, 3) model361 = ReflectModel(structure361, bkg=2e-5) model361.scale.vary = True model361.bkg.vary = True model361.scale.range(0.1, 2) model361.bkg.range(0, 5e-5) model361.dq = 5. # d2o structure361[-1].sld.real.vary = True structure361[-1].sld.real.range(6, 6.36) self.p = structure361[1].thick structure361[1].thick.vary = True structure361[1].thick.range(5, 20) structure361[2].thick.vary = True structure361[2].thick.range(100, 220) structure361[2].sld.real.vary = True structure361[2].sld.real.range(0.2, 1.5) self.structure361 = structure361 self.model361 = model361 # e361.x_err = None self.objective = Objective(self.model361, e361) self.fitter = CurveFitter(self.objective, nwalkers=200) self.fitter.initialise('jitter') def time_reflect_emcee(self): # test how fast the emcee sampler runs in serial mode self.fitter.sampler.run_mcmc(self.fitter._state, 30) def time_reflect_sampling_parallel(self): # discrepancies in different runs may be because of different numbers # of processors self.model361.threads = 1 self.fitter.sample(30, pool=-1) def time_pickle_objective(self): # time taken to pickle an objective s = pickle.dumps(self.objective) pickle.loads(s) def time_pickle_model(self): # time taken to pickle a model s = pickle.dumps(self.model361) pickle.loads(s) def time_pickle_model(self): # time taken to pickle a parameter s = pickle.dumps(self.p) pickle.loads(s) def time_structure_slabs(self): self.structure361.slabs()
[ "refnx.reflect.ReflectModel", "refnx.reflect._reflect.abeles", "refnx.reflect.SLD", "pickle.dumps", "refnx.analysis.Objective", "numpy.array", "refnx.reflect.reflectivity", "numpy.linspace", "pickle.loads", "refnx.analysis.CurveFitter", "refnx.reflect._creflect.abeles" ]
[((446, 476), 'numpy.linspace', 'np.linspace', (['(0.005)', '(0.5)', '(50000)'], {}), '(0.005, 0.5, 50000)\n', (457, 476), True, 'import numpy as np\n'), ((499, 609), 'numpy.array', 'np.array', (['[[0, 2.07, 0, 3], [50, 3.47, 0.0001, 4], [200, -0.5, 1e-05, 5], [50, 1, 0, \n 3], [0, 6.36, 0, 3]]'], {}), '([[0, 2.07, 0, 3], [50, 3.47, 0.0001, 4], [200, -0.5, 1e-05, 5], [\n 50, 1, 0, 3], [0, 6.36, 0, 3]])\n', (507, 609), True, 'import numpy as np\n'), ((819, 848), 'refnx.reflect._creflect.abeles', 'c_abeles', (['self.q', 'self.layers'], {}), '(self.q, self.layers)\n', (827, 848), True, 'from refnx.reflect._creflect import abeles as c_abeles\n'), ((885, 912), 'refnx.reflect._reflect.abeles', 'abeles', (['self.q', 'self.layers'], {}), '(self.q, self.layers)\n', (891, 912), False, 'from refnx.reflect._reflect import abeles\n'), ((969, 1002), 'refnx.reflect.reflectivity', 'reflectivity', (['self.q', 'self.layers'], {}), '(self.q, self.layers)\n', (981, 1002), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1058, 1109), 'refnx.reflect.reflectivity', 'reflectivity', (['self.q', 'self.layers'], {'dq': '(0.05 * self.q)'}), '(self.q, self.layers, dq=0.05 * self.q)\n', (1070, 1109), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1341, 1363), 'refnx.reflect.SLD', 'SLD', (['(3.47)'], {'name': '"""SiO2"""'}), "(3.47, name='SiO2')\n", (1344, 1363), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1377, 1397), 'refnx.reflect.SLD', 'SLD', (['(2.07)'], {'name': '"""Si"""'}), "(2.07, name='Si')\n", (1380, 1397), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1412, 1433), 'refnx.reflect.SLD', 'SLD', (['(6.36)'], {'name': '"""D2O"""'}), "(6.36, name='D2O')\n", (1415, 1433), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1452, 1474), 'refnx.reflect.SLD', 'SLD', (['(1)'], {'name': '"""polymer"""'}), "(1, name='polymer')\n", (1455, 1474), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((1624, 1661), 'refnx.reflect.ReflectModel', 'ReflectModel', (['structure361'], {'bkg': '(2e-05)'}), '(structure361, bkg=2e-05)\n', (1636, 1661), False, 'from refnx.reflect import SLD, Slab, Structure, ReflectModel, reflectivity\n'), ((2375, 2405), 'refnx.analysis.Objective', 'Objective', (['self.model361', 'e361'], {}), '(self.model361, e361)\n', (2384, 2405), False, 'from refnx.analysis import CurveFitter, Objective, Parameter\n'), ((2463, 2504), 'refnx.analysis.CurveFitter', 'CurveFitter', (['self.objective'], {'nwalkers': '(200)'}), '(self.objective, nwalkers=200)\n', (2474, 2504), False, 'from refnx.analysis import CurveFitter, Objective, Parameter\n'), ((3021, 3049), 'pickle.dumps', 'pickle.dumps', (['self.objective'], {}), '(self.objective)\n', (3033, 3049), False, 'import pickle\n'), ((3058, 3073), 'pickle.loads', 'pickle.loads', (['s'], {}), '(s)\n', (3070, 3073), False, 'import pickle\n'), ((3159, 3186), 'pickle.dumps', 'pickle.dumps', (['self.model361'], {}), '(self.model361)\n', (3171, 3186), False, 'import pickle\n'), ((3195, 3210), 'pickle.loads', 'pickle.loads', (['s'], {}), '(s)\n', (3207, 3210), False, 'import pickle\n'), ((3300, 3320), 'pickle.dumps', 'pickle.dumps', (['self.p'], {}), '(self.p)\n', (3312, 3320), False, 'import pickle\n'), ((3329, 3344), 'pickle.loads', 'pickle.loads', (['s'], {}), '(s)\n', (3341, 3344), False, 'import pickle\n')]
import tensorflow as tf import numpy as np from self_implement_learning_to_adapt.model import construct_fc_weights,construct_inputs,construct_loss,forward_fc from self_implement_learning_to_adapt.batch_sampler import ParrallelSampler from self_implement_learning_to_adapt.vectorized_sampler import VectorizedSampler from rllab.misc import ext import matplotlib.pyplot as plt import scipy.signal as signal from rllab.sampler.stateful_pool import singleton_pool class MAML(object): def __init__(self, step_size, env, batch_size, meta_batch_size, seed, n_itr, max_path_length, num_grad_updates, baseline, policy, num_samples = 1000, scope = None, sess = None, center_adv=True, positive_adv=False, store_paths=False, whole_paths=True, fixed_horizon=False, load_policy = False, fake_env = None, save_video = False, fast_lr = 0.1, lr = 0.001, discount = 0.99, gae_lambda = 1, ): self.step_size = step_size self.env = env self.fake_env = fake_env self.batch_size = batch_size self.meta_batch_size = meta_batch_size self.seed = seed self.n_itr = n_itr self.max_path_length = max_path_length self.num_grad_updates = num_grad_updates self.discount = discount self.baseline = baseline self.gae_lambda = gae_lambda self.policy = policy self.center_adv = center_adv self.positive_adv = positive_adv self.store_paths = store_paths self.whole_paths = whole_paths self.fixed_horizon = fixed_horizon self.load_policy = load_policy self.scope = scope self.num_samples = num_samples self.s_size = self.env.observation_space.shape[0] self.a_size = self.env.action_space.shape[0] print(self.s_size, self.a_size) self.lr = lr self.fast_lr = fast_lr self.loss_list = [] self.reward_list = [] self.fig = None self.save_video = save_video self.train_action_inputs, self.train_state_inputs, self.train_goal_inputs = [], [], [] self.test_action_inputs, self.test_state_inputs, self.test_goal_inputs = [], [], [] # select sampler if singleton_pool.n_parallel >1: self.sampler = ParrallelSampler(self, n_envs= self.meta_batch_size) else: self.sampler = VectorizedSampler(self, n_envs= self.meta_batch_size) # define trainer self.trainer = tf.train.AdamOptimizer(learning_rate=self.lr) # this is a hacker self.f_action_inputs, self.f_state_inputs, self.f_goal = construct_inputs(self.s_size, self.a_size, "first_test") with tf.variable_scope("meta_rl_global"): self.old_params = construct_fc_weights(self.s_size, self.s_size+ self.a_size, num_hidden= 512) self.first_outputs = forward_fc(self.f_action_inputs, self.f_state_inputs, self.old_params, reuse= False) self.f_loss = construct_loss(self.first_outputs, self.f_goal) self.f_optimizer = self.trainer.minimize(self.f_loss) # construct input tensors self.construct_tensor_graph() self.saver = tf.train.Saver() def construct_tensor_graph(self): ''' build maml final graph, directly optimize the initial prior model :return: ''' self.test_outputs, self.train_outputs, self.new_params, self.train_goal_inputs = [], [], [], [] # construct inputs and network for each meta task for i in range(self.meta_batch_size): tensor_action_inputs, tensor_state_inputs, tensor_goal_inputs = construct_inputs(a_size=self.a_size, s_size=self.s_size, scpoe="train_inputs" + str(i)) outputs = forward_fc(tensor_action_inputs, tensor_state_inputs, weights=self.old_params, reuse=True) self.train_action_inputs.append(tensor_action_inputs) self.train_state_inputs.append(tensor_state_inputs) self.train_goal_inputs.append(tensor_goal_inputs) self.train_outputs.append(outputs) # maml train case, do first gradients for i in range(self.meta_batch_size): loss = construct_loss(self.train_outputs[i], self.train_goal_inputs[i]) grads = tf.gradients(loss, list(self.old_params.values())) gradients = dict(zip(self.old_params.keys(), grads)) # save the params self.new_params.append(dict(zip(self.old_params.keys(), [self.old_params[key] - self.fast_lr * gradients[key] for key in self.old_params.keys()]))) # maml test case, second order gradients for i in range(self.meta_batch_size): tensor_action_inputs, tensor_state_inputs, tensor_goal_inputs = construct_inputs(a_size=self.a_size, s_size=self.s_size, scpoe="test_inputs" + str(i)) outputs = forward_fc(tensor_action_inputs, tensor_state_inputs, weights=self.new_params[i], reuse=True) self.test_action_inputs.append(tensor_action_inputs) self.test_state_inputs.append(tensor_state_inputs) self.test_goal_inputs.append(tensor_goal_inputs) self.test_outputs.append(outputs) self.cur_params = [self.old_params for i in range(self.meta_batch_size)] # define total loss self.total_loss_list = [] for i in range(self.meta_batch_size): # save the params self.total_loss_list.append(construct_loss(self.test_outputs[i], self.test_goal_inputs[i])) with tf.variable_scope("total_loss"): self.total_loss_before = tf.reduce_mean(tf.stack(self.total_loss_list)) self.second_gradients = self.trainer.minimize(self.total_loss_before, var_list= self.old_params) def obtain_samples(self, itr, init_state, reset_args ): paths = self.sampler.obtain_samples(itr,init_state = init_state,reset_args= reset_args, return_dict= True) return paths def process_samples(self, itr, path): return self.sampler.process_samples(itr, path, log = False) def update_target_graph(self, params, to_scope): to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope) op_holder = [] for from_var, to_var in zip(params, to_vars): op_holder.append(to_var.assign(from_var)) return op_holder def cheetah_cost_fn(self,state, action, next_state): if len(state.shape) > 1: heading_penalty_factor = 10 scores = np.zeros((state.shape[0],)) # dont move front shin back so far that you tilt forward front_leg = state[:, 5] my_range = 0.2 scores[front_leg >= my_range] += heading_penalty_factor front_shin = state[:, 6] my_range = 0 scores[front_shin >= my_range] += heading_penalty_factor front_foot = state[:, 7] my_range = 0 scores[front_foot >= my_range] += heading_penalty_factor scores -= (next_state[:, 17] - state[:, 17]) / 0.01 + 0.1 * (np.sum(action**2, axis=1)) return scores heading_penalty_factor = 10 score = 0 # dont move front shin back so far that you tilt forward front_leg = state[5] my_range = 0.2 if front_leg >= my_range: score += heading_penalty_factor front_shin = state[6] my_range = 0 if front_shin >= my_range: score += heading_penalty_factor front_foot = state[7] my_range = 0 if front_foot >= my_range: score += heading_penalty_factor score -= (next_state[17] - state[17]) / 0.01 + 0.1 * (np.sum(action**2)) return score def MPC(self,itr, num_samples, init_state, goal): ''' # disable multiple joints adv_list = np.zeros([num_samples]) old_obs = np.asarray([init_state for i in range(num_samples)]) new_obs = old_obs for i in range(self.batch_size): action = (np.random.rand(num_samples, self.a_size)-0.5)*2 action[:, goal] = 0.0 if i == 0: action_list = action diff = self.sess.run(self.first_outputs, feed_dict={self.f_state_inputs: np.asarray(new_obs).reshape([-1,self.s_size]), self.f_action_inputs: np.asarray(action).reshape([-1,self.a_size])}) new_obs = diff + old_obs rewards = diff[:,17]/0.01 - 0.05 * np.sum(np.square(action),axis=1) adv_list[:] += rewards index = np.argmax(adv_list) return action_list[index] ''' # multi friction adv_list = np.zeros([num_samples]) old_obs = np.asarray([init_state for i in range(num_samples)]) new_obs = old_obs for i in range(self.batch_size): action = (np.random.rand(num_samples, self.a_size)-0.5)*2 if i == 0: action_list = action diff = self.sess.run(self.first_outputs, feed_dict={self.f_state_inputs: np.asarray(new_obs).reshape([-1,self.s_size]), self.f_action_inputs: np.asarray(action).reshape([-1,self.a_size])}) new_obs = diff + old_obs #angle = np.arccos(old_obs[:,0]/goal) #rewards = -((((angle+np.pi) % (2*np.pi)) - np.pi) **2 + old_obs[:,2]**2*0.1 + 0.001* np.sum((action)**2)) rewards = diff[:,17]/0.01 - 0.05 * np.sum(np.square(action), axis=1)#self.cheetah_cost_fn(old_obs, action, new_obs) adv_list[:] += rewards index = np.argmax(adv_list) return action_list[index] def meta_online_train(self, goal): ''' meta online adaption: load prior meta model, select action by doing MPC, adapt model in each step :param goal: sample task :return: ''' self.goal = goal self.sess = tf.Session() with self.sess as sess: self.summary_writer = tf.summary.FileWriter("./graph/", self.sess.graph) loss_plot = None loss_summary = tf.Summary() loss_summary.value.add(tag='loss', simple_value=loss_plot) reward_plot = None reward_summary = tf.Summary() reward_summary.value.add(tag = 'reward', simple_value = reward_plot) diff_plot = None diff_summary = tf.Summary() diff_summary.value.add(tag='state_difference', simple_value=diff_plot) if self.load_policy: sess.run(tf.global_variables_initializer()) self.saver.restore(sess, tf.train.latest_checkpoint('./half_cheetah_model/')) self.sampler.start_worker() else: sess.run(tf.global_variables_initializer()) self.sampler.start_worker() self.env = self.env.wrapped_env self.env.reset(reset_args=goal) # set the goal for env nstep = 0 for itr in range(self.n_itr): rewards = [] obs, act, diffs, images = [], [], [], [] new_state = self.env.reset() for step in range(self.max_path_length): #if step>int(self.max_path_length)*0.7: # self.env.render() if len(act) > 0: indices = np.random.randint(0, len(act), len(act)) _ = sess.run([ self.f_optimizer], feed_dict={self.f_action_inputs: np.asarray(act)[indices,:], self.f_state_inputs: np.asarray(obs)[indices,:], self.f_goal: np.asarray(diffs)[indices,:]}) loss, output = sess.run([self.f_loss,self.first_outputs], feed_dict={self.f_action_inputs: np.asarray(act)[indices,:], self.f_state_inputs: np.asarray(obs)[indices,:], self.f_goal: np.asarray(diffs)[indices,:]}) #diff = np.mean(abs(np.asarray(obs[1:-1])-np.asarray(obs[0:-2]) - output[0:-2])) #diff_summary.value[0].simple_value = diff loss_summary.value[0].simple_value = loss self.summary_writer.add_summary(loss_summary, nstep) self.summary_writer.add_summary(diff_summary, nstep) obs.append(new_state) if step%100 == 0: print("Doing MPC, step:", step) action = self.MPC(itr = itr, num_samples= self.num_samples, goal= goal, init_state= new_state) new_obs, reward, done,_= self.env.step(action) act.append(action) diffs.append(new_obs - new_state) rewards.append(reward) nstep +=1 new_state = new_obs if done: break if self.save_video: from PIL import Image image = self.env.wrapped_env.get_viewer().get_image() pil_image = Image.frombytes('RGB', (image[1], image[2]), image[0]) images.append(np.flipud(np.array(pil_image))) if self.save_video and itr == self.n_itr -1 : import moviepy.editor as mpy clip = mpy.ImageSequenceClip(images, fps=20 * 1) clip.write_videofile("./video/half_cheetah/", fps=20 * 1) self.saver.save(sess, './MPC_model/mpc_model.cpkt', global_step=itr) if itr >= 0: sum_rewards = np.sum(np.asarray(rewards)) print(sum_rewards) self.reward_list.append(sum_rewards) reward_summary.value[0].simple_value = sum_rewards self.summary_writer.add_summary(reward_summary, itr) if self.fig == None : self.fig = plt.figure() self.fig.set_size_inches(12, 6) self.fig1= plt.figure() else: self.show_rewards(self.reward_list, self.fig, "rewards") def train(self): ''' meta training of transition model : sample trajectories based on different tasks, doing optimization :return: ''' self.sess = tf.Session() with self.sess as sess: self.summary_writer = tf.summary.FileWriter("./graph/", self.sess.graph) if self.load_policy: sess.run(tf.global_variables_initializer()) self.saver.restore(sess, tf.train.latest_checkpoint('./half_cheetah_model/')) self.sampler.start_worker() else: sess.run(tf.global_variables_initializer()) self.sampler.start_worker() self.env = self.env.wrapped_env loss_plot = None loss_summary = tf.Summary() loss_summary.value.add(tag='loss', simple_value=loss_plot) reward_plot = None reward_summary = tf.Summary() reward_summary.value.add(tag = 'reward', simple_value = reward_plot) for itr in range(self.n_itr): if itr>0: print("------------------ total loss: %f" % total_loss_before) print("------------------ total loss: %f" % total_loss) # set goals of meta tasks learner_goals = self.env.sample_goals(self.meta_batch_size) obs_list, action_list, adv_list, newobs_list, newaction_list, newadv_list = [], [], [], [], [], [] for step in range(self.num_grad_updates+1): print("-------------------- step: " + str(step)) print("-------------------- obtaining samples :") paths = self.obtain_samples(itr, reset_args= learner_goals,init_state= None) print("-------------------- processing samples :") samples = {} for key in paths.keys(): samples[key] = self.process_samples(itr, paths[key]) if step == 0: for i in range(self.meta_batch_size): inputs = ext.extract( samples[i], "observations", "actions", "rewards" ) obs_list.append(inputs[0]) action_list.append(inputs[1]) adv_list.append(np.asarray(inputs[2]).reshape([-1,1])) else: for i in range(self.meta_batch_size): inputs = ext.extract( samples[i], "observations", "actions", "rewards" ) newobs_list.append(inputs[0]) newaction_list.append(inputs[1]) newadv_list.append(np.asarray(inputs[2]).reshape([-1,1])) #if step == 0: # print("-------------------- Compute local gradients : ") # # apply first gradients, optimize original params # assign_op = [] print("-------------------------- optimize policy :") feedict = {} for i in range(self.meta_batch_size): feedict.update({self.train_action_inputs[i]: action_list[i][0:-1]}) feedict.update({self.train_state_inputs[i]: obs_list[i][0:-1]}) feedict.update({self.train_goal_inputs[i]: obs_list[i][1::] - obs_list[i][0:-1]}) feedict.update({self.test_action_inputs[i]: newaction_list[i][0:-1]}) feedict.update({self.test_state_inputs[i]: newobs_list[i][0:-1]}) feedict.update({self.test_goal_inputs[i]: newobs_list[i][1::] - newobs_list[i][0:-1] }) total_loss_before= sess.run(self.total_loss_before, feed_dict= feedict) _ = sess.run([ self.second_gradients], feed_dict= feedict) total_loss = sess.run(self.total_loss_before, feed_dict=feedict) if itr > 0: self.loss_list.append(total_loss_before) reward_summary.value[0].simple_value = total_loss_before self.summary_writer.add_summary(reward_summary, itr) if self.fig == None : self.fig = plt.figure() self.fig.set_size_inches(12, 6) else: self.show_rewards(self.loss_list, self.fig, "loss") if itr%1 == 0: save_path = self.saver.save(sess, './half_cheetah_model/maml_model.ckpt', global_step = itr) print("-------------save model : %s " % save_path) self.sampler.shutdown_worker() def show_rewards(self, rewards, fig, name,width=12, height=6, window_size=1000): # sanity checks for plotting assert (fig is not None) #if len(rewards) == 0: # return plt.figure(fig.number) plt.clf() moving_avg = self.compute_moving_average(rewards, window_size) gcf = plt.gcf() ax = plt.gca() gcf.set_size_inches(width, height) plt.xlim((0, len(rewards))) r, = plt.plot(rewards, color='red', linestyle='-', linewidth=0.5, label=name, alpha=0.5) ave_r, = plt.plot(moving_avg, color='blue', linestyle='-', linewidth=0.8, label='avg_' + name) # e, = plt.plot(epsilons, color='blue', linestyle='--', alpha=0.5, label='epsilon') plt.legend([r, ave_r], [name, 'average '+ name]) plt.ylabel(name) plt.xlabel('Episode #') plt.savefig(name+' fig') #plt.pause(0.1) def compute_moving_average(self, rewards, window): cur_window_size = 1 moving_average = [] for i in range(len(rewards) - 1): lower_idx = max(0, i - cur_window_size) average = sum(rewards[lower_idx:i + 1]) / cur_window_size moving_average.append(average) cur_window_size += 1 if cur_window_size > window: cur_window_size = window return moving_average def get_param_values(self): all_params = self.old_params param_values = tf.get_default_session().run(all_params) return param_values def set_param_values(self, params): tf.get_default_session().run(self.update_target_graph(params, "meta_rl" + str(i))) def _discount(self, x, gamma): return signal.lfilter([1.0], [1.0, gamma], x[::-1])[::-1] def add_params(self, param_1, param_2): if len(param_1) == 0: return param_2 return [param_1[i] + param_2[i] for i in range(len(param_1))] def sub_params(self, param_1, param_2): return [param_1[i] - param_2[i] for i in range(len(param_1))] def mult_params(self, param_1, param_2 ): return [param_1[i] - param_2[i] for i in range(len(param_1))] def divide_nums(self, param_1, num): return [param_1[i]/num for i in range(len(param_1))]
[ "numpy.random.rand", "matplotlib.pyplot.ylabel", "tensorflow.get_default_session", "numpy.array", "self_implement_learning_to_adapt.model.construct_inputs", "self_implement_learning_to_adapt.vectorized_sampler.VectorizedSampler", "matplotlib.pyplot.xlabel", "tensorflow.Session", "matplotlib.pyplot.plot", "numpy.asarray", "self_implement_learning_to_adapt.model.forward_fc", "rllab.misc.ext.extract", "tensorflow.train.AdamOptimizer", "self_implement_learning_to_adapt.model.construct_fc_weights", "tensorflow.stack", "matplotlib.pyplot.savefig", "tensorflow.variable_scope", "matplotlib.pyplot.gcf", "matplotlib.pyplot.gca", "moviepy.editor.ImageSequenceClip", "numpy.argmax", "self_implement_learning_to_adapt.model.construct_loss", "numpy.square", "tensorflow.train.latest_checkpoint", "PIL.Image.frombytes", "tensorflow.summary.FileWriter", "matplotlib.pyplot.legend", "tensorflow.Summary", "tensorflow.train.Saver", "matplotlib.pyplot.clf", "tensorflow.global_variables_initializer", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure", "scipy.signal.lfilter", "self_implement_learning_to_adapt.batch_sampler.ParrallelSampler", "tensorflow.get_collection" ]
[((2881, 2926), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.lr'}), '(learning_rate=self.lr)\n', (2903, 2926), True, 'import tensorflow as tf\n'), ((3020, 3076), 'self_implement_learning_to_adapt.model.construct_inputs', 'construct_inputs', (['self.s_size', 'self.a_size', '"""first_test"""'], {}), "(self.s_size, self.a_size, 'first_test')\n", (3036, 3076), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((3263, 3350), 'self_implement_learning_to_adapt.model.forward_fc', 'forward_fc', (['self.f_action_inputs', 'self.f_state_inputs', 'self.old_params'], {'reuse': '(False)'}), '(self.f_action_inputs, self.f_state_inputs, self.old_params,\n reuse=False)\n', (3273, 3350), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((3370, 3417), 'self_implement_learning_to_adapt.model.construct_loss', 'construct_loss', (['self.first_outputs', 'self.f_goal'], {}), '(self.first_outputs, self.f_goal)\n', (3384, 3417), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((3575, 3591), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (3589, 3591), True, 'import tensorflow as tf\n'), ((6827, 6888), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES', 'to_scope'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)\n', (6844, 6888), True, 'import tensorflow as tf\n'), ((9426, 9449), 'numpy.zeros', 'np.zeros', (['[num_samples]'], {}), '([num_samples])\n', (9434, 9449), True, 'import numpy as np\n'), ((10365, 10384), 'numpy.argmax', 'np.argmax', (['adv_list'], {}), '(adv_list)\n', (10374, 10384), True, 'import numpy as np\n'), ((10685, 10697), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10695, 10697), True, 'import tensorflow as tf\n'), ((15384, 15396), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (15394, 15396), True, 'import tensorflow as tf\n'), ((20367, 20389), 'matplotlib.pyplot.figure', 'plt.figure', (['fig.number'], {}), '(fig.number)\n', (20377, 20389), True, 'import matplotlib.pyplot as plt\n'), ((20398, 20407), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (20405, 20407), True, 'import matplotlib.pyplot as plt\n'), ((20493, 20502), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (20500, 20502), True, 'import matplotlib.pyplot as plt\n'), ((20516, 20525), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (20523, 20525), True, 'import matplotlib.pyplot as plt\n'), ((20618, 20705), 'matplotlib.pyplot.plot', 'plt.plot', (['rewards'], {'color': '"""red"""', 'linestyle': '"""-"""', 'linewidth': '(0.5)', 'label': 'name', 'alpha': '(0.5)'}), "(rewards, color='red', linestyle='-', linewidth=0.5, label=name,\n alpha=0.5)\n", (20626, 20705), True, 'import matplotlib.pyplot as plt\n'), ((20719, 20809), 'matplotlib.pyplot.plot', 'plt.plot', (['moving_avg'], {'color': '"""blue"""', 'linestyle': '"""-"""', 'linewidth': '(0.8)', 'label': "('avg_' + name)"}), "(moving_avg, color='blue', linestyle='-', linewidth=0.8, label=\n 'avg_' + name)\n", (20727, 20809), True, 'import matplotlib.pyplot as plt\n'), ((20905, 20954), 'matplotlib.pyplot.legend', 'plt.legend', (['[r, ave_r]', "[name, 'average ' + name]"], {}), "([r, ave_r], [name, 'average ' + name])\n", (20915, 20954), True, 'import matplotlib.pyplot as plt\n'), ((20962, 20978), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['name'], {}), '(name)\n', (20972, 20978), True, 'import matplotlib.pyplot as plt\n'), ((20987, 21010), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode #"""'], {}), "('Episode #')\n", (20997, 21010), True, 'import matplotlib.pyplot as plt\n'), ((21019, 21045), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(name + ' fig')"], {}), "(name + ' fig')\n", (21030, 21045), True, 'import matplotlib.pyplot as plt\n'), ((2684, 2735), 'self_implement_learning_to_adapt.batch_sampler.ParrallelSampler', 'ParrallelSampler', (['self'], {'n_envs': 'self.meta_batch_size'}), '(self, n_envs=self.meta_batch_size)\n', (2700, 2735), False, 'from self_implement_learning_to_adapt.batch_sampler import ParrallelSampler\n'), ((2778, 2830), 'self_implement_learning_to_adapt.vectorized_sampler.VectorizedSampler', 'VectorizedSampler', (['self'], {'n_envs': 'self.meta_batch_size'}), '(self, n_envs=self.meta_batch_size)\n', (2795, 2830), False, 'from self_implement_learning_to_adapt.vectorized_sampler import VectorizedSampler\n'), ((3090, 3125), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""meta_rl_global"""'], {}), "('meta_rl_global')\n", (3107, 3125), True, 'import tensorflow as tf\n'), ((3157, 3233), 'self_implement_learning_to_adapt.model.construct_fc_weights', 'construct_fc_weights', (['self.s_size', '(self.s_size + self.a_size)'], {'num_hidden': '(512)'}), '(self.s_size, self.s_size + self.a_size, num_hidden=512)\n', (3177, 3233), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((4213, 4308), 'self_implement_learning_to_adapt.model.forward_fc', 'forward_fc', (['tensor_action_inputs', 'tensor_state_inputs'], {'weights': 'self.old_params', 'reuse': '(True)'}), '(tensor_action_inputs, tensor_state_inputs, weights=self.\n old_params, reuse=True)\n', (4223, 4308), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((4687, 4751), 'self_implement_learning_to_adapt.model.construct_loss', 'construct_loss', (['self.train_outputs[i]', 'self.train_goal_inputs[i]'], {}), '(self.train_outputs[i], self.train_goal_inputs[i])\n', (4701, 4751), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((5522, 5620), 'self_implement_learning_to_adapt.model.forward_fc', 'forward_fc', (['tensor_action_inputs', 'tensor_state_inputs'], {'weights': 'self.new_params[i]', 'reuse': '(True)'}), '(tensor_action_inputs, tensor_state_inputs, weights=self.\n new_params[i], reuse=True)\n', (5532, 5620), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((6221, 6252), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""total_loss"""'], {}), "('total_loss')\n", (6238, 6252), True, 'import tensorflow as tf\n'), ((7198, 7225), 'numpy.zeros', 'np.zeros', (['(state.shape[0],)'], {}), '((state.shape[0],))\n', (7206, 7225), True, 'import numpy as np\n'), ((10765, 10815), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""./graph/"""', 'self.sess.graph'], {}), "('./graph/', self.sess.graph)\n", (10786, 10815), True, 'import tensorflow as tf\n'), ((10873, 10885), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (10883, 10885), True, 'import tensorflow as tf\n'), ((11017, 11029), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (11027, 11029), True, 'import tensorflow as tf\n'), ((11167, 11179), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (11177, 11179), True, 'import tensorflow as tf\n'), ((15464, 15514), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""./graph/"""', 'self.sess.graph'], {}), "('./graph/', self.sess.graph)\n", (15485, 15514), True, 'import tensorflow as tf\n'), ((15968, 15980), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (15978, 15980), True, 'import tensorflow as tf\n'), ((16112, 16124), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (16122, 16124), True, 'import tensorflow as tf\n'), ((21877, 21921), 'scipy.signal.lfilter', 'signal.lfilter', (['[1.0]', '[1.0, gamma]', 'x[::-1]'], {}), '([1.0], [1.0, gamma], x[::-1])\n', (21891, 21921), True, 'import scipy.signal as signal\n'), ((6144, 6206), 'self_implement_learning_to_adapt.model.construct_loss', 'construct_loss', (['self.test_outputs[i]', 'self.test_goal_inputs[i]'], {}), '(self.test_outputs[i], self.test_goal_inputs[i])\n', (6158, 6206), False, 'from self_implement_learning_to_adapt.model import construct_fc_weights, construct_inputs, construct_loss, forward_fc\n'), ((6306, 6336), 'tensorflow.stack', 'tf.stack', (['self.total_loss_list'], {}), '(self.total_loss_list)\n', (6314, 6336), True, 'import tensorflow as tf\n'), ((8397, 8416), 'numpy.sum', 'np.sum', (['(action ** 2)'], {}), '(action ** 2)\n', (8403, 8416), True, 'import numpy as np\n'), ((21625, 21649), 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (21647, 21649), True, 'import tensorflow as tf\n'), ((21743, 21767), 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), '()\n', (21765, 21767), True, 'import tensorflow as tf\n'), ((7767, 7794), 'numpy.sum', 'np.sum', (['(action ** 2)'], {'axis': '(1)'}), '(action ** 2, axis=1)\n', (7773, 7794), True, 'import numpy as np\n'), ((9610, 9650), 'numpy.random.rand', 'np.random.rand', (['num_samples', 'self.a_size'], {}), '(num_samples, self.a_size)\n', (9624, 9650), True, 'import numpy as np\n'), ((11323, 11356), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (11354, 11356), True, 'import tensorflow as tf\n'), ((11399, 11450), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['"""./half_cheetah_model/"""'], {}), "('./half_cheetah_model/')\n", (11425, 11450), True, 'import tensorflow as tf\n'), ((11539, 11572), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (11570, 11572), True, 'import tensorflow as tf\n'), ((14351, 14392), 'moviepy.editor.ImageSequenceClip', 'mpy.ImageSequenceClip', (['images'], {'fps': '(20 * 1)'}), '(images, fps=20 * 1)\n', (14372, 14392), True, 'import moviepy.editor as mpy\n'), ((15573, 15606), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (15604, 15606), True, 'import tensorflow as tf\n'), ((15649, 15700), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['"""./half_cheetah_model/"""'], {}), "('./half_cheetah_model/')\n", (15675, 15700), True, 'import tensorflow as tf\n'), ((15789, 15822), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (15820, 15822), True, 'import tensorflow as tf\n'), ((10239, 10256), 'numpy.square', 'np.square', (['action'], {}), '(action)\n', (10248, 10256), True, 'import numpy as np\n'), ((14087, 14141), 'PIL.Image.frombytes', 'Image.frombytes', (['"""RGB"""', '(image[1], image[2])', 'image[0]'], {}), "('RGB', (image[1], image[2]), image[0])\n", (14102, 14141), False, 'from PIL import Image\n'), ((14627, 14646), 'numpy.asarray', 'np.asarray', (['rewards'], {}), '(rewards)\n', (14637, 14646), True, 'import numpy as np\n'), ((14967, 14979), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14977, 14979), True, 'import matplotlib.pyplot as plt\n'), ((15071, 15083), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (15081, 15083), True, 'import matplotlib.pyplot as plt\n'), ((19720, 19732), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (19730, 19732), True, 'import matplotlib.pyplot as plt\n'), ((17331, 17392), 'rllab.misc.ext.extract', 'ext.extract', (['samples[i]', '"""observations"""', '"""actions"""', '"""rewards"""'], {}), "(samples[i], 'observations', 'actions', 'rewards')\n", (17342, 17392), False, 'from rllab.misc import ext\n'), ((17809, 17870), 'rllab.misc.ext.extract', 'ext.extract', (['samples[i]', '"""observations"""', '"""actions"""', '"""rewards"""'], {}), "(samples[i], 'observations', 'actions', 'rewards')\n", (17820, 17870), False, 'from rllab.misc import ext\n'), ((9803, 9822), 'numpy.asarray', 'np.asarray', (['new_obs'], {}), '(new_obs)\n', (9813, 9822), True, 'import numpy as np\n'), ((9932, 9950), 'numpy.asarray', 'np.asarray', (['action'], {}), '(action)\n', (9942, 9950), True, 'import numpy as np\n'), ((14190, 14209), 'numpy.array', 'np.array', (['pil_image'], {}), '(pil_image)\n', (14198, 14209), True, 'import numpy as np\n'), ((12332, 12347), 'numpy.asarray', 'np.asarray', (['act'], {}), '(act)\n', (12342, 12347), True, 'import numpy as np\n'), ((12436, 12451), 'numpy.asarray', 'np.asarray', (['obs'], {}), '(obs)\n', (12446, 12451), True, 'import numpy as np\n'), ((12532, 12549), 'numpy.asarray', 'np.asarray', (['diffs'], {}), '(diffs)\n', (12542, 12549), True, 'import numpy as np\n'), ((12678, 12693), 'numpy.asarray', 'np.asarray', (['act'], {}), '(act)\n', (12688, 12693), True, 'import numpy as np\n'), ((12782, 12797), 'numpy.asarray', 'np.asarray', (['obs'], {}), '(obs)\n', (12792, 12797), True, 'import numpy as np\n'), ((12878, 12895), 'numpy.asarray', 'np.asarray', (['diffs'], {}), '(diffs)\n', (12888, 12895), True, 'import numpy as np\n'), ((17644, 17665), 'numpy.asarray', 'np.asarray', (['inputs[2]'], {}), '(inputs[2])\n', (17654, 17665), True, 'import numpy as np\n'), ((18131, 18152), 'numpy.asarray', 'np.asarray', (['inputs[2]'], {}), '(inputs[2])\n', (18141, 18152), True, 'import numpy as np\n')]
import cv2 import numpy as np from numpy.linalg import norm import requests def _get_image_frame(camera) -> np.ndarray: _, frame = camera.read() return frame def _convert_frame_to_hsv(frame: np.ndarray) -> np.ndarray: return cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) def _post_to_michi() -> None: try: requests.post("https://tbaum.duckdns.org/api/webhook/awesome-leanix") except Exception: _post_to_michi() def main() -> None: camera = cv2.VideoCapture(0) while True: frame = _get_image_frame(camera) hsv_img = _convert_frame_to_hsv(frame) if np.average(norm(hsv_img, axis=2)) / np.sqrt(3) > 110: _post_to_michi() break print("Success!") if __name__ == "__main__": main()
[ "requests.post", "numpy.sqrt", "cv2.VideoCapture", "cv2.cvtColor", "numpy.linalg.norm" ]
[((239, 277), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (251, 277), False, 'import cv2\n'), ((477, 496), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (493, 496), False, 'import cv2\n'), ((326, 395), 'requests.post', 'requests.post', (['"""https://tbaum.duckdns.org/api/webhook/awesome-leanix"""'], {}), "('https://tbaum.duckdns.org/api/webhook/awesome-leanix')\n", (339, 395), False, 'import requests\n'), ((650, 660), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (657, 660), True, 'import numpy as np\n'), ((625, 646), 'numpy.linalg.norm', 'norm', (['hsv_img'], {'axis': '(2)'}), '(hsv_img, axis=2)\n', (629, 646), False, 'from numpy.linalg import norm\n')]
#%% # read full assignment # think algo before implementing # dont use a dict when you need a list # assignment is still = and not == # dont use itertools when you can use np.roll # check mathemathical functions if the parentheses are ok # networkx is awesome # sometimes while true is better than just too small for loop # networkx addes nodes when adding edge to nonexistent node # %% import os import re import numpy as np try: os.chdir(os.path.join(os.getcwd(), 'day 14')) print(os.getcwd()) except: pass from functools import reduce import operator import networkx as nx import numpy as np # f = open('input.txt','r').read().strip() def gethash(f): lengths = [ord(l) for l in f] lengths += [17, 31, 73, 47, 23] circular = np.arange(256) skip = 0 start = 0 for r in range(64): for l in lengths: circular = np.roll(circular,-start) circular[:l]=circular[:l][::-1] circular = np.roll(circular,+start) start = (start + l + skip)%len(circular) skip +=1 def densehash(inp): return (reduce(lambda a,b : operator.xor(a,b),inp)) hashcode = '' for i in range(16): hashcode += hex(densehash(circular[i*16:i*16+16]))[2:].zfill(2) return hashcode def getbits(inp): my_hexdata = inp scale = 16 ## equals to hexadecimal num_of_bits = 4 return bin(int(my_hexdata, scale))[2:].zfill(num_of_bits) count= 0 f = 'stpzcrnm' for r in range(128): h = gethash('stpzcrnm-'+str(r)) count+=len(''.join([getbits(b) for b in h]).replace('0','')) count # %% count= 0 grid = [] f = 'stpzcrnm' for r in range(128): h = gethash('stpzcrnm-'+str(r)) grid.append(list(''.join([getbits(b) for b in h]))) count+=len(''.join([getbits(b) for b in h]).replace('0','')) # %% grid = np.array(grid) print(grid.shape) G = nx.Graph() for index,output in np.ndenumerate(grid): if output == '1': i,j = index[0], index[1] G.add_edge((i,j),(i+1,j)) G.add_edge((i,j),(i-1,j)) G.add_edge((i,j),(i,j+1)) G.add_edge((i,j),(i,j-1)) for index,output in np.ndenumerate(grid): if output == '0': if G.has_node(index): G.remove_node(index) nx.number_connected_components(G) # %%
[ "numpy.roll", "networkx.Graph", "numpy.ndenumerate", "os.getcwd", "numpy.array", "networkx.number_connected_components", "operator.xor", "numpy.arange" ]
[((1816, 1830), 'numpy.array', 'np.array', (['grid'], {}), '(grid)\n', (1824, 1830), True, 'import numpy as np\n'), ((1853, 1863), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (1861, 1863), True, 'import networkx as nx\n'), ((1885, 1905), 'numpy.ndenumerate', 'np.ndenumerate', (['grid'], {}), '(grid)\n', (1899, 1905), True, 'import numpy as np\n'), ((2119, 2139), 'numpy.ndenumerate', 'np.ndenumerate', (['grid'], {}), '(grid)\n', (2133, 2139), True, 'import numpy as np\n'), ((2215, 2248), 'networkx.number_connected_components', 'nx.number_connected_components', (['G'], {}), '(G)\n', (2245, 2248), True, 'import networkx as nx\n'), ((746, 760), 'numpy.arange', 'np.arange', (['(256)'], {}), '(256)\n', (755, 760), True, 'import numpy as np\n'), ((486, 497), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (495, 497), False, 'import os\n'), ((455, 466), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (464, 466), False, 'import os\n'), ((861, 886), 'numpy.roll', 'np.roll', (['circular', '(-start)'], {}), '(circular, -start)\n', (868, 886), True, 'import numpy as np\n'), ((953, 978), 'numpy.roll', 'np.roll', (['circular', '(+start)'], {}), '(circular, +start)\n', (960, 978), True, 'import numpy as np\n'), ((1112, 1130), 'operator.xor', 'operator.xor', (['a', 'b'], {}), '(a, b)\n', (1124, 1130), False, 'import operator\n')]
import pygame import numpy as np from math import * import json WHITE = (255, 255, 255) BLACK = (0, 0, 0) RAINBOW = (0, 0, 0) rainbow = True WIDTH, HEIGHT = 800, 600 #WIDTH, HEIGHT = 1600, 900 def drawLine(point1, point2, screen): if rainbow: pygame.draw.line(screen, RAINBOW, (point1[0], point1[1]), (point2[0], point2[1])) else: pygame.draw.line(screen, BLACK, (point1[0], point1[1]), (point2[0], point2[1])) def rotateX(angle): return np.matrix([ [1, 0, 0], [0, cos(angle), -sin(angle)], [0, sin(angle), cos(angle)] ]) def rotateY(angle): return np.matrix([ [cos(angle), 0, sin(angle)], [0, 1, 0], [-sin(angle), 0, cos(angle)] ]) def rotateZ(angle): return np.matrix([ [cos(angle), -sin(angle), 0], [sin(angle), cos(angle), 0], [0, 0, 1] ]) def projectPoint(point, angle, offset, scale): rotated = point.reshape(3, 1) rotated = np.dot(rotateX(pi / 2), rotated) rotated = np.dot(rotateX(angle[0]), rotated) rotated = np.dot(rotateY(angle[1]), rotated) rotated = np.dot(rotateZ(angle[2]), rotated) projected = np.dot(np.matrix([[1, 0, 0], [0, 1, 0]]), rotated) x = int(projected[0][0] * scale) + WIDTH/2 y = int(projected[1][0] * scale) + HEIGHT/2 return [x, y] def renderObject(objectPath, offset, angle, scale, screen): f = open(objectPath) data = json.load(f) points = data.get("points") if points: temp = "" for pointName in points: point = points.get(pointName) point = np.matrix(point)+np.matrix([offset]) temp += '"'+pointName+'":'+str(projectPoint(point, angle, offset, scale))+',' projectedPoints = json.loads('{'+temp[:-1]+'}') lines = data.get("lines") if lines: for line in lines: for p1name in line: p1 = p1name p2 = projectedPoints.get(line.get(p1)) p1 = projectedPoints.get(p1) drawLine(p1, p2, screen) objects = data.get("objects") if objects: for obj in objects: renderObject(obj.get("objectPath"), np.squeeze(np.array(np.matrix(obj.get("offset"))+np.matrix(offset)*scale/obj.get("scale"))) ,np.squeeze(np.array(np.matrix(obj["angle"])+ angle)), obj.get("scale"), screen) screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() angle = 0 while True: # so spin rate is not super fast/constant clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() angle += 0.01 screen.fill(WHITE) # type ur code here renderObject("objects/2squares.json", [0, 0, 0], [angle, angle, angle], 100, screen) renderObject("objects/square.json", [0, 0, 1], [angle, angle, angle], 100, screen) pygame.display.update()
[ "json.loads", "pygame.quit", "pygame.draw.line", "pygame.event.get", "pygame.display.set_mode", "pygame.time.Clock", "json.load", "pygame.display.update", "numpy.matrix" ]
[((2393, 2433), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIDTH, HEIGHT)'], {}), '((WIDTH, HEIGHT))\n', (2416, 2433), False, 'import pygame\n'), ((2442, 2461), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (2459, 2461), False, 'import pygame\n'), ((1431, 1443), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1440, 1443), False, 'import json\n'), ((2566, 2584), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (2582, 2584), False, 'import pygame\n'), ((2920, 2943), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (2941, 2943), False, 'import pygame\n'), ((259, 344), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'RAINBOW', '(point1[0], point1[1])', '(point2[0], point2[1])'], {}), '(screen, RAINBOW, (point1[0], point1[1]), (point2[0],\n point2[1]))\n', (275, 344), False, 'import pygame\n'), ((359, 438), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'BLACK', '(point1[0], point1[1])', '(point2[0], point2[1])'], {}), '(screen, BLACK, (point1[0], point1[1]), (point2[0], point2[1]))\n', (375, 438), False, 'import pygame\n'), ((1175, 1208), 'numpy.matrix', 'np.matrix', (['[[1, 0, 0], [0, 1, 0]]'], {}), '([[1, 0, 0], [0, 1, 0]])\n', (1184, 1208), True, 'import numpy as np\n'), ((1757, 1790), 'json.loads', 'json.loads', (["('{' + temp[:-1] + '}')"], {}), "('{' + temp[:-1] + '}')\n", (1767, 1790), False, 'import json\n'), ((2636, 2649), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (2647, 2649), False, 'import pygame\n'), ((1604, 1620), 'numpy.matrix', 'np.matrix', (['point'], {}), '(point)\n', (1613, 1620), True, 'import numpy as np\n'), ((1621, 1640), 'numpy.matrix', 'np.matrix', (['[offset]'], {}), '([offset])\n', (1630, 1640), True, 'import numpy as np\n'), ((2322, 2345), 'numpy.matrix', 'np.matrix', (["obj['angle']"], {}), "(obj['angle'])\n", (2331, 2345), True, 'import numpy as np\n'), ((2258, 2275), 'numpy.matrix', 'np.matrix', (['offset'], {}), '(offset)\n', (2267, 2275), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import argparse import cv2 as cv import numpy as np import mediapipe as mp from utils import CvFpsCalc def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=int, default=0) parser.add_argument("--width", help='cap width', type=int, default=960) parser.add_argument("--height", help='cap height', type=int, default=540) parser.add_argument("--max_num_faces", type=int, default=1) parser.add_argument("--min_detection_confidence", help='min_detection_confidence', type=float, default=0.7) parser.add_argument("--min_tracking_confidence", help='min_tracking_confidence', type=int, default=0.5) parser.add_argument('--use_brect', action='store_true') args = parser.parse_args() return args def main(): # 引数解析 ################################################################# args = get_args() cap_device = args.device cap_width = args.width cap_height = args.height max_num_faces = args.max_num_faces min_detection_confidence = args.min_detection_confidence min_tracking_confidence = args.min_tracking_confidence use_brect = args.use_brect # カメラ準備 ############################################################### cap = cv.VideoCapture(cap_device) cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width) cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height) # モデルロード ############################################################# mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh( max_num_faces=max_num_faces, min_detection_confidence=min_detection_confidence, min_tracking_confidence=min_tracking_confidence, ) # FPS計測モジュール ######################################################## cvFpsCalc = CvFpsCalc(buffer_len=10) while True: display_fps = cvFpsCalc.get() # カメラキャプチャ ##################################################### ret, image = cap.read() if not ret: break image = cv.flip(image, 1) # ミラー表示 debug_image = copy.deepcopy(image) # 検出実施 ############################################################# image = cv.cvtColor(image, cv.COLOR_BGR2RGB) results = face_mesh.process(image) # 描画 ################################################################ if results.multi_face_landmarks is not None: for face_landmarks in results.multi_face_landmarks: # 外接矩形の計算 brect = calc_bounding_rect(debug_image, face_landmarks) # 描画 debug_image = draw_landmarks(debug_image, face_landmarks) debug_image = draw_bounding_rect(use_brect, debug_image, brect) cv.putText(debug_image, "FPS:" + str(display_fps), (10, 30), cv.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2, cv.LINE_AA) # キー処理(ESC:終了) ################################################# key = cv.waitKey(1) if key == 27: # ESC break # 画面反映 ############################################################# cv.imshow('MediaPipe Face Mesh Demo', debug_image) cap.release() cv.destroyAllWindows() def calc_bounding_rect(image, landmarks): image_width, image_height = image.shape[1], image.shape[0] landmark_array = np.empty((0, 2), int) for _, landmark in enumerate(landmarks.landmark): landmark_x = min(int(landmark.x * image_width), image_width - 1) landmark_y = min(int(landmark.y * image_height), image_height - 1) landmark_point = [np.array((landmark_x, landmark_y))] landmark_array = np.append(landmark_array, landmark_point, axis=0) x, y, w, h = cv.boundingRect(landmark_array) return [x, y, x + w, y + h] def draw_landmarks(image, landmarks): image_width, image_height = image.shape[1], image.shape[0] landmark_point = [] for index, landmark in enumerate(landmarks.landmark): if landmark.visibility < 0 or landmark.presence < 0: continue landmark_x = min(int(landmark.x * image_width), image_width - 1) landmark_y = min(int(landmark.y * image_height), image_height - 1) landmark_point.append((landmark_x, landmark_y)) cv.circle(image, (landmark_x, landmark_y), 1, (0, 255, 0), 1) if len(landmark_point) > 0: # 参考:https://github.com/tensorflow/tfjs-models/blob/master/facemesh/mesh_map.jpg # 左眉毛(55:内側、46:外側) cv.line(image, landmark_point[55], landmark_point[65], (0, 255, 0), 2) cv.line(image, landmark_point[65], landmark_point[52], (0, 255, 0), 2) cv.line(image, landmark_point[52], landmark_point[53], (0, 255, 0), 2) cv.line(image, landmark_point[53], landmark_point[46], (0, 255, 0), 2) # 右眉毛(285:内側、276:外側) cv.line(image, landmark_point[285], landmark_point[295], (0, 255, 0), 2) cv.line(image, landmark_point[295], landmark_point[282], (0, 255, 0), 2) cv.line(image, landmark_point[282], landmark_point[283], (0, 255, 0), 2) cv.line(image, landmark_point[283], landmark_point[276], (0, 255, 0), 2) # 左目 (133:目頭、246:目尻) cv.line(image, landmark_point[133], landmark_point[173], (0, 255, 0), 2) cv.line(image, landmark_point[173], landmark_point[157], (0, 255, 0), 2) cv.line(image, landmark_point[157], landmark_point[158], (0, 255, 0), 2) cv.line(image, landmark_point[158], landmark_point[159], (0, 255, 0), 2) cv.line(image, landmark_point[159], landmark_point[160], (0, 255, 0), 2) cv.line(image, landmark_point[160], landmark_point[161], (0, 255, 0), 2) cv.line(image, landmark_point[161], landmark_point[246], (0, 255, 0), 2) cv.line(image, landmark_point[246], landmark_point[163], (0, 255, 0), 2) cv.line(image, landmark_point[163], landmark_point[144], (0, 255, 0), 2) cv.line(image, landmark_point[144], landmark_point[145], (0, 255, 0), 2) cv.line(image, landmark_point[145], landmark_point[153], (0, 255, 0), 2) cv.line(image, landmark_point[153], landmark_point[154], (0, 255, 0), 2) cv.line(image, landmark_point[154], landmark_point[155], (0, 255, 0), 2) cv.line(image, landmark_point[155], landmark_point[133], (0, 255, 0), 2) # 右目 (362:目頭、466:目尻) cv.line(image, landmark_point[362], landmark_point[398], (0, 255, 0), 2) cv.line(image, landmark_point[398], landmark_point[384], (0, 255, 0), 2) cv.line(image, landmark_point[384], landmark_point[385], (0, 255, 0), 2) cv.line(image, landmark_point[385], landmark_point[386], (0, 255, 0), 2) cv.line(image, landmark_point[386], landmark_point[387], (0, 255, 0), 2) cv.line(image, landmark_point[387], landmark_point[388], (0, 255, 0), 2) cv.line(image, landmark_point[388], landmark_point[466], (0, 255, 0), 2) cv.line(image, landmark_point[466], landmark_point[390], (0, 255, 0), 2) cv.line(image, landmark_point[390], landmark_point[373], (0, 255, 0), 2) cv.line(image, landmark_point[373], landmark_point[374], (0, 255, 0), 2) cv.line(image, landmark_point[374], landmark_point[380], (0, 255, 0), 2) cv.line(image, landmark_point[380], landmark_point[381], (0, 255, 0), 2) cv.line(image, landmark_point[381], landmark_point[382], (0, 255, 0), 2) cv.line(image, landmark_point[382], landmark_point[362], (0, 255, 0), 2) # 口 (308:右端、78:左端) cv.line(image, landmark_point[308], landmark_point[415], (0, 255, 0), 2) cv.line(image, landmark_point[415], landmark_point[310], (0, 255, 0), 2) cv.line(image, landmark_point[310], landmark_point[311], (0, 255, 0), 2) cv.line(image, landmark_point[311], landmark_point[312], (0, 255, 0), 2) cv.line(image, landmark_point[312], landmark_point[13], (0, 255, 0), 2) cv.line(image, landmark_point[13], landmark_point[82], (0, 255, 0), 2) cv.line(image, landmark_point[82], landmark_point[81], (0, 255, 0), 2) cv.line(image, landmark_point[81], landmark_point[80], (0, 255, 0), 2) cv.line(image, landmark_point[80], landmark_point[191], (0, 255, 0), 2) cv.line(image, landmark_point[191], landmark_point[78], (0, 255, 0), 2) cv.line(image, landmark_point[78], landmark_point[95], (0, 255, 0), 2) cv.line(image, landmark_point[95], landmark_point[88], (0, 255, 0), 2) cv.line(image, landmark_point[88], landmark_point[178], (0, 255, 0), 2) cv.line(image, landmark_point[178], landmark_point[87], (0, 255, 0), 2) cv.line(image, landmark_point[87], landmark_point[14], (0, 255, 0), 2) cv.line(image, landmark_point[14], landmark_point[317], (0, 255, 0), 2) cv.line(image, landmark_point[317], landmark_point[402], (0, 255, 0), 2) cv.line(image, landmark_point[402], landmark_point[318], (0, 255, 0), 2) cv.line(image, landmark_point[318], landmark_point[324], (0, 255, 0), 2) cv.line(image, landmark_point[324], landmark_point[308], (0, 255, 0), 2) return image def draw_bounding_rect(use_brect, image, brect): if use_brect: # 外接矩形 cv.rectangle(image, (brect[0], brect[1]), (brect[2], brect[3]), (0, 255, 0), 2) return image if __name__ == '__main__': main()
[ "cv2.rectangle", "cv2.flip", "argparse.ArgumentParser", "cv2.boundingRect", "cv2.line", "cv2.imshow", "numpy.append", "numpy.array", "cv2.circle", "numpy.empty", "cv2.destroyAllWindows", "cv2.VideoCapture", "copy.deepcopy", "cv2.cvtColor", "cv2.waitKey", "utils.CvFpsCalc" ]
[((194, 219), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (217, 219), False, 'import argparse\n'), ((1449, 1476), 'cv2.VideoCapture', 'cv.VideoCapture', (['cap_device'], {}), '(cap_device)\n', (1464, 1476), True, 'import cv2 as cv\n'), ((1982, 2006), 'utils.CvFpsCalc', 'CvFpsCalc', ([], {'buffer_len': '(10)'}), '(buffer_len=10)\n', (1991, 2006), False, 'from utils import CvFpsCalc\n'), ((3391, 3413), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (3411, 3413), True, 'import cv2 as cv\n'), ((3543, 3564), 'numpy.empty', 'np.empty', (['(0, 2)', 'int'], {}), '((0, 2), int)\n', (3551, 3564), True, 'import numpy as np\n'), ((3925, 3956), 'cv2.boundingRect', 'cv.boundingRect', (['landmark_array'], {}), '(landmark_array)\n', (3940, 3956), True, 'import cv2 as cv\n'), ((2222, 2239), 'cv2.flip', 'cv.flip', (['image', '(1)'], {}), '(image, 1)\n', (2229, 2239), True, 'import cv2 as cv\n'), ((2271, 2291), 'copy.deepcopy', 'copy.deepcopy', (['image'], {}), '(image)\n', (2284, 2291), False, 'import copy\n'), ((2386, 2422), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2RGB'], {}), '(image, cv.COLOR_BGR2RGB)\n', (2397, 2422), True, 'import cv2 as cv\n'), ((3170, 3183), 'cv2.waitKey', 'cv.waitKey', (['(1)'], {}), '(1)\n', (3180, 3183), True, 'import cv2 as cv\n'), ((3317, 3367), 'cv2.imshow', 'cv.imshow', (['"""MediaPipe Face Mesh Demo"""', 'debug_image'], {}), "('MediaPipe Face Mesh Demo', debug_image)\n", (3326, 3367), True, 'import cv2 as cv\n'), ((3857, 3906), 'numpy.append', 'np.append', (['landmark_array', 'landmark_point'], {'axis': '(0)'}), '(landmark_array, landmark_point, axis=0)\n', (3866, 3906), True, 'import numpy as np\n'), ((4474, 4535), 'cv2.circle', 'cv.circle', (['image', '(landmark_x, landmark_y)', '(1)', '(0, 255, 0)', '(1)'], {}), '(image, (landmark_x, landmark_y), 1, (0, 255, 0), 1)\n', (4483, 4535), True, 'import cv2 as cv\n'), ((4694, 4764), 'cv2.line', 'cv.line', (['image', 'landmark_point[55]', 'landmark_point[65]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[55], landmark_point[65], (0, 255, 0), 2)\n', (4701, 4764), True, 'import cv2 as cv\n'), ((4773, 4843), 'cv2.line', 'cv.line', (['image', 'landmark_point[65]', 'landmark_point[52]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[65], landmark_point[52], (0, 255, 0), 2)\n', (4780, 4843), True, 'import cv2 as cv\n'), ((4852, 4922), 'cv2.line', 'cv.line', (['image', 'landmark_point[52]', 'landmark_point[53]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[52], landmark_point[53], (0, 255, 0), 2)\n', (4859, 4922), True, 'import cv2 as cv\n'), ((4931, 5001), 'cv2.line', 'cv.line', (['image', 'landmark_point[53]', 'landmark_point[46]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[53], landmark_point[46], (0, 255, 0), 2)\n', (4938, 5001), True, 'import cv2 as cv\n'), ((5040, 5112), 'cv2.line', 'cv.line', (['image', 'landmark_point[285]', 'landmark_point[295]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[285], landmark_point[295], (0, 255, 0), 2)\n', (5047, 5112), True, 'import cv2 as cv\n'), ((5137, 5209), 'cv2.line', 'cv.line', (['image', 'landmark_point[295]', 'landmark_point[282]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[295], landmark_point[282], (0, 255, 0), 2)\n', (5144, 5209), True, 'import cv2 as cv\n'), ((5234, 5306), 'cv2.line', 'cv.line', (['image', 'landmark_point[282]', 'landmark_point[283]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[282], landmark_point[283], (0, 255, 0), 2)\n', (5241, 5306), True, 'import cv2 as cv\n'), ((5331, 5403), 'cv2.line', 'cv.line', (['image', 'landmark_point[283]', 'landmark_point[276]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[283], landmark_point[276], (0, 255, 0), 2)\n', (5338, 5403), True, 'import cv2 as cv\n'), ((5458, 5530), 'cv2.line', 'cv.line', (['image', 'landmark_point[133]', 'landmark_point[173]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[133], landmark_point[173], (0, 255, 0), 2)\n', (5465, 5530), True, 'import cv2 as cv\n'), ((5555, 5627), 'cv2.line', 'cv.line', (['image', 'landmark_point[173]', 'landmark_point[157]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[173], landmark_point[157], (0, 255, 0), 2)\n', (5562, 5627), True, 'import cv2 as cv\n'), ((5652, 5724), 'cv2.line', 'cv.line', (['image', 'landmark_point[157]', 'landmark_point[158]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[157], landmark_point[158], (0, 255, 0), 2)\n', (5659, 5724), True, 'import cv2 as cv\n'), ((5749, 5821), 'cv2.line', 'cv.line', (['image', 'landmark_point[158]', 'landmark_point[159]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[158], landmark_point[159], (0, 255, 0), 2)\n', (5756, 5821), True, 'import cv2 as cv\n'), ((5846, 5918), 'cv2.line', 'cv.line', (['image', 'landmark_point[159]', 'landmark_point[160]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[159], landmark_point[160], (0, 255, 0), 2)\n', (5853, 5918), True, 'import cv2 as cv\n'), ((5943, 6015), 'cv2.line', 'cv.line', (['image', 'landmark_point[160]', 'landmark_point[161]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[160], landmark_point[161], (0, 255, 0), 2)\n', (5950, 6015), True, 'import cv2 as cv\n'), ((6040, 6112), 'cv2.line', 'cv.line', (['image', 'landmark_point[161]', 'landmark_point[246]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[161], landmark_point[246], (0, 255, 0), 2)\n', (6047, 6112), True, 'import cv2 as cv\n'), ((6138, 6210), 'cv2.line', 'cv.line', (['image', 'landmark_point[246]', 'landmark_point[163]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[246], landmark_point[163], (0, 255, 0), 2)\n', (6145, 6210), True, 'import cv2 as cv\n'), ((6235, 6307), 'cv2.line', 'cv.line', (['image', 'landmark_point[163]', 'landmark_point[144]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[163], landmark_point[144], (0, 255, 0), 2)\n', (6242, 6307), True, 'import cv2 as cv\n'), ((6332, 6404), 'cv2.line', 'cv.line', (['image', 'landmark_point[144]', 'landmark_point[145]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[144], landmark_point[145], (0, 255, 0), 2)\n', (6339, 6404), True, 'import cv2 as cv\n'), ((6429, 6501), 'cv2.line', 'cv.line', (['image', 'landmark_point[145]', 'landmark_point[153]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[145], landmark_point[153], (0, 255, 0), 2)\n', (6436, 6501), True, 'import cv2 as cv\n'), ((6526, 6598), 'cv2.line', 'cv.line', (['image', 'landmark_point[153]', 'landmark_point[154]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[153], landmark_point[154], (0, 255, 0), 2)\n', (6533, 6598), True, 'import cv2 as cv\n'), ((6623, 6695), 'cv2.line', 'cv.line', (['image', 'landmark_point[154]', 'landmark_point[155]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[154], landmark_point[155], (0, 255, 0), 2)\n', (6630, 6695), True, 'import cv2 as cv\n'), ((6720, 6792), 'cv2.line', 'cv.line', (['image', 'landmark_point[155]', 'landmark_point[133]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[155], landmark_point[133], (0, 255, 0), 2)\n', (6727, 6792), True, 'import cv2 as cv\n'), ((6847, 6919), 'cv2.line', 'cv.line', (['image', 'landmark_point[362]', 'landmark_point[398]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[362], landmark_point[398], (0, 255, 0), 2)\n', (6854, 6919), True, 'import cv2 as cv\n'), ((6944, 7016), 'cv2.line', 'cv.line', (['image', 'landmark_point[398]', 'landmark_point[384]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[398], landmark_point[384], (0, 255, 0), 2)\n', (6951, 7016), True, 'import cv2 as cv\n'), ((7041, 7113), 'cv2.line', 'cv.line', (['image', 'landmark_point[384]', 'landmark_point[385]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[384], landmark_point[385], (0, 255, 0), 2)\n', (7048, 7113), True, 'import cv2 as cv\n'), ((7138, 7210), 'cv2.line', 'cv.line', (['image', 'landmark_point[385]', 'landmark_point[386]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[385], landmark_point[386], (0, 255, 0), 2)\n', (7145, 7210), True, 'import cv2 as cv\n'), ((7235, 7307), 'cv2.line', 'cv.line', (['image', 'landmark_point[386]', 'landmark_point[387]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[386], landmark_point[387], (0, 255, 0), 2)\n', (7242, 7307), True, 'import cv2 as cv\n'), ((7332, 7404), 'cv2.line', 'cv.line', (['image', 'landmark_point[387]', 'landmark_point[388]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[387], landmark_point[388], (0, 255, 0), 2)\n', (7339, 7404), True, 'import cv2 as cv\n'), ((7429, 7501), 'cv2.line', 'cv.line', (['image', 'landmark_point[388]', 'landmark_point[466]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[388], landmark_point[466], (0, 255, 0), 2)\n', (7436, 7501), True, 'import cv2 as cv\n'), ((7527, 7599), 'cv2.line', 'cv.line', (['image', 'landmark_point[466]', 'landmark_point[390]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[466], landmark_point[390], (0, 255, 0), 2)\n', (7534, 7599), True, 'import cv2 as cv\n'), ((7624, 7696), 'cv2.line', 'cv.line', (['image', 'landmark_point[390]', 'landmark_point[373]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[390], landmark_point[373], (0, 255, 0), 2)\n', (7631, 7696), True, 'import cv2 as cv\n'), ((7721, 7793), 'cv2.line', 'cv.line', (['image', 'landmark_point[373]', 'landmark_point[374]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[373], landmark_point[374], (0, 255, 0), 2)\n', (7728, 7793), True, 'import cv2 as cv\n'), ((7818, 7890), 'cv2.line', 'cv.line', (['image', 'landmark_point[374]', 'landmark_point[380]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[374], landmark_point[380], (0, 255, 0), 2)\n', (7825, 7890), True, 'import cv2 as cv\n'), ((7915, 7987), 'cv2.line', 'cv.line', (['image', 'landmark_point[380]', 'landmark_point[381]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[380], landmark_point[381], (0, 255, 0), 2)\n', (7922, 7987), True, 'import cv2 as cv\n'), ((8012, 8084), 'cv2.line', 'cv.line', (['image', 'landmark_point[381]', 'landmark_point[382]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[381], landmark_point[382], (0, 255, 0), 2)\n', (8019, 8084), True, 'import cv2 as cv\n'), ((8109, 8181), 'cv2.line', 'cv.line', (['image', 'landmark_point[382]', 'landmark_point[362]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[382], landmark_point[362], (0, 255, 0), 2)\n', (8116, 8181), True, 'import cv2 as cv\n'), ((8234, 8306), 'cv2.line', 'cv.line', (['image', 'landmark_point[308]', 'landmark_point[415]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[308], landmark_point[415], (0, 255, 0), 2)\n', (8241, 8306), True, 'import cv2 as cv\n'), ((8331, 8403), 'cv2.line', 'cv.line', (['image', 'landmark_point[415]', 'landmark_point[310]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[415], landmark_point[310], (0, 255, 0), 2)\n', (8338, 8403), True, 'import cv2 as cv\n'), ((8428, 8500), 'cv2.line', 'cv.line', (['image', 'landmark_point[310]', 'landmark_point[311]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[310], landmark_point[311], (0, 255, 0), 2)\n', (8435, 8500), True, 'import cv2 as cv\n'), ((8525, 8597), 'cv2.line', 'cv.line', (['image', 'landmark_point[311]', 'landmark_point[312]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[311], landmark_point[312], (0, 255, 0), 2)\n', (8532, 8597), True, 'import cv2 as cv\n'), ((8622, 8693), 'cv2.line', 'cv.line', (['image', 'landmark_point[312]', 'landmark_point[13]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[312], landmark_point[13], (0, 255, 0), 2)\n', (8629, 8693), True, 'import cv2 as cv\n'), ((8702, 8772), 'cv2.line', 'cv.line', (['image', 'landmark_point[13]', 'landmark_point[82]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[13], landmark_point[82], (0, 255, 0), 2)\n', (8709, 8772), True, 'import cv2 as cv\n'), ((8781, 8851), 'cv2.line', 'cv.line', (['image', 'landmark_point[82]', 'landmark_point[81]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[82], landmark_point[81], (0, 255, 0), 2)\n', (8788, 8851), True, 'import cv2 as cv\n'), ((8860, 8930), 'cv2.line', 'cv.line', (['image', 'landmark_point[81]', 'landmark_point[80]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[81], landmark_point[80], (0, 255, 0), 2)\n', (8867, 8930), True, 'import cv2 as cv\n'), ((8939, 9010), 'cv2.line', 'cv.line', (['image', 'landmark_point[80]', 'landmark_point[191]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[80], landmark_point[191], (0, 255, 0), 2)\n', (8946, 9010), True, 'import cv2 as cv\n'), ((9019, 9090), 'cv2.line', 'cv.line', (['image', 'landmark_point[191]', 'landmark_point[78]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[191], landmark_point[78], (0, 255, 0), 2)\n', (9026, 9090), True, 'import cv2 as cv\n'), ((9100, 9170), 'cv2.line', 'cv.line', (['image', 'landmark_point[78]', 'landmark_point[95]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[78], landmark_point[95], (0, 255, 0), 2)\n', (9107, 9170), True, 'import cv2 as cv\n'), ((9179, 9249), 'cv2.line', 'cv.line', (['image', 'landmark_point[95]', 'landmark_point[88]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[95], landmark_point[88], (0, 255, 0), 2)\n', (9186, 9249), True, 'import cv2 as cv\n'), ((9258, 9329), 'cv2.line', 'cv.line', (['image', 'landmark_point[88]', 'landmark_point[178]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[88], landmark_point[178], (0, 255, 0), 2)\n', (9265, 9329), True, 'import cv2 as cv\n'), ((9338, 9409), 'cv2.line', 'cv.line', (['image', 'landmark_point[178]', 'landmark_point[87]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[178], landmark_point[87], (0, 255, 0), 2)\n', (9345, 9409), True, 'import cv2 as cv\n'), ((9418, 9488), 'cv2.line', 'cv.line', (['image', 'landmark_point[87]', 'landmark_point[14]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[87], landmark_point[14], (0, 255, 0), 2)\n', (9425, 9488), True, 'import cv2 as cv\n'), ((9497, 9568), 'cv2.line', 'cv.line', (['image', 'landmark_point[14]', 'landmark_point[317]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[14], landmark_point[317], (0, 255, 0), 2)\n', (9504, 9568), True, 'import cv2 as cv\n'), ((9577, 9649), 'cv2.line', 'cv.line', (['image', 'landmark_point[317]', 'landmark_point[402]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[317], landmark_point[402], (0, 255, 0), 2)\n', (9584, 9649), True, 'import cv2 as cv\n'), ((9674, 9746), 'cv2.line', 'cv.line', (['image', 'landmark_point[402]', 'landmark_point[318]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[402], landmark_point[318], (0, 255, 0), 2)\n', (9681, 9746), True, 'import cv2 as cv\n'), ((9771, 9843), 'cv2.line', 'cv.line', (['image', 'landmark_point[318]', 'landmark_point[324]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[318], landmark_point[324], (0, 255, 0), 2)\n', (9778, 9843), True, 'import cv2 as cv\n'), ((9868, 9940), 'cv2.line', 'cv.line', (['image', 'landmark_point[324]', 'landmark_point[308]', '(0, 255, 0)', '(2)'], {}), '(image, landmark_point[324], landmark_point[308], (0, 255, 0), 2)\n', (9875, 9940), True, 'import cv2 as cv\n'), ((10067, 10146), 'cv2.rectangle', 'cv.rectangle', (['image', '(brect[0], brect[1])', '(brect[2], brect[3])', '(0, 255, 0)', '(2)'], {}), '(image, (brect[0], brect[1]), (brect[2], brect[3]), (0, 255, 0), 2)\n', (10079, 10146), True, 'import cv2 as cv\n'), ((3795, 3829), 'numpy.array', 'np.array', (['(landmark_x, landmark_y)'], {}), '((landmark_x, landmark_y))\n', (3803, 3829), True, 'import numpy as np\n')]
import keras from keras import layers from keras.layers import Dropout, Dense from keras.preprocessing.image import ImageDataGenerator import numpy as np import tensorflow_hub as hub import cv2 import pandas as p IMAGE_SHAPE = (224, 224) #(HEIGHT, WIDTH) TRAINING_DATA_DIRECTORY = '/content/drive/My Drive/Colab Notebooks/FlowerClassification/data/TrainingData' datagen_kwargs = dict(rescale=1./255, validation_split=.2) def get_validation_generator(): validation_datagen = ImageDataGenerator(**datagen_kwargs) validation_generator = validation_datagen.flow_from_directory( TRAINING_DATA_DIRECTORY, subset='validation', shuffle=True, target_size=IMAGE_SHAPE ) return validation_generator def get_training_generator(): training_datagen = ImageDataGenerator(**datagen_kwargs) training_generator = training_datagen.flow_from_directory( TRAINING_DATA_DIRECTORY, subset='training', shuffle=True, target_size=IMAGE_SHAPE ) return training_generator def get_mobile_net_model(): model = keras.Sequential() model.add(hub.KerasLayer( 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4', output_shape=[1280], trainable=False) ) model.add(Dropout(0.4)) model.add(Dense(training_generator.num_classes, activation='softmax')) model.build([None, 224, 224, 3]) model.summary() return model def train_model(model, training_generator=None, validation_generator=None): if (training_generator == None): training_generator = get_training_generator() if (validation_generator == None): validation_generator = get_validation_generator() optimizer = keras.optimizers.Adam(lr=1e-3) model.compile( optimizer=optimizer, loss='categorical_crossentropy', metrics=['acc'] ) steps_per_epoch = np.ceil( training_generator.samples / training_generator.batch_size ) validation_steps_per_epoch = np.ceil( validation_generator.samples / validation_generator.batch_size ) hist = model.fit( training_generator, epochs=20, verbose=1, steps_per_epoch=steps_per_epoch, validation_data=validation_generator, validation_steps=validation_steps_per_epoch ).history print('model trained') model.save('/content/drive/My Drive/Colab Notebooks/FlowerClassification/model_100_epochs.h5') print('model saved') #converting history.history dictionary to pandas dataframe hist_df = pd.DataFrame(history.history) # save to json hist_json_file = 'history_100_epochs.json' with open(hist_json_file, mode='w') as f: hist_df.to_json(f) return model def evaluate_model(model): final_loss, final_accuracy = model.evaluate(validation_generator, steps = validation_steps_per_epoch) print("Final Loss: ", final_loss) print("Final accuracy: ", final_accuracy * 100) if __name__ == '__main__': model = get_mobile_net_model() model = train_model(model) evaluate_model(model)
[ "keras.optimizers.Adam", "keras.Sequential", "numpy.ceil", "keras.preprocessing.image.ImageDataGenerator", "keras.layers.Dense", "tensorflow_hub.KerasLayer", "keras.layers.Dropout" ]
[((489, 525), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {}), '(**datagen_kwargs)\n', (507, 525), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((812, 848), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {}), '(**datagen_kwargs)\n', (830, 848), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((1111, 1129), 'keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (1127, 1129), False, 'import keras\n'), ((1774, 1805), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (1795, 1805), False, 'import keras\n'), ((1948, 2015), 'numpy.ceil', 'np.ceil', (['(training_generator.samples / training_generator.batch_size)'], {}), '(training_generator.samples / training_generator.batch_size)\n', (1955, 2015), True, 'import numpy as np\n'), ((2064, 2135), 'numpy.ceil', 'np.ceil', (['(validation_generator.samples / validation_generator.batch_size)'], {}), '(validation_generator.samples / validation_generator.batch_size)\n', (2071, 2135), True, 'import numpy as np\n'), ((1144, 1275), 'tensorflow_hub.KerasLayer', 'hub.KerasLayer', (['"""https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"""'], {'output_shape': '[1280]', 'trainable': '(False)'}), "(\n 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4',\n output_shape=[1280], trainable=False)\n", (1158, 1275), True, 'import tensorflow_hub as hub\n'), ((1313, 1325), 'keras.layers.Dropout', 'Dropout', (['(0.4)'], {}), '(0.4)\n', (1320, 1325), False, 'from keras.layers import Dropout, Dense\n'), ((1341, 1400), 'keras.layers.Dense', 'Dense', (['training_generator.num_classes'], {'activation': '"""softmax"""'}), "(training_generator.num_classes, activation='softmax')\n", (1346, 1400), False, 'from keras.layers import Dropout, Dense\n')]
""" A set of functions for extracting header information from PSG objects Typically only used internally in from unet.io.header.header_extractors Each function takes some PSG or header-like object and returns a dictionary with at least the following keys: { 'n_channels': int, 'channel_names': list of strings, 'sample_rate': int 'date': datetime or None 'length': int } Note: length gives the number of samples, divide by sample_rate to get length_sec """ import logging import warnings import numpy as np import h5py from datetime import datetime from psg_utils.errors import (MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning) logger = logging.getLogger(__name__) def _assert_header(header): """ Checks that a standardized header: 1) contains the right field names 2) each value has an expected type 3) the 'length' value is greater than 0 Args: header: dict Returns: dict """ field_requirements = [ ("n_channels", [int]), ("channel_names", [list]), ("sample_rate", [int]), ("date", [datetime, type(None)]), ("length", [int]) ] for field, valid_types in field_requirements: if field not in header: raise MissingHeaderFieldError(f"Missing value '{field}' from header '{header}'. " "This could be an error in the code implementation. " "Please raise this issue on GitHub.") type_ = type(header[field]) if type_ not in valid_types: raise HeaderFieldTypeError(f"Field {field} of type {type_} was not expected, expected one of {valid_types}") if header['length'] <= 0: raise LengthZeroSignalError(f"Expected key 'length' to be a non-zero integer, " f"but header {header} has value {header['length']}") # Warn on duplicate channels from psg_utils.io.channels.utils import check_duplicate_channels check_duplicate_channels(header['channel_names'], raise_or_warn="warn") return header def _sample_rate_as_int(sample_rate, raise_or_warn='warn'): """ Returns the sample rate rounded to the nearest whole integer. If the integer sample rate is not exactly (as determined by np.isclose) equal to the original, possibly floating, value an warning is issued if raise_or_warn="warn" or an FloatSampleRateError is raised if raise_or_warn="raise". Raises ValueError if raise_or_warn not in ('raise', 'warn', 'warning'). Args: sample_rate: int, float sample rate Returns: sample_rate, int """ new_sample_rate = int(np.round(sample_rate)) if not np.isclose(new_sample_rate, sample_rate): s = f"The loaded file has a float sample rate of value {sample_rate} which is not exactly equal to the " \ f"rounded integer value of {new_sample_rate}. Please note: Integer value {new_sample_rate} will be used." if raise_or_warn.lower() == "raise": raise FloatSampleRateWarning(s) elif raise_or_warn.lower() in ("warn", "warning"): warnings.warn(s, FloatSampleRateWarning) else: raise ValueError("raise_or_warn argument must be one of 'raise' or 'warn'.") return new_sample_rate def _standardized_edf_header(raw_edf, channel_names_overwrite=None): """ Header extraction function for RawEDF and Raw objects. Reads the number of channels, channel names and sample rate properties If existing, reads the date information as well. channel_names_overwrite allows passing a list of channel names to use instead of those loaded by MNE per default. This is useful e.g. to set the raw EDF names in the header instead of the truncated / renamed (on duplicates) used by MNE. Returns: Header information as dict """ # Each tuple below follows the format: # 1) output name, 2) edf_obj name, 3) function to apply to the read # value, 4) whether a missing value should raise an error. header_map = [("n_channels", "nchan", int, True), ("channel_names", "ch_names", list, True), ("sample_rate", "sfreq", _sample_rate_as_int, True), ("date", "meas_date", datetime.utcfromtimestamp, False)] if isinstance(raw_edf.info["meas_date"], (tuple, list)): assert raw_edf.info["meas_date"][1] == 0 raw_edf.info["meas_date"] = raw_edf.info["meas_date"][0] header = {} for renamed, org, transform, raise_err in header_map: value = raw_edf.info.get(org) try: value = transform(value) except Exception as e: if raise_err: raise HeaderFieldTypeError("Missing or invalid value in EDF file for key {} " "- got {}".format(org, value)) from e header[renamed] = value header["length"] = len(raw_edf) header["channel_names"] = list(channel_names_overwrite) or header["channel_names"] return _assert_header(header) def _standardized_wfdb_header(wfdb_record): """ Header extraction function for WFDB Record objects. Reads the number of channels, channel names and sample rate properties If existing, reads the date information as well. Returns: Header information as dict """ # Each tuple below follows the format: # 1) output name, 2) record_obj name, 3) function to apply to the read # value, 4) whether a missing value should raise an error. header_map = [("n_channels", "n_sig", int, True), ("channel_names", "sig_name", list, True), ("sample_rate", "fs", _sample_rate_as_int, True), ("date", "base_date", datetime.utcfromtimestamp, False), ("length", "sig_len", int, True)] header = {} for renamed, org, transform, raise_err in header_map: value = getattr(wfdb_record, org, None) try: value = transform(value) except Exception as e: if raise_err: raise HeaderFieldTypeError("Missing or invalid value in WFDB file for key {} " "- got {}".format(org, value)) from e header[renamed] = value return _assert_header(header) def _traverse_h5_file(root_node, attributes=None): attributes = dict((attributes or {})) attributes.update(root_node.attrs) results = {} if isinstance(root_node, h5py.Dataset): # Leaf node attributes["length"] = len(root_node) results[root_node.name] = attributes else: for key in root_node: results.update(_traverse_h5_file(root_node[key], attributes)) return results def _get_unique_value(items): """ Takes a list of items, checks that all are equal (in value, ==) and returns the unique value. Returns None if the list is empty. Raises ValueError if not all items are not equal. Args: items: List Returns: The unique item in list """ if len(items) == 0: return None for item in items[1:]: if item != items[0]: raise H5VariableAttributesError(f"The input list '{items}' contains more than 1 unique value") return items[0] def _standardized_h5_header(h5_file, channel_group_name="channels"): """ Header extraction function for h5py.File objects. The object must: - Have an attribute 'sample_rate' - Have a group named {channel_group_name} which stores the data for all channels as Dataset entries under the group (can be nested in deeper groups too) Can have: - An attribute 'date' which gives a date string or unix timestamp integer Currently raises an error if any attribute in ('date', 'sample_rate', 'length') are not equal among all datasets in the archive. All attributes may be set at any node, and will affect any non-attributed node deeper in the tree. E.g. setting the 'sample_rate' attribute on the root note will have it affect all datasets, unless the attribute is set on deeper nodes too in which case the later will overwrite the root attribute for all its nested, un-attributed children. Returns: Header information as dict """ # Traverse the h5 archive for datasets and assigned attributes h5_content = _traverse_h5_file(h5_file[channel_group_name], attributes=h5_file.attrs) header = { "channel_names": [], "channel_paths": {}, # will store channel_name: channel path entries "sample_rate": [], "date": [], "length": [] } for channel_path, attributes in h5_content.items(): channel_name = channel_path.split("/")[-1] header["channel_paths"][channel_name] = channel_path header["channel_names"].append(channel_name) header["sample_rate"].append(attributes.get("sample_rate")) header["date"].append(attributes.get("date")) header["length"].append(attributes.get("length")) header["n_channels"] = len(h5_content) # Ensure all dates, lengths and sample rate attributes are equal # TODO: Remove this restriction at least for sample rates; requires handling at PSG loading time try: header["date"] = _get_unique_value(header["date"]) header["sample_rate"] = _sample_rate_as_int(_get_unique_value(header["sample_rate"])) header["length"] = int(_get_unique_value(header["length"])) except H5VariableAttributesError as e: raise H5VariableAttributesError("Datasets stored in the specified H5 archive differ with respect to one or " "multiple of the following attributes: 'date', 'sampling_rate', 'length'. " "All datasets must currently match with respect to those attributes.") from e # Get datetime date or set to None date = header["date"] if not isinstance(date, str) and (isinstance(date, int) or np.issubdtype(date, np.integer)): date = datetime.utcfromtimestamp(date) elif not isinstance(date, datetime): date = None header["date"] = date return _assert_header(header) def _standardized_bin_header(raw_header): """ Header extraction function for custom dict type headers for data in .bin files. Raw header has structure: {"CHX": [list of channel inds], "NAME": [list of channel names], "TYPE": [list of channel types], "FS": [list of channel sample rates]} All values stored in the header are strings and should be cast to ints. etc as appropriate for header standardization. Currently raises an error if all attribute in header["FS"] are not equal (i.e., same sample rate is required for all channels). Returns: Header information as dict """ # Assert upper case keys raw_header = {key.upper(): values for key, values in raw_header.items()} # Order header entries according to CHX column order = np.argsort(np.array(raw_header['CHX'], dtype=np.int)) raw_header = {key: ([entry[i] for i in order] if isinstance(entry, (list, tuple, np.ndarray)) else entry) for key, entry in raw_header.items()} # Assert that all samples rates are equal sample_rates = np.array(raw_header["FS"], dtype=np.int32) if not (sample_rates[0] == sample_rates).all(): raise VariableSampleRateError(f"Sample rates in header {raw_header} are not " f"all equal with rates: {sample_rates}. " f"The data loaders for .bin formatted files currently " f"support only files with all channels sampled at equal rates.") # Build standardized header header = { "n_channels": len(raw_header["NAME"]), "channel_names": list(raw_header["NAME"]), "sample_rate": _sample_rate_as_int(sample_rates[0]), "date": None, "length": int(raw_header["LENGTH"]), "channel_types": [type_.upper() for type_ in raw_header.get("TYPE", [])] } return _assert_header(header)
[ "logging.getLogger", "datetime.datetime.utcfromtimestamp", "psg_utils.errors.VariableSampleRateError", "numpy.isclose", "psg_utils.io.channels.utils.check_duplicate_channels", "numpy.array", "psg_utils.errors.HeaderFieldTypeError", "numpy.issubdtype", "psg_utils.errors.FloatSampleRateWarning", "warnings.warn", "psg_utils.errors.H5VariableAttributesError", "psg_utils.errors.MissingHeaderFieldError", "numpy.round", "psg_utils.errors.LengthZeroSignalError" ]
[((821, 848), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (838, 848), False, 'import logging\n'), ((2174, 2245), 'psg_utils.io.channels.utils.check_duplicate_channels', 'check_duplicate_channels', (["header['channel_names']"], {'raise_or_warn': '"""warn"""'}), "(header['channel_names'], raise_or_warn='warn')\n", (2198, 2245), False, 'from psg_utils.io.channels.utils import check_duplicate_channels\n'), ((11568, 11610), 'numpy.array', 'np.array', (["raw_header['FS']"], {'dtype': 'np.int32'}), "(raw_header['FS'], dtype=np.int32)\n", (11576, 11610), True, 'import numpy as np\n'), ((1905, 2037), 'psg_utils.errors.LengthZeroSignalError', 'LengthZeroSignalError', (['f"""Expected key \'length\' to be a non-zero integer, but header {header} has value {header[\'length\']}"""'], {}), '(\n f"Expected key \'length\' to be a non-zero integer, but header {header} has value {header[\'length\']}"\n )\n', (1926, 2037), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((2845, 2866), 'numpy.round', 'np.round', (['sample_rate'], {}), '(sample_rate)\n', (2853, 2866), True, 'import numpy as np\n'), ((2879, 2919), 'numpy.isclose', 'np.isclose', (['new_sample_rate', 'sample_rate'], {}), '(new_sample_rate, sample_rate)\n', (2889, 2919), True, 'import numpy as np\n'), ((10270, 10301), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['date'], {}), '(date)\n', (10295, 10301), False, 'from datetime import datetime\n'), ((11245, 11286), 'numpy.array', 'np.array', (["raw_header['CHX']"], {'dtype': 'np.int'}), "(raw_header['CHX'], dtype=np.int)\n", (11253, 11286), True, 'import numpy as np\n'), ((11677, 11909), 'psg_utils.errors.VariableSampleRateError', 'VariableSampleRateError', (['f"""Sample rates in header {raw_header} are not all equal with rates: {sample_rates}. The data loaders for .bin formatted files currently support only files with all channels sampled at equal rates."""'], {}), "(\n f'Sample rates in header {raw_header} are not all equal with rates: {sample_rates}. The data loaders for .bin formatted files currently support only files with all channels sampled at equal rates.'\n )\n", (11700, 11909), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((1415, 1586), 'psg_utils.errors.MissingHeaderFieldError', 'MissingHeaderFieldError', (['f"""Missing value \'{field}\' from header \'{header}\'. This could be an error in the code implementation. Please raise this issue on GitHub."""'], {}), '(\n f"Missing value \'{field}\' from header \'{header}\'. This could be an error in the code implementation. Please raise this issue on GitHub."\n )\n', (1438, 1586), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((1758, 1870), 'psg_utils.errors.HeaderFieldTypeError', 'HeaderFieldTypeError', (['f"""Field {field} of type {type_} was not expected, expected one of {valid_types}"""'], {}), "(\n f'Field {field} of type {type_} was not expected, expected one of {valid_types}'\n )\n", (1778, 1870), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((3217, 3242), 'psg_utils.errors.FloatSampleRateWarning', 'FloatSampleRateWarning', (['s'], {}), '(s)\n', (3239, 3242), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((7383, 7476), 'psg_utils.errors.H5VariableAttributesError', 'H5VariableAttributesError', (['f"""The input list \'{items}\' contains more than 1 unique value"""'], {}), '(\n f"The input list \'{items}\' contains more than 1 unique value")\n', (7408, 7476), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((9755, 10008), 'psg_utils.errors.H5VariableAttributesError', 'H5VariableAttributesError', (['"""Datasets stored in the specified H5 archive differ with respect to one or multiple of the following attributes: \'date\', \'sampling_rate\', \'length\'. All datasets must currently match with respect to those attributes."""'], {}), '(\n "Datasets stored in the specified H5 archive differ with respect to one or multiple of the following attributes: \'date\', \'sampling_rate\', \'length\'. All datasets must currently match with respect to those attributes."\n )\n', (9780, 10008), False, 'from psg_utils.errors import MissingHeaderFieldError, HeaderFieldTypeError, LengthZeroSignalError, H5VariableAttributesError, VariableSampleRateError, FloatSampleRateWarning\n'), ((10221, 10252), 'numpy.issubdtype', 'np.issubdtype', (['date', 'np.integer'], {}), '(date, np.integer)\n', (10234, 10252), True, 'import numpy as np\n'), ((3314, 3354), 'warnings.warn', 'warnings.warn', (['s', 'FloatSampleRateWarning'], {}), '(s, FloatSampleRateWarning)\n', (3327, 3354), False, 'import warnings\n')]
# setup.py # This script will build the main subpackages # See LICENSE for details from __future__ import print_function, absolute_import from numpy.distutils.misc_util import Configuration from os.path import join TTFORT_DIR = '../tt-fort' EXPM_DIR = '../tt-fort/expm' EXPOKIT_SRC = [ 'explib.f90', 'normest.f90', 'expokit.f', 'dlacn1.f', 'dlapst.f', 'dlarpc.f', 'zlacn1.f', ] TTKSL_SRC = [ 'ttals.f90', 'tt_ksl.f90', 'tt_diag_ksl.f90' ] def configuration(parent_package='', top_path=None): expokit_src = [join(EXPM_DIR, x) for x in EXPOKIT_SRC] ttksl_src = [join(TTFORT_DIR, x) for x in TTKSL_SRC] ttksl_src.append('tt_ksl.pyf') config = Configuration('ksl', parent_package, top_path) config.add_library( 'expokit', sources=expokit_src, ) config.add_extension( 'dyn_tt', sources=ttksl_src, depends=[ 'print_lib', 'expokit', 'mytt', ], libraries=[ 'print_lib', 'expokit', 'mytt', ], ) return config if __name__ == '__main__': print('This is the wrong setup.py to run')
[ "os.path.join", "numpy.distutils.misc_util.Configuration" ]
[((711, 757), 'numpy.distutils.misc_util.Configuration', 'Configuration', (['"""ksl"""', 'parent_package', 'top_path'], {}), "('ksl', parent_package, top_path)\n", (724, 757), False, 'from numpy.distutils.misc_util import Configuration\n'), ((564, 581), 'os.path.join', 'join', (['EXPM_DIR', 'x'], {}), '(EXPM_DIR, x)\n', (568, 581), False, 'from os.path import join\n'), ((622, 641), 'os.path.join', 'join', (['TTFORT_DIR', 'x'], {}), '(TTFORT_DIR, x)\n', (626, 641), False, 'from os.path import join\n')]
import numpy as np from cdlib.evaluation.internal import onmi from cdlib.evaluation.internal.omega import Omega from nf1 import NF1 from collections import namedtuple, defaultdict __all__ = [ "MatchingResult", "normalized_mutual_information", "overlapping_normalized_mutual_information_LFK", "overlapping_normalized_mutual_information_MGH", "omega", "f1", "nf1", "adjusted_rand_index", "adjusted_mutual_information", "variation_of_information", "partition_closeness_simple", ] # MatchingResult = namedtuple("MatchingResult", ['mean', 'std']) MatchingResult = namedtuple("MatchingResult", "score std") MatchingResult.__new__.__defaults__ = (None,) * len(MatchingResult._fields) def __check_partition_coverage(first_partition: object, second_partition: object): nodes_first = { node: None for community in first_partition.communities for node in community } nodes_second = { node: None for community in second_partition.communities for node in community } if len(set(nodes_first.keys()) ^ set(nodes_second.keys())) != 0: raise ValueError("Both partitions should cover the same node set") def __check_partition_overlap(first_partition: object, second_partition: object): if first_partition.overlap or second_partition.overlap: raise ValueError("Not defined for overlapping partitions") def normalized_mutual_information( first_partition: object, second_partition: object ) -> MatchingResult: """ Normalized Mutual Information between two clusterings. Normalized Mutual Information (NMI) is an normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by ``sqrt(H(labels_true) * H(labels_pred))`` :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.normalized_mutual_information(louvain_communities,leiden_communities) """ __check_partition_coverage(first_partition, second_partition) __check_partition_overlap(first_partition, second_partition) first_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(first_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] second_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(second_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] from sklearn.metrics import normalized_mutual_info_score return MatchingResult( score=normalized_mutual_info_score(first_partition_c, second_partition_c) ) def overlapping_normalized_mutual_information_LFK( first_partition: object, second_partition: object ) -> MatchingResult: """ Overlapping Normalized Mutual Information between two clusterings. Extension of the Normalized Mutual Information (NMI) score to cope with overlapping partitions. This is the version proposed by Lancichinetti et al. (1) :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.overlapping_normalized_mutual_information_LFK(louvain_communities,leiden_communities) :Reference: 1. <NAME>., <NAME>., & <NAME>. (2009). Detecting the overlapping and hierarchical community structure in complex networks. New Journal of Physics, 11(3), 033015. """ return MatchingResult( score=onmi.onmi( [set(x) for x in first_partition.communities], [set(x) for x in second_partition.communities], ) ) def overlapping_normalized_mutual_information_MGH( first_partition: object, second_partition: object, normalization: str = "max" ) -> MatchingResult: """ Overlapping Normalized Mutual Information between two clusterings. Extension of the Normalized Mutual Information (NMI) score to cope with overlapping partitions. This is the version proposed by McDaid et al. using a different normalization than the original LFR one. See ref. for more details. :param first_partition: NodeClustering object :param second_partition: NodeClustering object :param normalization: one of "max" or "LFK". Default "max" (corresponds to the main method described in the article) :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.overlapping_normalized_mutual_information_MGH(louvain_communities,leiden_communities) :Reference: 1. <NAME>., <NAME>., & <NAME>. (2011). Normalized mutual information to evaluate overlapping community finding algorithms. arXiv preprint arXiv:1110.2515. Chicago """ if normalization == "max": variant = "MGH" elif normalization == "LFK": variant = "MGH_LFK" else: raise ValueError( "Wrong 'normalization' value. Please specify one among [max, LFK]." ) return MatchingResult( score=onmi.onmi( [set(x) for x in first_partition.communities], [set(x) for x in second_partition.communities], variant=variant, ) ) def omega(first_partition: object, second_partition: object) -> MatchingResult: """ Index of resemblance for overlapping, complete coverage, network clusterings. :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.omega(louvain_communities,leiden_communities) :Reference: 1. <NAME>, <NAME>, and <NAME>. 2012. `Using the omega index for evaluating abstractive algorithms detection. <https://pdfs.semanticscholar.org/59d6/5d5aa09d789408fd9fd3c009a1b070ff5859.pdf/>`_ In Proceedings of Workshop on Evaluation Metrics and System Comparison for Automatic Summarization. Association for Computational Linguistics, Stroudsburg, PA, USA, 10-18. """ __check_partition_coverage(first_partition, second_partition) first_partition = {k: v for k, v in enumerate(first_partition.communities)} second_partition = {k: v for k, v in enumerate(second_partition.communities)} om_idx = Omega(first_partition, second_partition) return MatchingResult(score=om_idx.omega_score) def f1(first_partition: object, second_partition: object) -> MatchingResult: """ Compute the average F1 score of the optimal algorithms matches among the partitions in input. Works on overlapping/non-overlapping complete/partial coverage partitions. :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.f1(louvain_communities,leiden_communities) :Reference: 1. <NAME>., <NAME>., & <NAME>. (2016). `A novel approach to evaluate algorithms detection internal on ground truth. <https://www.researchgate.net/publication/287204505_A_novel_approach_to_evaluate_community_detection_algorithms_on_ground_truth/>`_ In Complex Networks VII (pp. 133-144). Springer, Cham. """ nf = NF1(first_partition.communities, second_partition.communities) results = nf.summary() return MatchingResult( score=results["details"]["F1 mean"][0], std=results["details"]["F1 std"][0] ) def nf1(first_partition: object, second_partition: object) -> MatchingResult: """ Compute the Normalized F1 score of the optimal algorithms matches among the partitions in input. Works on overlapping/non-overlapping complete/partial coverage partitions. :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.nf1(louvain_communities,leiden_communities) :Reference: 1. <NAME>., <NAME>., & <NAME>. (2016). `A novel approach to evaluate algorithms detection internal on ground truth. <https://www.researchgate.net/publication/287204505_A_novel_approach_to_evaluate_community_detection_algorithms_on_ground_truth/>`_ 2. <NAME>. (2017). : `RDyn: graph benchmark handling algorithms dynamics. Journal of Complex Networks. <https://academic.oup.com/comnet/article-abstract/5/6/893/3925036?redirectedFrom=PDF/>`_ 5(6), 893-912. """ nf = NF1(first_partition.communities, second_partition.communities) results = nf.summary() return MatchingResult(score=results["scores"].loc["NF1"][0]) def adjusted_rand_index( first_partition: object, second_partition: object ) -> MatchingResult: """Rand index adjusted for chance. The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings. The raw RI score is then "adjusted for chance" into the ARI score using the following scheme:: ARI = (RI - Expected_RI) / (max(RI) - Expected_RI) The adjusted Rand index is thus ensured to have a value close to 0.0 for random labeling independently of the number of clusters and samples and exactly 1.0 when the clusterings are identical (up to a permutation). ARI is a symmetric measure:: adjusted_rand_index(a, b) == adjusted_rand_index(b, a) :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.adjusted_rand_index(louvain_communities,leiden_communities) :Reference: 1. <NAME>., & <NAME>. (1985). `Comparing partitions. <https://link.springer.com/article/10.1007/BF01908075/>`_ Journal of classification, 2(1), 193-218. """ __check_partition_coverage(first_partition, second_partition) __check_partition_overlap(first_partition, second_partition) first_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(first_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] second_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(second_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] from sklearn.metrics import adjusted_rand_score return MatchingResult( score=adjusted_rand_score(first_partition_c, second_partition_c) ) def adjusted_mutual_information( first_partition: object, second_partition: object ) -> MatchingResult: """Adjusted Mutual Information between two clusterings. Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. For two clusterings :math:`U` and :math:`V`, the AMI is given as:: AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [max(H(U), H(V)) - E(MI(U, V))] This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Be mindful that this function is an order of magnitude slower than other metrics, such as the Adjusted Rand Index. :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.adjusted_mutual_information(louvain_communities,leiden_communities) :Reference: 1. <NAME>., <NAME>., & <NAME>. (2010). `Information theoretic measures for clusterings comparison: Variants, properties, normalization and correction for chance. <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf/>`_ Journal of Machine Learning Research, 11(Oct), 2837-2854. """ __check_partition_coverage(first_partition, second_partition) __check_partition_overlap(first_partition, second_partition) first_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(first_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] second_partition_c = [ x[1] for x in sorted( [ (node, nid) for nid, cluster in enumerate(second_partition.communities) for node in cluster ], key=lambda x: x[0], ) ] from sklearn.metrics import adjusted_mutual_info_score return MatchingResult( score=adjusted_mutual_info_score(first_partition_c, second_partition_c) ) def variation_of_information( first_partition: object, second_partition: object ) -> MatchingResult: """Variation of Information among two nodes partitions. $$ H(p)+H(q)-2MI(p, q) $$ where MI is the mutual information, H the partition entropy and p,q are the algorithms sets :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.variation_of_information(louvain_communities,leiden_communities) :Reference: 1. Meila, M. (2007). `Comparing clusterings - an information based distance. <https://www.sciencedirect.com/science/article/pii/S0047259X06002016/>`_ Journal of Multivariate Analysis, 98, 873-895. doi:10.1016/j.jmva.2006.11.013 """ __check_partition_coverage(first_partition, second_partition) __check_partition_overlap(first_partition, second_partition) n = float(sum([len(c1) for c1 in first_partition.communities])) sigma = 0.0 for c1 in first_partition.communities: p = len(c1) / n for c2 in second_partition.communities: q = len(c2) / n r = len(set(c1) & set(c2)) / n if r > 0.0: sigma += r * (np.log2(r / p) + np.log2(r / q)) return MatchingResult(score=abs(sigma)) def partition_closeness_simple( first_partition: object, second_partition: object ) -> MatchingResult: """Community size density closeness. Simple implementation that does not leverage kernel density estimator. $$ S_G(A,B) = \frac{1}{2} \Sum_{i=1}^{r}\Sum_{j=1}^{s} min(\frac{n^a(x^a_i)}{N^a}, \frac{n^b_j(x^b_j)}{N^b}) \delta(x_i^a,x_j^b) $$ where: $$ N^a $$ total number of communities in A of any size; $$ x^a $$ ordered list of community sizes for A; $$ n^a $$ multiplicity of community sizes for A. (symmetrically for B) :param first_partition: NodeClustering object :param second_partition: NodeClustering object :return: MatchingResult object :Example: >>> from cdlib import evaluation, algorithms >>> g = nx.karate_club_graph() >>> louvain_communities = algorithms.louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> evaluation.partition_closeness_simple(louvain_communities,leiden_communities) :Reference: 1. Dao, Vinh-Loc, <NAME>, and <NAME>. "Estimating the similarity of community detection methods based on cluster size distribution." International Conference on Complex Networks and their Applications. Springer, Cham, 2018. """ coms_a = sorted(list(set([len(c) for c in first_partition.communities]))) freq_a = defaultdict(int) for a in coms_a: freq_a[a] += 1 freq_a = [freq_a[a] for a in sorted(freq_a)] n_a = sum([coms_a[i] * freq_a[i] for i in range(0, len(coms_a))]) coms_b = sorted(list(set([len(c) for c in second_partition.communities]))) freq_b = defaultdict(int) for b in coms_b: freq_b[b] += 1 freq_b = [freq_b[b] for b in sorted(freq_b)] n_b = sum([coms_b[i] * freq_b[i] for i in range(0, len(coms_b))]) closeness = 0 for i in range(0, len(coms_a)): for j in range(0, len(coms_b)): if coms_a[i] == coms_b[j]: closeness += min( (coms_a[i] * freq_a[i]) / n_a, (coms_b[j] * freq_b[j]) / n_b ) closeness *= 0.5 return MatchingResult(score=closeness)
[ "cdlib.evaluation.internal.omega.Omega", "collections.namedtuple", "sklearn.metrics.adjusted_mutual_info_score", "numpy.log2", "sklearn.metrics.adjusted_rand_score", "collections.defaultdict", "sklearn.metrics.normalized_mutual_info_score", "nf1.NF1" ]
[((606, 647), 'collections.namedtuple', 'namedtuple', (['"""MatchingResult"""', '"""score std"""'], {}), "('MatchingResult', 'score std')\n", (616, 647), False, 'from collections import namedtuple, defaultdict\n'), ((7282, 7322), 'cdlib.evaluation.internal.omega.Omega', 'Omega', (['first_partition', 'second_partition'], {}), '(first_partition, second_partition)\n', (7287, 7322), False, 'from cdlib.evaluation.internal.omega import Omega\n'), ((8383, 8445), 'nf1.NF1', 'NF1', (['first_partition.communities', 'second_partition.communities'], {}), '(first_partition.communities, second_partition.communities)\n', (8386, 8445), False, 'from nf1 import NF1\n'), ((9760, 9822), 'nf1.NF1', 'NF1', (['first_partition.communities', 'second_partition.communities'], {}), '(first_partition.communities, second_partition.communities)\n', (9763, 9822), False, 'from nf1 import NF1\n'), ((17907, 17923), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (17918, 17923), False, 'from collections import namedtuple, defaultdict\n'), ((18180, 18196), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (18191, 18196), False, 'from collections import namedtuple, defaultdict\n'), ((3107, 3174), 'sklearn.metrics.normalized_mutual_info_score', 'normalized_mutual_info_score', (['first_partition_c', 'second_partition_c'], {}), '(first_partition_c, second_partition_c)\n', (3135, 3174), False, 'from sklearn.metrics import normalized_mutual_info_score\n'), ((12174, 12232), 'sklearn.metrics.adjusted_rand_score', 'adjusted_rand_score', (['first_partition_c', 'second_partition_c'], {}), '(first_partition_c, second_partition_c)\n', (12193, 12232), False, 'from sklearn.metrics import adjusted_rand_score\n'), ((14986, 15051), 'sklearn.metrics.adjusted_mutual_info_score', 'adjusted_mutual_info_score', (['first_partition_c', 'second_partition_c'], {}), '(first_partition_c, second_partition_c)\n', (15012, 15051), False, 'from sklearn.metrics import adjusted_mutual_info_score\n'), ((16491, 16505), 'numpy.log2', 'np.log2', (['(r / p)'], {}), '(r / p)\n', (16498, 16505), True, 'import numpy as np\n'), ((16508, 16522), 'numpy.log2', 'np.log2', (['(r / q)'], {}), '(r / q)\n', (16515, 16522), True, 'import numpy as np\n')]
import math from typing import List import numpy as np from datasets.Dataset import Dataset from models.Solution import Solution def calculate_avgValue(population: List[Solution]) -> float: avgValue = 0 for ind in population: avgValue += ind.compute_mono_objective_score() avgValue /= len(population) return avgValue def calculate_bestAvgValue(population: List[Solution]) -> float: bestAvgValue = 0 for ind in population: if bestAvgValue < ind.compute_mono_objective_score(): bestAvgValue = ind.compute_mono_objective_score() return bestAvgValue def calculate_numSolutions(population: List[Solution]) -> int: return len(set(population)) def calculate_spacing(population: List[Solution]) -> float: n = len(population) N = 2 spacing = 0 mean_objectives = [] objective = 0 for j in range(0, len(population)): objective += population[j].total_cost objective /= len(population) mean_objectives.append(objective) objective = 0 for j in range(0, len(population)): objective += population[j].total_satisfaction objective /= len(population) mean_objectives.append(objective) for j in range(0, len(population)): aux_spacing = 0 for i in range(0, N): di = mean_objectives[i] if i == 0: dij = population[j].total_cost elif i == 1: dij = population[j].total_satisfaction aux = (1 - (abs(dij) / di)) ** 2 aux_spacing += aux aux_spacing = math.sqrt(aux_spacing) spacing += aux_spacing spacing /= (n * N) return spacing def calculate_hypervolume(population: List[Solution]) -> float: objectives_diff = [] aux_max_cost, aux_max_sat = population[0].get_max_cost_satisfactions() aux_min_cost, aux_min_sat = population[0].get_min_cost_satisfactions() aux_min = float('inf') aux_max = 0 for ind in population: if ind.total_cost < aux_min: aux_min = ind.total_cost if ind.total_cost > aux_max: aux_max = ind.total_cost aux_max_norm = (aux_max-aux_min_cost)/(aux_max_cost-aux_min_cost) aux_min_norm = (aux_min-aux_min_cost)/(aux_max_cost-aux_min_cost) aux_val = aux_max_norm-aux_min_norm objectives_diff.append(aux_val) aux_min = float('inf') aux_max = 0 for ind in population: if ind.total_satisfaction < aux_min: aux_min = ind.total_satisfaction if ind.total_satisfaction > aux_max: aux_max = ind.total_satisfaction aux_max_norm = (aux_max-aux_min_sat)/(aux_max_sat-aux_min_sat) aux_min_norm = (aux_min-aux_min_sat)/(aux_max_sat-aux_min_sat) aux_val = aux_max_norm-aux_min_norm objectives_diff.append(aux_val) hypervolume = 1 for i in range(0, len(objectives_diff)): hypervolume *= objectives_diff[i] return hypervolume def eudis2(v1: float, v2: float) -> float: return math.dist(v1, v2) # return distance.euclidean(v1, v2) def calculate_spread(population: List[Solution], dataset: Dataset) -> float: MIN_OBJ1 = 0 MIN_OBJ2 = 0 MAX_OBJ1 = np.max(dataset.pbis_satisfaction_scaled) MAX_OBJ2 = np.max(dataset.pbis_cost_scaled) df = None dl = None davg = None sum_dist = None N = len(population) spread = None first_solution = population[0] last_solution = population[len(population) - 1] first_extreme = [MIN_OBJ1, MIN_OBJ2] last_extreme = [MAX_OBJ1, MAX_OBJ2] df = eudis2([first_solution.total_satisfaction, first_solution.total_cost], first_extreme) dl = eudis2([last_solution.total_satisfaction, last_solution.total_cost], last_extreme) davg = 0 dist_count = 0 for i in range(0, len(population)): for j in range(0, len(population)): # avoid distance from a point to itself if i != j: dist_count += 1 davg += eudis2([population[i].total_satisfaction, population[i].total_cost], [population[j].total_satisfaction, population[j].total_cost]) davg /= dist_count # calculate sumatory(i=1->N-1) |di-davg| sum_dist = 0 for i in range(0, len(population) - 1): di = eudis2([population[i].total_satisfaction, population[i].total_cost], [population[i + 1].total_satisfaction, population[i + 1].total_cost]) sum_dist += abs(di - davg) # spread formula spread = (df + dl + sum_dist) / (df + dl + (N - 1) * davg) return spread def calculate_mean_bits_per_sol(solutions: List[Solution]) -> float: genes = 0 n_sols = len(solutions) for sol in solutions: genes += np.count_nonzero(sol.selected) return genes/n_sols
[ "numpy.count_nonzero", "math.sqrt", "math.dist", "numpy.max" ]
[((3003, 3020), 'math.dist', 'math.dist', (['v1', 'v2'], {}), '(v1, v2)\n', (3012, 3020), False, 'import math\n'), ((3190, 3230), 'numpy.max', 'np.max', (['dataset.pbis_satisfaction_scaled'], {}), '(dataset.pbis_satisfaction_scaled)\n', (3196, 3230), True, 'import numpy as np\n'), ((3246, 3278), 'numpy.max', 'np.max', (['dataset.pbis_cost_scaled'], {}), '(dataset.pbis_cost_scaled)\n', (3252, 3278), True, 'import numpy as np\n'), ((1581, 1603), 'math.sqrt', 'math.sqrt', (['aux_spacing'], {}), '(aux_spacing)\n', (1590, 1603), False, 'import math\n'), ((4782, 4812), 'numpy.count_nonzero', 'np.count_nonzero', (['sol.selected'], {}), '(sol.selected)\n', (4798, 4812), True, 'import numpy as np\n')]
import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt import numpy as np import os from nanopores.tools import fields from scipy.interpolate import interp1d HOME = os.path.expanduser("~") DATADIR = os.path.join(HOME, "Dropbox", "nanopores", "fields") fields.set_dir(DATADIR) data = fields.get_fields("pugh_diff3D_cross", bulkbc=True, rMolecule=2.0779) def smooth3(l): A=np.array(l) B=A[:] ker=np.array([1./3,1./3,1./3]) n=int(ker.shape[0]/2.) for i in range(n,A.shape[0]-n): B[i]=np.inner(A[i-n:i+n+1],ker) return list(B) def smooth5(l): A=np.array(l) B=A[:] ker=np.array([.2,.2,.2,.2,.2]) n=int(ker.shape[0]/2.) for i in range(n,A.shape[0]-n): B[i]=np.inner(A[i-n:i+n+1],ker) return list(B) def smootha(l): A=np.array(l) B=A[:] ker=np.array([10.,12.,15.,12.,10.]) ker=ker/np.sum(ker) n=int(ker.shape[0]/2.) for i in range(n,A.shape[0]-n): B[i]=np.inner(A[i-n:i+n+1],ker) return list(B) x = [z[0] for z in data["x"]] data, x = fields._sorted(data, x) eps=5e-3 x_=x[:] #x_.extend([1.,1.+eps,1.+2*eps,1.+3*eps]) x.extend([(x[-1]+1.)/2.,1.,1.+eps,1.+2*eps,1.+3*eps,1.+4*eps,1.+5*eps]) dstr = ["x", "y", "z"] Dxx = [D[0][0] for D in data["D"]] Dyy = [D[1][1] for D in data["D"]] Dzz = [D[2][2] for D in data["D"]] Dxx_ = [D[0][0] for D in data["D"]] Dyy_ = [D[1][1] for D in data["D"]] Dzz_ = [D[2][2] for D in data["D"]] Dxx.extend([0.,0.,0.,0.,0.,0.,0.]) Dyy.extend([Dyy[-1]/2.,0.,0.,0.,0.,0.,0.]) Dzz.extend([Dzz[-1]/2.,0.,0.,0.,0.,0.,0.]) #Dxx_.extend([0.,0.,0.,0.]) #Dyy_.extend([0.,0.,0.,0.]) #Dzz_.extend([0.,0.,0.,0.]) Dxx=smooth5(smooth3(Dxx)) Dyy=smooth5(smooth3(Dyy)) Dzz=smooth5(smooth3(Dzz)) Dx = interp1d(x,Dxx) Dy = interp1d(x,Dyy) Dz = interp1d(x,Dzz) DDxx = [0.]+[(Dxx[i+1]-Dxx[i-1])/(x[i+1]-x[i-1]) for i in range(1,len(x)-1)]+[0.] DDyy = [0.]+[(Dyy[i+1]-Dyy[i-1])/(x[i+1]-x[i-1]) for i in range(1,len(x)-1)]+[0.] DDzz = [0.]+[(Dzz[i+1]-Dzz[i-1])/(x[i+1]-x[i-1]) for i in range(1,len(x)-1)]+[0.] dDx = interp1d(x,DDxx) dDy = interp1d(x,DDyy) dDz = interp1d(x,DDzz) if __name__=='__main__': xc=np.linspace(0.,1.,100) plt.plot(x_,Dxx_,color='blue',linestyle=':') plt.scatter(x_,Dxx_,color='blue') plt.scatter(x,Dxx,color='blue') #plt.plot(x,Dxx,color='blue') plt.plot(xc,Dx(xc),color='blue',label=r"$D_{%s%s}$" % (dstr[0], dstr[0])) plt.scatter(x,DDxx,color='blue') #plt.plot(x,DDxx,color='blue') plt.plot(xc,dDx(xc),color='blue') plt.plot(x_,Dyy_,color='red',linestyle=':') plt.scatter(x_,Dyy_,color='red') plt.scatter(x,Dyy,color='red') #plt.plot(x,Dyy,color='red') plt.plot(xc,Dy(xc),color='red',label=r"$D_{%s%s}$" % (dstr[1], dstr[1])) plt.scatter(x,DDyy,color='red') #plt.plot(x,DDyy,color='red') plt.plot(xc,dDy(xc),color='red') plt.plot(x_,Dzz_,color='green',linestyle=':') plt.scatter(x_,Dzz_,color='green') plt.scatter(x,Dzz,color='green') #plt.plot(x,Dzz,color='green') plt.plot(xc,Dz(xc),color='green',label=r"$D_{%s%s}$" % (dstr[2], dstr[2])) plt.scatter(x,DDzz,color='green') #plt.plot(x,DDzz,color='green') plt.plot(xc,dDz(xc),color='green') plt.xlabel('distance from pore center [nm]') plt.ylabel('diffusivity relative to bulk') plt.legend(loc='lower left') plt.tight_layout() plt.savefig('get_new.png')
[ "nanopores.tools.fields.get_fields", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.use", "matplotlib.pyplot.legend", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "os.path.join", "scipy.interpolate.interp1d", "numpy.inner", "numpy.array", "numpy.linspace", "numpy.sum", "nanopores.tools.fields._sorted", "matplotlib.pyplot.scatter", "matplotlib.pyplot.tight_layout", "os.path.expanduser", "nanopores.tools.fields.set_dir" ]
[((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((188, 211), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (206, 211), False, 'import os\n'), ((222, 274), 'os.path.join', 'os.path.join', (['HOME', '"""Dropbox"""', '"""nanopores"""', '"""fields"""'], {}), "(HOME, 'Dropbox', 'nanopores', 'fields')\n", (234, 274), False, 'import os\n'), ((275, 298), 'nanopores.tools.fields.set_dir', 'fields.set_dir', (['DATADIR'], {}), '(DATADIR)\n', (289, 298), False, 'from nanopores.tools import fields\n'), ((307, 376), 'nanopores.tools.fields.get_fields', 'fields.get_fields', (['"""pugh_diff3D_cross"""'], {'bulkbc': '(True)', 'rMolecule': '(2.0779)'}), "('pugh_diff3D_cross', bulkbc=True, rMolecule=2.0779)\n", (324, 376), False, 'from nanopores.tools import fields\n'), ((1053, 1076), 'nanopores.tools.fields._sorted', 'fields._sorted', (['data', 'x'], {}), '(data, x)\n', (1067, 1076), False, 'from nanopores.tools import fields\n'), ((1732, 1748), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'Dxx'], {}), '(x, Dxx)\n', (1740, 1748), False, 'from scipy.interpolate import interp1d\n'), ((1753, 1769), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'Dyy'], {}), '(x, Dyy)\n', (1761, 1769), False, 'from scipy.interpolate import interp1d\n'), ((1774, 1790), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'Dzz'], {}), '(x, Dzz)\n', (1782, 1790), False, 'from scipy.interpolate import interp1d\n'), ((2044, 2061), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'DDxx'], {}), '(x, DDxx)\n', (2052, 2061), False, 'from scipy.interpolate import interp1d\n'), ((2067, 2084), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'DDyy'], {}), '(x, DDyy)\n', (2075, 2084), False, 'from scipy.interpolate import interp1d\n'), ((2090, 2107), 'scipy.interpolate.interp1d', 'interp1d', (['x', 'DDzz'], {}), '(x, DDzz)\n', (2098, 2107), False, 'from scipy.interpolate import interp1d\n'), ((399, 410), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (407, 410), True, 'import numpy as np\n'), ((430, 467), 'numpy.array', 'np.array', (['[1.0 / 3, 1.0 / 3, 1.0 / 3]'], {}), '([1.0 / 3, 1.0 / 3, 1.0 / 3])\n', (438, 467), True, 'import numpy as np\n'), ((601, 612), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (609, 612), True, 'import numpy as np\n'), ((632, 667), 'numpy.array', 'np.array', (['[0.2, 0.2, 0.2, 0.2, 0.2]'], {}), '([0.2, 0.2, 0.2, 0.2, 0.2])\n', (640, 667), True, 'import numpy as np\n'), ((803, 814), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (811, 814), True, 'import numpy as np\n'), ((834, 874), 'numpy.array', 'np.array', (['[10.0, 12.0, 15.0, 12.0, 10.0]'], {}), '([10.0, 12.0, 15.0, 12.0, 10.0])\n', (842, 874), True, 'import numpy as np\n'), ((2137, 2163), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(100)'], {}), '(0.0, 1.0, 100)\n', (2148, 2163), True, 'import numpy as np\n'), ((2161, 2208), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', 'Dxx_'], {'color': '"""blue"""', 'linestyle': '""":"""'}), "(x_, Dxx_, color='blue', linestyle=':')\n", (2169, 2208), True, 'from matplotlib import pyplot as plt\n'), ((2207, 2242), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_', 'Dxx_'], {'color': '"""blue"""'}), "(x_, Dxx_, color='blue')\n", (2218, 2242), True, 'from matplotlib import pyplot as plt\n'), ((2242, 2275), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'Dxx'], {'color': '"""blue"""'}), "(x, Dxx, color='blue')\n", (2253, 2275), True, 'from matplotlib import pyplot as plt\n'), ((2382, 2416), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'DDxx'], {'color': '"""blue"""'}), "(x, DDxx, color='blue')\n", (2393, 2416), True, 'from matplotlib import pyplot as plt\n'), ((2486, 2532), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', 'Dyy_'], {'color': '"""red"""', 'linestyle': '""":"""'}), "(x_, Dyy_, color='red', linestyle=':')\n", (2494, 2532), True, 'from matplotlib import pyplot as plt\n'), ((2531, 2565), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_', 'Dyy_'], {'color': '"""red"""'}), "(x_, Dyy_, color='red')\n", (2542, 2565), True, 'from matplotlib import pyplot as plt\n'), ((2565, 2597), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'Dyy'], {'color': '"""red"""'}), "(x, Dyy, color='red')\n", (2576, 2597), True, 'from matplotlib import pyplot as plt\n'), ((2702, 2735), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'DDyy'], {'color': '"""red"""'}), "(x, DDyy, color='red')\n", (2713, 2735), True, 'from matplotlib import pyplot as plt\n'), ((2803, 2851), 'matplotlib.pyplot.plot', 'plt.plot', (['x_', 'Dzz_'], {'color': '"""green"""', 'linestyle': '""":"""'}), "(x_, Dzz_, color='green', linestyle=':')\n", (2811, 2851), True, 'from matplotlib import pyplot as plt\n'), ((2850, 2886), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_', 'Dzz_'], {'color': '"""green"""'}), "(x_, Dzz_, color='green')\n", (2861, 2886), True, 'from matplotlib import pyplot as plt\n'), ((2886, 2920), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'Dzz'], {'color': '"""green"""'}), "(x, Dzz, color='green')\n", (2897, 2920), True, 'from matplotlib import pyplot as plt\n'), ((3029, 3064), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'DDzz'], {'color': '"""green"""'}), "(x, DDzz, color='green')\n", (3040, 3064), True, 'from matplotlib import pyplot as plt\n'), ((3136, 3180), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""distance from pore center [nm]"""'], {}), "('distance from pore center [nm]')\n", (3146, 3180), True, 'from matplotlib import pyplot as plt\n'), ((3182, 3224), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""diffusivity relative to bulk"""'], {}), "('diffusivity relative to bulk')\n", (3192, 3224), True, 'from matplotlib import pyplot as plt\n'), ((3226, 3254), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""'}), "(loc='lower left')\n", (3236, 3254), True, 'from matplotlib import pyplot as plt\n'), ((3256, 3274), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3272, 3274), True, 'from matplotlib import pyplot as plt\n'), ((3276, 3302), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""get_new.png"""'], {}), "('get_new.png')\n", (3287, 3302), True, 'from matplotlib import pyplot as plt\n'), ((533, 566), 'numpy.inner', 'np.inner', (['A[i - n:i + n + 1]', 'ker'], {}), '(A[i - n:i + n + 1], ker)\n', (541, 566), True, 'import numpy as np\n'), ((735, 768), 'numpy.inner', 'np.inner', (['A[i - n:i + n + 1]', 'ker'], {}), '(A[i - n:i + n + 1], ker)\n', (743, 768), True, 'import numpy as np\n'), ((878, 889), 'numpy.sum', 'np.sum', (['ker'], {}), '(ker)\n', (884, 889), True, 'import numpy as np\n'), ((966, 999), 'numpy.inner', 'np.inner', (['A[i - n:i + n + 1]', 'ker'], {}), '(A[i - n:i + n + 1], ker)\n', (974, 999), True, 'import numpy as np\n')]
import os import nibabel import numpy as np import random from scipy import ndimage import SimpleITK as sitk def load_nifty_volume_as_array(filename, with_header = False): """ load nifty image into numpy array, and transpose it based on the [z,y,x] axis order The output array shape is like [Depth, Height, Width] inputs: filename: the input file name, should be *.nii or *.nii.gz with_header: return affine and hearder infomation outputs: data: a numpy data array """ img = nibabel.load(filename) data = img.get_data() data = np.transpose(data, [2,1,0]) if(with_header): return data, img.affine, img.header else: return data def save_array_as_nifty_volume(data, filename, reference_name = None): """ save a numpy array as nifty image inputs: data: a numpy array with shape [Depth, Height, Width] filename: the ouput file name reference_name: file name of the reference image of which affine and header are used outputs: None """ img = sitk.GetImageFromArray(data) if(reference_name is not None): img_ref = sitk.ReadImage(reference_name) img.CopyInformation(img_ref) sitk.WriteImage(img, filename)
[ "SimpleITK.GetImageFromArray", "nibabel.load", "SimpleITK.WriteImage", "SimpleITK.ReadImage", "numpy.transpose" ]
[((529, 551), 'nibabel.load', 'nibabel.load', (['filename'], {}), '(filename)\n', (541, 551), False, 'import nibabel\n'), ((589, 618), 'numpy.transpose', 'np.transpose', (['data', '[2, 1, 0]'], {}), '(data, [2, 1, 0])\n', (601, 618), True, 'import numpy as np\n'), ((1071, 1099), 'SimpleITK.GetImageFromArray', 'sitk.GetImageFromArray', (['data'], {}), '(data)\n', (1093, 1099), True, 'import SimpleITK as sitk\n'), ((1226, 1256), 'SimpleITK.WriteImage', 'sitk.WriteImage', (['img', 'filename'], {}), '(img, filename)\n', (1241, 1256), True, 'import SimpleITK as sitk\n'), ((1154, 1184), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['reference_name'], {}), '(reference_name)\n', (1168, 1184), True, 'import SimpleITK as sitk\n')]
#!/usr/bin/env python import rospy as rp import numpy as np import math as math from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint from scipy.spatial import KDTree from std_msgs.msg import Int32 ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the doc, you should ideally first implement a version which does not care about traffic lights or obstacles. Once you have created dbw_node, you will update this node to use the status of traffic lights too. Please note that our simulator also provides the exact location of traffic lights and their current status in `/vehicle/traffic_lights` message. You can use this message to build this node as well as to verify your TL classifier. TODO (for Yousuf and Aaron): Stopline location for each traffic light. ''' # Number of waypoints we will publish. LOOKAHEAD_WPS = 150 MAX_DECEL = 0.5 class MotionState( ): Go, Stop = range( 2 ) class WaypointUpdater( object ): def __init__( self ): rp.init_node( 'waypoint_updater' ) # TODO: Add a subscriber for /traffic_waypoint and /obstacle_waypoint below rp.Subscriber( '/current_pose', PoseStamped, self.pose_cb ) rp.Subscriber( '/base_waypoints', Lane, self.waypoints_cb ) rp.Subscriber( '/traffic_waypoint', Int32, self.traffic_cb ) rp.Subscriber( '/current_velocity', TwistStamped, self.velocity_cb ) self.final_waypoints_pub = rp.Publisher( 'final_waypoints', Lane, queue_size=1 ) # TODO: Add other member variables you need below self.base_lane = None self.pose = None self.waypoints_2d = None self.waypoint_tree = None self.nearest_light = None self.vehicle_velocity = None # in m/s self.motion_state = MotionState.Go self.deceleration_rate = None self.acceleration_rate = 0.75 # m/s self.previous_velocity = None self.loop( ) def loop( self ): rate = rp.Rate( 10 ) while not rp.is_shutdown( ): if self.pose and self.base_lane and self.waypoint_tree: # get closest waypoint #closest_waypoint_index = self.get_closest_waypoint_id( ) self.publish_waypoints( ) self.previous_velocity = self.vehicle_velocity rate.sleep( ) def publish_waypoints( self ): self.final_waypoints_pub.publish( self.generate_lane( ) ) def generate_lane( self ): lane = Lane( ) closest_idx = self.get_closest_waypoint_id( ) farthest_idx = closest_idx + LOOKAHEAD_WPS base_waypoints = self.base_lane[ closest_idx:farthest_idx ] if self.nearest_light != None and \ self.nearest_light <= farthest_idx and \ self.nearest_light >= closest_idx: self.motion_state = MotionState.Stop base_waypoints = self.decelerate( base_waypoints, closest_idx ) elif self.motion_state == MotionState.Stop: self.motion_state = MotionState.Go self.deceleration_rate = None if self.motion_state == MotionState.Go: if abs( self.vehicle_velocity - self.get_waypoint_velocity( \ base_waypoints[ 0 ] ) ) > 1.0: if self.previous_velocity == None: start_vel = self.vehicle_velocity else: start_vel = max( self.previous_velocity + 0.2, self.vehicle_velocity ) base_waypoints = self.accelerate( base_waypoints, start_vel ) else: self.acceleration_start_velocity = None lane.waypoints = base_waypoints return lane def accelerate( self, waypoints, start_velocity ): new_waypoints = [ ] for i, wp in enumerate( waypoints ): p = Waypoint( ) p.pose = wp.pose distance = self.distance( waypoints, 0, i ) target_vel = start_velocity + distance * self.acceleration_rate if target_vel < 0.5: target_vel = 0.5 p.twist.twist.linear.x = min( target_vel, self.get_waypoint_velocity( wp ) ) new_waypoints.append( p ) return new_waypoints def decelerate( self, waypoints, start_idx ): new_waypoints = [ ] speed = self.vehicle_velocity # two waypoints back from line so front of car stops earlier stop_idx = self.nearest_light - start_idx - 2 for i, wp in enumerate( waypoints ): p = Waypoint( ) p.pose = wp.pose dist = self.distance( waypoints, i, stop_idx ) if i >= stop_idx: target_vel = 0 elif dist < 15: if self.deceleration_rate == None: self.deceleration_rate = self.vehicle_velocity / dist target_vel = self.deceleration_rate * dist if target_vel <= 1.0: target_vel = 0.0 target_vel = min( target_vel, self.get_waypoint_velocity( wp ) ) else: target_vel = self.get_waypoint_velocity( wp ) p.twist.twist.linear.x = target_vel new_waypoints.append( p ) return new_waypoints def get_closest_waypoint_id( self ): x = self.pose.pose.position.x y = self.pose.pose.position.y closest_idx = self.waypoint_tree.query( [x, y], 1 )[1] # Check if closest waypoint is ahead or behind the vehicle closest_wp = np.array( self.waypoints_2d[ closest_idx ] ) previous_wp = np.array( self.waypoints_2d[ closest_idx - 1 ] ) # Equation for hyperplane through closest_coords waypoint_vector = closest_wp - previous_wp position_vector = np.array( [x, y] ) - closest_wp val = np.dot( waypoint_vector, position_vector ) if val > 0: closest_idx = ( closest_idx + 1 ) % len( self.waypoints_2d ) return closest_idx def pose_cb(self, msg): # TODO: Implement self.pose = msg def waypoints_cb( self, waypoints ): # TODO: Implement self.base_lane = waypoints.waypoints if not self.waypoints_2d: self.waypoints_2d = [ [ waypoint.pose.pose.position.x, waypoint.pose.pose.position.y ] for waypoint in waypoints.waypoints ] self.waypoint_tree = KDTree( self.waypoints_2d ) def traffic_cb( self, msg ): # TODO: Callback for /traffic_waypoint message. Implement if( msg.data == -1 ): self.nearest_light = None else: self.nearest_light = msg.data def velocity_cb( self, velocity ): self.vehicle_velocity = velocity.twist.linear.x def obstacle_cb(self, msg): # TODO: Callback for /obstacle_waypoint message. We will implement it later pass def get_waypoint_velocity( self, waypoint ): return waypoint.twist.twist.linear.x def set_waypoint_velocity( self, waypoints, waypoint, velocity ): waypoints[ waypoint ].twist.twist.linear.x = velocity def distance(self, waypoints, wp1, wp2): dist = 0 dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2) for i in range(wp1, wp2+1): dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position) wp1 = i return dist if __name__ == '__main__': try: WaypointUpdater() except rp.ROSInterruptException: rp.logerr('Could not start waypoint updater node.')
[ "rospy.logerr", "rospy.Subscriber", "rospy.is_shutdown", "rospy.init_node", "scipy.spatial.KDTree", "math.sqrt", "numpy.array", "numpy.dot", "rospy.Rate", "styx_msgs.msg.Waypoint", "rospy.Publisher", "styx_msgs.msg.Lane" ]
[((1071, 1103), 'rospy.init_node', 'rp.init_node', (['"""waypoint_updater"""'], {}), "('waypoint_updater')\n", (1083, 1103), True, 'import rospy as rp\n'), ((1199, 1256), 'rospy.Subscriber', 'rp.Subscriber', (['"""/current_pose"""', 'PoseStamped', 'self.pose_cb'], {}), "('/current_pose', PoseStamped, self.pose_cb)\n", (1212, 1256), True, 'import rospy as rp\n'), ((1267, 1324), 'rospy.Subscriber', 'rp.Subscriber', (['"""/base_waypoints"""', 'Lane', 'self.waypoints_cb'], {}), "('/base_waypoints', Lane, self.waypoints_cb)\n", (1280, 1324), True, 'import rospy as rp\n'), ((1335, 1393), 'rospy.Subscriber', 'rp.Subscriber', (['"""/traffic_waypoint"""', 'Int32', 'self.traffic_cb'], {}), "('/traffic_waypoint', Int32, self.traffic_cb)\n", (1348, 1393), True, 'import rospy as rp\n'), ((1404, 1470), 'rospy.Subscriber', 'rp.Subscriber', (['"""/current_velocity"""', 'TwistStamped', 'self.velocity_cb'], {}), "('/current_velocity', TwistStamped, self.velocity_cb)\n", (1417, 1470), True, 'import rospy as rp\n'), ((1509, 1560), 'rospy.Publisher', 'rp.Publisher', (['"""final_waypoints"""', 'Lane'], {'queue_size': '(1)'}), "('final_waypoints', Lane, queue_size=1)\n", (1521, 1560), True, 'import rospy as rp\n'), ((2099, 2110), 'rospy.Rate', 'rp.Rate', (['(10)'], {}), '(10)\n', (2106, 2110), True, 'import rospy as rp\n'), ((2613, 2619), 'styx_msgs.msg.Lane', 'Lane', ([], {}), '()\n', (2617, 2619), False, 'from styx_msgs.msg import Lane, Waypoint\n'), ((5765, 5805), 'numpy.array', 'np.array', (['self.waypoints_2d[closest_idx]'], {}), '(self.waypoints_2d[closest_idx])\n', (5773, 5805), True, 'import numpy as np\n'), ((5832, 5876), 'numpy.array', 'np.array', (['self.waypoints_2d[closest_idx - 1]'], {}), '(self.waypoints_2d[closest_idx - 1])\n', (5840, 5876), True, 'import numpy as np\n'), ((6063, 6103), 'numpy.dot', 'np.dot', (['waypoint_vector', 'position_vector'], {}), '(waypoint_vector, position_vector)\n', (6069, 6103), True, 'import numpy as np\n'), ((2132, 2148), 'rospy.is_shutdown', 'rp.is_shutdown', ([], {}), '()\n', (2146, 2148), True, 'import rospy as rp\n'), ((4024, 4034), 'styx_msgs.msg.Waypoint', 'Waypoint', ([], {}), '()\n', (4032, 4034), False, 'from styx_msgs.msg import Lane, Waypoint\n'), ((4767, 4777), 'styx_msgs.msg.Waypoint', 'Waypoint', ([], {}), '()\n', (4775, 4777), False, 'from styx_msgs.msg import Lane, Waypoint\n'), ((6016, 6032), 'numpy.array', 'np.array', (['[x, y]'], {}), '([x, y])\n', (6024, 6032), True, 'import numpy as np\n'), ((6668, 6693), 'scipy.spatial.KDTree', 'KDTree', (['self.waypoints_2d'], {}), '(self.waypoints_2d)\n', (6674, 6693), False, 'from scipy.spatial import KDTree\n'), ((7468, 7533), 'math.sqrt', 'math.sqrt', (['((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)'], {}), '((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2)\n', (7477, 7533), True, 'import math as math\n'), ((7799, 7850), 'rospy.logerr', 'rp.logerr', (['"""Could not start waypoint updater node."""'], {}), "('Could not start waypoint updater node.')\n", (7808, 7850), True, 'import rospy as rp\n')]
import unittest import os import numpy as np from constants import ( del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR, ) from perform.constants import REAL_TYPE from perform.system_solver import SystemSolver from perform.input_funcs import read_restart_file from perform.gas_model.calorically_perfect_gas import CaloricallyPerfectGas from perform.time_integrator.implicit_integrator import BDF from perform.solution.solution_interior import SolutionInterior class SolutionIntInitTestCase(unittest.TestCase): def setUp(self): self.output_mode, self.output_dir = get_output_mode() # set chemistry self.chem_dict = CHEM_DICT_REACT self.gas = CaloricallyPerfectGas(self.chem_dict) # set time integrator self.param_dict = {} self.param_dict["dt"] = 1e-7 self.param_dict["time_scheme"] = "bdf" self.param_dict["time_order"] = 2 self.time_int = BDF(self.param_dict) # generate working directory gen_test_dir() # generate input text files solution_domain_setup() # set SystemSolver self.solver = SystemSolver(TEST_DIR) self.num_cells = 2 self.num_reactions = 1 def tearDown(self): del_test_dir() def test_solution_int_init(self): sol = SolutionInterior( self.gas, SOL_PRIM_IN_REACT, self.solver, self.num_cells, self.num_reactions, self.time_int ) if self.output_mode: np.save(os.path.join(self.output_dir, "sol_int_init_sol_cons.npy"), sol.sol_cons) else: self.assertTrue(np.array_equal(sol.sol_prim, SOL_PRIM_IN_REACT)) self.assertTrue( np.allclose(sol.sol_cons, np.load(os.path.join(self.output_dir, "sol_int_init_sol_cons.npy"))) ) # TODO: a LOT of checking of other variables class SolutionIntMethodsTestCase(unittest.TestCase): def setUp(self): self.output_mode, self.output_dir = get_output_mode() # set chemistry self.chem_dict = CHEM_DICT_REACT self.gas = CaloricallyPerfectGas(self.chem_dict) # set time integrator self.param_dict = {} self.param_dict["dt"] = 1e-7 self.param_dict["time_scheme"] = "bdf" self.param_dict["time_order"] = 2 self.time_int = BDF(self.param_dict) # generate working directory gen_test_dir() # generate input text files solution_domain_setup() # set SystemSolver self.solver = SystemSolver(TEST_DIR) self.num_cells = 2 self.num_reactions = 1 self.sol = SolutionInterior( self.gas, SOL_PRIM_IN_REACT, self.solver, self.num_cells, self.num_reactions, self.time_int ) def tearDown(self): del_test_dir() def test_calc_sol_jacob(self): sol_jacob = self.sol.calc_sol_jacob(inverse=False) sol_jacob_inv = self.sol.calc_sol_jacob(inverse=True) if self.output_mode: np.save(os.path.join(self.output_dir, "sol_int_sol_jacob.npy"), sol_jacob) np.save(os.path.join(self.output_dir, "sol_int_sol_jacob_inv.npy"), sol_jacob_inv) else: self.assertTrue(np.allclose(sol_jacob, np.load(os.path.join(self.output_dir, "sol_int_sol_jacob.npy")))) self.assertTrue( np.allclose(sol_jacob_inv, np.load(os.path.join(self.output_dir, "sol_int_sol_jacob_inv.npy"))) ) def test_update_snapshots(self): # update the snapshot matrix for self.solver.iter in range(1, self.solver.num_steps + 1): if (self.solver.iter % self.solver.out_interval) == 0: self.sol.update_snapshots(self.solver) self.assertTrue(np.array_equal(self.sol.prim_snap, np.repeat(self.sol.sol_prim[:, :, None], 6, axis=2))) self.assertTrue(np.array_equal(self.sol.cons_snap, np.repeat(self.sol.sol_cons[:, :, None], 6, axis=2))) self.assertTrue( np.array_equal(self.sol.reaction_source_snap, np.repeat(self.sol.reaction_source[:, :, None], 5, axis=2)) ) self.assertTrue( np.array_equal(self.sol.heat_release_snap, np.repeat(self.sol.heat_release[:, None], 5, axis=1)) ) self.assertTrue(np.array_equal(self.sol.rhs_snap, np.repeat(self.sol.rhs[:, :, None], 5, axis=2))) def test_snapshot_output(self): for self.solver.iter in range(1, self.solver.num_steps + 1): # update the snapshot matrix if (self.solver.iter % self.solver.out_interval) == 0: self.sol.update_snapshots(self.solver) # write and check intermediate results if ((self.solver.iter % self.solver.out_itmdt_interval) == 0) and ( self.solver.iter != self.solver.num_steps ): self.sol.write_snapshots(self.solver, intermediate=True, failed=False) sol_prim_itmdt = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_prim_" + self.solver.sim_type + "_ITMDT.npy") ) sol_cons_itmdt = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_cons_" + self.solver.sim_type + "_ITMDT.npy") ) source_itmdt = np.load( os.path.join(self.solver.unsteady_output_dir, "source_" + self.solver.sim_type + "_ITMDT.npy") ) heat_release_itmdt = np.load( os.path.join(self.solver.unsteady_output_dir, "heat_release_" + self.solver.sim_type + "_ITMDT.npy") ) rhs_itmdt = np.load( os.path.join(self.solver.unsteady_output_dir, "rhs_" + self.solver.sim_type + "_ITMDT.npy") ) self.assertTrue(np.array_equal(sol_prim_itmdt, np.repeat(self.sol.sol_prim[:, :, None], 3, axis=2))) self.assertTrue(np.array_equal(sol_cons_itmdt, np.repeat(self.sol.sol_cons[:, :, None], 3, axis=2))) self.assertTrue( np.array_equal(source_itmdt, np.repeat(self.sol.reaction_source[:, :, None], 2, axis=2)) ) self.assertTrue( np.array_equal(heat_release_itmdt, np.repeat(self.sol.heat_release[:, None], 2, axis=1)) ) self.assertTrue(np.array_equal(rhs_itmdt, np.repeat(self.sol.rhs[:, :, None], 2, axis=2))) # write and check "failed" snapshots if self.solver.iter == 7: self.sol.write_snapshots(self.solver, intermediate=False, failed=True) sol_prim_failed = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_prim_" + self.solver.sim_type + "_FAILED.npy") ) sol_cons_failed = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_cons_" + self.solver.sim_type + "_FAILED.npy") ) source_failed = np.load( os.path.join(self.solver.unsteady_output_dir, "source_" + self.solver.sim_type + "_FAILED.npy") ) heat_release_failed = np.load( os.path.join( self.solver.unsteady_output_dir, "heat_release_" + self.solver.sim_type + "_FAILED.npy" ) ) rhs_failed = np.load( os.path.join(self.solver.unsteady_output_dir, "rhs_" + self.solver.sim_type + "_FAILED.npy") ) self.assertTrue(np.array_equal(sol_prim_failed, np.repeat(self.sol.sol_prim[:, :, None], 4, axis=2))) self.assertTrue(np.array_equal(sol_cons_failed, np.repeat(self.sol.sol_cons[:, :, None], 4, axis=2))) self.assertTrue( np.array_equal(source_failed, np.repeat(self.sol.reaction_source[:, :, None], 3, axis=2)) ) self.assertTrue( np.array_equal(heat_release_failed, np.repeat(self.sol.heat_release[:, None], 3, axis=1)) ) self.assertTrue(np.array_equal(rhs_failed, np.repeat(self.sol.rhs[:, :, None], 3, axis=2))) # delete intermediate results and check that they deleted properly self.sol.delete_itmdt_snapshots(self.solver) self.assertFalse( os.path.isfile( os.path.join(self.solver.unsteady_output_dir, "sol_prim_" + self.solver.sim_type + "_ITMDT.npy") ) ) self.assertFalse( os.path.isfile( os.path.join(self.solver.unsteady_output_dir, "sol_cons_" + self.solver.sim_type + "_ITMDT.npy") ) ) self.assertFalse( os.path.isfile( os.path.join(self.solver.unsteady_output_dir, "source_" + self.solver.sim_type + "_ITMDT.npy") ) ) self.assertFalse( os.path.isfile( os.path.join(self.solver.unsteady_output_dir, "heat_release_" + self.solver.sim_type + "_ITMDT.npy") ) ) self.assertFalse( os.path.isfile(os.path.join(self.solver.unsteady_output_dir, "rhs_" + self.solver.sim_type + "_ITMDT.npy")) ) # write final snapshots self.sol.write_snapshots(self.solver, intermediate=False, failed=False) sol_prim_final = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_prim_" + self.solver.sim_type + ".npy") ) sol_cons_final = np.load( os.path.join(self.solver.unsteady_output_dir, "sol_cons_" + self.solver.sim_type + ".npy") ) source_final = np.load(os.path.join(self.solver.unsteady_output_dir, "source_" + self.solver.sim_type + ".npy")) heat_release_final = np.load( os.path.join(self.solver.unsteady_output_dir, "heat_release_" + self.solver.sim_type + ".npy") ) rhs_final = np.load(os.path.join(self.solver.unsteady_output_dir, "rhs_" + self.solver.sim_type + ".npy")) self.assertTrue(np.array_equal(sol_prim_final, np.repeat(self.sol.sol_prim[:, :, None], 6, axis=2))) self.assertTrue(np.array_equal(sol_cons_final, np.repeat(self.sol.sol_cons[:, :, None], 6, axis=2))) self.assertTrue(np.array_equal(source_final, np.repeat(self.sol.reaction_source[:, :, None], 5, axis=2))) self.assertTrue(np.array_equal(heat_release_final, np.repeat(self.sol.heat_release[:, None], 5, axis=1))) self.assertTrue(np.array_equal(rhs_final, np.repeat(self.sol.rhs[:, :, None], 5, axis=2))) def test_write_restart_file(self): sol_cons = self.sol.sol_cons self.solver.sol_time = 1e-4 self.solver.iter = 2 self.solver.restart_iter = 4 self.sol.write_restart_file(self.solver) self.assertEqual(self.solver.restart_iter, 5) # check restart files restart_data = np.load(os.path.join(self.solver.restart_output_dir, "restart_file_4.npz")) self.assertTrue( np.array_equal( restart_data["sol_prim"], np.repeat(SOL_PRIM_IN_REACT[:, :, None], 2, axis=-1), ) ) self.assertTrue( np.array_equal( restart_data["sol_cons"], np.repeat(sol_cons[:, :, None], 2, axis=-1), ) ) self.assertEqual(float(restart_data["sol_time"]), 1e-4) # check iteration files restart_iter = int(np.loadtxt(os.path.join(self.solver.restart_output_dir, "restart_iter.dat"))) self.assertEqual(restart_iter, 4) def test_read_restart_file(self): self.solver.sol_time = 1e-4 self.solver.iter = 2 self.solver.restart_iter = 4 self.sol.write_restart_file(self.solver) sol_time, sol_prim, restart_iter = read_restart_file(self.solver) self.assertEqual(sol_time, 1e-4) self.assertEqual(restart_iter, 5) # 1 is added to avoid overwriting self.assertTrue( np.array_equal( sol_prim, np.repeat(SOL_PRIM_IN_REACT[:, :, None], 2, axis=-1), ) ) def test_calc_d_sol_norms(self): self.solver.iter = 3 self.sol.d_sol_norm_hist = np.zeros((self.solver.num_steps, 2), dtype=REAL_TYPE) self.sol.sol_hist_prim[0] = self.sol.sol_prim * 2.0 self.sol.calc_d_sol_norms(self.solver, "implicit") self.assertAlmostEqual(self.sol.d_sol_norm_hist[2, 0], 3.46573790883) self.assertAlmostEqual(self.sol.d_sol_norm_hist[2, 1], 3.45416666667) def test_calc_res_norms(self): self.solver.iter = 3 self.sol.res = self.sol.sol_prim.copy() self.sol.calc_res_norms(self.solver, 0) self.assertAlmostEqual(self.sol.res_norm_hist[2, 0], 3.46573790883) self.assertAlmostEqual(self.sol.res_norm_hist[2, 1], 3.45416666667)
[ "numpy.repeat", "perform.input_funcs.read_restart_file", "constants.del_test_dir", "perform.solution.solution_interior.SolutionInterior", "os.path.join", "constants.gen_test_dir", "constants.get_output_mode", "perform.time_integrator.implicit_integrator.BDF", "constants.solution_domain_setup", "perform.system_solver.SystemSolver", "numpy.zeros", "numpy.array_equal", "perform.gas_model.calorically_perfect_gas.CaloricallyPerfectGas" ]
[((670, 687), 'constants.get_output_mode', 'get_output_mode', ([], {}), '()\n', (685, 687), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((773, 810), 'perform.gas_model.calorically_perfect_gas.CaloricallyPerfectGas', 'CaloricallyPerfectGas', (['self.chem_dict'], {}), '(self.chem_dict)\n', (794, 810), False, 'from perform.gas_model.calorically_perfect_gas import CaloricallyPerfectGas\n'), ((1021, 1041), 'perform.time_integrator.implicit_integrator.BDF', 'BDF', (['self.param_dict'], {}), '(self.param_dict)\n', (1024, 1041), False, 'from perform.time_integrator.implicit_integrator import BDF\n'), ((1088, 1102), 'constants.gen_test_dir', 'gen_test_dir', ([], {}), '()\n', (1100, 1102), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((1148, 1171), 'constants.solution_domain_setup', 'solution_domain_setup', ([], {}), '()\n', (1169, 1171), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((1222, 1244), 'perform.system_solver.SystemSolver', 'SystemSolver', (['TEST_DIR'], {}), '(TEST_DIR)\n', (1234, 1244), False, 'from perform.system_solver import SystemSolver\n'), ((1338, 1352), 'constants.del_test_dir', 'del_test_dir', ([], {}), '()\n', (1350, 1352), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((1407, 1520), 'perform.solution.solution_interior.SolutionInterior', 'SolutionInterior', (['self.gas', 'SOL_PRIM_IN_REACT', 'self.solver', 'self.num_cells', 'self.num_reactions', 'self.time_int'], {}), '(self.gas, SOL_PRIM_IN_REACT, self.solver, self.num_cells,\n self.num_reactions, self.time_int)\n', (1423, 1520), False, 'from perform.solution.solution_interior import SolutionInterior\n'), ((2090, 2107), 'constants.get_output_mode', 'get_output_mode', ([], {}), '()\n', (2105, 2107), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((2193, 2230), 'perform.gas_model.calorically_perfect_gas.CaloricallyPerfectGas', 'CaloricallyPerfectGas', (['self.chem_dict'], {}), '(self.chem_dict)\n', (2214, 2230), False, 'from perform.gas_model.calorically_perfect_gas import CaloricallyPerfectGas\n'), ((2441, 2461), 'perform.time_integrator.implicit_integrator.BDF', 'BDF', (['self.param_dict'], {}), '(self.param_dict)\n', (2444, 2461), False, 'from perform.time_integrator.implicit_integrator import BDF\n'), ((2508, 2522), 'constants.gen_test_dir', 'gen_test_dir', ([], {}), '()\n', (2520, 2522), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((2568, 2591), 'constants.solution_domain_setup', 'solution_domain_setup', ([], {}), '()\n', (2589, 2591), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((2642, 2664), 'perform.system_solver.SystemSolver', 'SystemSolver', (['TEST_DIR'], {}), '(TEST_DIR)\n', (2654, 2664), False, 'from perform.system_solver import SystemSolver\n'), ((2744, 2857), 'perform.solution.solution_interior.SolutionInterior', 'SolutionInterior', (['self.gas', 'SOL_PRIM_IN_REACT', 'self.solver', 'self.num_cells', 'self.num_reactions', 'self.time_int'], {}), '(self.gas, SOL_PRIM_IN_REACT, self.solver, self.num_cells,\n self.num_reactions, self.time_int)\n', (2760, 2857), False, 'from perform.solution.solution_interior import SolutionInterior\n'), ((2910, 2924), 'constants.del_test_dir', 'del_test_dir', ([], {}), '()\n', (2922, 2924), False, 'from constants import del_test_dir, gen_test_dir, get_output_mode, solution_domain_setup, CHEM_DICT_REACT, SOL_PRIM_IN_REACT, TEST_DIR\n'), ((12021, 12051), 'perform.input_funcs.read_restart_file', 'read_restart_file', (['self.solver'], {}), '(self.solver)\n', (12038, 12051), False, 'from perform.input_funcs import read_restart_file\n'), ((12446, 12499), 'numpy.zeros', 'np.zeros', (['(self.solver.num_steps, 2)'], {'dtype': 'REAL_TYPE'}), '((self.solver.num_steps, 2), dtype=REAL_TYPE)\n', (12454, 12499), True, 'import numpy as np\n'), ((9573, 9668), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_prim_' + self.solver.sim_type + '.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_prim_' + self.solver.\n sim_type + '.npy')\n", (9585, 9668), False, 'import os\n'), ((9720, 9815), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_cons_' + self.solver.sim_type + '.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_cons_' + self.solver.\n sim_type + '.npy')\n", (9732, 9815), False, 'import os\n'), ((9852, 9945), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('source_' + self.solver.sim_type + '.npy')"], {}), "(self.solver.unsteady_output_dir, 'source_' + self.solver.\n sim_type + '.npy')\n", (9864, 9945), False, 'import os\n'), ((9992, 10091), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('heat_release_' + self.solver.sim_type + '.npy')"], {}), "(self.solver.unsteady_output_dir, 'heat_release_' + self.solver\n .sim_type + '.npy')\n", (10004, 10091), False, 'import os\n'), ((10125, 10214), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('rhs_' + self.solver.sim_type + '.npy')"], {}), "(self.solver.unsteady_output_dir, 'rhs_' + self.solver.sim_type +\n '.npy')\n", (10137, 10214), False, 'import os\n'), ((11104, 11170), 'os.path.join', 'os.path.join', (['self.solver.restart_output_dir', '"""restart_file_4.npz"""'], {}), "(self.solver.restart_output_dir, 'restart_file_4.npz')\n", (11116, 11170), False, 'import os\n'), ((1590, 1648), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_init_sol_cons.npy"""'], {}), "(self.output_dir, 'sol_int_init_sol_cons.npy')\n", (1602, 1648), False, 'import os\n'), ((1708, 1755), 'numpy.array_equal', 'np.array_equal', (['sol.sol_prim', 'SOL_PRIM_IN_REACT'], {}), '(sol.sol_prim, SOL_PRIM_IN_REACT)\n', (1722, 1755), True, 'import numpy as np\n'), ((3134, 3188), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_sol_jacob.npy"""'], {}), "(self.output_dir, 'sol_int_sol_jacob.npy')\n", (3146, 3188), False, 'import os\n'), ((3221, 3279), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_sol_jacob_inv.npy"""'], {}), "(self.output_dir, 'sol_int_sol_jacob_inv.npy')\n", (3233, 3279), False, 'import os\n'), ((3911, 3962), 'numpy.repeat', 'np.repeat', (['self.sol.sol_prim[:, :, None]', '(6)'], {'axis': '(2)'}), '(self.sol.sol_prim[:, :, None], 6, axis=2)\n', (3920, 3962), True, 'import numpy as np\n'), ((4024, 4075), 'numpy.repeat', 'np.repeat', (['self.sol.sol_cons[:, :, None]', '(6)'], {'axis': '(2)'}), '(self.sol.sol_cons[:, :, None], 6, axis=2)\n', (4033, 4075), True, 'import numpy as np\n'), ((4161, 4219), 'numpy.repeat', 'np.repeat', (['self.sol.reaction_source[:, :, None]', '(5)'], {'axis': '(2)'}), '(self.sol.reaction_source[:, :, None], 5, axis=2)\n', (4170, 4219), True, 'import numpy as np\n'), ((4311, 4363), 'numpy.repeat', 'np.repeat', (['self.sol.heat_release[:, None]', '(5)'], {'axis': '(1)'}), '(self.sol.heat_release[:, None], 5, axis=1)\n', (4320, 4363), True, 'import numpy as np\n'), ((4433, 4479), 'numpy.repeat', 'np.repeat', (['self.sol.rhs[:, :, None]', '(5)'], {'axis': '(2)'}), '(self.sol.rhs[:, :, None], 5, axis=2)\n', (4442, 4479), True, 'import numpy as np\n'), ((8562, 8663), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_prim_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_prim_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (8574, 8663), False, 'import os\n'), ((8753, 8854), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_cons_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_cons_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (8765, 8854), False, 'import os\n'), ((8944, 9043), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('source_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'source_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (8956, 9043), False, 'import os\n'), ((9133, 9238), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('heat_release_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'heat_release_' + self.solver\n .sim_type + '_ITMDT.npy')\n", (9145, 9238), False, 'import os\n'), ((9311, 9406), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('rhs_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'rhs_' + self.solver.sim_type +\n '_ITMDT.npy')\n", (9323, 9406), False, 'import os\n'), ((10267, 10318), 'numpy.repeat', 'np.repeat', (['self.sol.sol_prim[:, :, None]', '(6)'], {'axis': '(2)'}), '(self.sol.sol_prim[:, :, None], 6, axis=2)\n', (10276, 10318), True, 'import numpy as np\n'), ((10376, 10427), 'numpy.repeat', 'np.repeat', (['self.sol.sol_cons[:, :, None]', '(6)'], {'axis': '(2)'}), '(self.sol.sol_cons[:, :, None], 6, axis=2)\n', (10385, 10427), True, 'import numpy as np\n'), ((10483, 10541), 'numpy.repeat', 'np.repeat', (['self.sol.reaction_source[:, :, None]', '(5)'], {'axis': '(2)'}), '(self.sol.reaction_source[:, :, None], 5, axis=2)\n', (10492, 10541), True, 'import numpy as np\n'), ((10603, 10655), 'numpy.repeat', 'np.repeat', (['self.sol.heat_release[:, None]', '(5)'], {'axis': '(1)'}), '(self.sol.heat_release[:, None], 5, axis=1)\n', (10612, 10655), True, 'import numpy as np\n'), ((10708, 10754), 'numpy.repeat', 'np.repeat', (['self.sol.rhs[:, :, None]', '(5)'], {'axis': '(2)'}), '(self.sol.rhs[:, :, None], 5, axis=2)\n', (10717, 10754), True, 'import numpy as np\n'), ((11284, 11336), 'numpy.repeat', 'np.repeat', (['SOL_PRIM_IN_REACT[:, :, None]', '(2)'], {'axis': '(-1)'}), '(SOL_PRIM_IN_REACT[:, :, None], 2, axis=-1)\n', (11293, 11336), True, 'import numpy as np\n'), ((11473, 11516), 'numpy.repeat', 'np.repeat', (['sol_cons[:, :, None]', '(2)'], {'axis': '(-1)'}), '(sol_cons[:, :, None], 2, axis=-1)\n', (11482, 11516), True, 'import numpy as np\n'), ((11677, 11741), 'os.path.join', 'os.path.join', (['self.solver.restart_output_dir', '"""restart_iter.dat"""'], {}), "(self.solver.restart_output_dir, 'restart_iter.dat')\n", (11689, 11741), False, 'import os\n'), ((12265, 12317), 'numpy.repeat', 'np.repeat', (['SOL_PRIM_IN_REACT[:, :, None]', '(2)'], {'axis': '(-1)'}), '(SOL_PRIM_IN_REACT[:, :, None], 2, axis=-1)\n', (12274, 12317), True, 'import numpy as np\n'), ((5108, 5209), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_prim_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_prim_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (5120, 5209), False, 'import os\n'), ((5285, 5386), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_cons_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_cons_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (5297, 5386), False, 'import os\n'), ((5460, 5559), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('source_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'source_' + self.solver.\n sim_type + '_ITMDT.npy')\n", (5472, 5559), False, 'import os\n'), ((5639, 5744), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('heat_release_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'heat_release_' + self.solver\n .sim_type + '_ITMDT.npy')\n", (5651, 5744), False, 'import os\n'), ((5815, 5910), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('rhs_' + self.solver.sim_type + '_ITMDT.npy')"], {}), "(self.solver.unsteady_output_dir, 'rhs_' + self.solver.sim_type +\n '_ITMDT.npy')\n", (5827, 5910), False, 'import os\n'), ((6825, 6927), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_prim_' + self.solver.sim_type + '_FAILED.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_prim_' + self.solver.\n sim_type + '_FAILED.npy')\n", (6837, 6927), False, 'import os\n'), ((7004, 7106), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('sol_cons_' + self.solver.sim_type + '_FAILED.npy')"], {}), "(self.solver.unsteady_output_dir, 'sol_cons_' + self.solver.\n sim_type + '_FAILED.npy')\n", (7016, 7106), False, 'import os\n'), ((7181, 7281), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('source_' + self.solver.sim_type + '_FAILED.npy')"], {}), "(self.solver.unsteady_output_dir, 'source_' + self.solver.\n sim_type + '_FAILED.npy')\n", (7193, 7281), False, 'import os\n'), ((7362, 7468), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('heat_release_' + self.solver.sim_type + '_FAILED.npy')"], {}), "(self.solver.unsteady_output_dir, 'heat_release_' + self.solver\n .sim_type + '_FAILED.npy')\n", (7374, 7468), False, 'import os\n'), ((7586, 7682), 'os.path.join', 'os.path.join', (['self.solver.unsteady_output_dir', "('rhs_' + self.solver.sim_type + '_FAILED.npy')"], {}), "(self.solver.unsteady_output_dir, 'rhs_' + self.solver.sim_type +\n '_FAILED.npy')\n", (7598, 7682), False, 'import os\n'), ((1836, 1894), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_init_sol_cons.npy"""'], {}), "(self.output_dir, 'sol_int_init_sol_cons.npy')\n", (1848, 1894), False, 'import os\n'), ((3371, 3425), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_sol_jacob.npy"""'], {}), "(self.output_dir, 'sol_int_sol_jacob.npy')\n", (3383, 3425), False, 'import os\n'), ((3509, 3567), 'os.path.join', 'os.path.join', (['self.output_dir', '"""sol_int_sol_jacob_inv.npy"""'], {}), "(self.output_dir, 'sol_int_sol_jacob_inv.npy')\n", (3521, 3567), False, 'import os\n'), ((5988, 6039), 'numpy.repeat', 'np.repeat', (['self.sol.sol_prim[:, :, None]', '(3)'], {'axis': '(2)'}), '(self.sol.sol_prim[:, :, None], 3, axis=2)\n', (5997, 6039), True, 'import numpy as np\n'), ((6105, 6156), 'numpy.repeat', 'np.repeat', (['self.sol.sol_cons[:, :, None]', '(3)'], {'axis': '(2)'}), '(self.sol.sol_cons[:, :, None], 3, axis=2)\n', (6114, 6156), True, 'import numpy as np\n'), ((6241, 6299), 'numpy.repeat', 'np.repeat', (['self.sol.reaction_source[:, :, None]', '(2)'], {'axis': '(2)'}), '(self.sol.reaction_source[:, :, None], 2, axis=2)\n', (6250, 6299), True, 'import numpy as np\n'), ((6407, 6459), 'numpy.repeat', 'np.repeat', (['self.sol.heat_release[:, None]', '(2)'], {'axis': '(1)'}), '(self.sol.heat_release[:, None], 2, axis=1)\n', (6416, 6459), True, 'import numpy as np\n'), ((6537, 6583), 'numpy.repeat', 'np.repeat', (['self.sol.rhs[:, :, None]', '(2)'], {'axis': '(2)'}), '(self.sol.rhs[:, :, None], 2, axis=2)\n', (6546, 6583), True, 'import numpy as np\n'), ((7761, 7812), 'numpy.repeat', 'np.repeat', (['self.sol.sol_prim[:, :, None]', '(4)'], {'axis': '(2)'}), '(self.sol.sol_prim[:, :, None], 4, axis=2)\n', (7770, 7812), True, 'import numpy as np\n'), ((7879, 7930), 'numpy.repeat', 'np.repeat', (['self.sol.sol_cons[:, :, None]', '(4)'], {'axis': '(2)'}), '(self.sol.sol_cons[:, :, None], 4, axis=2)\n', (7888, 7930), True, 'import numpy as np\n'), ((8016, 8074), 'numpy.repeat', 'np.repeat', (['self.sol.reaction_source[:, :, None]', '(3)'], {'axis': '(2)'}), '(self.sol.reaction_source[:, :, None], 3, axis=2)\n', (8025, 8074), True, 'import numpy as np\n'), ((8183, 8235), 'numpy.repeat', 'np.repeat', (['self.sol.heat_release[:, None]', '(3)'], {'axis': '(1)'}), '(self.sol.heat_release[:, None], 3, axis=1)\n', (8192, 8235), True, 'import numpy as np\n'), ((8314, 8360), 'numpy.repeat', 'np.repeat', (['self.sol.rhs[:, :, None]', '(3)'], {'axis': '(2)'}), '(self.sol.rhs[:, :, None], 3, axis=2)\n', (8323, 8360), True, 'import numpy as np\n')]
"""Test the module SMOTE ENN.""" # Authors: <NAME> <<EMAIL>> # <NAME> # License: MIT import pytest import numpy as np from sklearn.utils.testing import assert_allclose, assert_array_equal from imblearn.combine import SMOTEENN from imblearn.under_sampling import EditedNearestNeighbours from imblearn.over_sampling import SMOTE RND_SEED = 0 X = np.array([[0.11622591, -0.0317206], [0.77481731, 0.60935141], [ 1.25192108, -0.22367336 ], [0.53366841, -0.30312976], [1.52091956, -0.49283504], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.3084254, 0.33299982], [0.70472253, -0.73309052], [0.28893132, -0.38761769], [1.15514042, 0.0129463], [ 0.88407872, 0.35454207 ], [1.31301027, -0.92648734], [-1.11515198, -0.93689695], [ -0.18410027, -0.45194484 ], [0.9281014, 0.53085498], [-0.14374509, 0.27370049], [ -0.41635887, -0.38299653 ], [0.08711622, 0.93259929], [1.70580611, -0.11219234]]) Y = np.array([0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]) R_TOL = 1e-4 def test_sample_regular(): smote = SMOTEENN(random_state=RND_SEED) X_resampled, y_resampled = smote.fit_resample(X, Y) X_gt = np.array([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [ 0.61319159, -0.11571667 ], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.08711622, 0.93259929]]) y_gt = np.array([0, 0, 0, 0, 1, 1, 1]) assert_allclose(X_resampled, X_gt, rtol=R_TOL) assert_array_equal(y_resampled, y_gt) def test_sample_regular_pass_smote_enn(): smote = SMOTEENN( smote=SMOTE(sampling_strategy='auto', random_state=RND_SEED), enn=EditedNearestNeighbours(sampling_strategy='all'), random_state=RND_SEED) X_resampled, y_resampled = smote.fit_resample(X, Y) X_gt = np.array([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [ 0.61319159, -0.11571667 ], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.08711622, 0.93259929]]) y_gt = np.array([0, 0, 0, 0, 1, 1, 1]) assert_allclose(X_resampled, X_gt, rtol=R_TOL) assert_array_equal(y_resampled, y_gt) def test_sample_regular_half(): sampling_strategy = {0: 10, 1: 12} smote = SMOTEENN( sampling_strategy=sampling_strategy, random_state=RND_SEED) X_resampled, y_resampled = smote.fit_resample(X, Y) X_gt = np.array([[1.52091956, -0.49283504], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.08711622, 0.93259929]]) y_gt = np.array([0, 1, 1, 1]) assert_allclose(X_resampled, X_gt) assert_array_equal(y_resampled, y_gt) def test_validate_estimator_init(): smote = SMOTE(random_state=RND_SEED) enn = EditedNearestNeighbours(sampling_strategy='all') smt = SMOTEENN(smote=smote, enn=enn, random_state=RND_SEED) X_resampled, y_resampled = smt.fit_resample(X, Y) X_gt = np.array([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [ 0.61319159, -0.11571667 ], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.08711622, 0.93259929]]) y_gt = np.array([0, 0, 0, 0, 1, 1, 1]) assert_allclose(X_resampled, X_gt, rtol=R_TOL) assert_array_equal(y_resampled, y_gt) def test_validate_estimator_default(): smt = SMOTEENN(random_state=RND_SEED) X_resampled, y_resampled = smt.fit_resample(X, Y) X_gt = np.array([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [ 0.61319159, -0.11571667 ], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.08711622, 0.93259929]]) y_gt = np.array([0, 0, 0, 0, 1, 1, 1]) assert_allclose(X_resampled, X_gt, rtol=R_TOL) assert_array_equal(y_resampled, y_gt) def test_parallelisation(): # Check if default job count is 1 smt = SMOTEENN(random_state=RND_SEED) smt._validate_estimator() assert smt.n_jobs == 1 assert smt.smote_.n_jobs == 1 assert smt.enn_.n_jobs == 1 # Check if job count is set smt = SMOTEENN(random_state=RND_SEED, n_jobs=8) smt._validate_estimator() assert smt.n_jobs == 8 assert smt.smote_.n_jobs == 8 assert smt.enn_.n_jobs == 8 @pytest.mark.parametrize( "smote_params, err_msg", [({'smote': 'rnd'}, "smote needs to be a SMOTE"), ({'enn': 'rnd'}, "enn needs to be an ")] ) def test_error_wrong_object(smote_params, err_msg): smt = SMOTEENN(**smote_params) with pytest.raises(ValueError, match=err_msg): smt.fit_resample(X, Y)
[ "sklearn.utils.testing.assert_array_equal", "imblearn.under_sampling.EditedNearestNeighbours", "imblearn.over_sampling.SMOTE", "imblearn.combine.SMOTEENN", "numpy.array", "pytest.mark.parametrize", "pytest.raises", "sklearn.utils.testing.assert_allclose" ]
[((357, 935), 'numpy.array', 'np.array', (['[[0.11622591, -0.0317206], [0.77481731, 0.60935141], [1.25192108, -\n 0.22367336], [0.53366841, -0.30312976], [1.52091956, -0.49283504], [-\n 0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.3084254, \n 0.33299982], [0.70472253, -0.73309052], [0.28893132, -0.38761769], [\n 1.15514042, 0.0129463], [0.88407872, 0.35454207], [1.31301027, -\n 0.92648734], [-1.11515198, -0.93689695], [-0.18410027, -0.45194484], [\n 0.9281014, 0.53085498], [-0.14374509, 0.27370049], [-0.41635887, -\n 0.38299653], [0.08711622, 0.93259929], [1.70580611, -0.11219234]]'], {}), '([[0.11622591, -0.0317206], [0.77481731, 0.60935141], [1.25192108, \n -0.22367336], [0.53366841, -0.30312976], [1.52091956, -0.49283504], [-\n 0.28162401, -2.10400981], [0.83680821, 1.72827342], [0.3084254, \n 0.33299982], [0.70472253, -0.73309052], [0.28893132, -0.38761769], [\n 1.15514042, 0.0129463], [0.88407872, 0.35454207], [1.31301027, -\n 0.92648734], [-1.11515198, -0.93689695], [-0.18410027, -0.45194484], [\n 0.9281014, 0.53085498], [-0.14374509, 0.27370049], [-0.41635887, -\n 0.38299653], [0.08711622, 0.93259929], [1.70580611, -0.11219234]])\n', (365, 935), True, 'import numpy as np\n'), ((1087, 1157), 'numpy.array', 'np.array', (['[0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]'], {}), '([0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0])\n', (1095, 1157), True, 'import numpy as np\n'), ((4433, 4577), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""smote_params, err_msg"""', "[({'smote': 'rnd'}, 'smote needs to be a SMOTE'), ({'enn': 'rnd'},\n 'enn needs to be an ')]"], {}), "('smote_params, err_msg', [({'smote': 'rnd'},\n 'smote needs to be a SMOTE'), ({'enn': 'rnd'}, 'enn needs to be an ')])\n", (4456, 4577), False, 'import pytest\n'), ((1212, 1243), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'random_state': 'RND_SEED'}), '(random_state=RND_SEED)\n', (1220, 1243), False, 'from imblearn.combine import SMOTEENN\n'), ((1312, 1519), 'numpy.array', 'np.array', (['[[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159, -\n 0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]]'], {}), '([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159,\n -0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]])\n', (1320, 1519), True, 'import numpy as np\n'), ((1557, 1588), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 1, 1, 1]'], {}), '([0, 0, 0, 0, 1, 1, 1])\n', (1565, 1588), True, 'import numpy as np\n'), ((1593, 1639), 'sklearn.utils.testing.assert_allclose', 'assert_allclose', (['X_resampled', 'X_gt'], {'rtol': 'R_TOL'}), '(X_resampled, X_gt, rtol=R_TOL)\n', (1608, 1639), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((1644, 1681), 'sklearn.utils.testing.assert_array_equal', 'assert_array_equal', (['y_resampled', 'y_gt'], {}), '(y_resampled, y_gt)\n', (1662, 1681), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((1979, 2186), 'numpy.array', 'np.array', (['[[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159, -\n 0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]]'], {}), '([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159,\n -0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]])\n', (1987, 2186), True, 'import numpy as np\n'), ((2224, 2255), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 1, 1, 1]'], {}), '([0, 0, 0, 0, 1, 1, 1])\n', (2232, 2255), True, 'import numpy as np\n'), ((2260, 2306), 'sklearn.utils.testing.assert_allclose', 'assert_allclose', (['X_resampled', 'X_gt'], {'rtol': 'R_TOL'}), '(X_resampled, X_gt, rtol=R_TOL)\n', (2275, 2306), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((2311, 2348), 'sklearn.utils.testing.assert_array_equal', 'assert_array_equal', (['y_resampled', 'y_gt'], {}), '(y_resampled, y_gt)\n', (2329, 2348), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((2434, 2502), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'sampling_strategy': 'sampling_strategy', 'random_state': 'RND_SEED'}), '(sampling_strategy=sampling_strategy, random_state=RND_SEED)\n', (2442, 2502), False, 'from imblearn.combine import SMOTEENN\n'), ((2580, 2702), 'numpy.array', 'np.array', (['[[1.52091956, -0.49283504], [-0.28162401, -2.10400981], [0.83680821, \n 1.72827342], [0.08711622, 0.93259929]]'], {}), '([[1.52091956, -0.49283504], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]])\n', (2588, 2702), True, 'import numpy as np\n'), ((2730, 2752), 'numpy.array', 'np.array', (['[0, 1, 1, 1]'], {}), '([0, 1, 1, 1])\n', (2738, 2752), True, 'import numpy as np\n'), ((2757, 2791), 'sklearn.utils.testing.assert_allclose', 'assert_allclose', (['X_resampled', 'X_gt'], {}), '(X_resampled, X_gt)\n', (2772, 2791), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((2796, 2833), 'sklearn.utils.testing.assert_array_equal', 'assert_array_equal', (['y_resampled', 'y_gt'], {}), '(y_resampled, y_gt)\n', (2814, 2833), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((2884, 2912), 'imblearn.over_sampling.SMOTE', 'SMOTE', ([], {'random_state': 'RND_SEED'}), '(random_state=RND_SEED)\n', (2889, 2912), False, 'from imblearn.over_sampling import SMOTE\n'), ((2923, 2971), 'imblearn.under_sampling.EditedNearestNeighbours', 'EditedNearestNeighbours', ([], {'sampling_strategy': '"""all"""'}), "(sampling_strategy='all')\n", (2946, 2971), False, 'from imblearn.under_sampling import EditedNearestNeighbours\n'), ((2982, 3035), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'smote': 'smote', 'enn': 'enn', 'random_state': 'RND_SEED'}), '(smote=smote, enn=enn, random_state=RND_SEED)\n', (2990, 3035), False, 'from imblearn.combine import SMOTEENN\n'), ((3101, 3308), 'numpy.array', 'np.array', (['[[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159, -\n 0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]]'], {}), '([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159,\n -0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]])\n', (3109, 3308), True, 'import numpy as np\n'), ((3346, 3377), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 1, 1, 1]'], {}), '([0, 0, 0, 0, 1, 1, 1])\n', (3354, 3377), True, 'import numpy as np\n'), ((3382, 3428), 'sklearn.utils.testing.assert_allclose', 'assert_allclose', (['X_resampled', 'X_gt'], {'rtol': 'R_TOL'}), '(X_resampled, X_gt, rtol=R_TOL)\n', (3397, 3428), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((3433, 3470), 'sklearn.utils.testing.assert_array_equal', 'assert_array_equal', (['y_resampled', 'y_gt'], {}), '(y_resampled, y_gt)\n', (3451, 3470), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((3522, 3553), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'random_state': 'RND_SEED'}), '(random_state=RND_SEED)\n', (3530, 3553), False, 'from imblearn.combine import SMOTEENN\n'), ((3619, 3826), 'numpy.array', 'np.array', (['[[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159, -\n 0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]]'], {}), '([[1.52091956, -0.49283504], [0.84976473, -0.15570176], [0.61319159,\n -0.11571667], [0.66052536, -0.28246518], [-0.28162401, -2.10400981], [\n 0.83680821, 1.72827342], [0.08711622, 0.93259929]])\n', (3627, 3826), True, 'import numpy as np\n'), ((3864, 3895), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 1, 1, 1]'], {}), '([0, 0, 0, 0, 1, 1, 1])\n', (3872, 3895), True, 'import numpy as np\n'), ((3900, 3946), 'sklearn.utils.testing.assert_allclose', 'assert_allclose', (['X_resampled', 'X_gt'], {'rtol': 'R_TOL'}), '(X_resampled, X_gt, rtol=R_TOL)\n', (3915, 3946), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((3951, 3988), 'sklearn.utils.testing.assert_array_equal', 'assert_array_equal', (['y_resampled', 'y_gt'], {}), '(y_resampled, y_gt)\n', (3969, 3988), False, 'from sklearn.utils.testing import assert_allclose, assert_array_equal\n'), ((4067, 4098), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'random_state': 'RND_SEED'}), '(random_state=RND_SEED)\n', (4075, 4098), False, 'from imblearn.combine import SMOTEENN\n'), ((4265, 4306), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {'random_state': 'RND_SEED', 'n_jobs': '(8)'}), '(random_state=RND_SEED, n_jobs=8)\n', (4273, 4306), False, 'from imblearn.combine import SMOTEENN\n'), ((4651, 4675), 'imblearn.combine.SMOTEENN', 'SMOTEENN', ([], {}), '(**smote_params)\n', (4659, 4675), False, 'from imblearn.combine import SMOTEENN\n'), ((4685, 4725), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': 'err_msg'}), '(ValueError, match=err_msg)\n', (4698, 4725), False, 'import pytest\n'), ((1762, 1816), 'imblearn.over_sampling.SMOTE', 'SMOTE', ([], {'sampling_strategy': '"""auto"""', 'random_state': 'RND_SEED'}), "(sampling_strategy='auto', random_state=RND_SEED)\n", (1767, 1816), False, 'from imblearn.over_sampling import SMOTE\n'), ((1830, 1878), 'imblearn.under_sampling.EditedNearestNeighbours', 'EditedNearestNeighbours', ([], {'sampling_strategy': '"""all"""'}), "(sampling_strategy='all')\n", (1853, 1878), False, 'from imblearn.under_sampling import EditedNearestNeighbours\n')]
# Copyright 2021 TileDB Inc. # Licensed under the MIT License. import numpy as np import pytest from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype netCDF4 = pytest.importorskip("netCDF4") @pytest.mark.parametrize( "input_dtype,scale_factor,add_offset,output_dtype", ( (np.int16, None, None, np.int16), (np.int16, np.float32(1), None, np.float32), (np.int16, None, np.float32(1), np.float32), (np.int16, np.float64(1), np.float32(1), np.float64), ), ) def test_unpacked_dtype(input_dtype, scale_factor, add_offset, output_dtype): """Tests computing the unpacked data type for a NetCDF variable.""" with netCDF4.Dataset("tmp.nc", diskless=True, mode="w") as dataset: dataset.createDimension("t", None) variable = dataset.createVariable("x", dimensions=("t",), datatype=input_dtype) if scale_factor is not None: variable.setncattr("scale_factor", scale_factor) if add_offset is not None: variable.setncattr("add_offset", add_offset) dtype = get_unpacked_dtype(variable) assert dtype == output_dtype def test_unpacked_dtype_unsupported_dtype_error(): """Tests attempting to unpack a NetCDF variable with a data type that does not support packing/unpacking.""" with netCDF4.Dataset("tmp.nc", diskless=True, mode="w") as dataset: variable = dataset.createVariable("x", dimensions=tuple(), datatype="S1") with pytest.raises(ValueError): get_unpacked_dtype(variable) @pytest.mark.parametrize( "value, expected_result", ( (np.float64(1), np.float64(1)), (np.array((1), dtype=np.float64), np.float64(1)), (np.array([1], dtype=np.int32), np.int32(1)), ), ) def test_get_netcdf_metadata_number(value, expected_result): """Tests computing the unpacked data type for a NetCDF variable.""" key = "name" with netCDF4.Dataset("tmp.nc", diskless=True, mode="w") as dataset: dataset.setncattr(key, value) result = get_netcdf_metadata(dataset, key, is_number=True) assert result == expected_result @pytest.mark.parametrize("value", (("",), (1, 2))) def test_get_netcdf_metadata_number_with_warning(value): """Tests computing the unpacked data type for a NetCDF variable.""" key = "name" with netCDF4.Dataset("tmp.nc", diskless=True, mode="w") as dataset: dataset.setncattr(key, value) with pytest.warns(Warning): result = get_netcdf_metadata(dataset, key, is_number=True) assert result is None
[ "tiledb.cf.netcdf_engine._utils.get_unpacked_dtype", "numpy.float64", "numpy.int32", "pytest.mark.parametrize", "numpy.array", "pytest.importorskip", "tiledb.cf.netcdf_engine._utils.get_netcdf_metadata", "pytest.raises", "numpy.float32", "pytest.warns" ]
[((191, 221), 'pytest.importorskip', 'pytest.importorskip', (['"""netCDF4"""'], {}), "('netCDF4')\n", (210, 221), False, 'import pytest\n'), ((2153, 2202), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""value"""', "(('',), (1, 2))"], {}), "('value', (('',), (1, 2)))\n", (2176, 2202), False, 'import pytest\n'), ((1090, 1118), 'tiledb.cf.netcdf_engine._utils.get_unpacked_dtype', 'get_unpacked_dtype', (['variable'], {}), '(variable)\n', (1108, 1118), False, 'from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype\n'), ((2059, 2108), 'tiledb.cf.netcdf_engine._utils.get_netcdf_metadata', 'get_netcdf_metadata', (['dataset', 'key'], {'is_number': '(True)'}), '(dataset, key, is_number=True)\n', (2078, 2108), False, 'from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype\n'), ((373, 386), 'numpy.float32', 'np.float32', (['(1)'], {}), '(1)\n', (383, 386), True, 'import numpy as np\n'), ((432, 445), 'numpy.float32', 'np.float32', (['(1)'], {}), '(1)\n', (442, 445), True, 'import numpy as np\n'), ((479, 492), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (489, 492), True, 'import numpy as np\n'), ((494, 507), 'numpy.float32', 'np.float32', (['(1)'], {}), '(1)\n', (504, 507), True, 'import numpy as np\n'), ((1489, 1514), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1502, 1514), False, 'import pytest\n'), ((1528, 1556), 'tiledb.cf.netcdf_engine._utils.get_unpacked_dtype', 'get_unpacked_dtype', (['variable'], {}), '(variable)\n', (1546, 1556), False, 'from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype\n'), ((1630, 1643), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (1640, 1643), True, 'import numpy as np\n'), ((1645, 1658), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (1655, 1658), True, 'import numpy as np\n'), ((1670, 1699), 'numpy.array', 'np.array', (['(1)'], {'dtype': 'np.float64'}), '(1, dtype=np.float64)\n', (1678, 1699), True, 'import numpy as np\n'), ((1703, 1716), 'numpy.float64', 'np.float64', (['(1)'], {}), '(1)\n', (1713, 1716), True, 'import numpy as np\n'), ((1728, 1757), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int32'}), '([1], dtype=np.int32)\n', (1736, 1757), True, 'import numpy as np\n'), ((1759, 1770), 'numpy.int32', 'np.int32', (['(1)'], {}), '(1)\n', (1767, 1770), True, 'import numpy as np\n'), ((2472, 2493), 'pytest.warns', 'pytest.warns', (['Warning'], {}), '(Warning)\n', (2484, 2493), False, 'import pytest\n'), ((2516, 2565), 'tiledb.cf.netcdf_engine._utils.get_netcdf_metadata', 'get_netcdf_metadata', (['dataset', 'key'], {'is_number': '(True)'}), '(dataset, key, is_number=True)\n', (2535, 2565), False, 'from tiledb.cf.netcdf_engine._utils import get_netcdf_metadata, get_unpacked_dtype\n')]
import nose.tools import unittest import os import json import pandas as pd import numpy as np import mia from mia.io_tools import * from ..test_utils import get_file_path class IOTests(unittest.TestCase): @classmethod def setupClass(cls): cls._output_files = [] @classmethod def teardownClass(cls): for f in cls._output_files: if os.path.isfile(f): os.remove(f) def test_iterate_directory(self): img_directory = get_file_path("texture_patches") expected_files = ['texture1.png', 'texture2.png', 'texture3.png', 'texture4.png', 'texture5.png'] expected_files = [os.path.join(img_directory, p) for p in expected_files] dirs = list(iterate_directory(img_directory)) nose.tools.assert_equal(len(dirs), len(expected_files)) for img_path, expected in zip(dirs, expected_files): nose.tools.assert_equal(img_path, expected) def test_iterate_directories(self): img_directory = get_file_path("texture_patches") expected_files = ['texture1.png', 'texture2.png', 'texture3.png', 'texture4.png', 'texture5.png'] expected_files = [os.path.join(img_directory, p) for p in expected_files] dirs = list(iterate_directories(img_directory, img_directory)) nose.tools.assert_equal(len(dirs), len(expected_files)) for (img_path, msk_path), expected in zip(dirs, expected_files): nose.tools.assert_equal(img_path, expected) nose.tools.assert_equal(msk_path, expected) def test_check_is_file(self): img_path = get_file_path("texture_patches/texture1.png") nose.tools.assert_true(check_is_file(img_path, ".png")) def test_check_is_file_multiple_images(self): img_path = get_file_path("synthetic_patch.dcm") nose.tools.assert_true(check_is_file(img_path, ".png", ".dcm")) def test_check_is_file_wrong_extension(self): img_path = get_file_path("blob_detection.csv") nose.tools.assert_false(check_is_file(img_path, ".png", ".dcm")) def test_check_is_image_raises_on_not_a_file(self): img_path = get_file_path("texture_patches") nose.tools.assert_false(check_is_file(img_path, ".png", ".dcm")) def test_check_is_directory(self): directory = get_file_path("texture_patches") try: check_is_directory(directory) except: self.fail("check_is_directory raised when it shouldn't have.") def test_check_is_directory_raises(self): img_path = get_file_path("texture_patches/not_a_directory") nose.tools.assert_raises(ValueError, check_is_directory, img_path) def test_dump_mapping_to_json(self): output_file = 'test_data.json' mapping = pd.DataFrame(np.ones((10, 2)), columns=['x', 'y']) dump_mapping_to_json(mapping, ['x', 'y'], np.zeros(10), output_file) nose.tools.assert_true(os.path.isfile(output_file)) with open(output_file, 'rb') as f: data = json.load(f) nose.tools.assert_equal(len(data), 1) nose.tools.assert_equal(data[0]['name'], 'Class: 0') nose.tools.assert_equal(len(data[0]['data']), 10) self._output_files.append(output_file)
[ "numpy.ones", "os.path.join", "os.path.isfile", "numpy.zeros", "json.load", "os.remove" ]
[((380, 397), 'os.path.isfile', 'os.path.isfile', (['f'], {}), '(f)\n', (394, 397), False, 'import os\n'), ((683, 713), 'os.path.join', 'os.path.join', (['img_directory', 'p'], {}), '(img_directory, p)\n', (695, 713), False, 'import os\n'), ((1233, 1263), 'os.path.join', 'os.path.join', (['img_directory', 'p'], {}), '(img_directory, p)\n', (1245, 1263), False, 'import os\n'), ((2856, 2872), 'numpy.ones', 'np.ones', (['(10, 2)'], {}), '((10, 2))\n', (2863, 2872), True, 'import numpy as np\n'), ((2944, 2956), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (2952, 2956), True, 'import numpy as np\n'), ((3003, 3030), 'os.path.isfile', 'os.path.isfile', (['output_file'], {}), '(output_file)\n', (3017, 3030), False, 'import os\n'), ((3095, 3107), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3104, 3107), False, 'import json\n'), ((415, 427), 'os.remove', 'os.remove', (['f'], {}), '(f)\n', (424, 427), False, 'import os\n')]