def __init__(self, inputDirectory, outputDirectory, simulationFile, amountRequest): self.inputDirectory = inputDirectory self.outputDirectory = outputDirectory self.simulationFile = simulationFile self.amountRequest = amountRequest self.priorityQueue = ST.readSimulationFile(inputDirectory, simulationFile, amountRequest) self.countRequestAccepted = 0 self.countRequestRejected = 0 self.solutions = [] self.totalCost = 0 self.totalRevenue1 = 0 self.totalRevenue2 = 0 self.optimalSolutions = 0 self.executionTime = 0 self.minCPU = [] self.minAverageCPU = [] self.minBandwith = [] self.minAverageBandwith = [] self.minPhysicalRevenue = [] self.rejectedRequest = [] self.links = [] self.penaltyValue = [] self.physicalNetwork = ST.Network(inputDirectory, ST.PHYSICAL) self.initialNetwork = ST.Network(inputDirectory, ST.PHYSICAL) self.requestList = ST.readRequests(inputDirectory, amountRequest)
def optimizationFunction(vals, args): # Parse the constant variables jobName = args[0] workingDirectory = args[1] batFileName = args[2] experimentalResults = args[3] # Change the material properties in the Abaqus simulation updateSimulationVariable(vals, workingDirectory) # Run the simulation SimulationTools.runSimulation(jobName, workingDirectory, abaqusBatFile=batFileName) # Get the results from the simulation, and save them using cPickle odbFileName = '{}\\{}.odb'.format(workingDirectory, jobName) # Create the path to the odb file. SimulationTools.getResults(workingDirectory, odbFileName, abaqusBatFile=batFileName) # The specific results have been written to the working directory, so we can now open them as the variable that we saved. saveResultsFileName = workingDirectory + '\\specificResults.dat' # Define the saved results file name. This needs to be the same result file name that was saved in ExtractResults.py with open(saveResultsFileName, mode='r') as file: simResults = cPickle.load(file) # Load the saved results. This will be the same variable that we saved in ExtractResults.py error = (simResults - experimentalResults)**2 # Define the error error = np.sum(error) # Sum the error to return a constant value. This may be an array, depending on the choice of optimization. return error
def runEmbedSim(self, jobName, workingDirectory, genericInputFile): _checkIfDirExists(workingDirectory) #: Check if workingDirectory exists, if not, make one. springs.writeGeometry(workingDirectory, self.pointsPerSide, self.pointsPerLength, self.sideLength, self.sideLength, self.ligamentLength, self.stiffness, self.matrixStiffness, self.offset, self.damping, self.mass, twist=self.twist, phi=self.phi, rMl=self.rMl, rAp=self.rAp, embeded=True) copyfile(genericInputFile, workingDirectory+'/'+jobName+'.inp') SimulationTools.runSimulation(jobName, workingDirectory) return
def runBatch(experimentObject, batchDirectory, genericInputFile, baseJobName, rMl, springs=True): for param in rMl: jobName = '{}_{}'.format(baseJobName, int(param)) workingDirectory = '{}/{}'.format(batchDirectory, jobName) experimentObject.rMl = param if springs is True: experimentObject.runSpringSim(jobName, workingDirectory, genericInputFile) else: experimentObject.runEmbedSim(jobName, workingDirectory, genericInputFile) odbFileName = '{}/{}.odb'.format(workingDirectory, jobName) SimulationTools.getResults(workingDirectory, odbFileName) return
def _test(): pointsPerSide = 5 # Nodes per edge of insertion area. femSideLength = 14 # Width and height of femoral Insertion area. tibSideLength = 18 # Width and height of tibial Insertion area. ligamentLength = 30 # Length of the ligament. twist = 0 # Twist between the femoral insertion and the tibial insertion phi = 0 # The angle between the planes that define the femoral insertion and the tibial insertion pointsPerLength = 5 stiffness = 1000 # N/mm offset = -0.0 # mm matrixStiffness = 1000 # N/mm damping = 0.1 # damping value mass = 0.00001 workingDirectory = "../Simulations/Test03" writeGeometry( workingDirectory, pointsPerSide, pointsPerLength, tibSideLength, femSideLength, ligamentLength, stiffness, matrixStiffness, offset, damping, mass, twist=twist, phi=phi, ) from shutil import copyfile genericInputFile = "../Simulations/InputFiles/GenericInputExplicit.inp" jobName = "test03.inp" copyfile(genericInputFile, workingDirectory + "/" + jobName) # Run the simulation SimulationTools.runSimulation(jobName, workingDirectory) # mesh = springsMesh(name='SpringMesh') # mesh.getNodes(pointsPerSide, pointsPerLength, tibSideLength, femSideLength, ligamentLength, twist=twist, phi=phi) # mesh.getElements(pointsPerSide, pointsPerLength) # mesh.setFibers(pointsPerSide, pointsPerLength) # mesh.setFiberProperties(stiffness, offset) # mesh.setMatrixMaterialProperties(matrixStiffness) # mesh.getElementsText() return
def initializeSolutions(amountSolutions, vectorSize, amountNodes): solutions = [] for i in range(amountSolutions): vector = np.arange(amountNodes) np.random.shuffle(vector) vector = vector[0:vectorSize] solutions.append(ST.Solution(vector.copy())) return solutions
def L2S2intialization(amountSolutions, vectorSize, amountNodes, physicalNetwork, virtualNetwork): solutions = [] for j in range(amountSolutions): vector = [] for i in range(vectorSize): flag2 = True selectedNodes = physicalNetwork.vs.select( CPU_ge=virtualNetwork.vs[i]['CPU']) candidateNodesList = [] for nodo in selectedNodes: candidateNodesList.append(nodo.index) #print len(candidateNodesList) if len(candidateNodesList) != 0: flag2 = False cpu = np.asarray(physicalNetwork.vs[candidateNodesList]['CPU']) sumbandwidth = np.asarray( physicalNetwork.strength(candidateNodesList, weights='bandwidth')) physicalNRU = cpu * sumbandwidth sumNRU = np.sum(physicalNRU) probabilitiesNRU = physicalNRU / float(sumNRU) flag = True count = 0 while flag == True: count += 1 cumulativeSum = 0 coin = np.random.uniform() for k in range(len(probabilitiesNRU)): cumulativeSum = cumulativeSum + probabilitiesNRU[k] if cumulativeSum >= coin and candidateNodesList[ k] not in vector: vector.append(candidateNodesList[k]) flag = False break if count == 1000: flag = False flag2 = True if flag2 == True: number = np.random.randint(0, amountNodes) while number in vector: number = np.random.randint(0, amountNodes) vector.append(number) vector = np.asarray(vector) solutions.append(ST.Solution(vector.copy())) return solutions
def improviseNewHarmony(self, solutions, amountNodes): amountNotes = len(solutions[0].permutation) newVector = np.ones(amountNotes, dtype=int) * amountNodes for i in range(amountNotes): coin = np.random.uniform() if coin <= self.hcmr: memoryPosition = np.random.randint(0, len(solutions)) number = solutions[memoryPosition].permutation[i] count = 0 while number in newVector: count += 1 memoryPosition = np.random.randint(0, len(solutions)) number = solutions[memoryPosition].permutation[i] if count > 1000: number = np.random.randint(0, amountNodes) newVector[i] = number coin = np.random.uniform() if coin <= self.par / float(2): number = newVector[i] - 1 if number < 0: number = amountNodes - 1 while number in newVector: number = number - 1 if number < 0: number = amountNodes - 1 newVector[i] = number elif coin <= self.par: number = newVector[i] + 1 #print numero if number >= amountNodes: number = 0 while number in newVector: number = number + 1 if number >= amountNodes: number = 0 #print numero newVector[i] = number else: number = np.random.randint(0, amountNodes) while number in newVector: number = np.random.randint(0, amountNodes) newVector[i] = number #print newVector return ST.Solution(newVector.copy())
def mapLinks(self, vector, PhysicalNetwork, virtualNetwork): paths = [] infeasiblePaths = 0 pathsCost = 0 adjacencyList = virtualNetwork.graph.get_adjlist(mode='ALL') c = 0 bandwidthNormalization = 0 #bandera=0 #print "__________Solucion: "+str(vector)+"__________" for i in range(virtualNetwork.graph.vcount()): for j in range(len(adjacencyList[i])): if adjacencyList[i][j] > i: #print "******************************************************" #print "Enlace virtual: "+str(i)+" , "+str(listaAdyacencia[i][j]) bandwitdhRequired = virtualNetwork.graph.es[ virtualNetwork.graph.get_eid(adjacencyList[i][j], i)]["bandwidth"] graphCopy = ST.prune(PhysicalNetwork.graph, bandwitdhRequired, self.vectorForwarding) #if copia.ecount()==66 and bandera==0: #print copia # bandera=2 #print copia source = vector[i] dest = vector[adjacencyList[i][j]] #print "Enlace Fisico: "+ str(origen)+" , "+str(destino) #camino=copia.shortest_paths_dijkstra(source=origen, target=destino, weights=None, mode='ALL') #camino=copia.shortest_paths(source=origen, target=destino, weights=None, mode='OUT') path = graphCopy.get_shortest_paths(v=source, to=dest, weights=None, mode='ALL', output="vpath") #print "sdjdhkdhkdjhdkjhdkjhdjkhdjkdhfjkhfkjhfjkfhkjfh" c = c + 1 #print camino #if virtualNetwork.vcount()==8 and virtualNetwork.ecount()==16: #print "camino: "+str(c)+" tamano: "+str(len(camino[0]))+" nodos: "+str(camino)+ " BW: "+str(anchoBanda) if (len(path[0]) == 0): infeasiblePaths = infeasiblePaths + 1 pathCost = 0 #print "no se encontro camino" else: if len(self.vectorForwarding) == 0: pathCost = (bandwitdhRequired * (len(path[0]) - 1)) else: pathCost = (bandwitdhRequired * (len(path[0]) - 1)) + ( self.vectorForwarding[ int(bandwitdhRequired) - 1] * (len(path[0]) - 2)) #print (vectorForwarding[int(anchoBanda)-1]*(len(camino[0])-2)) #print path[0] paths.append(ST.Path(path[0], bandwitdhRequired, pathCost)) pathsCost = pathsCost + pathCost bandwidthNormalization += PhysicalNetwork.reserveFreeResourcesPath( paths[len(paths) - 1], 0, self.vectorForwarding, self.optFX) PhysicalNetwork.reserveFreeResourcesPaths(paths, 1, self.vectorForwarding) #print PhysicalNetwork.es["bandwidth"] #print costoCaminos return paths, pathsCost, infeasiblePaths, bandwidthNormalization
def improviseNewHarmony2(self, solutions, amountNodes): amountNotes = len(solutions[0].permutation) newVector = np.ones(amountNotes, dtype=int) * amountNodes for i in range(amountNotes): vectorPosition = self.order[i] coin = np.random.uniform() size = len(self.candidateNodes[vectorPosition]) if coin <= self.hcmr: memoryPosition = np.random.randint(0, len(solutions)) number = solutions[memoryPosition].permutation[vectorPosition] count = 0 while number in newVector: count += 1 memoryPosition = np.random.randint(0, len(solutions)) number = solutions[memoryPosition].permutation[ vectorPosition] if count > 1000: number = np.random.randint( 0, len(self.candidateNodes[vectorPosition])) number = self.candidateNodes[vectorPosition][number] newVector[vectorPosition] = number coin = np.random.uniform() #print "number: "+str(number) if coin <= self.par / float(2) and size != 1: #print "***************************"+str(vectorPosition) #print self.candidateNodes[vectorPosition] indexList = self.candidateNodes[vectorPosition].index( newVector[vectorPosition]) #print indexList newPosition = indexList - 1 if newPosition < 0: newPosition = len( self.candidateNodes[vectorPosition]) - 1 number = self.candidateNodes[vectorPosition][newPosition] while number in newVector: newPosition = newPosition - 1 if newPosition < 0: newPosition = len( self.candidateNodes[vectorPosition]) - 1 number = self.candidateNodes[vectorPosition][ newPosition] newVector[vectorPosition] = number elif coin <= self.par and size != 1: #print "----------------------------"+str(vectorPosition) #print self.candidateNodes[vectorPosition] indexList = self.candidateNodes[vectorPosition].index( newVector[vectorPosition]) #print indexList newPosition = indexList + 1 if newPosition >= len(self.candidateNodes[vectorPosition]): newPosition = 0 #print "position: "+str(newPosition)+" size: "+str(size) number = self.candidateNodes[vectorPosition][newPosition] while number in newVector: newPosition = newPosition + 1 if newPosition >= len( self.candidateNodes[vectorPosition]): newPosition = 0 #print "position: "+str(newPosition) number = self.candidateNodes[vectorPosition][ newPosition] newVector[vectorPosition] = number else: if size != 1: position = np.random.randint(0, size) number = self.candidateNodes[vectorPosition][position] while number in newVector: position = np.random.randint(0, size) number = self.candidateNodes[vectorPosition][position] newVector[vectorPosition] = number else: newVector[vectorPosition] = self.candidateNodes[ vectorPosition][0] #print newVector #print newVector return ST.Solution(newVector.copy())
def simulate(self, vneAlgorithm, objFunction): c = 0 while self.priorityQueue.empty() != True: c = c + 1 #Get the first event in the Queue event = self.priorityQueue.get() #print "_--------------------------------------------------------------------------------------" #print "Time: "+str(event[0])+" event type: "+str(event[1]) #"If" to determine if the event is the arrival of a request if event[1].typeRequest == ST.ARRIVAL: #We calculate the revenue of the request revenue = self.requestList[ event[1].idRequest].calculateRevenue() self.totalRevenue1 += revenue[0] #print "try to embedd the request with revnue"+str(revenue) # bw_tmp = np.array(self.physicalNetwork.graph.es["bandwidth"]) # averagebw=np.average(bw_tmp) # cpu_tmp=np.array(self.physicalNetwork.graph.vs["CPU"]) # averageCPU=np.average(cpu_tmp) # if averagebw>40 and averagebw<50 and averageCPU<=64: # print str(averagebw)+"-------------- "+str(averageCPU) # self.physicalNetwork.graph.write_graphml("/Users/CAF/Documents/DoctoralInstances/medios/red"+str(c)+".graphml") # if averageCPU<=65: # print "cpu" # print averageCPU # if averagebw<=50: # print "bw" # print averagebw #We use the VNE Algorithm to find a solution. #self.physicalNetwork=object with the current state of physical network. #self.requestList[event[1].idRequest] we get the current request form the virtual networks stored in the memory #objFunction we pass tothe algorithm the object with the objective function #revenue we pass the revenue to the algorithm intialTime = time() vneSolution = vneAlgorithm.embeddVirtualNetwork( self.physicalNetwork, self.requestList[event[1].idRequest], objFunction, revenue) finalTime = time() #print vneSolution.vneCost self.executionTime = self.executionTime + (finalTime - intialTime) self.solutions.append(vneSolution) if vneSolution.penaltyValue == 0: #print vneSolution self.countRequestAccepted = self.countRequestAccepted + 1 self.totalCost = self.totalCost + vneSolution.vneCost self.totalRevenue2 = self.totalRevenue2 + revenue[0] if vneSolution.vneCost == revenue[0]: self.optimalSolutions = self.optimalSolutions + 1 self.physicalNetwork.reserveFreeResourcesPaths( vneSolution.pathsList, 0, objFunction.vectorForwarding) self.physicalNetwork.reserveFreeResourcesNodes( self.requestList[event[1].idRequest].graph, vneSolution.permutation, 0) departureEvent = ST.Request(event[1].idRequest, ST.DEPARTURE, 0) departureTime = event[1].lifetime + event[0] self.priorityQueue.put((departureTime, departureEvent)) else: self.rejectedRequest.append( self.requestList[event[1].idRequest].graph.vcount()) self.links.append( self.requestList[event[1].idRequest].graph.ecount()) self.penaltyValue.append(vneSolution.constraints) self.countRequestRejected = self.countRequestRejected + 1 pyshicalRevenue = self.physicalNetwork.calculateRevenue() self.minPhysicalRevenue.append(float(pyshicalRevenue[0])) self.minCPU.append(pyshicalRevenue[1]) self.minAverageCPU.append(pyshicalRevenue[2]) self.minBandwith.append(pyshicalRevenue[3]) self.minAverageBandwith.append(pyshicalRevenue[4]) #We need to add here an elif if exist an event of elasticity. #If the event is a departure free the resources. else: #print "Evento Salida :" +str(evento[1]) solution = self.solutions[event[1].idRequest] self.physicalNetwork.reserveFreeResourcesPaths( solution.pathsList, 1, objFunction.vectorForwarding) self.physicalNetwork.reserveFreeResourcesNodes( self.requestList[event[1].idRequest].graph, solution.permutation, 1)