void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *event){ QGraphicsItem *activeItem = itemAt(event->scenePos().x(),event->scenePos().y(),transform); if (activeItem != 0 and ((CustomItem*)activeItem)->isClickable()){ QGraphicsItem *selection = itemAt(event->scenePos().x(),event->scenePos().y(),transform); if(((CustomItem*)selection)->getName() == std::string("Dot")){ selectionActive = true; selectedDot = ((Dot*)selection); } } else{ if (event->button() == Qt::LeftButton){ QGraphicsItem *newDot = new Dot(event->scenePos(),dotRadius,Qt::white); addItem(newDot); connectToNearest(((Dot*)newDot)); totalCost = calculateCost(); emit costChanged(totalCost); } else{ QGraphicsItem *newDot = new Dot(event->scenePos(),dotRadius,Qt::red); addItem(newDot); ((Dot*)newDot)->makeCenter(); centersPointers.append(((Dot*)newDot)); updateConnections(); totalCost = calculateCost(); emit costChanged(totalCost); } } update(QRectF(-50,-50,1000,1000)); }
Data MatrixGraph::tabuSearch(uint tabuListSize, uint iterations) { clock_t overallTime = clock(); initRand(); if (!iterations) iterations = 1 << 10; //iterations = 50; stringstream results; vector<uint> currentPath, bestPath; currentPath.reserve(vertexNumber), bestPath.reserve(vertexNumber); //TabuArray tabuList(vertexNumber, tabuListSize); TabuList tabuList(tabuListSize); uint currentCost = 0, bestCost = 0, diverseLimit = (iterations >> 4) + 1, noChange = 0; // 1 - Create an initial solution(could be created randomly), now call it the current solution. for (uint i = 0; i < vertexNumber; ++i) currentPath.push_back(i); currentCost = calculateCost(currentPath); bestPath = currentPath; bestCost = currentCost; for (uint i = 0; i < iterations; ++i) { // 2 - Find the best neighbor of the current solution by applying certain moves. currentCost = getBestNeighbour(tabuList, currentPath); // 3 - If the best neighbor is reached my performing a non - tabu move, accept as the new current solution. // else, find another neighbor(best non - tabu neighbour). if (currentCost < bestCost) { bestPath = currentPath; bestCost = currentCost; noChange = 0; } else { if (++noChange > diverseLimit) { random_shuffle(currentPath.begin(), currentPath.end()); currentCost = calculateCost(currentPath); tabuList.clear(); noChange = 0; } } } // 4 - If maximum number of iterations are reached(or any other stopping condition), go to 5, else go to 2. // 5 - Globally best solution is the best solution we found throughout the iterations. double duration = (clock() - overallTime) / (double)CLOCKS_PER_SEC; results << "Koszt drogi: " << bestCost << "\nCalkowity czas trwania: " << duration << " sekund\n"; return Data(bestPath, bestCost, results.str(), duration); }
float SurfaceAreaHeuristic::findMedian(BoundingBox box, vector<RTShape*> shapes, int axis) { _box = box; _axis = axis; _shapes = &shapes; sort(); float cost; float bestpos = 0; if (shapes.size() == 0) { return 0; } float bestcost = calculateCost(shapes[0]->getBoundingBox().getOrigin().get(axis),0); float bmin = box.getOrigin().get(axis); float bmax = box.getOrigin().get(axis) + box.getDelta().get(axis); vector<RTShape*>::iterator it; int i=0; for (it = shapes.begin(); it != shapes.end(); ++it) { BoundingBox sBox = (*it)->getBoundingBox(); float min = sBox.getOrigin().get(axis); float max = sBox.getOrigin().get(axis) + sBox.getDelta().get(axis); if ((cost = calculateCost(min,i)) < bestcost && min > bmin && fabs(min - bmin) > 0.0001) { //DPRINTF("%f %f %f\n", min, bmin, min-bmin); bestcost = cost; bestpos = min; } //DPRINTF("%d\n", cost); if ((cost = calculateCost(max,i)) < bestcost && max < bmax && fabs(max - bmax) > 0.0001) { bestcost = cost; bestpos = max; } //DPRINTF("%d\n", cost); i += 1; } //DPRINTF("\n"); box.print(); //DPRINTF("%d %d %f\n", i, axis, bestpos); return bestpos; }
QUuid EntityScriptingInterface::addEntity(const EntityItemProperties& properties) { EntityItemProperties propertiesWithSimID = convertLocationFromScriptSemantics(properties); propertiesWithSimID.setDimensionsInitialized(properties.dimensionsChanged()); auto dimensions = propertiesWithSimID.getDimensions(); float volume = dimensions.x * dimensions.y * dimensions.z; auto density = propertiesWithSimID.getDensity(); auto newVelocity = propertiesWithSimID.getVelocity().length(); float cost = calculateCost(density * volume, 0, newVelocity); cost *= costMultiplier; if (cost > _currentAvatarEnergy) { return QUuid(); } EntityItemID id = EntityItemID(QUuid::createUuid()); // If we have a local entity tree set, then also update it. bool success = true; if (_entityTree) { _entityTree->withWriteLock([&] { EntityItemPointer entity = _entityTree->addEntity(id, propertiesWithSimID); if (entity) { if (propertiesWithSimID.parentRelatedPropertyChanged()) { // due to parenting, the server may not know where something is in world-space, so include the bounding cube. bool success; AACube queryAACube = entity->getQueryAACube(success); if (success) { propertiesWithSimID.setQueryAACube(queryAACube); } } if (_bidOnSimulationOwnership) { // This Node is creating a new object. If it's in motion, set this Node as the simulator. auto nodeList = DependencyManager::get<NodeList>(); const QUuid myNodeID = nodeList->getSessionUUID(); // and make note of it now, so we can act on it right away. propertiesWithSimID.setSimulationOwner(myNodeID, SCRIPT_POKE_SIMULATION_PRIORITY); entity->setSimulationOwner(myNodeID, SCRIPT_POKE_SIMULATION_PRIORITY); } entity->setLastBroadcast(usecTimestampNow()); } else { qCDebug(entities) << "script failed to add new Entity to local Octree"; success = false; } }); } // queue the packet if (success) { emit debitEnergySource(cost); queueEntityMessage(PacketType::EntityAdd, id, propertiesWithSimID); } return id; }
/*! @brief Calculates energy over a period. * * @param voltageSample - Instantaneous voltage sample * @param currentSample - Instantaneous current sample * @param allSamplesCollected - if TRUE, this means that this last sample was the final sample over the period (do extra calculations). */ static void calculateEnergy(int16_t voltageSample, int16_t currentSample, BOOL allSamplesCollected) { static int32_t instantaneousPower = 0; instantaneousPower += (voltageSample * currentSample); //Accumulate instantaneous power over the period if (allSamplesCollected) { Meter_TotalEnergy += instantaneousPower; //All samples are collected accumulate into total energy (Ts is accounted for in base) calculateCost(instantaneousPower); //Calculate Cost for the period instantaneousPower = 0; } }
uint MatrixGraph::getBestNeighbour(TabuContainer &tabuList, vector<uint> ¤tPath) { vector<uint> resultPath = currentPath; uint currentCost = calculateCost(currentPath); uint resultCost = currentCost; bool first = true; uint v1 = 0, v2 = 0; uint row = (rand() % (vertexNumber - 1)) + 1; //uint col = (rand() % (vertexNumber - 2)) + 1; //if (col >= row) // ++col; for (uint col = 1; col < vertexNumber; ++col) { vector<uint> newPath(currentPath); iter_swap(newPath.begin() + row, newPath.begin() + col); uint newCost = calculateCost(newPath); if ((newCost < resultCost || first) && !tabuList.getTabu(newPath[row], newPath[col])) { first = false; v1 = newPath[row]; v2 = newPath[col]; resultPath = newPath; resultCost = newCost; } } if (v1) { tabuList.decrementTabu(); tabuList.setTabu(v1, v2); } currentPath = resultPath; return currentCost; }
void DFS(graph *G, std::vector<int> &visited, int end, int &cost) { int temp; int back; int i; back = visited.back(); std::vector<int> adjNodes = getAdjNodes(G, back); //get the last node adiance nodes for (std::vector<int>::iterator node_it = adjNodes.begin(); //for all adiance nodes node_it != adjNodes.end(); node_it++) { int node = (*node_it); if (nodeVisited(visited, node)) continue; //check if the node has ben visited if (node == end) //if the node is the one we search { visited.push_back(*node_it); //add it to the path int hops = (int)visited.size(); for (i = 0; i < hops; i++) { //std::cout << visited[i] << " "; temp = calculateCost(G, visited); //calculate the path cost if (cost > temp) cost = temp; } int n = (int)visited.size() - 1; visited.erase(visited.begin() + n); //clear the path and keep only the source vertex break; } } for (std::vector<int>::iterator node_it = adjNodes.begin(); //for each node in the adiance list node_it != adjNodes.end(); node_it++) { int node = (*node_it); if (nodeVisited(visited, node) || node == end) //if the node has been visited or it's the node we search continue continue; visited.push_back(node); //otherwise put the node in the path DFS(G, visited, end, cost); //backtrack int n = (int)visited.size() - 1; visited.erase(visited.begin() + n); //clear the path and keep only the source vertex } }
/* UNFINISHED // Ads new edge to appropriate position in edgeListVector */ void Graph::AddEdge(std::shared_ptr<Node> start, std::shared_ptr<Node> end, int cost) { std::shared_ptr<Edge> edge(new Edge(start, end, calculateCost(start, end))); std::list<std::shared_ptr<Edge>> edgeList; // Sequenced container of Edge pointers //if (!edgeListVector[start->getIndex()]) { // std::list<std::shared_ptr<Edge>> edgeList = edgeListVector[start->getIndex()]; // Sequenced container of Edge pointers //} edgeList.push_back(edge); edgeListVector[start->getIndex()] = edgeList; }
void GraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent * event){ if (selectionActive){ selectedDot->setPos(event->scenePos()); if (selectedDot->isCenter()){ updateConnections(); } else{ removeItem(((QGraphicsItem*)selectedDot->getConnection())); connectToNearest(selectedDot); } totalCost = calculateCost(); emit costChanged(totalCost); update(QRectF(-50,-50,1000,1000)); } }
void GraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event){ QGraphicsItem *selection = itemAt(event->scenePos().x(),event->scenePos().y(),transform); if(((CustomItem*)selection)->getName() == std::string("Dot")){ if(((Dot*)selection)->isCenter()){ removeCenter(((Dot*)selection)); updateConnections(); } else{ removeItem((QGraphicsItem*)((Dot*)selection)->getConnection()); removeItem(selection); } totalCost = calculateCost(); emit costChanged(totalCost); update(QRectF(-50,-50,1000,1000)); } }
void EntityScriptingInterface::deleteEntity(QUuid id) { EntityItemID entityID(id); bool shouldDelete = true; // If we have a local entity tree set, then also update it. if (_entityTree) { _entityTree->withWriteLock([&] { EntityItemPointer entity = _entityTree->findEntityByEntityItemID(entityID); if (entity) { auto dimensions = entity->getDimensions(); float volume = dimensions.x * dimensions.y * dimensions.z; auto density = entity->getDensity(); auto velocity = entity->getVelocity().length(); float cost = calculateCost(density * volume, velocity, 0); cost *= costMultiplier; if (cost > _currentAvatarEnergy) { shouldDelete = false; return; } else { //debit the avatar energy and continue emit debitEnergySource(cost); } if (entity->getLocked()) { shouldDelete = false; } else { _entityTree->deleteEntity(entityID); } } }); } // if at this point, we know the id, and we should still delete the entity, send the update to the entity server if (shouldDelete) { getEntityPacketSender()->queueEraseEntityMessage(entityID); } }
TriangleCost (int _index, bool calcCost=false) : index(_index) { if (calcCost) calculateCost(); }
Data MatrixGraph::simulatedAnnealing(uint temperature) { clock_t overallTime = clock(); initRand(); stringstream results; vector<uint> route, bestRoute; route.reserve(vertexNumber); bestRoute.reserve(vertexNumber); uint prevCost = greedyAlg(route), bestCost; route.pop_back(); bestRoute = route; bestCost = prevCost; if (!temperature) temperature = vertexNumber << 10; default_random_engine gen(uint(time(nullptr))); uniform_real_distribution<double> doubleRnd(0.0, 1.0); uint i = 0; for (; temperature; --temperature, ++i) { i %= route.size(); uint firstIndex = rand() % (route.size()); uint secondIndex = rand() % (route.size() - 1); if (secondIndex >= firstIndex) ++secondIndex; vector<uint> tmpVector(route); uint tmp = tmpVector[firstIndex]; tmpVector[firstIndex] = tmpVector[secondIndex]; tmpVector[secondIndex] = tmp; uint tmpCost = calculateCost(tmpVector); if (tmpCost < prevCost) { route = tmpVector; prevCost = tmpCost; } else { if (acceptanceProbability(prevCost, tmpCost, temperature) >= doubleRnd(gen)) { route = tmpVector; prevCost = tmpCost; } } // Śledzenie najlepszego rozwiązania if (prevCost < bestCost) { bestRoute = route; bestCost = prevCost; } } double duration = (clock() - overallTime) / (double)CLOCKS_PER_SEC; results << "Koszt drogi: " << bestCost << "\nCalkowity czas trwania: " << duration << " sekund\n"; return Data(bestRoute, bestCost, results.str(), duration); }
SpecialOrderEditor::SpecialOrderEditor( QWidget *parent, bool newOne ) : KDialog( parent ) { m_modelAssigned = false; priceEach = 0; paymentEach = 0; groupInfo.isAvailable = true; groupInfo.cost = 0; groupInfo.price = 0; groupInfo.count = 0; groupInfo.name = ""; ui = new SpecialOrderUI( this ); setMainWidget( ui ); setCaption( i18n("Special Orders") ); setButtons( KDialog::Ok|KDialog::Cancel ); //Set Validators for input boxes ui->editAddQty->setValidator(new QDoubleValidator(0.00, 999999999999.99, 3, ui->editAddQty)); ui->editQty->setValue(1); ui->editAddQty->setText("1.00"); connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(calculateCost())); connect( ui->editQty, SIGNAL(valueChanged(int)), this, SLOT(calculateCost())); connect( ui->editQty, SIGNAL(editingFinished()), this, SLOT(checkFieldsState())); connect( ui->editPayment, SIGNAL(valueChanged(double)), this, SLOT(checkFieldsState())); connect( ui->editFilter, SIGNAL(textEdited ( const QString &)), SLOT(applyFilter(const QString &)) ); connect( ui->btnAdd, SIGNAL(clicked()), SLOT(addItem()) ); connect( ui->editAddQty, SIGNAL(returnPressed()), SLOT(addItem()) ); connect( ui->btnRemove, SIGNAL(clicked()), SLOT(removeItem()) ); connect( ui->groupView, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), SLOT(itemDoubleClicked(QTableWidgetItem*)) ); connect( ui->deliveryDT, SIGNAL(valueChanged(QDateTime)), this, SLOT(checkDate(QDateTime)) ); connect( ui->editNotes, SIGNAL(textChanged()), SLOT(updateNoteLength()) ); //for now, when creating a s.o. the status cannot be modified. It can be when edited. if (newOne) { dateTime = QDateTime::currentDateTime(); ui->deliveryDT->setDateTime(QDateTime::currentDateTime().addDays(1)); } //tip QString path = KStandardDirs::locate("appdata", "styles/"); path = path+"tip.svg"; qtyTip = new MibitTip(this, ui->editQty, path, DesktopIcon("dialog-warning",32) ); path = KStandardDirs::locate("appdata", "styles/")+"rotated_tip.svg"; groupTip = new MibitTip(this, ui->groupView, path, DesktopIcon("dialog-warning",32), tpAbove ); path = KStandardDirs::locate("appdata", "styles/"); path = path+"floating_bottom.svg"; newClientPanel = new MibitFloatPanel(this, path, Top); newClientPanel->setSize(550,250); newClientPanel->addWidget(ui->frameClient); newClientPanel->setMode(pmManual); newClientPanel->setHiddenTotally(true); ui->editClientName->setEmptyMessage(i18n("Enter client name here...")); ui->editClientPhone->setEmptyMessage(i18n("Enter client phone here...")); ui->editClientCell->setEmptyMessage(i18n("Enter client cell phone here...")); connect( ui->btnNewClient, SIGNAL(clicked()), newClientPanel, SLOT(showPanel() )); connect( ui->btnNewClient, SIGNAL(clicked()), this, SLOT(enableCreateClient() )); connect( ui->btnClientCancel, SIGNAL(clicked()), newClientPanel, SLOT(hidePanel())); connect( ui->btnClientAdd, SIGNAL(clicked()), this, SLOT(createClient())); connect( ui->editClientName, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); connect( ui->editClientAddress, SIGNAL(textChanged()), this, SLOT(checkValidInfo()) ); connect( ui->editClientPhone, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); connect( ui->editClientCell, SIGNAL(textEdited(const QString &)), this, SLOT(checkValidInfo()) ); setDefaultButton(KDialog::None); ui->btnFilter->setDefault(true); ui->btnFilter->hide(); //hack to dont have a default OK or Cancel button ui->clientsCombo->setFocus(); enableButtonOk(false); }
// ----------------------------------------------------------------------------- // Main ICD reconstruction // ----------------------------------------------------------------------------- void BFReconstructionEngine::execute() { uint64_t totalTime = EIMTOMO_getMilliSeconds(); int32_t err = 0; std::stringstream ss; // int16_t i,j,k,Idx; size_t dims[3]; uint16_t maxNumberOfDetectorElts; uint8_t status; //set to 1 if ICD has converged Real_t checksum = 0, temp; RealImageType::Pointer voxelProfile; RealVolumeType::Pointer detectorResponse; RealVolumeType::Pointer h_t; RealVolumeType::Pointer y_Est; //Estimated Sinogram RealVolumeType::Pointer finalSinogram; //To store and write the final sinogram resulting from our reconstruction RealVolumeType::Pointer errorSino; //Error Sinogram std::string indent(""); //#ifdef COST_CALCULATE //Commented out because if not the code fails to run. std::string filepath(m_TomoInputs->tempDir); filepath = filepath.append(MXADir::getSeparator()).append(MBIR::Defaults::CostFunctionFile); CostData::Pointer cost = CostData::New(); cost->initOutputFile(filepath); //#endif #if OpenMBIR_USE_PARALLEL_ALGORITHMS tbb::task_scheduler_init init; #endif // Initialize the Sinogram if(m_TomoInputs == NULL) { setErrorCondition(-1); notify("Error: The TomoInput Structure was NULL. The proper API is to supply this class with that structure,", 100, Observable::UpdateErrorMessage); return; } //Based on the inputs , calculate the "other" variables in the structure definition if(m_Sinogram == NULL) { setErrorCondition(-1); notify("Error: The Sinogram Structure was NULL. The proper API is to supply this class with that structure,", 100, Observable::UpdateErrorMessage); return; } if(m_Geometry == NULL) { setErrorCondition(-1); notify("Error: The Geometry Structure was NULL. The proper API is to supply this class with that structure,", 100, Observable::UpdateErrorMessage); return; } if (m_ForwardModel.get() == NULL) { setErrorCondition(-1); notify("Error: The forward model was not set.", 100, Observable::UpdateErrorMessage); return; } // Read the Input data from the supplied data file - reconstruction from previous resolution ? err = readInputData(); if(err < 0) { return; } if (getCancel() == true) { setErrorCondition(-999); return; } if (getCancel() == true) { setErrorCondition(-999); return; } //Additional parameters associated with the system err = m_ForwardModel->createNuisanceParameters(m_Sinogram); if(err < 0) { return; } //Periodically checking if user has sent a cancel signal from the GUI if (getCancel() == true) { setErrorCondition(-999); return; } m_ForwardModel->printNuisanceParameters(m_Sinogram); //Take log of the input data after subtracting offset m_ForwardModel->processRawCounts(m_Sinogram); // Initialize the Geometry data from a rough reconstruction err = initializeRoughReconstructionData(); if(err < 0) { return; } if (getCancel() == true) { setErrorCondition(-999); return; } // Get the actual boundaries in the X Direction since we "Extend Object" which makes // the output mrc file much wider than they really need to be. uint16_t cropStart = 0; uint16_t cropEnd = m_Geometry->N_x; computeOriginalXDims(cropStart, cropEnd); // std::cout << "Crop Start: " << cropStart << std::endl; // std::cout << "Crop End: " << cropEnd << std::endl; m_ForwardModel->allocateNuisanceParameters(m_Sinogram); //#ifdef COST_CALCULATE // dims[0] = (m_TomoInputs->NumIter+1)*m_TomoInputs->NumOuterIter*3; //#endif dims[0] = m_Sinogram->N_theta; dims[1] = m_Sinogram->N_r; dims[2] = m_Sinogram->N_t; y_Est = RealVolumeType::New(dims, "y_Est");//y_Est = A*x_{initial} errorSino = RealVolumeType::New(dims, "ErrorSino");// y - y_est m_ForwardModel->weightInitialization(dims); //Initialize the \lambda matrix finalSinogram = RealVolumeType::New(dims, "Final Sinogram"); //Debug variable to store the final A*x_{Final} /*************** Computation of partial Amatrix *************/ //calculate the trapezoidal voxel profile for each angle.Also the angles in the Sinogram // Structure are converted to radians voxelProfile = calculateVoxelProfile(); //This is used for computation of the partial A matrix //Pre compute sine and cos theta to speed up computations DetectorParameters::Pointer haadfParameters = DetectorParameters::New(); haadfParameters->setOffsetR ( ((m_TomoInputs->delta_xz / sqrt(3.0)) + m_Sinogram->delta_r / 2) / m_AdvParams->DETECTOR_RESPONSE_BINS); haadfParameters->setOffsetT ( ((m_TomoInputs->delta_xz / 2) + m_Sinogram->delta_t / 2) / m_AdvParams->DETECTOR_RESPONSE_BINS); haadfParameters->setBeamWidth(m_Sinogram->delta_r); haadfParameters->calculateSinCos(m_Sinogram); //Initialize the e-beam haadfParameters->initializeBeamProfile(m_Sinogram, m_AdvParams); //The shape of the averaging kernel for the detector if (getCancel() == true) { setErrorCondition(-999); return; } //calculate sine and cosine of all angles and store in the global arrays sine and cosine DetectorResponse::Pointer dResponseFilter = DetectorResponse::New(); dResponseFilter->setTomoInputs(m_TomoInputs); dResponseFilter->setSinogram(m_Sinogram); dResponseFilter->setAdvParams(m_AdvParams); dResponseFilter->setDetectorParameters(haadfParameters); dResponseFilter->setVoxelProfile(voxelProfile); dResponseFilter->setObservers(getObservers()); dResponseFilter->setVerbose(getVerbose()); dResponseFilter->setVeryVerbose(getVeryVerbose()); dResponseFilter->execute(); if(dResponseFilter->getErrorCondition() < 0) { ss.str(""); ss << "Error Calling function detectorResponse in file " << __FILE__ << "(" << __LINE__ << ")" << std::endl; setErrorCondition(-2); notify(ss.str(), 100, Observable::UpdateErrorMessage); return; } detectorResponse = dResponseFilter->getResponse(); // Writer the Detector Response to an output file DetectorResponseWriter::Pointer responseWriter = DetectorResponseWriter::New(); responseWriter->setTomoInputs(m_TomoInputs); responseWriter->setSinogram(m_Sinogram); responseWriter->setAdvParams(m_AdvParams); responseWriter->setObservers(getObservers()); responseWriter->setResponse(detectorResponse); responseWriter->setVerbose(getVerbose()); responseWriter->setVeryVerbose(getVeryVerbose()); responseWriter->execute(); if(responseWriter->getErrorCondition() < 0) { ss.str(""); ss << __FILE__ << "(" << __LINE__ << ") " << "Error writing detector response to file." << std::endl; setErrorCondition(-3); notify(ss.str(), 100, Observable::UpdateErrorMessage); return; } if (getCancel() == true) { setErrorCondition(-999); return; } // Initialize H_t volume dims[0] = 1; dims[1] = m_Sinogram->N_theta; dims[2] = m_AdvParams->DETECTOR_RESPONSE_BINS; h_t = RealVolumeType::New(dims, "h_t"); initializeHt(h_t, haadfParameters->getOffsetT() ); checksum = 0; ss.str(""); ss << "Calculating A Matrix...."; notify(ss.str(), 0, Observable::UpdateProgressMessage); std::vector<AMatrixCol::Pointer> voxelLineResponse(m_Geometry->N_y); maxNumberOfDetectorElts = (uint16_t)((m_TomoInputs->delta_xy / m_Sinogram->delta_t) + 2); dims[0] = maxNumberOfDetectorElts; for (uint16_t i = 0; i < m_Geometry->N_y; i++) { AMatrixCol::Pointer vlr = AMatrixCol::New(dims, 0); voxelLineResponse[i] = vlr; } //Calculating A-Matrix one column at a time //For each entry the idea is to initially allocate space for Sinogram.N_theta * Sinogram.N_x // And then store only the non zero entries by allocating a new array of the desired size std::vector<AMatrixCol::Pointer> tempCol(m_Geometry->N_x * m_Geometry->N_z); checksum = 0; temp = 0; uint32_t voxel_count = 0; for (uint16_t z = 0; z < m_Geometry->N_z; z++) { for (uint16_t x = 0; x < m_Geometry->N_x; x++) { tempCol[voxel_count] = AMatrixCol::calculateAMatrixColumnPartial(m_Sinogram, m_Geometry, m_TomoInputs, m_AdvParams, z, x, 0, detectorResponse, haadfParameters); temp += tempCol[voxel_count]->count; if(0 == tempCol[voxel_count]->count ) { //If this line is never hit and the Object is badly initialized //set it to zero for (uint16_t y = 0; y < m_Geometry->N_y; y++) { m_Geometry->Object->setValue(0.0, z, x, y); } } voxel_count++; } } storeVoxelResponse(h_t, voxelLineResponse, haadfParameters); if (getCancel() == true) { setErrorCondition(-999); return; } if(getVerbose()) { printf("Number of non zero entries of the forward projector is %lf\n", temp); printf("Geometry-Z %d\n", m_Geometry->N_z); } /************ End of A matrix partial computations **********************/ //Gain and Offset Parameters Initialization of the forward model m_ForwardModel->gainAndOffsetInitialization(m_Sinogram->N_theta); initializeVolume(y_Est, 0.0); if (getCancel() == true) { setErrorCondition(-999); return; } //Forward Project Geometry->Object one slice at a time and compute the Sinogram for each slice // Forward Project using the Forward Model err = m_ForwardModel->forwardProject(m_Sinogram, m_Geometry, tempCol, voxelLineResponse, y_Est , errorSino); if (err < 0) { return; } if (getCancel() == true) { setErrorCondition(-999); return; } #ifdef FORWARD_PROJECT_MODE return 0; //exit the program once we finish forward projecting the object #endif//Forward Project mode // Initialize the Prior Model parameters - here we are using a QGGMRF Prior Model QGGMRF::QGGMRF_Values QGGMRF_values; QGGMRF::initializePriorModel(m_TomoInputs, &QGGMRF_values, NULL); #ifdef COST_CALCULATE err = calculateCost(cost, m_Sinogram, m_Geometry, errorSino, &QGGMRF_values); #endif //Cost calculation endif Real_t TempBraggValue, DesBraggValue; #ifdef BRAGG_CORRECTION if(m_TomoInputs->NumIter > 1) { //Get the value of the Bragg threshold from the User Interface the first time DesBraggValue = m_ForwardModel->getBraggThreshold(); if (getVeryVerbose()) {std::cout << "Desired Bragg threshold =" << DesBraggValue << std::endl;} TempBraggValue = DefBraggThreshold;//m_ForwardModel->getBraggThreshold(); m_ForwardModel->setBraggThreshold(TempBraggValue); //setting the Threshold T of \beta_{T,\delta} //the \delta value is set in BFMultiResolutionReconstruction.cpp } else { TempBraggValue = m_ForwardModel->getBraggThreshold(); m_ForwardModel->setBraggThreshold(TempBraggValue); } #endif //Bragg correction if (getVeryVerbose()) {std::cout << "Bragg threshold =" << TempBraggValue << std::endl;} //Generate a List if (getVeryVerbose()) {std::cout << "Generating a list of voxels to update" << std::endl;} //Takes all the voxels along x-z slice and forms a list m_VoxelIdxList = VoxelUpdateList::GenRegularList(m_Geometry->N_z, m_Geometry->N_x); //Randomize the list of voxels m_VoxelIdxList = VoxelUpdateList::GenRandList(m_VoxelIdxList); if(getVerbose()) { std::cout << "Initial random order list .." << std::endl; m_VoxelIdxList->printMaxList(std::cout); } // Create a copy of the Voxel Update List because we are going to adjust the VoxelUpdateList instance variable // with values for the array pointer and number of elements based on the iteration VoxelUpdateList::Pointer TempList = VoxelUpdateList::New(m_VoxelIdxList->numElements(), m_VoxelIdxList->getArray() ); uint32_t listselector = 0; //For the homogenous updates this cycles through the random list one sublist at a time //Initialize the update magnitude arrays (for NHICD mainly) & stopping criteria dims[0] = m_Geometry->N_z; //height dims[1] = m_Geometry->N_x; //width dims[2] = 0; RealImageType::Pointer magUpdateMap = RealImageType::New(dims, "Update Map for voxel lines"); RealImageType::Pointer filtMagUpdateMap = RealImageType::New(dims, "Filter Update Map for voxel lines"); UInt8Image_t::Pointer magUpdateMask = UInt8Image_t::New(dims, "Update Mask for selecting voxel lines NHICD");//TODO: Remove this variable. Under the new formulation not needed Real_t PrevMagSum = 0; magUpdateMap->initializeWithZeros(); filtMagUpdateMap->initializeWithZeros(); #if ROI //A mask to check the stopping criteria for the algorithm initializeROIMask(magUpdateMask); #endif //Debugging variable to check if all voxels are visited dims[0] = m_Geometry->N_z; dims[1] = m_Geometry->N_x; dims[2] = 0; UInt8Image_t::Pointer m_VisitCount = UInt8Image_t::New(dims, "VisitCount"); uint32_t EffIterCount = 0; //Maintains number of calls to updatevoxelroutine //Loop through every voxel updating it by solving a cost function for (int16_t reconOuterIter = 0; reconOuterIter < m_TomoInputs->NumOuterIter; reconOuterIter++) { ss.str(""); // Clear the string stream indent = ""; //The first time we may need to update voxels multiple times and then on //just optimize over I,d,sigma,f once each outer loop; //Each outer loop after the first outer iter updates a subset of the voxels //followed by other parameters if needed if(reconOuterIter > 0) { m_TomoInputs->NumIter = 1;//Inner iterations m_ForwardModel->setBraggThreshold(TempBraggValue); } for (int16_t reconInnerIter = 0; reconInnerIter < m_TomoInputs->NumIter; reconInnerIter++) { // If at the inner most loops at the coarsest resolution donot apply Bragg // Only at the coarsest scale the NumIter > 1 if(m_TomoInputs->NumIter > 1 && reconInnerIter == 0) { m_ForwardModel->setBraggThreshold(DefBraggThreshold); } #ifdef DEBUG //Prints the ratio of the sinogram entries selected m_ForwardModel->printRatioSelected(m_Sinogram); #endif //DEBUG ss.str(""); ss << "Outer Iterations: " << reconOuterIter << "/" << m_TomoInputs->NumOuterIter << " Inner Iterations: " << reconInnerIter << "/" << m_TomoInputs->NumIter << std::endl; indent = " "; #ifdef DEBUG // This is all done PRIOR to calling what will become a method if (getVeryVerbose()) {std::cout << "Bragg Threshold =" << m_ForwardModel->getBraggThreshold() << std::endl;} #endif //DEBUG // This could contain multiple Subloops also - voxel update /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ #ifdef NHICD //NHICD alternates between updating a fixed subset of voxels and a //list created on the fly based on the previous iterations // Creating a sublist of voxels for the Homogenous // iterations - cycle through the partial sub lists if(EffIterCount % 2 == 0) //Even iterations == Homogenous update { listselector %= MBIR::Constants::k_NumHomogeniousIter;// A variable to cycle through the randmoized list of voxels int32_t nElements = floor((Real_t)TempList->numElements() / MBIR::Constants::k_NumHomogeniousIter); //If the number of voxels is NOT exactly divisible by NUM_NON .. then compensate and make the last of the lists longer if(listselector == MBIR::Constants::k_NumHomogeniousIter - 1) { nElements += (TempList->numElements() - nElements * MBIR::Constants::k_NumHomogeniousIter); if(getVeryVerbose()) { std::cout << "**********Adjusted number of voxel lines for last iter**************" << std::endl; std::cout << nElements << std::endl; std::cout << "**********************************" << std::endl; } } //Set the list array for updating voxels int32_t start = (uint32_t)(floor(((Real_t)TempList->numElements() / MBIR::Constants::k_NumHomogeniousIter)) * listselector); m_VoxelIdxList = TempList->subList(nElements, start); //m_VoxelIdxList.Array = &(TempList.Array[]); if (getVeryVerbose()) { std::cout << "Partial random order list for homogenous ICD .." << std::endl; m_VoxelIdxList->printMaxList(std::cout); } listselector++; //printList(m_VoxelIdxList); } #endif //NHICD #ifdef DEBUG Real_t TempSum = 0; for (int32_t j = 0; j < m_Geometry->N_z; j++) { for (int32_t k = 0; k < m_Geometry->N_x; k++) { TempSum += magUpdateMap->getValue(j, k); } } if (getVeryVerbose()) { std::cout << "**********************************************" << std::endl; std::cout << "Average mag prior to calling update voxel = " << TempSum / (m_Geometry->N_z * m_Geometry->N_x) << std::endl; std::cout << "**********************************************" << std::endl; } #endif //debug status = updateVoxels(reconOuterIter, reconInnerIter, tempCol, errorSino, voxelLineResponse, cost, &QGGMRF_values, magUpdateMap, filtMagUpdateMap, magUpdateMask, m_VisitCount, PrevMagSum, EffIterCount); #ifdef NHICD if(EffIterCount % MBIR::Constants::k_NumNonHomogeniousIter == 0) // At the end of half an //equivalent iteration compute average Magnitude of recon to test //stopping criteria { PrevMagSum = roiVolumeSum(magUpdateMask); if (getVeryVerbose()) {std::cout << " Previous Magnitude of the Recon = " << PrevMagSum << std::endl;} } #else PrevMagSum = roiVolumeSum(magUpdateMask); std::cout << " Previous Magnitude of the Recon = " << PrevMagSum << std::endl; #endif //NHICD //Debugging information to test if every voxel is getting touched #ifdef NHICD //Debug every equivalent iteration if(EffIterCount % (2 * MBIR::Constants::k_NumNonHomogeniousIter) == 0 && EffIterCount > 0) #endif //NHICD { for (int16_t j = 0; j < m_Geometry->N_z; j++) { for (int16_t k = 0; k < m_Geometry->N_x; k++) { if(m_VisitCount->getValue(j, k) == 0) { printf("Pixel (%d %d) not visited\n", j, k); } } } //Reset the visit counter once we have cycled through //all voxels once via the homogenous updates for (int16_t j = 0; j < m_Geometry->N_z; j++) { for (int16_t k = 0; k < m_Geometry->N_x; k++) { m_VisitCount->setValue(0, j, k); } } } //end of debug EffIterCount++; //cycles between the two types of voxel updates /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ if(status == 0) { break; //stop inner loop if we have hit the threshold value for x } // Check to see if we are canceled. if (getCancel() == true) { setErrorCondition(-999); return; } // Write out the MRC File ; If NHICD only after half an equit do a write #ifdef NHICD if(EffIterCount % (MBIR::Constants::k_NumNonHomogeniousIter) == 0) #endif //NHICD { ss.str(""); ss << m_TomoInputs->tempDir << MXADir::getSeparator() << reconOuterIter << "_" << reconInnerIter << "_" << MBIR::Defaults::ReconstructedMrcFile; writeMRCFile(ss.str(), cropStart, cropEnd); notify(ss.str(), 0, Observable::UpdateIntermediateImage); m_TomoInputs->tempFiles.push_back(ss.str()); } #ifdef COST_CALCULATE //typically run only for debugging /*********************Cost Calculation*************************************/ int16_t err = calculateCost(cost, m_Sinogram, m_Geometry, errorSino, &QGGMRF_values); if(err < 0) { std::cout << "Cost went up after voxel update" << std::endl; return; // break; } /**************************************************************************/ #endif //Cost calculation endif #ifdef BRAGG_CORRECTION //If at the last iteration of the inner loops at coarsest resolution adjust parameters if(reconInnerIter == m_TomoInputs->NumIter - 1 && reconInnerIter != 0) { //The first time at the coarsest resolution at the end of // inner iterations set the Bragg Threshold TempBraggValue = DesBraggValue;//threshold; m_ForwardModel->setBraggThreshold(TempBraggValue); } #endif //Bragg correction } /* ++++++++++ END Inner Iteration Loop +++++++++++++++ */ if(0 == status && reconOuterIter >= 1) //if stopping criteria is met and //number of iterations is greater than 1 { if (getVeryVerbose()) {std::cout << "Exiting the code because status =0" << std::endl;} break; } if(getVeryVerbose()) { std::cout << " Starting nuisance parameter estimation" << std::endl; } if(m_TomoInputs->NumOuterIter > 1) //Dont update any parameters if we just have one outer iteration { if(m_AdvParams->JOINT_ESTIMATION) { m_ForwardModel->jointEstimation(m_Sinogram, errorSino, y_Est, cost); m_ForwardModel->updateSelector(m_Sinogram, errorSino); #ifdef COST_CALCULATE //Debug info int16_t err = calculateCost(cost, m_Sinogram, m_Geometry, errorSino, &QGGMRF_values); if(err < 0) { std::cout << "Cost went up after offset update" << std::endl; break; } #endif//cost } //Joint estimation endif if(m_AdvParams->NOISE_ESTIMATION) { m_ForwardModel->updateWeights(m_Sinogram, errorSino); m_ForwardModel->updateSelector(m_Sinogram, errorSino); #ifdef COST_CALCULATE //err = calculateCost(cost, Weight, errorSino); err = calculateCost(cost, m_Sinogram, m_Geometry, errorSino, &QGGMRF_values); if (err < 0 && reconOuterIter > 1) { std::cout << "Cost went up after variance update" << std::endl; std::cout << "Effective iterations =" << EffIterCount << std::endl; return; //break; } #endif//cost } if(getVeryVerbose()) { std::cout << " Ending nuisance parameter estimation" << std::endl; } } }/* ++++++++++ END Outer Iteration Loop +++++++++++++++ */ indent = ""; #if DEBUG_COSTS cost->printCosts(std::cout); #endif #ifdef FORWARD_PROJECT_MODE int fileError = 0; FILE* Fp6; MAKE_OUTPUT_FILE(Fp6, fileError, m_TomoInputs->tempDir, MBIR::Defaults::BFForwardProjectedObjectFile); if (fileError == 1) { } #endif if (getCancel() == true) { setErrorCondition(-999); return; } /* Write the Gains,Offsets and variance to an output file */ m_ForwardModel->writeNuisanceParameters(m_Sinogram); //Compute final value of Ax_{final} Real_t temp_final = 0.0; for (uint16_t i_theta = 0; i_theta < m_Sinogram->N_theta; i_theta++) { for (uint16_t i_r = 0; i_r < m_Sinogram->N_r; i_r++) { for (uint16_t i_t = 0; i_t < m_Sinogram->N_t; i_t++) { temp_final = m_Sinogram->counts->getValue(i_theta, i_r, i_t) - errorSino->getValue(i_theta, i_r, i_t); finalSinogram->setValue(temp_final, i_theta, i_r, i_t); } } } // This is writing the "ReconstructedSinogram.bin" file m_ForwardModel->writeSinogramFile(m_Sinogram, finalSinogram); // Writes the sinogram to a file if (getCancel() == true) { setErrorCondition(-999); return; } // Writes ReconstructedObject.bin file for next resolution { std::stringstream ss; ss << m_TomoInputs->tempDir << MXADir::getSeparator() << MBIR::Defaults::ReconstructedObjectFile; writeReconstructionFile(ss.str()); } // Write out the VTK file if (m_TomoInputs->vtkOutputFile.empty() == false) { writeVtkFile(m_TomoInputs->vtkOutputFile, cropStart, cropEnd); } // Write out the MRC File if (m_TomoInputs->mrcOutputFile.empty() == false) { writeMRCFile(m_TomoInputs->mrcOutputFile, cropStart, cropEnd); } //Write out avizo fire file if (m_TomoInputs->avizoOutputFile.empty() == false) { writeAvizoFile(m_TomoInputs->avizoOutputFile, cropStart, cropEnd); } //Debug : Writing out the selector array as an MRC file m_ForwardModel->writeSelectorMrc(m_TomoInputs->braggSelectorFile, m_Sinogram, m_Geometry, errorSino); if (getVerbose()) { std::cout << "Final Dimensions of Object: " << std::endl; std::cout << " Nx = " << m_Geometry->N_x << std::endl; std::cout << " Ny = " << m_Geometry->N_y << std::endl; std::cout << " Nz = " << m_Geometry->N_z << std::endl; #ifdef NHICD std::cout << "Number of equivalet iterations taken =" << EffIterCount / MBIR::Constants::k_NumNonHomogeniousIter << std::endl; #else std::cout << "Number of equivalet iterations taken =" << EffIterCount / MBIR::Constants::k_NumHomogeniousIter << std::endl; #endif //NHICD } notify("Reconstruction Complete", 100, Observable::UpdateProgressValueAndMessage); setErrorCondition(0); if (getVerbose()) {std::cout << "Total Running Time for Execute: " << (EIMTOMO_getMilliSeconds() - totalTime) / 1000 << std::endl;} return; }
QUuid EntityScriptingInterface::editEntity(QUuid id, const EntityItemProperties& scriptSideProperties) { EntityItemProperties properties = scriptSideProperties; auto dimensions = properties.getDimensions(); float volume = dimensions.x * dimensions.y * dimensions.z; auto density = properties.getDensity(); auto newVelocity = properties.getVelocity().length(); float oldVelocity = { 0.0f }; EntityItemID entityID(id); if (!_entityTree) { queueEntityMessage(PacketType::EntityEdit, entityID, properties); //if there is no local entity entity tree, no existing velocity, use 0. float cost = calculateCost(density * volume, oldVelocity, newVelocity); cost *= costMultiplier; if (cost > _currentAvatarEnergy) { return QUuid(); } else { //debit the avatar energy and continue emit debitEnergySource(cost); } return id; } // If we have a local entity tree set, then also update it. bool updatedEntity = false; _entityTree->withWriteLock([&] { if (scriptSideProperties.parentRelatedPropertyChanged()) { // All of parentID, parentJointIndex, position, rotation are needed to make sense of any of them. // If any of these changed, pull any missing properties from the entity. EntityItemPointer entity = _entityTree->findEntityByEntityItemID(entityID); if (!entity) { return; } //existing entity, retrieve old velocity for check down below oldVelocity = entity->getVelocity().length(); if (!scriptSideProperties.parentIDChanged()) { properties.setParentID(entity->getParentID()); } if (!scriptSideProperties.parentJointIndexChanged()) { properties.setParentJointIndex(entity->getParentJointIndex()); } if (!scriptSideProperties.localPositionChanged() && !scriptSideProperties.positionChanged()) { properties.setPosition(entity->getPosition()); } if (!scriptSideProperties.localRotationChanged() && !scriptSideProperties.rotationChanged()) { properties.setRotation(entity->getOrientation()); } } properties = convertLocationFromScriptSemantics(properties); float cost = calculateCost(density * volume, oldVelocity, newVelocity); cost *= costMultiplier; if (cost > _currentAvatarEnergy) { updatedEntity = false; } else { //debit the avatar energy and continue updatedEntity = _entityTree->updateEntity(entityID, properties); if (updatedEntity) { emit debitEnergySource(cost); } } }); if (!updatedEntity) { return QUuid(); } _entityTree->withReadLock([&] { EntityItemPointer entity = _entityTree->findEntityByEntityItemID(entityID); if (entity) { // make sure the properties has a type, so that the encode can know which properties to include properties.setType(entity->getType()); bool hasTerseUpdateChanges = properties.hasTerseUpdateChanges(); bool hasPhysicsChanges = properties.hasMiscPhysicsChanges() || hasTerseUpdateChanges; if (_bidOnSimulationOwnership && hasPhysicsChanges) { auto nodeList = DependencyManager::get<NodeList>(); const QUuid myNodeID = nodeList->getSessionUUID(); if (entity->getSimulatorID() == myNodeID) { // we think we already own the simulation, so make sure to send ALL TerseUpdate properties if (hasTerseUpdateChanges) { entity->getAllTerseUpdateProperties(properties); } // TODO: if we knew that ONLY TerseUpdate properties have changed in properties AND the object // is dynamic AND it is active in the physics simulation then we could chose to NOT queue an update // and instead let the physics simulation decide when to send a terse update. This would remove // the "slide-no-rotate" glitch (and typical double-update) that we see during the "poke rolling // balls" test. However, even if we solve this problem we still need to provide a "slerp the visible // proxy toward the true physical position" feature to hide the final glitches in the remote watcher's // simulation. if (entity->getSimulationPriority() < SCRIPT_POKE_SIMULATION_PRIORITY) { // we re-assert our simulation ownership at a higher priority properties.setSimulationOwner(myNodeID, SCRIPT_POKE_SIMULATION_PRIORITY); } } else { // we make a bid for simulation ownership properties.setSimulationOwner(myNodeID, SCRIPT_POKE_SIMULATION_PRIORITY); entity->pokeSimulationOwnership(); } } if (properties.parentRelatedPropertyChanged() && entity->computePuffedQueryAACube()) { properties.setQueryAACube(entity->getQueryAACube()); } entity->setLastBroadcast(usecTimestampNow()); // if we've moved an entity with children, check/update the queryAACube of all descendents and tell the server // if they've changed. entity->forEachDescendant([&](SpatiallyNestablePointer descendant) { if (descendant->getNestableType() == NestableType::Entity) { if (descendant->computePuffedQueryAACube()) { EntityItemPointer entityDescendant = std::static_pointer_cast<EntityItem>(descendant); EntityItemProperties newQueryCubeProperties; newQueryCubeProperties.setQueryAACube(descendant->getQueryAACube()); newQueryCubeProperties.setLastEdited(properties.getLastEdited()); queueEntityMessage(PacketType::EntityEdit, descendant->getID(), newQueryCubeProperties); entityDescendant->setLastBroadcast(usecTimestampNow()); } } }); } }); queueEntityMessage(PacketType::EntityEdit, entityID, properties); return id; }
void Graph::seedNodesAndEdges() { /* Upon construction: seed graph with nodes and edges to connect them. * For now this happens manually. Ideally this happens by algorithm */ std::shared_ptr<Node> nodeA(new Node(0, "0", 100, 50)); std::shared_ptr<Node> nodeB(new Node(1, "1", 500, 40)); std::shared_ptr<Node> nodeC(new Node(2, "2", 200, 300)); std::shared_ptr<Node> nodeD(new Node(3, "3", 700, 100)); std::shared_ptr<Node> nodeE(new Node(4, "4", 600, 400)); std::shared_ptr<Node> nodeF(new Node(5, "5", 250, 450)); std::shared_ptr<Node> nodeG(new Node(6, "6", 750, 500)); std::shared_ptr<Node> nodeH(new Node(7, "7", 400, 150)); std::shared_ptr<Node> nodeI(new Node(8, "8", 550, 250)); std::shared_ptr<Node> nodeJ(new Node(9, "9", 100, 400)); std::list<std::shared_ptr<Edge>> edgeList; // Sequenced container of Edge pointers nodeVector.push_back(nodeA); std::shared_ptr<Edge> edge1(new Edge(nodeA, nodeB, calculateCost(nodeA, nodeB))); edgeList.push_back(edge1); std::shared_ptr<Edge> edge2(new Edge(nodeA, nodeC, calculateCost(nodeA, nodeC))); edgeList.push_back(edge2); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeB); std::shared_ptr<Edge> edge3(new Edge(nodeB, nodeA, calculateCost(nodeB, nodeA))); edgeList.push_back(edge3); std::shared_ptr<Edge> edge4(new Edge(nodeB, nodeH, calculateCost(nodeB, nodeH))); edgeList.push_back(edge4); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeC); std::shared_ptr<Edge> edge5(new Edge(nodeC, nodeA, calculateCost(nodeC, nodeA))); edgeList.push_back(edge5); std::shared_ptr<Edge> edge6(new Edge(nodeC, nodeH, calculateCost(nodeC, nodeH))); edgeList.push_back(edge6); std::shared_ptr<Edge> edge7(new Edge(nodeC, nodeE, calculateCost(nodeC, nodeE))); edgeList.push_back(edge7); std::shared_ptr<Edge> edge8(new Edge(nodeC, nodeF, calculateCost(nodeC, nodeF))); edgeList.push_back(edge8); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeD); std::shared_ptr<Edge> edge9(new Edge(nodeD, nodeH, calculateCost(nodeD, nodeH))); edgeList.push_back(edge9); std::shared_ptr<Edge> edge10(new Edge(nodeD, nodeE, calculateCost(nodeD, nodeE))); edgeList.push_back(edge10); std::shared_ptr<Edge> edge11(new Edge(nodeD, nodeG, calculateCost(nodeD, nodeG))); edgeList.push_back(edge11); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeE); std::shared_ptr<Edge> edge12(new Edge(nodeE, nodeC, calculateCost(nodeE, nodeC))); edgeList.push_back(edge12); std::shared_ptr<Edge> edge13(new Edge(nodeE, nodeD, calculateCost(nodeE, nodeD))); edgeList.push_back(edge13); std::shared_ptr<Edge> edge14(new Edge(nodeE, nodeG, calculateCost(nodeE, nodeG))); edgeList.push_back(edge14); std::shared_ptr<Edge> edge15(new Edge(nodeE, nodeI, calculateCost(nodeE, nodeI))); edgeList.push_back(edge15); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeF); std::shared_ptr<Edge> edge16(new Edge(nodeF, nodeG, calculateCost(nodeF, nodeG))); edgeList.push_back(edge16); std::shared_ptr<Edge> edge17(new Edge(nodeF, nodeC, calculateCost(nodeF, nodeC))); edgeList.push_back(edge17); std::shared_ptr<Edge> edge18(new Edge(nodeF, nodeJ, calculateCost(nodeF, nodeJ))); edgeList.push_back(edge18); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeG); std::shared_ptr<Edge> edge19(new Edge(nodeG, nodeF, calculateCost(nodeG, nodeF))); edgeList.push_back(edge19); std::shared_ptr<Edge> edge20(new Edge(nodeG, nodeD, calculateCost(nodeG, nodeD))); edgeList.push_back(edge20); std::shared_ptr<Edge> edge21(new Edge(nodeG, nodeE, calculateCost(nodeG, nodeE))); edgeList.push_back(edge21); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeH); std::shared_ptr<Edge> edge22(new Edge(nodeH, nodeD, calculateCost(nodeH, nodeD))); edgeList.push_back(edge22); std::shared_ptr<Edge> edge23(new Edge(nodeH, nodeC, calculateCost(nodeH, nodeC))); edgeList.push_back(edge23); std::shared_ptr<Edge> edge24(new Edge(nodeH, nodeB, calculateCost(nodeH, nodeB))); edgeList.push_back(edge24); std::shared_ptr<Edge> edge25(new Edge(nodeH, nodeI, calculateCost(nodeH, nodeI))); edgeList.push_back(edge25); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeI); std::shared_ptr<Edge> edge26(new Edge(nodeI, nodeH, calculateCost(nodeI, nodeH))); edgeList.push_back(edge26); std::shared_ptr<Edge> edge27(new Edge(nodeI, nodeE, calculateCost(nodeI, nodeE))); edgeList.push_back(edge27); edgeListVector.push_back(edgeList); edgeList.clear(); nodeVector.push_back(nodeJ); std::shared_ptr<Edge> edge28(new Edge(nodeJ, nodeF, calculateCost(nodeJ, nodeF))); edgeList.push_back(edge28); edgeListVector.push_back(edgeList); edgeList.clear(); }
int main(int argc, char* argv[]) { // spit out error if less then two elements if (argc < 3) { usage(argv[0]); exit(1); } // Load ppm image of floor textures to use Image<Color> floor_texture; std::string image_file = std::string(argv[1]); std::cout << "Loading " << argv[1] << std::endl; floor_texture.Load(image_file); // Load in location of furniture std::ifstream in_str(argv[2]); // Is this file is good if (!in_str.good()) { std::cerr << "Can't open " << argv[2] << " to read.\n"; exit(1); } //Load into vector as furnature objects std::vector<Furniture> furnitureVec; int itemCount = 0; loadFurnitureState(in_str,furnitureVec, itemCount); // INITAL RANDOMIZATION if(std::string(argv[3])=="start"){ std::cout << "Initial Randomization" << std::endl; setupInitalRandomPos(furnitureVec,floor_texture); // is file good to write std::ofstream out_str(argv[2]); if (!out_str.good()) { std::cerr << "Can't open " << argv[4] << " to write.\n"; exit(1); } saveFurnitureState(out_str,furnitureVec, itemCount); return 0; } // Randomly moves my furniture until they are in good starting positions std::cout <<"OLD COST " <<calculateCost(furnitureVec, floor_texture) << std::endl; std::cout << furnitureVec.size() <<std::endl; double current_cost = calculateCost(furnitureVec, floor_texture); unsigned int HEAT = 100; unsigned int SAVES = 0; while(0 < HEAT){ for(int i = 0; i < furnitureVec.size(); i ++){ Furniture curItem = furnitureVec[i]; float orginal_x = curItem.getPos().x; float orginal_y = curItem.getPos().y; // try and jitter cur item, this will change the value deskMove(furnitureVec[i],HEAT,floor_texture); // check new cost double new_cost = calculateCost(furnitureVec, floor_texture); // I got a better cost if(new_cost < current_cost){ current_cost = new_cost; // I did worst }else{ // place item back furnitureVec[i].setPos(orginal_x,orginal_y); } }//for HEAT--; if(HEAT%5 == 0){ std::string save_str = convertInt(SAVES); save_str = "saved_state_" + save_str + ".st"; const char *cstr = save_str.c_str(); std::ofstream out_str(cstr); if (!out_str.good()) { std::cerr << "Can't open " << argv[2] << " to write.\n"; exit(1); } saveFurnitureState(out_str,furnitureVec, itemCount); out_str.close(); SAVES++; }//sav }//while }//main