QVariant QAccessibleProgressBar::minimumStepSize() const { // This is arbitrary since any value between min and max is valid. // Some screen readers (orca use it to calculate how many digits to display though, // so it makes sense to return a "sensible" value. Providing 100 increments seems ok. return (progressBar()->maximum() - progressBar()->minimum()) / 100.0; }
void QFStatusBar::hideProgress() { progressBar()->setTextVisible(true); progressBar()->hide(); fProgressBarLabel->hide(); //qApp->processEvents(); }
void Dialog::on_syncButton_clicked() { time.restart(); ui->traceTextEdit->clear(); // Checking QString src = ui->srcLineEdit->text(); QString dst = ui->dstLineEdit->text(); if (src.isEmpty()) { QMessageBox msgBox; msgBox.setText("You have to choose a folder to synchronize"); msgBox.exec(); return; } if (dst.isEmpty()) { QMessageBox msgBox; msgBox.setText("You have to choose a destination folder"); msgBox.exec(); return; } // Starting synchronizing (long asynchrone operation) enableProcess(true); QCoreApplication::processEvents(); Worker* worker = new Worker(this); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(worker, SIGNAL(finished()), this, SLOT(finishedProcess())); connect(worker, SIGNAL(print(const char*)), this, SLOT(print(const char*))); qRegisterMetaType<int64>("int64"); connect(worker, SIGNAL(progressBar(int64,int64)), this, SLOT(progressBar(int64, int64))); QtConcurrent::run(worker, &Worker::process); }
akuWaitDialog::akuWaitDialog(QWidget *parent) : KProgressDialog(parent, i18n("Processing Archive"), i18n("Work in progress, aKu is not freezed")) { progressBar() -> setMaximumSize(654999, 20); progressBar() -> setMaximum(0); progressBar() -> setMinimum(0); progressBar() -> setValue(0); setMinimumSize(320, 100); setMaximumSize(320, 100); setModal(true); setAutoClose(false); setAutoReset(false); setAllowCancel(false); }
/** * Sets a new value to the progress bar. * If the new value is non-zero, the progress bar is advanced. Otherwise, the * idle timer is initiated to display a busy indicator. * @param nValue The new value to set. */ void ProgressDlg::setValue(int nValue) { QProgressBar* pProgress; pProgress = progressBar(); if (nValue != 0) { // Do nothing if the value hasn't changed if (nValue == pProgress->value()) return; // Handle first non-zero value if (m_nIdleValue >= 0) { m_pIdleTimer->stop(); m_nIdleValue = -1; pProgress->setTextVisible(true); } // Set the new value pProgress->setValue(nValue); } else if (m_nIdleValue == -1) { // Handle first 0 value pProgress->setValue(0); pProgress->setTextVisible(false); m_nIdleValue = 0; m_pIdleTimer->start(200); } }
// Read the Greens function values in from a specified file void GreensFuncFileParse::CalculateGreens(VCSimulation* sim) { HDF5GreensDataReader *greens_file_reader; BlockID gid; int i, j, num_global_blocks; double *in_shear_green, *in_normal_green; // Open the Greens data file and initialize arrays to read in Greens values if (sim->getGreensInputfile().empty()) { sim->errConsole() << "ERROR: Greens input file undefined. Quitting." << std::endl; exit(-1); } num_global_blocks = sim->numGlobalBlocks(); greens_file_reader = new HDF5GreensDataReader(sim->getGreensInputfile()); in_shear_green = new double[num_global_blocks]; in_normal_green = new double[num_global_blocks]; // Read the Greens function shear and normal values for (i=0;i<sim->numLocalBlocks();++i) { progressBar(sim, 0, i); gid = sim->getGlobalBID(i); greens_file_reader->getGreensVals(gid, in_shear_green, in_normal_green); for (j=0;j<num_global_blocks;++j) { sim->setGreens(gid, j, in_shear_green[j], in_normal_green[j]); } } delete greens_file_reader; delete in_shear_green; delete in_normal_green; }
void ConsoleUpdater::printProgress() { // Progress bar Logger::update( "\r" ); std::size_t numTicks = static_cast<std::size_t>(floor(_d->info.progressFraction * PROGRESS_METER_WIDTH)); std::string progressBar(numTicks, '='); std::string progressSpace(PROGRESS_METER_WIDTH - numTicks, ' '); std::string line = " [" + progressBar + progressSpace + "]"; // Percent line += utils::format( 0xff, " %2.1f%%", _d->info.progressFraction*100 ); switch (_d->info.type) { case ProgressInfo::FileDownload: { line += " at " + Util::getHumanReadableBytes( _d->info.connection.speed ) + "/sec "; } break; case ProgressInfo::FileOperation: { std::string verb; switch (_d->info.operationType) { case ProgressInfo::Check: verb = "Checking: "; break; case ProgressInfo::Remove: verb = "Removing: "; break; case ProgressInfo::Replace: verb = "Replacing: "; break; case ProgressInfo::Add: verb = "Adding: "; break; case ProgressInfo::RemoveFilesFromPK4: verb = "Preparing PK4: "; break; default: verb = "File: "; }; line += " " + verb; std::size_t remainingLength = line.length() > 79 ? 0 : 79 - line.length(); line += utils::toShortString( _d->info.file.baseName().toString(), remainingLength); } break; default: break; }; // Expand the line length to 79 characters if (line.length() < 79) { line += std::string(79 - line.length(), ' '); } else if (line.length() > 79) { line = line.substr(0, 79); } Logger::update( line ); }
//run the main loop void run(void){ if(v) printf("CURRENT LINE NUME: %d\n", program.runNumber); pageRequested = grabPTE(line.currentAddress); if(pageRequested != -1){ //check if it was in the TLB int TLBCheck = checkTLB(pageRequested); if(!TLBCheck){ //check if it was in the page table int pageTableCheck = checkMainMemory(pageRequested); if(pageTableCheck == -1){ numPageFaults = markWSPage(&processWorkingSets[line.processId], 1); if(v){ puts("PAGE FAULT"); printf("Addding %d ns for a disk hit\n", DISKtime); } pageFault(pageRequested); redo = 1; } else {//checkPageTable if(!redo) numPageFaults = markWSPage(&processWorkingSets[line.processId], 0); if(v){ puts("FOUND IT IN THE PAGE TABLE"); printf("Adding %d ns for a memory hit\n", MMtime); } redo = 0; } } else {//checkTLB numPageFaults = markWSPage(&processWorkingSets[line.processId], 0); if(v){ puts("FOUND IT IN THE CACHE"); printf("Adding %d ns for a cache hit\n", TLBtime); } } } else printf("ERROR: SEG FAULT\n"); if(program.runNumber > WSW){ if ( numPageFaults < minPageFault ) { // remove allocated pages from the working set for that process processWorkingSets[line.processId].availWorkingSet--; int idx = evictPage(); struct frame *thisFrame = &mainMemory[idx]; thisFrame->vAddress = -1; thisFrame->dirtyBit = 0; thisFrame->referenceBit = 0; thisFrame->processId = -1; } if ( numPageFaults > maxPageFault ) { // add free pages to the working set for that process processWorkingSets[line.processId].availWorkingSet++; } } if (!v) progressBar(); }//run
void QFStatusBar::setProgressValue(double val, const QString &label_text) { qfLogFuncFrame() << "val:" << val << "text:" << label_text; if(val < 0 || val > 1) hideProgress(); else { progressBar()->setValue(progressBar()->minimum() + (int)((progressBar()->maximum() - progressBar()->minimum()) * val)); if(progressBar()->isHidden()) { progressBar()->show(); //fProgressBarLabel->show(); } } if(label_text.isEmpty()) fProgressBarLabel->hide(); else { fProgressBarLabel->show(); fProgressBarLabel->setText(label_text); } QApplication::processEvents(); }
KQProgressModalDialog::KQProgressModalDialog ( const QString & captionText, const QString & labelText, const QString & cancelButtonText, int totalSteps, QWidget * creator ) : KProgressDialog( creator, captionText, labelText ) { setAllowCancel( true ); showCancelButton( true ); setAutoClose( true ); setButtonText( cancelButtonText ); progressBar()->setMaximum( totalSteps ); setMinimumDuration( 1 ); }
/** * Increaes the value of the dummy counter by 1. * This slot is called by the timeout() event of the idle timer. */ void ProgressDlg::slotShowBusy() { // Increase the counter m_nIdleValue += 5; if (m_nIdleValue == 100) m_nIdleValue = 0; // Set the value of the progress-bar progressBar()->setValue(m_nIdleValue); }
int main() { int i; for (i = 1; i <= 100; ++i) { progressBar(i); mysleep(1); } printf("/n"); return 0; }
// ************************************************************************** // *** Standard Okada code // ************************************************************************** void GreensFuncCalcStandard::CalculateGreens(Simulation *sim) { std::vector<int> row_sizes; int num_blocks, t_num, n; num_blocks = sim->numGlobalBlocks(); row_sizes.clear(); for (n=0; n<sim->numGlobalBlocks(); ++n) row_sizes.push_back(sim->isLocalBlockID(n)?num_blocks:sim->numLocalBlocks()); GreensValsSparseMatrix ssh = GreensValsSparseMatrix(row_sizes); row_sizes.clear(); for (n=0; n<sim->numGlobalBlocks(); ++n) row_sizes.push_back(sim->isLocalBlockID(n)?num_blocks:0); GreensValsSparseMatrix snorm = GreensValsSparseMatrix(row_sizes); // Get the current thread # for OpenMP to avoid printing multiple progress bars. #ifdef _OPENMP t_num = omp_get_thread_num(); #else t_num = 0; #endif // Use OpenMP to parallelize the loop, with each thread calculating // the Greens function for a block at a time #pragma omp parallel for schedule(static,1) for (n=0; n<sim->numLocalBlocks(); ++n) { progressBar(sim, t_num, n); InnerCalcStandard(sim, sim->getGlobalBID(n), ssh, snorm); } // Symmetrize the shear stress matrix symmetrizeMatrix(sim, ssh); // Set the simulation Greens values to the local ones calculated for (int r=0; r<sim->numLocalBlocks(); ++r) { for (int c=0; c<num_blocks; ++c) { int global_r = sim->getGlobalBID(r); //// Schultz, excluding zero slip rate elements from sim by setting Greens to zero if (sim->getBlock(global_r).slip_rate()==0 || sim->getBlock(c).slip_rate()==0) { sim->setGreens(global_r, c, 0, 0); } else { sim->setGreens(global_r, c, ssh[global_r][c], snorm[global_r][c]); } } } }
void WMediaPlayer::updateProgressBarState(BarControlId id) { WProgressBar *bar = progressBar(id); if (bar) { switch (id) { case Time: bar->setState(0, status_.seekPercent * status_.duration, status_.currentTime); break; case Volume: bar->setState(0, 1, status_.volume); } } }
QImage FileTransferInstance::drawProgressBarImg(const double &part, int w, int h) { QImage progressBar(w, h, QImage::Format_Mono); QPainter qPainter(&progressBar); qPainter.setBrush(Qt::NoBrush); qPainter.setPen(Qt::black); qPainter.drawRect(0, 0, w - 1, h - 1); qPainter.setBrush(Qt::SolidPattern); qPainter.setPen(Qt::black); qPainter.drawRect(1, 0, (w - 2) * (part), h - 1); return progressBar; }
QImage CFileTransferAction::drawProgressBarImg(const double &part, int w, int h, Qt::GlobalColor clrBack, Qt::GlobalColor clrFront) { QImage progressBar(w, h, QImage::Format_RGB16); QPainter qPainter(&progressBar); qPainter.setBrush(QBrush(clrBack)); qPainter.setPen(Qt::white); qPainter.drawRect(0, 0, w, h); if(0 != part) { qPainter.setBrush(QBrush(clrFront)); qPainter.setPen(Qt::green); qPainter.drawRect(0, 0, w * part, h); } return progressBar; }
// Read the Greens function values in from a specified file void GreensFuncFileParse::CalculateGreens(Simulation *sim) { #ifdef HDF5_FOUND HDF5GreensDataReader *greens_file_reader; BlockID gid; int i, j, num_global_blocks; double *in_shear_green, *in_normal_green; // Open the Greens data file and initialize arrays to read in Greens values if (sim->getGreensInputfile().empty()) { sim->errConsole() << "ERROR: Greens input file undefined. Quitting." << std::endl; exit(-1); } num_global_blocks = sim->numGlobalBlocks(); greens_file_reader = new HDF5GreensDataReader(sim->getGreensInputfile()); assertThrow(greens_file_reader->getGreensDim() == num_global_blocks, "Greens input file not same dimension as model."); in_shear_green = new double[num_global_blocks]; in_normal_green = new double[num_global_blocks]; // Read the Greens function shear and normal values for (i=0; i<sim->numLocalBlocks(); ++i) { progressBar(sim, 0, i); gid = sim->getGlobalBID(i); greens_file_reader->getGreensVals(gid, in_shear_green, in_normal_green); for (j=0; j<num_global_blocks; ++j) { //// Schultz, excluding zero slip rate elements from sim by setting Greens to zero if (sim->getBlock(gid).slip_rate()==0 || sim->getBlock(j).slip_rate()==0) { sim->setGreens(gid, j, 0, 0); } else { sim->setGreens(gid, j, in_shear_green[j], in_normal_green[j]); } } } // use delete [] for c-arrays. delete greens_file_reader; delete [] in_shear_green; delete [] in_normal_green; #else assertThrow(false, "HDF5 is required to use Greens function file I/O."); #endif }
ImageshackWidget::ImageshackWidget(QWidget* const parent, Imageshack* const imageshack, KIPI::Interface* const iface, const QString& pluginName) : KPSettingsWidget(parent, iface, pluginName), m_imageshack(imageshack) { m_imgList = imagesList(); m_headerLbl = getHeaderLbl(); m_accountNameLbl = getUserNameLabel(); m_chgRegCodeBtn = getChangeUserBtn(); m_reloadGalleriesBtn = getReloadBtn(); m_galleriesCob = getAlbumsCoB(); m_progressBar = progressBar(); connect(m_reloadGalleriesBtn, SIGNAL(clicked()), this, SLOT(slotReloadGalleries())); QGroupBox* const tagsBox = new QGroupBox(QString::fromLatin1(""), getSettingsBox()); QGridLayout* const tagsLayout = new QGridLayout(tagsBox); m_privateImagesChb = new QCheckBox(tagsBox); m_privateImagesChb->setText(i18n("Make private")); m_privateImagesChb->setChecked(false); m_tagsFld = new QLineEdit(tagsBox); QLabel* const tagsLbl = new QLabel(i18n("Tags (optional):"), tagsBox); m_remBarChb = new QCheckBox(i18n("Remove information bar on thumbnails")); m_remBarChb->setChecked(false); tagsLayout->addWidget(m_privateImagesChb, 0, 0); tagsLayout->addWidget(tagsLbl, 1, 0); tagsLayout->addWidget(m_tagsFld, 1, 1); addWidgetToSettingsBox(tagsBox); getUploadBox()->hide(); getSizeBox()->hide(); updateLabels(); }
void RayTracer::RayTrace( const SceneData& scene, unsigned int x0, unsigned int x1, unsigned int y0, unsigned int y1) { // Set the current y; m_y_mux.try_lock(); m_current_y = y0; m_y_mux.unlock(); // Row-by-row unsigned int y; for (;;) { m_y_mux.lock(); m_current_y += 1; y = m_current_y; if (m_current_y >= y1) { m_y_mux.unlock(); break; } m_y_mux.unlock(); progressBar(y, y1, 10, 50); for (unsigned int x = x0; x < x1; ++x) { float distance = INFINITY; const Ray& R = computeEyeRay(x, y, m_image->width(), m_image->height()); Vector3 color; for (unsigned int t = 0; t < m_scene.m_geometry.size(); ++t) { const Triangle& T = m_scene.m_geometry[t]; if (SampleTriangle(R, T, color, distance)) m_image->set(x, y, color); } } } }
void GreensFuncCalcBarnesHut::CalculateGreens(Simulation *sim) { BlockList::iterator bit; quakelib::Octree<3> *tree; quakelib::RectBound<3> total_bound; unsigned int n; int t_num; // Get a list of 3D midpoints of all segments for (bit=sim->begin(); bit!=sim->end(); ++bit) { total_bound.extend_bound(bit->center()); } // Set up an octree of the model space tree = new quakelib::Octree<3>(total_bound); // Fill the octree with center points of the faults for (bit=sim->begin(); bit!=sim->end(); ++bit) { tree->add_point(bit->center(), bit->getBlockID()); } // Get the current thread # for OpenMP to avoid printing multiple progress bars. #ifdef _OPENMP t_num = omp_get_thread_num(); #else t_num = 0; #endif // TO FIX: Problem with shared global variables (run_bounds) //#pragma omp parallel for shared(last_update) schedule(static,1) for (n=0; n<sim->numLocalBlocks(); ++n) { progressBar(sim, t_num, n); bhInnerCalc(sim, tree, sim->getGlobalBID(n)); } // TODO: symmetrize Greens matrix }
void ApplyMask::loop() { for (ULong64_t nevent = _startEvent; nevent <= _endEvent; nevent++) { Storage::Event* refEvent = _refStorage->readEvent(nevent); Storage::Event* maskedEvent = new Storage::Event(_refDevice->getNumSensors()); for (unsigned int nhit = 0; nhit < refEvent->getNumHits(); nhit++) { Storage::Hit* hit = refEvent->getHit(nhit); const unsigned int nplane = hit->getPlane()->getPlaneNum(); const unsigned int x = hit->getPixX(); const unsigned int y = hit->getPixY(); if (!_refDevice->getSensor(nplane)->isPixelNoisy(x, y)) { Storage::Hit* copy = maskedEvent->newHit(nplane); copy->setPix(x, y); copy->setValue(hit->getValue()); copy->setTiming(hit->getTiming()); } } maskedEvent->setTimeStamp(refEvent->getTimeStamp()); maskedEvent->setFrameNumber(refEvent->getFrameNumber()); maskedEvent->setTriggerOffset(refEvent->getTriggerOffset()); maskedEvent->setTriggerInfo(refEvent->getTriggerInfo()); maskedEvent->setInvalid(refEvent->getInvalid()); // Write the event _refOutput->writeEvent(maskedEvent); progressBar(nevent); delete refEvent; delete maskedEvent; } }
void ConfigChecker::setPercentageDone(int p) { progressBar()->setProgress(p); }
OcrEngine::EngineError OcrGocrDialog::setupGui() { OcrBaseDialog::setupGui(); KConfigGroup grp1 = KGlobal::config()->group(CFG_GROUP_GOCR); QWidget *w = addExtraSetupWidget(); QGridLayout *gl = new QGridLayout(w); QLabel *l = new QLabel(i18n("Gray level:"), w); gl->addWidget(l, 0, 0); sliderGrayLevel = new KScanSlider(w, QString::null, 0, 254, true, 160 ); int numdefault = grp1.readEntry(CFG_GOCR_GRAYLEVEL, 160); sliderGrayLevel->setValue(numdefault); sliderGrayLevel->setToolTip(i18n("The threshold value below which gray pixels are\nconsidered to be black.\n\nThe default is 160.")); l->setBuddy(sliderGrayLevel); gl->addWidget(sliderGrayLevel, 0, 1); l = new QLabel(i18n("Dust size:"), w); gl->addWidget(l, 1, 0); sliderDustSize = new KScanSlider(w, QString::null, 0, 60, true, 10 ); numdefault = grp1.readEntry(CFG_GOCR_DUSTSIZE, 10); sliderDustSize->setValue(numdefault); sliderDustSize->setToolTip(i18n("Clusters smaller than this value\nwill be considered to be dust, and\nremoved from the image.\n\nThe default is 10.")); l->setBuddy(sliderDustSize); gl->addWidget(sliderDustSize, 1, 1); l = new QLabel(i18n("Space width:"), w); gl->addWidget(l, 2, 0); sliderSpace = new KScanSlider(w, QString::null, 0, 60, true, 0 ); numdefault = grp1.readEntry(CFG_GOCR_SPACEWIDTH, 0); sliderSpace->setValue(numdefault); sliderSpace->setToolTip(i18n("Spacing between characters.\n\nThe default is 0 which means autodetection.")); l->setBuddy(sliderSpace); gl->addWidget(sliderSpace, 2, 1); gl->setRowStretch(3, 1); // for top alignment /* find the GOCR binary */ KConfigGroup grp2 = KGlobal::config()->group(CFG_GROUP_OCR_DIA); QString res = grp2.readPathEntry(CFG_GOCR_BINARY, ""); if (res.isEmpty()) { res = KookaPref::tryFindGocr(); if (res.isEmpty()) { /* Popup here telling that the config needs to be called */ KMessageBox::sorry(this, i18n("The path to the GOCR binary is not configured or is not valid.\n" "Please enter or check the path in the Kooka configuration."), i18n("GOCR Software Not Found")); enableButton(KDialog::User1, false); } } /* retrieve program version and display */ if (res.isEmpty()) res = i18n("Not found"); else m_ocrCmd = res; ocrShowInfo(res, version()); // show binary and version progressBar()->setMaximum(0); // animation only m_setupWidget = w; return (OcrEngine::ENG_OK); }
void ULListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QString byteUnits[4] = {tr("B"), tr("KB"), tr("MB"), tr("GB")}; QStyleOptionViewItem opt = option; QStyleOptionProgressBarV2 newopt; QRect pixmapRect; QPixmap pixmap; qlonglong fileSize; double ulspeed, multi; QString temp , status; qlonglong transferred; // prepare painter->save(); painter->setClipRect(opt.rect); //set text color QVariant value = index.data(Qt::TextColorRole); if(value.isValid() && qvariant_cast<QColor>(value).isValid()) { opt.palette.setColor(QPalette::Text, qvariant_cast<QColor>(value)); } QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if(option.state & QStyle::State_Selected){ painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(opt.palette.color(cg, QPalette::Text)); } // draw the background color if(index.column() != COLUMN_UPROGRESS) { if(option.showDecorationSelected && (option.state & QStyle::State_Selected)) { if(cg == QPalette::Normal && !(option.state & QStyle::State_Active)) { cg = QPalette::Inactive; } painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight)); } else { value = index.data(Qt::BackgroundRole); if(value.isValid() && qvariant_cast<QColor>(value).isValid()) { painter->fillRect(option.rect, qvariant_cast<QColor>(value)); } } } switch(index.column()) { case COLUMN_USIZE: fileSize = index.data().toLongLong(); if(fileSize <= 0){ temp = ""; } else { multi = 1.0; for(int i = 0; i < 4; ++i) { if (fileSize < 1024) { fileSize = index.data().toLongLong(); temp.sprintf("%.2f ", fileSize / multi); temp += byteUnits[i]; break; } fileSize /= 1024; multi *= 1024.0; } } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_UTRANSFERRED: transferred = index.data().toLongLong(); if(transferred <= 0){ temp = ""; } else { multi = 1.0; for(int i = 0; i < 4; ++i) { if (transferred < 1024) { transferred = index.data().toLongLong(); temp.sprintf("%.2f ", transferred / multi); temp += byteUnits[i]; break; } transferred /= 1024; multi *= 1024.0; } } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_ULSPEED: ulspeed = index.data().toDouble(); if (ulspeed <= 0) { temp = ""; } else { temp.clear(); temp.sprintf("%.2f", ulspeed/1024.); temp += " KB/s"; } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_UPROGRESS: { FileProgressInfo pinfo = index.data().value<FileProgressInfo>() ; // create a xProgressBar painter->save() ; xProgressBar progressBar(pinfo,option.rect,painter,0);// the 3rd param is the color schema (0 is the default value) QString ext = QFileInfo(QString::fromStdString(index.sibling(index.row(), COLUMN_UNAME).data().toString().toStdString())).suffix();; if (ext == "rsfc" || ext == "rsrl" || ext == "dist" || ext == "rsfb") progressBar.setColorSchema( 9); else progressBar.setColorSchema( 8); progressBar.setDisplayText(true); // should display % text? progressBar.setVerticalSpan(1); progressBar.paint(); // paint the progress bar painter->restore() ; } painter->drawText(option.rect, Qt::AlignCenter, newopt.text); break; case COLUMN_UNAME: // decoration value = index.data(Qt::DecorationRole); pixmap = qvariant_cast<QIcon>(value).pixmap(option.decorationSize, option.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled, option.state & QStyle::State_Open ? QIcon::On : QIcon::Off); pixmapRect = (pixmap.isNull() ? QRect(0, 0, 0, 0): QRect(QPoint(0, 0), option.decorationSize)); if (pixmapRect.isValid()){ QPoint p = QStyle::alignedRect(option.direction, Qt::AlignLeft, pixmap.size(), option.rect).topLeft(); painter->drawPixmap(p, pixmap); } painter->drawText(option.rect.translated(pixmap.size().width(), 0), Qt::AlignLeft, index.data().toString()); break; case COLUMN_USTATUS: painter->drawText(option.rect.translated(pixmap.size().width(), 0), Qt::AlignCenter, index.data().toString()); break; default: painter->drawText(option.rect, Qt::AlignCenter, index.data().toString()); } // done painter->restore(); }
/** * Main program for the simulation on a single SWE_WavePropagationBlock. */ int main( int argc, char** argv ) { /** * Initialization. */ // Parse command line parameters tools::Args args; #ifndef READXML args.addOption("grid-size-x", 'x', "Number of cells in x direction"); args.addOption("grid-size-y", 'y', "Number of cells in y direction"); args.addOption("output-basepath", 'o', "Output base file name"); #endif tools::Args::Result ret = args.parse(argc, argv); switch (ret) { case tools::Args::Error: return 1; case tools::Args::Help: return 0; } //! number of grid cells in x- and y-direction. int l_nX, l_nY; //! l_baseName of the plots. std::string l_baseName; // read command line parameters #ifndef READXML l_nX = args.getArgument<int>("grid-size-x"); l_nY = args.getArgument<int>("grid-size-y"); l_baseName = args.getArgument<std::string>("output-basepath"); #endif // read xml file #ifdef READXML assert(false); //TODO: not implemented. if(argc != 2) { s_sweLogger.printString("Aborting. Please provide a proper input file."); s_sweLogger.printString("Example: ./SWE_gnu_debug_none_augrie config.xml"); return 1; } s_sweLogger.printString("Reading xml-file."); std::string l_xmlFile = std::string(argv[1]); s_sweLogger.printString(l_xmlFile); CXMLConfig l_xmlConfig; l_xmlConfig.loadConfig(l_xmlFile.c_str()); #endif #ifdef ASAGI /* Information about the example bathymetry grid (tohoku_gebco_ucsb3_500m_hawaii_bath.nc): * * Pixel node registration used [Cartesian grid] * Grid file format: nf = GMT netCDF format (float) (COARDS-compliant) * x_min: -500000 x_max: 6500000 x_inc: 500 name: x nx: 14000 * y_min: -2500000 y_max: 1500000 y_inc: 500 name: y ny: 8000 * z_min: -6.48760175705 z_max: 16.1780223846 name: z * scale_factor: 1 add_offset: 0 * mean: 0.00217145586762 stdev: 0.245563641735 rms: 0.245573241263 */ //simulation area float simulationArea[4]; simulationArea[0] = -450000; simulationArea[1] = 6450000; simulationArea[2] = -2450000; simulationArea[3] = 1450000; SWE_AsagiScenario l_scenario( ASAGI_INPUT_DIR "tohoku_gebco_ucsb3_500m_hawaii_bath.nc", ASAGI_INPUT_DIR "tohoku_gebco_ucsb3_500m_hawaii_displ.nc", (float) 28800., simulationArea); #else // create a simple artificial scenario SWE_RadialDamBreakScenario l_scenario; #endif //! number of checkpoints for visualization (at each checkpoint in time, an output file is written). int l_numberOfCheckPoints = 200; //! size of a single cell in x- and y-direction float l_dX, l_dY; // compute the size of a single cell l_dX = (l_scenario.getBoundaryPos(BND_RIGHT) - l_scenario.getBoundaryPos(BND_LEFT) )/l_nX; l_dY = (l_scenario.getBoundaryPos(BND_TOP) - l_scenario.getBoundaryPos(BND_BOTTOM) )/l_nY; // create a single wave propagation block #ifndef CUDA SWE_WavePropagationBlock l_wavePropgationBlock(l_nX,l_nY,l_dX,l_dY); #else SWE_WavePropagationBlockCuda l_wavePropgationBlock(l_nX,l_nY,l_dX,l_dY); #endif //! origin of the simulation domain in x- and y-direction float l_originX, l_originY; // get the origin from the scenario l_originX = l_scenario.getBoundaryPos(BND_LEFT); l_originY = l_scenario.getBoundaryPos(BND_BOTTOM); // initialize the wave propagation block l_wavePropgationBlock.initScenario(l_originX, l_originY, l_scenario); //! time when the simulation ends. float l_endSimulation = l_scenario.endSimulation(); //! checkpoints when output files are written. float* l_checkPoints = new float[l_numberOfCheckPoints+1]; // compute the checkpoints in time for(int cp = 0; cp <= l_numberOfCheckPoints; cp++) { l_checkPoints[cp] = cp*(l_endSimulation/l_numberOfCheckPoints); } // Init fancy progressbar tools::ProgressBar progressBar(l_endSimulation); // write the output at time zero tools::Logger::logger.printOutputTime((float) 0.); progressBar.update(0.); std::string l_fileName = generateBaseFileName(l_baseName,0,0); //boundary size of the ghost layers io::BoundarySize l_boundarySize = {{1, 1, 1, 1}}; #ifdef WRITENETCDF //construct a NetCdfWriter io::NetCdfWriter l_writer( l_fileName, l_wavePropgationBlock.getBathymetry(), l_boundarySize, l_nX, l_nY, l_dX, l_dY, l_originX, l_originY); #else // consturct a VtkWriter io::VtkWriter l_writer( l_fileName, l_wavePropgationBlock.getBathymetry(), l_boundarySize, l_nX, l_nY, l_dX, l_dY ); #endif // Write zero time step l_writer.writeTimeStep( l_wavePropgationBlock.getWaterHeight(), l_wavePropgationBlock.getDischarge_hu(), l_wavePropgationBlock.getDischarge_hv(), (float) 0.); /** * Simulation. */ // print the start message and reset the wall clock time progressBar.clear(); tools::Logger::logger.printStartMessage(); tools::Logger::logger.initWallClockTime(time(NULL)); //! simulation time. float l_t = 0.0; progressBar.update(l_t); unsigned int l_iterations = 0; // loop over checkpoints for(int c=1; c<=l_numberOfCheckPoints; c++) { // do time steps until next checkpoint is reached while( l_t < l_checkPoints[c] ) { // set values in ghost cells: l_wavePropgationBlock.setGhostLayer(); // reset the cpu clock tools::Logger::logger.resetClockToCurrentTime("Cpu"); // approximate the maximum time step // TODO: This calculation should be replaced by the usage of the wave speeds occuring during the flux computation // Remark: The code is executed on the CPU, therefore a "valid result" depends on the CPU-GPU-synchronization. // l_wavePropgationBlock.computeMaxTimestep(); // compute numerical flux on each edge l_wavePropgationBlock.computeNumericalFluxes(); //! maximum allowed time step width. float l_maxTimeStepWidth = l_wavePropgationBlock.getMaxTimestep(); // update the cell values l_wavePropgationBlock.updateUnknowns(l_maxTimeStepWidth); // update the cpu time in the logger tools::Logger::logger.updateTime("Cpu"); // update simulation time with time step width. l_t += l_maxTimeStepWidth; l_iterations++; // print the current simulation time progressBar.clear(); tools::Logger::logger.printSimulationTime(l_t); progressBar.update(l_t); } // print current simulation time of the output progressBar.clear(); tools::Logger::logger.printOutputTime(l_t); progressBar.update(l_t); // write output l_writer.writeTimeStep( l_wavePropgationBlock.getWaterHeight(), l_wavePropgationBlock.getDischarge_hu(), l_wavePropgationBlock.getDischarge_hv(), l_t); } /** * Finalize. */ // write the statistics message progressBar.clear(); tools::Logger::logger.printStatisticsMessage(); // print the cpu time tools::Logger::logger.printTime("Cpu", "CPU time"); // print the wall clock time (includes plotting) tools::Logger::logger.printWallClockTime(time(NULL)); // printer iteration counter tools::Logger::logger.printIterationsDone(l_iterations); return 0; }
void ConsoleUpdater::PrintProgress() { TraceLog::Write(LOG_PROGRESS, "\r"); // Progress bar std::size_t numTicks = static_cast<std::size_t>(floor(_info.progressFraction * PROGRESS_METER_WIDTH)); std::string progressBar(numTicks, '='); std::string progressSpace(PROGRESS_METER_WIDTH - numTicks, ' '); std::string line = " [" + progressBar + progressSpace + "]"; // Percent line += (boost::format(" %2.1f%%") % (_info.progressFraction*100)).str(); switch (_info.type) { case ProgressInfo::FileDownload: { line += " at " + Util::GetHumanReadableBytes(static_cast<std::size_t>(_info.downloadSpeed)) + "/sec "; } break; case ProgressInfo::FileOperation: { std::string verb; switch (_info.operationType) { case ProgressInfo::Check: verb = "Checking: "; break; case ProgressInfo::Remove: verb = "Removing: "; break; case ProgressInfo::Replace: verb = "Replacing: "; break; case ProgressInfo::Add: verb = "Adding: "; break; case ProgressInfo::RemoveFilesFromPK4: verb = "Preparing PK4: "; break; default: verb = "File: "; }; line += " " + verb; std::size_t remainingLength = line.length() > 79 ? 0 : 79 - line.length(); line += GetShortenedString(_info.file.leaf().string(), remainingLength); } break; }; // Expand the line length to 79 characters if (line.length() < 79) { line += std::string(79 - line.length(), ' '); } else if (line.length() > 79) { line = line.substr(0, 79); } TraceLog::Write(LOG_PROGRESS, line); }
int main() { sf::Texture texture, backgroundTexture; if (!texture.loadFromFile("resources/uv map.jpg") || !backgroundTexture.loadFromFile("resources/BlueYellowGradient.png")) { std::cerr << "Unable to load textures." << std::endl; return EXIT_FAILURE; } sf::RenderWindow window(sf::VideoMode(800, 600), "Progress Bar example"); sw::ProgressBar progressBar({ 300.f, 40.f }); // set origin and position progressBar.setOrigin(progressBar.getSize() / 2.f); progressBar.setPosition(sf::Vector2f(window.getSize() / 2u)); // customise visual representation progressBar.setShowBackgroundAndFrame(true); progressBar.setBackgroundColor(sf::Color(128, 128, 128)); progressBar.setFrameColor(sf::Color(128, 128, 255, 192)); progressBar.setFrameThickness(2.f); progressBar.setRotation(-30); // set textures progressBar.setTexture(texture); progressBar.setTextureRect({ sf::Vector2i(0, texture.getSize().y / 10), sf::Vector2i(texture.getSize().x, texture.getSize().y / 10 + 1) }); progressBar.setBackgroundTexture(backgroundTexture); progressBar.setBackgroundTextureRect({ { 0, 0 }, { 1, static_cast<int>(backgroundTexture.getSize().y) } }); // set current progression progressBar.setFromValueInRange(9u, 0u, 10u); // marker std::vector<sf::CircleShape> markers(3, sf::CircleShape(3.f)); for (auto& marker : markers) marker.setOrigin(marker.getRadius(), marker.getRadius()); markers[0].setFillColor(sf::Color::Red); markers[1].setFillColor(sf::Color::Yellow); markers[2].setFillColor(sf::Color::Green); sf::Clock clock; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if ((event.type == sf::Event::Closed) || (event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)) window.close(); } markers[0].setPosition(progressBar.getAnchorProgressTop()); markers[1].setPosition(progressBar.getAnchorProgressCenter()); markers[2].setPosition(progressBar.getAnchorProgressBottom()); float frameTime{ clock.restart().asSeconds() }; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Add)) // [+] (number pad) increase progress progressBar.setRatio(progressBar.getRatio() + frameTime * 0.3f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract)) // [-] (number pad) decrease progress progressBar.setRatio(progressBar.getRatio() - frameTime * 0.3f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Period)) // [.]/[>] rotate left progressBar.rotate(frameTime * 30.f); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Comma)) // [,]/[<] rotate right progressBar.rotate(-frameTime * 30.f); window.clear(); window.draw(progressBar); for (auto& marker : markers) window.draw(marker); window.display(); } return EXIT_SUCCESS; }
void DLListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QString byteUnits[4] = {tr("B"), tr("KB"), tr("MB"), tr("GB")}; QStyleOptionViewItem opt = option; QStyleOptionProgressBarV2 newopt; QRect pixmapRect; QPixmap pixmap; qlonglong fileSize; double dlspeed, multi; int seconds,minutes, hours, days; qlonglong remaining; QString temp ; qlonglong completed; qlonglong downloadtime; qint64 qi64Value; // prepare painter->save(); painter->setClipRect(opt.rect); //set text color QVariant value = index.data(Qt::TextColorRole); if(value.isValid() && qvariant_cast<QColor>(value).isValid()) { opt.palette.setColor(QPalette::Text, qvariant_cast<QColor>(value)); } QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if(option.state & QStyle::State_Selected){ painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(opt.palette.color(cg, QPalette::Text)); } // draw the background color if not the progress column or if progress is not displayed if(index.column() != COLUMN_PROGRESS) { if(option.showDecorationSelected && (option.state & QStyle::State_Selected)) { if(cg == QPalette::Normal && !(option.state & QStyle::State_Active)) { cg = QPalette::Inactive; } painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight)); } else { value = index.data(Qt::BackgroundRole); if(value.isValid() && qvariant_cast<QColor>(value).isValid()) { painter->fillRect(option.rect, qvariant_cast<QColor>(value)); } } } switch(index.column()) { case COLUMN_SIZE: fileSize = index.data().toLongLong(); if(fileSize <= 0){ temp = ""; } else { multi = 1.0; for(int i = 0; i < 5; ++i) { if (fileSize < 1024) { fileSize = index.data().toLongLong(); temp.sprintf("%.2f ", fileSize / multi); temp += byteUnits[i]; break; } fileSize /= 1024; multi *= 1024.0; } } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_REMAINING: remaining = index.data().toLongLong(); if(remaining <= 0){ temp = ""; } else { multi = 1.0; for(int i = 0; i < 5; ++i) { if (remaining < 1024) { remaining = index.data().toLongLong(); temp.sprintf("%.2f ", remaining / multi); temp += byteUnits[i]; break; } remaining /= 1024; multi *= 1024.0; } } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_COMPLETED: completed = index.data().toLongLong(); if(completed <= 0){ temp = ""; } else { multi = 1.0; for(int i = 0; i < 5; ++i) { if (completed < 1024) { completed = index.data().toLongLong(); temp.sprintf("%.2f ", completed / multi); temp += byteUnits[i]; break; } completed /= 1024; multi *= 1024.0; } } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_DLSPEED: dlspeed = index.data().toDouble(); if (dlspeed <= 0) { temp = ""; } else { temp.clear(); temp.sprintf("%.2f", dlspeed/1024.); temp += " KB/s"; } painter->drawText(option.rect, Qt::AlignRight, temp); break; case COLUMN_PROGRESS: { // create a xProgressBar FileProgressInfo pinfo = index.data().value<FileProgressInfo>() ; // std::cerr << "drawing progress info: nb_chunks = " << pinfo.nb_chunks ; // for(uint i=0;i<pinfo.cmap._map.size();++i) // std::cerr << pinfo.cmap._map[i] << " " ; // std::cerr << std::endl ; painter->save() ; xProgressBar progressBar(pinfo,option.rect, painter); // the 3rd param is the color schema (0 is the default value) if(pinfo.type == FileProgressInfo::DOWNLOAD_LINE) { progressBar.setDisplayText(true); // should display % text? progressBar.setColorSchema(0) ; } else { progressBar.setDisplayText(false); // should display % text? progressBar.setColorSchema(1) ; } progressBar.setVerticalSpan(1); progressBar.paint(); // paint the progress bar painter->restore() ; } painter->drawText(option.rect, Qt::AlignCenter, newopt.text); break; case COLUMN_SOURCES: { double dblValue = index.data().toDouble(); temp = dblValue!=0 ? QString("%1 (%2)").arg((int)dblValue).arg((int)((fmod(dblValue,1)*1000)+0.5)) : ""; painter->drawText(option.rect, Qt::AlignCenter, temp); } break; case COLUMN_DOWNLOADTIME: downloadtime = index.data().toLongLong(); minutes = downloadtime / 60; seconds = downloadtime % 60; hours = minutes / 60; minutes = minutes % 60 ; days = hours / 24; hours = hours % 24 ; if(days > 0) { temp = QString::number(days)+"d "+QString::number(hours)+"h" ; } else if(hours > 0 || days > 0) { temp = QString::number(hours)+"h "+QString::number(minutes)+"m" ; } else if(minutes > 0 || hours > 0) { temp = QString::number(minutes)+"m"+QString::number(seconds)+"s" ; } else if(seconds > 0) { temp = QString::number(seconds)+"s" ; } else temp = "" ; painter->drawText(option.rect, Qt::AlignCenter, temp); break; case COLUMN_NAME: // decoration value = index.data(Qt::DecorationRole); temp = index.data().toString(); pixmap = qvariant_cast<QIcon>(value).pixmap(option.decorationSize, option.state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled, option.state & QStyle::State_Open ? QIcon::On : QIcon::Off); pixmapRect = (pixmap.isNull() ? QRect(0, 0, 0, 0): QRect(QPoint(0, 0), option.decorationSize)); if (pixmapRect.isValid()){ QPoint p = QStyle::alignedRect(option.direction, Qt::AlignLeft, pixmap.size(), option.rect).topLeft(); painter->drawPixmap(p, pixmap); temp = " " + temp; } painter->drawText(option.rect.translated(pixmap.size().width(), 0), Qt::AlignLeft, temp); break; case COLUMN_LASTDL: qi64Value = index.data().value<qint64>(); if (qi64Value < std::numeric_limits<qint64>::max()){ QDateTime qdtLastDL = QDateTime::fromTime_t(qi64Value); painter->drawText(option.rect, Qt::AlignCenter, qdtLastDL.toString("yyyy-MM-dd_hh:mm:ss")); } else { painter->drawText(option.rect, Qt::AlignCenter, tr("File Never Seen")); } break; default: painter->drawText(option.rect, Qt::AlignCenter, index.data().toString()); } // done painter->restore(); }
/** * Main program for the simulation on a single SWE_WavePropagationBlock. */ int main( int argc, char** argv ) { /** * Initialization. */ //! MPI Rank of a process. int l_mpiRank; //! number of MPI processes. int l_numberOfProcesses; // initialize MPI if ( MPI_Init(&argc,&argv) != MPI_SUCCESS ) { std::cerr << "MPI_Init failed." << std::endl; } // determine local MPI rank MPI_Comm_rank(MPI_COMM_WORLD,&l_mpiRank); // determine total number of processes MPI_Comm_size(MPI_COMM_WORLD,&l_numberOfProcesses); // initialize a logger for every MPI process tools::Logger::logger.setProcessRank(l_mpiRank); // print the welcome message tools::Logger::logger.printWelcomeMessage(); // set current wall clock time within the solver tools::Logger::logger.initWallClockTime( MPI_Wtime() ); //print the number of processes tools::Logger::logger.printNumberOfProcesses(l_numberOfProcesses); // check if the necessary command line input parameters are given #ifndef READXML std::vector<std::string> vargs; vargs.push_back(argv[0]); vargs.push_back("grid_size_x"); vargs.push_back("grid_size_y"); vargs.push_back("output_basepath"); vargs.push_back("output_steps_count"); #ifdef ASAGI vargs.push_back("bathymetry_file"); vargs.push_back("displacement_file"); vargs.push_back("simul_area_min_x"); vargs.push_back("simul_area_max_x"); vargs.push_back("simul_area_min_y"); vargs.push_back("simul_area_max_y"); vargs.push_back("simul_duration_secs"); #endif if (argc != vargs.size()) { std::cout << "Usage: " << vargs[0]; for (int i = 1, e = vargs.size(); i != e; i++) std::cout << " <" << vargs[i] << ">"; std::cout << std::endl << std::flush; MPI_Finalize(); return 1; } #endif //! total number of grid cell in x- and y-direction. int l_nX, l_nY; //! l_baseName of the plots. std::string l_baseName; // read command line parameters #ifndef READXML l_nX = atoi(ARG("grid_size_x")); l_nY = atoi(ARG("grid_size_y")); l_baseName = std::string(ARG("output_basepath")); #endif // read xml file #ifdef READXML assert(false); //TODO: not implemented. if(argc != 2) { l_sweLogger.printString("Aborting. Please provide a proper input file."); l_sweLogger.printString("Example: ./SWE_gnu_debug_none_augrie config.xml"); return 1; } l_sweLogger.printString("Reading xml-file."); std::string l_xmlFile = std::string(argv[1]); l_sweLogger.printString(l_xmlFile); CXMLConfig l_xmlConfig; l_xmlConfig.loadConfig(l_xmlFile.c_str()); #endif // READXML //! number of SWE_Blocks in x- and y-direction. int l_blocksX, l_blocksY; // determine the layout of MPI-ranks: use l_blocksX*l_blocksY grid blocks l_blocksY = computeNumberOfBlockRows(l_numberOfProcesses); l_blocksX = l_numberOfProcesses/l_blocksY; // print information about the grid tools::Logger::logger.printNumberOfCells(l_nX, l_nY); tools::Logger::logger.printNumberOfBlocks(l_blocksX, l_blocksY); //! local position of each MPI process in x- and y-direction. int l_blockPositionX, l_blockPositionY; // determine local block coordinates of each SWE_Block l_blockPositionX = l_mpiRank / l_blocksY; l_blockPositionY = l_mpiRank % l_blocksY; #ifdef ASAGI /* * Pixel node registration used [Cartesian grid] * Grid file format: nf = GMT netCDF format (float) (COARDS-compliant) * x_min: -500000 x_max: 6500000 x_inc: 500 name: x nx: 14000 * y_min: -2500000 y_max: 1500000 y_inc: 500 name: y ny: 8000 * z_min: -6.48760175705 z_max: 16.1780223846 name: z * scale_factor: 1 add_offset: 0 * mean: 0.00217145586762 stdev: 0.245563641735 rms: 0.245573241263 */ //simulation area float simulationArea[4]; simulationArea[0] = atof(ARG("simul_area_min_x")); simulationArea[1] = atof(ARG("simul_area_max_x")); simulationArea[2] = atof(ARG("simul_area_min_y")); simulationArea[3] = atof(ARG("simul_area_max_y")); float simulationDuration = atof(ARG("simul_duration_secs")); SWE_AsagiScenario l_scenario(ARG("bathymetry_file"), ARG("displacement_file"), simulationDuration, simulationArea); #else // create a simple artificial scenario SWE_BathymetryDamBreakScenario l_scenario; #endif //! number of checkpoints for visualization (at each checkpoint in time, an output file is written). int l_numberOfCheckPoints = atoi(ARG("output_steps_count")); //! number of grid cells in x- and y-direction per process. int l_nXLocal, l_nYLocal; //! size of a single cell in x- and y-direction float l_dX, l_dY; // compute local number of cells for each SWE_Block l_nXLocal = (l_blockPositionX < l_blocksX-1) ? l_nX/l_blocksX : l_nX - (l_blocksX-1)*(l_nX/l_blocksX); l_nYLocal = (l_blockPositionY < l_blocksY-1) ? l_nY/l_blocksY : l_nY - (l_blocksY-1)*(l_nY/l_blocksY); // compute the size of a single cell l_dX = (l_scenario.getBoundaryPos(BND_RIGHT) - l_scenario.getBoundaryPos(BND_LEFT) )/l_nX; l_dY = (l_scenario.getBoundaryPos(BND_TOP) - l_scenario.getBoundaryPos(BND_BOTTOM) )/l_nY; // print information about the cell size and local number of cells tools::Logger::logger.printCellSize(l_dX, l_dY); tools::Logger::logger.printNumberOfCellsPerProcess(l_nXLocal, l_nYLocal); //! origin of the simulation domain in x- and y-direction float l_originX, l_originY; // get the origin from the scenario l_originX = l_scenario.getBoundaryPos(BND_LEFT) + l_blockPositionX*l_nXLocal*l_dX;; l_originY = l_scenario.getBoundaryPos(BND_BOTTOM) + l_blockPositionY*l_nYLocal*l_dY; // create a single wave propagation block #ifndef CUDA SWE_WavePropagationBlock l_wavePropgationBlock(l_nXLocal,l_nYLocal,l_dX,l_dY); #else //! number of CUDA devices per node TODO: hardcoded int l_cudaDevicesPerNode = 7; //! the id of the node local GPU int l_cudaDeviceId = l_mpiRank % l_cudaDevicesPerNode; SWE_BlockCUDA::init(l_cudaDeviceId); SWE_WavePropagationBlockCuda l_wavePropgationBlock(l_nXLocal,l_nYLocal,l_dX,l_dY); #endif // initialize the wave propgation block l_wavePropgationBlock.initScenario(l_originX, l_originY, l_scenario, true); //! time when the simulation ends. float l_endSimulation = l_scenario.endSimulation(); //! checkpoints when output files are written. float* l_checkPoints = new float[l_numberOfCheckPoints+1]; // compute the checkpoints in time for(int cp = 0; cp <= l_numberOfCheckPoints; cp++) { l_checkPoints[cp] = cp*(l_endSimulation/l_numberOfCheckPoints); } /* * Connect SWE blocks at boundaries */ // left and right boundaries tools::Logger::logger.printString("Connecting SWE blocks at left boundaries."); SWE_Block1D* l_leftInflow = l_wavePropgationBlock.grabGhostLayer(BND_LEFT); SWE_Block1D* l_leftOutflow = l_wavePropgationBlock.registerCopyLayer(BND_LEFT); if (l_blockPositionX == 0) l_wavePropgationBlock.setBoundaryType(BND_LEFT, OUTFLOW); tools::Logger::logger.printString("Connecting SWE blocks at right boundaries."); SWE_Block1D* l_rightInflow = l_wavePropgationBlock.grabGhostLayer(BND_RIGHT); SWE_Block1D* l_rightOutflow = l_wavePropgationBlock.registerCopyLayer(BND_RIGHT); if (l_blockPositionX == l_blocksX-1) l_wavePropgationBlock.setBoundaryType(BND_RIGHT, OUTFLOW); // bottom and top boundaries tools::Logger::logger.printString("Connecting SWE blocks at bottom boundaries."); SWE_Block1D* l_bottomInflow = l_wavePropgationBlock.grabGhostLayer(BND_BOTTOM); SWE_Block1D* l_bottomOutflow = l_wavePropgationBlock.registerCopyLayer(BND_BOTTOM); if (l_blockPositionY == 0) l_wavePropgationBlock.setBoundaryType(BND_BOTTOM, OUTFLOW); tools::Logger::logger.printString("Connecting SWE blocks at top boundaries."); SWE_Block1D* l_topInflow = l_wavePropgationBlock.grabGhostLayer(BND_TOP); SWE_Block1D* l_topOutflow = l_wavePropgationBlock.registerCopyLayer(BND_TOP); if (l_blockPositionY == l_blocksY-1) l_wavePropgationBlock.setBoundaryType(BND_TOP, OUTFLOW); /* * The grid is stored column wise in memory: * * ************************** . . . ********** * * * ny+2 *2(ny+2)* * (ny+1)* * * ny+1 * +ny+1 * +ny+1 * * (ny+2)* * * * * * * +ny+1 * * ************************** . . . ********** * * * * * * * * . . . . . . * . . . . . . * . . . . . . * * * * * * * * ************************** . . . ********** * * * ny+2 *2(ny+2)* * (ny+1)* * * 1 * +1 * +1 * * (ny+2)* * * * * * * +1 * * ************************** . . . ********** * * * ny+2 *2(ny+2)* * (ny+1)* * * 0 * +0 * +0 * * (ny+2)* * * * * * * +0 * * ************************** . . . *********** * * * -> The stride for a row is ny+2, because we have to jump over a whole column * for every row-element. This holds only in the CPU-version, in CUDA a buffer is implemented. * See SWE_BlockCUDA.hh/.cu for details. * -> The stride for a column is 1, because we can access the elements linear in memory. */ //! MPI row-vector: l_nXLocal+2 blocks, 1 element per block, stride of l_nYLocal+2 MPI_Datatype l_mpiRow; #ifndef CUDA MPI_Type_vector(l_nXLocal+2, 1 , l_nYLocal+2, MPI_FLOAT, &l_mpiRow); #else MPI_Type_vector(1, l_nXLocal+2, 1 , MPI_FLOAT, &l_mpiRow); #endif MPI_Type_commit(&l_mpiRow); //! MPI row-vector: 1 block, l_nYLocal+2 elements per block, stride of 1 MPI_Datatype l_mpiCol; MPI_Type_vector(1, l_nYLocal+2, 1, MPI_FLOAT, &l_mpiCol); MPI_Type_commit(&l_mpiCol); //! MPI ranks of the neighbors int l_leftNeighborRank, l_rightNeighborRank, l_bottomNeighborRank, l_topNeighborRank; // compute MPI ranks of the neighbour processes l_leftNeighborRank = (l_blockPositionX > 0) ? l_mpiRank-l_blocksY : MPI_PROC_NULL; l_rightNeighborRank = (l_blockPositionX < l_blocksX-1) ? l_mpiRank+l_blocksY : MPI_PROC_NULL; l_bottomNeighborRank = (l_blockPositionY > 0) ? l_mpiRank-1 : MPI_PROC_NULL; l_topNeighborRank = (l_blockPositionY < l_blocksY-1) ? l_mpiRank+1 : MPI_PROC_NULL; // print the MPI grid tools::Logger::logger.cout() << "neighbors: " << l_leftNeighborRank << " (left), " << l_rightNeighborRank << " (right), " << l_bottomNeighborRank << " (bottom), " << l_topNeighborRank << " (top)" << std::endl; // intially exchange ghost and copy layers exchangeLeftRightGhostLayers( l_leftNeighborRank, l_leftInflow, l_leftOutflow, l_rightNeighborRank, l_rightInflow, l_rightOutflow, l_mpiCol ); exchangeBottomTopGhostLayers( l_bottomNeighborRank, l_bottomInflow, l_bottomOutflow, l_topNeighborRank, l_topInflow, l_topOutflow, l_mpiRow ); // Init fancy progressbar tools::ProgressBar progressBar(l_endSimulation, l_mpiRank); // write the output at time zero tools::Logger::logger.printOutputTime(0); progressBar.update(0.); std::string l_fileName = generateBaseFileName(l_baseName,l_blockPositionX,l_blockPositionY); //boundary size of the ghost layers io::BoundarySize l_boundarySize = {{1, 1, 1, 1}}; #ifdef WRITENETCDF //construct a NetCdfWriter io::NetCdfWriter l_writer( l_fileName, l_wavePropgationBlock.getBathymetry(), l_boundarySize, l_nXLocal, l_nYLocal, l_dX, l_dY, l_originX, l_originY ); #else // Construct a VtkWriter io::VtkWriter l_writer( l_fileName, l_wavePropgationBlock.getBathymetry(), l_boundarySize, l_nXLocal, l_nYLocal, l_dX, l_dY, l_blockPositionX*l_nXLocal, l_blockPositionY*l_nYLocal ); #endif // Write zero time step l_writer.writeTimeStep( l_wavePropgationBlock.getWaterHeight(), l_wavePropgationBlock.getDischarge_hu(), l_wavePropgationBlock.getDischarge_hv(), (float) 0.); /** * Simulation. */ // print the start message and reset the wall clock time progressBar.clear(); tools::Logger::logger.printStartMessage(); tools::Logger::logger.initWallClockTime(time(NULL)); //! simulation time. float l_t = 0.0; progressBar.update(l_t); unsigned int l_iterations = 0; // loop over checkpoints for(int c=1; c<=l_numberOfCheckPoints; c++) { // do time steps until next checkpoint is reached while( l_t < l_checkPoints[c] ) { //reset CPU-Communication clock tools::Logger::logger.resetCpuCommunicationClockToCurrentTime(); // exchange ghost and copy layers exchangeLeftRightGhostLayers( l_leftNeighborRank, l_leftInflow, l_leftOutflow, l_rightNeighborRank, l_rightInflow, l_rightOutflow, l_mpiCol ); exchangeBottomTopGhostLayers( l_bottomNeighborRank, l_bottomInflow, l_bottomOutflow, l_topNeighborRank, l_topInflow, l_topOutflow, l_mpiRow ); // reset the cpu clock tools::Logger::logger.resetCpuClockToCurrentTime(); // set values in ghost cells l_wavePropgationBlock.setGhostLayer(); // compute numerical flux on each edge l_wavePropgationBlock.computeNumericalFluxes(); //! maximum allowed time step width within a block. float l_maxTimeStepWidth = l_wavePropgationBlock.getMaxTimestep(); // update the cpu time in the logger tools::Logger::logger.updateCpuTime(); //! maximum allowed time steps of all blocks float l_maxTimeStepWidthGlobal; // determine smallest time step of all blocks MPI_Allreduce(&l_maxTimeStepWidth, &l_maxTimeStepWidthGlobal, 1, MPI_FLOAT, MPI_MIN, MPI_COMM_WORLD); // reset the cpu time tools::Logger::logger.resetCpuClockToCurrentTime(); // update the cell values l_wavePropgationBlock.updateUnknowns(l_maxTimeStepWidthGlobal); // update the cpu and CPU-communication time in the logger tools::Logger::logger.updateCpuTime(); tools::Logger::logger.updateCpuCommunicationTime(); // update simulation time with time step width. l_t += l_maxTimeStepWidthGlobal; l_iterations++; // print the current simulation time progressBar.clear(); tools::Logger::logger.printSimulationTime(l_t); progressBar.update(l_t); } // print current simulation time progressBar.clear(); tools::Logger::logger.printOutputTime(l_t); progressBar.update(l_t); // write output l_writer.writeTimeStep( l_wavePropgationBlock.getWaterHeight(), l_wavePropgationBlock.getDischarge_hu(), l_wavePropgationBlock.getDischarge_hv(), l_t); } /** * Finalize. */ #ifdef ASAGI // Free ASAGI resources l_scenario.deleteGrids(); #endif progressBar.clear(); // write the statistics message tools::Logger::logger.printStatisticsMessage(); // print the cpu time tools::Logger::logger.printCpuTime("CPU time"); // print CPU + Communication time tools::Logger::logger.printCpuCommunicationTime(); // print the wall clock time (includes plotting) tools::Logger::logger.printWallClockTime(time(NULL)); // printer iteration counter tools::Logger::logger.printIterationsDone(l_iterations); // print the finish message tools::Logger::logger.printFinishMessage(); // finalize MPI execution MPI_Finalize(); return 0; }
void MainWindow::makeTimerProgressBar() { progress = new QTimer(this); connect(progress, SIGNAL(timeout()), this, SLOT(progressBar())); }