int CDECL main(int argc, char *argv[]) { int ret; #ifdef WITH_COCOA cocoaSetupAutoreleasePool(); /* This is passed if we are launched by double-clicking */ if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) { argv[1] = NULL; argc = 1; } #endif CrashLog::InitialiseCrashLog(); SetRandomSeed(time(NULL)); signal(SIGPIPE, SIG_IGN); ret = openttd_main(argc, argv); #ifdef WITH_COCOA cocoaReleaseAutoreleasePool(); #endif return ret; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc; char *argv[64]; // max 64 command line arguments CrashLog::InitialiseCrashLog(); #if defined(UNICODE) /* Check if a win9x user started the win32 version */ if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again."); #endif /* Convert the command line to UTF-8. We need a dedicated buffer * for this because argv[] points into this buffer and this needs to * be available between subsequent calls to FS2OTTD(). */ char *cmdline = stredup(FS2OTTD(GetCommandLine())); #if defined(_DEBUG) CreateConsole(); #endif _set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox /* setup random seed to something quite random */ SetRandomSeed(GetTickCount()); argc = ParseCommandLine(cmdline, argv, lengthof(argv)); /* Make sure our arguments contain only valid UTF-8 characters. */ for (int i = 0; i < argc; i++) ValidateString(argv[i]); openttd_main(argc, argv); free(cmdline); return 0; }
Context::Context() : eventHandler_(0) { #ifdef ANDROID // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs SetRandomSeed(1); #endif }
int CDECL main(int argc, char *argv[]) { SetRandomSeed(time(NULL)); /* Make sure our arguments contain only valid UTF-8 characters. */ for (int i = 0; i < argc; i++) ValidateString(argv[i]); return openttd_main(argc, argv); }
Context::Context() : eventHandler_(0) { #ifdef ANDROID // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs SetRandomSeed(1); #endif // Set the main thread ID (assuming the Context is created in it) Thread::SetMainThread(); }
void InitTransaction(void) { SleepTime=1; SetRandomSeed(); InitMem(); InitTransactionIdAssign(); InitClientBuffer(); /* initialize pthread_key_t array for thread global variables. */ InitThreadGlobalKey(); }
namespace sf { //////////////////////////////////////////////////////////// // Static member variables //////////////////////////////////////////////////////////// unsigned int Randomizer::ourSeed = SetRandomSeed(); //////////////////////////////////////////////////////////// /// Set the seed for the generator. Using a known seed /// allows you to reproduce the same sequence of random number //////////////////////////////////////////////////////////// void Randomizer::SetSeed(unsigned int Seed) { srand(Seed); ourSeed = Seed; } //////////////////////////////////////////////////////////// /// Get the seed used to generate random numbers the generator. //////////////////////////////////////////////////////////// unsigned int Randomizer::GetSeed() { return ourSeed; } //////////////////////////////////////////////////////////// /// Get a random float number in a given range //////////////////////////////////////////////////////////// float Randomizer::Random(float Begin, float End) { // This is not the best algorithm, but it is fast and will be enough in most cases // (see Google for best approaches) return static_cast<float>(rand()) / RAND_MAX * (End - Begin) + Begin; } //////////////////////////////////////////////////////////// /// Get a random integer number in a given range //////////////////////////////////////////////////////////// int Randomizer::Random(int Begin, int End) { // This is not the best algorithm, but it is fast and will be enough in most cases // (see Google for best approaches) return rand() % (End - Begin + 1) + Begin; } } // namespace sf
/*---------------------------------------------------------------------- | NPT_System::GetRandomInteger +---------------------------------------------------------------------*/ NPT_UInt32 NPT_System::GetRandomInteger() { static bool seeded = false; if (seeded == false) { NPT_TimeStamp now; GetCurrentTimeStamp(now); SetRandomSeed((NPT_UInt32)now.ToNanos()); seeded = true; } return rand(); }
Context::Context() : eventHandler_(0), // ATOMIC BEGIN editorContext_(false) // ATOMIC END { #ifdef __ANDROID__ // Always reset the random seed on Android, as the Urho3D library might not be unloaded between runs SetRandomSeed(1); #endif // Set the main thread ID (assuming the Context is created in it) Thread::SetMainThread(); }
void handle_init(AppContextRef ctx) { (void)ctx; PblTm currentTime; unsigned int unixTime; resource_init_current_app(&APP_RESOURCES); get_time(¤tTime); unixTime = GetUnixTime(¤tTime); SetRandomSeed(unixTime); InitializeExitConfirmationWindow(); handle_minute_tick(ctx, NULL); ResetGame(); ShowAdventureWindow(); }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) #endif { int argc; char *argv[64]; // max 64 command line arguments char *cmdline; #if !defined(UNICODE) _codepage = GetACP(); // get system codepage as some kind of a default #endif /* UNICODE */ CrashLog::InitialiseCrashLog(); #if defined(UNICODE) #if !defined(WINCE) /* Check if a win9x user started the win32 version */ if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again."); #endif /* For UNICODE we need to convert the commandline to char* _AND_ * save it because argv[] points into this buffer and thus needs to * be available between subsequent calls to FS2OTTD() */ char cmdlinebuf[MAX_PATH]; #endif /* UNICODE */ cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf)); #if defined(_DEBUG) CreateConsole(); #endif #if !defined(WINCE) _set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox #endif /* setup random seed to something quite random */ SetRandomSeed(GetTickCount()); argc = ParseCommandLine(cmdline, argv, lengthof(argv)); ttd_main(argc, argv); return 0; }
//---------------------------------------------------------------------------------------------------------------------- Simulation* SimulationFactory::create() { SetRandomSeed((long)-time(0)); Model* model = 0; App* app = 0; // Check whether to run visually or not bool visual = false; if (SETTINGS->hasChild("Config/Globals/Visual")) { visual = SETTINGS->getChild("Config/Globals/Visual").getAttributeValue<bool>("Value"); } const std::string modelName = SETTINGS->getChild("Config/Globals/Model").getAttributeValue<std::string>("Value"); // Switch on the chosen kind of model to run. if ("GA" == modelName || "GAEval" == modelName) { Evolvable* evolvable; const std::string evolvableName = SETTINGS->getChild("Config/GA/Evolvable").getAttributeValue<std::string>("Name"); // Evolve or Evaluate? bool evaluateOnly = true; if(SETTINGS->hasChild("Config/GA/Eval")) { evaluateOnly = SETTINGS->getChild("Config/GA/Eval").getAttributeValue<bool>("Run"); } if ("TestEvolvableCTRNN" == evolvableName) { const int numNeurons = SETTINGS->getChild("Config/GA/Evolvable/NumNeurons").getAttributeValue<int>("Value"); evolvable = new TestEvolvableCTRNN(numNeurons); model = new GARunner (evolvable); if(visual) { View* view = new TestViewEvolvableCTRNN((GARunner*)model); app = new App(model, view); } } else if ("SMCAgentEvo" == evolvableName) { evolvable = new SMCAgentEvo(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCView((SMCAgentEvo*)evolvable); app = new App(model, view); } } else if ("Bacterium" == evolvableName) { Bacterium* b = new Bacterium(); evolvable = new BacteriumEvo(b); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCView((BacteriumEvo*)evolvable); app = new App(model, view); } } else if ("LegBac" == evolvableName) { evolvable = new LegBac(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new LegBacView((LegBac*)evolvable); app = new App(model, view); } } else if ("SMCAgentLineDis" == evolvableName) { evolvable = new SMCAgentLineDis(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCView((SMCAgentEvo*)evolvable); app = new App(model, view); } } else if ("SMCAgentGaussian" == evolvableName) { evolvable = new SMCAgentGaussian(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCView((SMCAgentEvo*)evolvable); app = new App(model, view); } } else if ("SMCAgentMeta1d" == evolvableName) { evolvable = new SMCAgentMeta1d(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCView1d((SMCAgentMeta1d*)evolvable); app = new App(model, view); } } else if ("SMCArm" == evolvableName) { evolvable = new SMCArm(); model = evaluateOnly ? (Model*) new GATester(evolvable) : (Model*) new GARunner (evolvable); if(visual) { View* view = new SMCArmView((SMCArm*)evolvable); app = new App(model, view); } } else if ("TestEvolvable" == evolvableName) { // Doesn't have a visualisation const int fitnessFunction = SETTINGS->getChild("Config/GA/Evolvable/FitnessFunction").getAttributeValue<int>("Value"); evolvable = new TestEvolvable(fitnessFunction); model = new GARunner (evolvable); } else if ("EvoArmCoCon" == evolvableName) { EvoArmCoCon* evoArm = new EvoArmCoCon(); model = evaluateOnly ? new GATester(evoArm) : model = new GARunner(evoArm); if(visual) { View* view = new ArmReflexView(evoArm->m_arm); app = new App(model, view); } } // Enable highest level of logging if(evaluateOnly) { ((GATester*)model)->setVerbosity(GARunner::kGAVerbosityTrial); } } else if ("TestArm" == modelName) { model = new Arm(); model->init(); if (visual) { View* view = new ArmView((Arm*)model); app = new App(model, view); } } else if ("TestArmPD" == modelName) { model = new TestModelArmPD(); model->init(); if (visual) { View* view = new ArmPDView(((TestModelArmPD*)model)->m_arm); app = new App(model, view); } } else if ("TestArmMuscled" == modelName) { model = new ArmMuscled(); model->init(); if (visual) { View* view = new ArmMuscledView(((ArmMuscled*)model)); app = new App(model, view); } } else if ("TestArmReflex" == modelName) { TestModelArmReflex* armR = new TestModelArmReflex(); model = armR; if (visual) { View* view = new ArmReflexView(((ArmReflex*)armR->m_arm)); app = new App(model, view); } } else if ("TestCTRNN" == modelName) { const int numNeurons = SETTINGS->getChild("Config/CTRNN/NumNeurons").getAttributeValue<int>("Value"); model = new TestModelCTRNN(numNeurons); if(visual) { app = new TestAppCTRNN((TestModelCTRNN*)model); } } /* else if ("SMCAgent" == modelName) { model = new SMCAgent(); if(visual) { View* view = new SMCView((SMCAgent*)model); app = new App(model, view); } } */ else if ("Test" == modelName) { model = new TestModel(); if(visual) { View* view = new TestView((TestModel*)model); app = new App(model, view); } } else if ("Spin" == modelName) { model = new SpinningWheel(); if(visual) { View* view = new SpinningWheelView((SpinningWheel*)model); app = new App(model, view); } } // If a model could be created given the information in the config file, return it, otherwise indicate failure. if(model != 0) { return Simulation::create(model, app); } else { std::cout << "AppFail: No model found with name as specified in Config.xml!" << endl; } return 0; }
int CDECL main(int argc, char *argv[]) { SetRandomSeed(time(NULL)); return ttd_main(argc, argv); }
// Recognizes the image_data, returning the labels, // scores, and corresponding pairs of start, end x-coords in coords. bool LSTMRecognizer::RecognizeLine(const ImageData& image_data, bool invert, bool debug, bool re_invert, float* scale_factor, NetworkIO* inputs, NetworkIO* outputs) { // Maximum width of image to train on. const int kMaxImageWidth = 2560; // This ensures consistent recognition results. SetRandomSeed(); int min_width = network_->XScaleFactor(); Pix* pix = Input::PrepareLSTMInputs(image_data, network_, min_width, &randomizer_, scale_factor); if (pix == NULL) { tprintf("Line cannot be recognized!!\n"); return false; } if (network_->IsTraining() && pixGetWidth(pix) > kMaxImageWidth) { tprintf("Image too large to learn!! Size = %dx%d\n", pixGetWidth(pix), pixGetHeight(pix)); pixDestroy(&pix); return false; } // Reduction factor from image to coords. *scale_factor = min_width / *scale_factor; inputs->set_int_mode(IsIntMode()); SetRandomSeed(); Input::PreparePixInput(network_->InputShape(), pix, &randomizer_, inputs); network_->Forward(debug, *inputs, NULL, &scratch_space_, outputs); // Check for auto inversion. float pos_min, pos_mean, pos_sd; OutputStats(*outputs, &pos_min, &pos_mean, &pos_sd); if (invert && pos_min < 0.5) { // Run again inverted and see if it is any better. NetworkIO inv_inputs, inv_outputs; inv_inputs.set_int_mode(IsIntMode()); SetRandomSeed(); pixInvert(pix, pix); Input::PreparePixInput(network_->InputShape(), pix, &randomizer_, &inv_inputs); network_->Forward(debug, inv_inputs, NULL, &scratch_space_, &inv_outputs); float inv_min, inv_mean, inv_sd; OutputStats(inv_outputs, &inv_min, &inv_mean, &inv_sd); if (inv_min > pos_min && inv_mean > pos_mean && inv_sd < pos_sd) { // Inverted did better. Use inverted data. if (debug) { tprintf("Inverting image: old min=%g, mean=%g, sd=%g, inv %g,%g,%g\n", pos_min, pos_mean, pos_sd, inv_min, inv_mean, inv_sd); } *outputs = inv_outputs; *inputs = inv_inputs; } else if (re_invert) { // Inverting was not an improvement, so undo and run again, so the // outputs match the best forward result. SetRandomSeed(); network_->Forward(debug, *inputs, NULL, &scratch_space_, outputs); } } pixDestroy(&pix); if (debug) { GenericVector<int> labels, coords; LabelsFromOutputs(*outputs, &labels, &coords); DisplayForward(*inputs, labels, coords, "LSTMForward", &debug_win_); DebugActivationPath(*outputs, labels, coords); } return true; }
int main(int argc, char **argv) { struct opts Options; int i; time_t CurrentTime; clock_t TotalClock = clock(); /* Apply Mondriaan options. */ SetDefaultOptions(&Options); if (!SetOptionsFromFile(&Options, "Mondriaan.defaults")) { fprintf(stderr, "main(): warning, cannot set options from 'Mondriaan.defaults', using default options!\n"); } if (!ParseCommandLineOptions(&Options, argc, argv)) { fprintf(stderr, "main(): invalid command line parameters!\n"); exit(EXIT_FAILURE); } if (!ApplyOptions(&Options)) { fprintf(stderr, "main(): could not apply given options!\n"); exit(EXIT_FAILURE); } if (NumMatrices <= 0 || Matrices == NULL) { fprintf(stderr, "main(): Invalid number of supplied matrices or samples!\n"); exit(EXIT_FAILURE); } /* Start profiling ... */ fprintf(stderr, "Profiling Mondriaan for %d matrices, %d samples, %s processors, and %f imbalance.\n", NumMatrices, NumSamples, argv[1], Options.eps); for (i = 0; i < NumMatrices*NumNumProcs; ++i) { int j; fprintf(stderr, "[% 4d/%d] (% 4ld) %s ", i + 1, NumMatrices*NumNumProcs, Matrices[i].P, Matrices[i].File); fflush(stderr); if (!SetupAttributes(&Matrices[i])) { fprintf(stderr, "main(): Cannot setup attributes!\n"); exit(EXIT_FAILURE); } Options.P = Matrices[i].P; /* Take the requested number of samples. */ for (j = 0; j < NumSamples; ++j) { struct sparsematrix A; long int *UAssign, *VAssign, Symmetric; FILE *File; long l; int k; clock_t Clock; double Duration; long MaxNz, MinNz; long MaxComU, MaxComV, ComVolU, ComVolV; fprintf(stderr, "."); fflush(stderr); /* Read matrix from disk. */ File = fopen(Matrices[i].File, "r"); if (!File) { fprintf(stderr, "main(): Could not open '%s' for reading!\n", Matrices[i].File); exit(EXIT_FAILURE); } if (!MMReadSparseMatrix(File, &A)) { fprintf(stderr, "main(): Could not read matrix!\n"); exit(EXIT_FAILURE); } fclose(File); /* Remove double zeroes. */ if (!SparseMatrixRemoveDuplicates(&A)) exit(EXIT_FAILURE); /* Check symmetry. */ if (A.m == A.n && (A.MMTypeCode[3] == 'S' || A.MMTypeCode[3] == 'K' || A.MMTypeCode[3] == 'H')) Symmetric = TRUE; else Symmetric = FALSE; if (Symmetric) { if (Options.SymmetricMatrix_UseSingleEntry == SingleEntNo) SparseMatrixSymmetric2Full(&A); else if (Options.SymmetricMatrix_SingleEntryType == ETypeRandom) SparseMatrixSymmetricLower2Random(&A); } /* Add dummies if requested. */ if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes && Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes) AddDummiesToSparseMatrix(&A); /* Initialise processor array. */ A.NrProcs = Options.P; A.Pstart = (long *)malloc((A.NrProcs + 1)*sizeof(long)); if (A.Pstart == NULL) { fprintf(stderr, "main(): Cannot allocate processor array!\n"); exit(EXIT_FAILURE); } A.Pstart[0] = 0; for (k = 1; k <= A.NrProcs; ++k) { A.Pstart[k] = A.NrNzElts; } /* Distribute the processors among the matrix entries. */ SetRandomSeed(Options.Seed = 137*j + 12345); /* ==== Start Mondriaan */ Clock = clock(); if (!DistributeMatrixMondriaan(&A, Options.P, Options.eps, &Options, NULL)) { fprintf(stderr, "main(): Unable to distribute matrix!\n"); exit(EXIT_FAILURE); } /* Remove dummies. */ if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes && Options.SquareMatrix_DistributeVectorsEqual_AddDummies == DumYes) RemoveDummiesFromSparseMatrix(&A); /* Convert randomly represented matrix to lower triangular form. */ if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes && Options.SymmetricMatrix_SingleEntryType == ETypeRandom) SparseMatrixSymmetricRandom2Lower(&A); /* Distribute vectors. */ UAssign = (long int *)malloc(A.m*sizeof(long int)); VAssign = (long int *)malloc(A.n*sizeof(long int)); if (UAssign == NULL || VAssign == NULL) { fprintf(stderr, "main(): Cannot allocate vertex assign arrays!\n"); exit(EXIT_FAILURE); } /* Convert symmetrically partitioned matrix to full form. */ if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) SparseMatrixSymmetric2Full(&A); if (A.m == A.n && Options.SquareMatrix_DistributeVectorsEqual == EqVecYes) { if (Symmetric && Options.SymmetricMatrix_UseSingleEntry == SingleEntYes) { MaxComV = DistributeVec(&A, VAssign, ROW, &Options); if (MaxComV < 0) { fprintf(stderr, "main(): Unable to distribute vector!\n"); exit(EXIT_FAILURE); } for (k = 0; k < A.m; k++) { UAssign[k] = VAssign[k]; } MaxComU = MaxComV; } else { MaxComU = DistributeVecOrigEq(&A, UAssign, VAssign, &Options); if (MaxComU < 0) { fprintf(stderr, "main(): Unable to distribute vector!\n"); exit(EXIT_FAILURE); } MaxComV = 0; } } else { MaxComV = DistributeVec(&A, VAssign, ROW, &Options); MaxComU = DistributeVec(&A, UAssign, COL, &Options); if (MaxComV < 0 || MaxComU < 0) { fprintf(stderr, "main(): Unable to distribute vector!\n"); exit(EXIT_FAILURE); } } /* ==== Stop Mondriaan */ /* Calculate duration. */ Duration = (double)(clock() - Clock)/(double)CLOCKS_PER_SEC; /* Determine minimum and maximum number of assigned nonzeroes. */ MaxNz = MinNz = A.Pstart[1] - A.Pstart[0]; for (k = 1; k < A.NrProcs; ++k) { l = A.Pstart[k + 1] - A.Pstart[k]; if (l > MaxNz) MaxNz = l; if (l < MinNz) MinNz = l; } /* Calculate communication volume. */ if (!CalcCom(&A, VAssign, ROW, &ComVolV, &l, &l, &l, &l) || !CalcCom(&A, UAssign, COL, &ComVolU, &l, &l, &l, &l)) { fprintf(stderr, "main(): Unable to calculate communication volume!\n"); exit(EXIT_FAILURE); } /* Store attributes. */ Matrices[i].NumNz = A.NrNzElts; Matrices[i].Rows = A.m; Matrices[i].Cols = A.n; Matrices[i].Attributes[0].Data[j] = Duration; Matrices[i].Attributes[1].Data[j] = (double)(Options.P*MaxNz - A.NrNzElts)/(double)A.NrNzElts; Matrices[i].Attributes[2].Data[j] = (double)(MaxComV + MaxComU); Matrices[i].Attributes[3].Data[j] = (double)(ComVolV + ComVolU); /* Free memory. */ MMDeleteSparseMatrix(&A); free(UAssign); free(VAssign); } /* Average attributes. */ if (!AverageAndFreeAttributes(&Matrices[i])) { fprintf(stderr, "main(): Cannot setup attributes!\n"); exit(EXIT_FAILURE); } fprintf(stderr, "\n"); } /* Write accumulated data to stdout. */ fprintf(stderr, "Finished profiling, writing data ...\n"); printf("%% Profiled Mondriaan for %d matrices, %d samples, and %f imbalance.\n", NumMatrices, NumSamples, Options.eps); printf("\\documentclass[a4paper, 10pt]{article}\n\n"); printf("\\usepackage{lscape}\n"); printf("\\usepackage{longtable}\n\n"); printf("\\author{\\texttt{Profile.c}}\n"); CurrentTime = time(NULL); printf("\\date{%s}\n", asctime(localtime(&CurrentTime))); printf("\\title{Profiling Mondriaan %s with %d %s}\n\n", MONDRIAANVERSION, NumMatrices, NumMatrices > 1 ? "matrices" : "matrix"); printf("\\begin{document}\n\n"); printf("\\maketitle\n\n"); printf("\\section{Results}\n\n"); printf("Used Mondriaan version %s to distribute %d matrices (listed in table \\ref{MondriaanMatrices}) over %d processors with maximum imbalance %f, taking the average of %d samples. The used options can be found in table \\ref{MondriaanSettings} en the numerical results in table \\ref{MondriaanResults}.\n", MONDRIAANVERSION, NumMatrices, Options.P, Options.eps, NumSamples); printf("This took %.1f minutes in total.\n\n", (double)(clock() - TotalClock)/(60.0*(double)CLOCKS_PER_SEC)); /* Export options. */ printf("\\begin{table}\n"); printf("\\caption{Mondriaan configuration.}\n"); printf("\\label{MondriaanSettings}\n"); printf("\\begin{center}\n"); if (!ExportOptionsToLaTeX(stdout, &Options)) { fprintf(stderr, "main(): Unable to create option table!\n"); exit(EXIT_FAILURE); } printf("\\end{center}\n"); printf("\\end{table}\n\n"); /* Export list of test matrices. */ printf("\\begin{table}\n"); printf("\\caption{%d tested matrices.}\n", NumMatrices); printf("\\label{MondriaanMatrices}\n"); printf("\\begin{center}\n"); printf("\\begin{tabular}{l|lll}\nFile & $\\mathit{nz}$ & $m$ & $n$ \\\\\n\\hline\n"); for (i = 0; i < NumMatrices*NumNumProcs; i += NumNumProcs) { printf("\\verb|%s| & %ld & %ld & %ld \\\\\n", Matrices[i].File, Matrices[i].NumNz, Matrices[i].Rows, Matrices[i].Cols); } printf("\\hline\n"); printf("\\end{tabular}\n"); printf("\\end{center}\n"); printf("\\end{table}\n\n"); /* Export test data. */ printf("\\begin{landscape}\n"); printf("\\begin{longtable}{lrrrrr}"); printf("\\caption[Profile results]{Profile results for %d matrices.}\n", NumMatrices); printf("\\label{MondriaanResults} \\\\\n\n"); printf("\\multicolumn{1}{c}{File} & \\multicolumn{1}{c}{$p$} & \\multicolumn{1}{c}{Time (s)} & \\multicolumn{1}{c}{$\\varepsilon$} & \\multicolumn{1}{c}{Max. com.} & \\multicolumn{1}{c}{Com. vol.} \\\\ \\hline\n"); printf("\\endfirsthead\n\n"); printf("\\multicolumn{6}{c}{\\tablename\\ \\thetable{} -- continued from previous page.} \\\\\n"); printf("\\multicolumn{1}{c}{File} & \\multicolumn{1}{c}{$p$} & \\multicolumn{1}{c}{Time (s)} & \\multicolumn{1}{c}{$\\varepsilon$} & \\multicolumn{1}{c}{Max. com.} & \\multicolumn{1}{c}{Com. vol.} \\\\ \\hline\n"); printf("\\endhead\n\n"); printf("\\multicolumn{6}{c}{Continued on next page.} \\\\\n"); printf("\\endfoot\n\n"); printf("\\hline\n\\endlastfoot\n\n"); for (i = 0; i < NumMatrices*NumNumProcs; i += NumNumProcs) { int j; for (j = 0; j < NumNumProcs; ++j) { char Tmp[256]; const struct sMatrixData *Mat = &Matrices[i + j]; if (j == 0) printf("\\verb|%s| & %ld", Mat->File, Mat->P); else printf(" & %ld", Mat->P); /* int k; for (k = 0; k < NUM_ATTRIBUTES; ++k) { char Tmp[256]; DoubleToLaTeX(Tmp, Mat->Attributes[k].Average, 3); printf(" & $%s \\pm ", Tmp); DoubleToLaTeX(Tmp, sqrt(Mat->Attributes[k].Variance), 1); printf("%s$", Tmp); } */ DoubleToLaTeX(Tmp, Mat->Attributes[0].Average, 3); printf(" & $%s \\pm ", Tmp); DoubleToLaTeX(Tmp, sqrt(Mat->Attributes[0].Variance), 1); printf("%s$", Tmp); DoubleToLaTeX(Tmp, Mat->Attributes[1].Average, 3); printf(" & $%s$", Tmp); printf(" & $%ld \\pm %ld$", (long)Mat->Attributes[2].Average, (long)sqrt(Mat->Attributes[2].Variance)); printf(" & $%ld \\pm %ld$", (long)Mat->Attributes[3].Average, (long)sqrt(Mat->Attributes[3].Variance)); printf(" \\\\\n"); } printf("\\hline\n"); } printf("\n\\end{longtable}\n"); printf("\\end{landscape}\n\n"); printf("\\end{document}\n\n"); /* Append raw data. */ printf("Raw data:\n"); for (i = 0; i < NumMatrices*NumNumProcs; ++i) { int j; printf("%s\t%ld\t%ld\t%ld\t%ld\t", Matrices[i].File, Matrices[i].NumNz, Matrices[i].Rows, Matrices[i].Cols, Matrices[i].P); for (j = 0; j < NUM_ATTRIBUTES - 1; ++j) printf("%e\t%e\t", Matrices[i].Attributes[j].Average, sqrt(Matrices[i].Attributes[j].Variance)); printf("%e\t%e\n", Matrices[i].Attributes[j].Average, sqrt(Matrices[i].Attributes[j].Variance)); } printf("\n"); free(Matrices); fprintf(stderr, "Done!\n"); exit(EXIT_SUCCESS); }
void InitializeSystem(void* parameter, Uint16 followUpItemIndex) { Uns interruptStatus; Uint16 i, j; double executionTime = 0; double genAvgTime = 0; double genMinTime = DBL_MAX; double genMaxTime = DBL_MIN; double avgTime[9] = {0,0,0,0,0,0,0,0,0}; double minTime[9] = {DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX,DBL_MAX}; double maxTime[9] = {DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN,DBL_MIN}; Uint32 startTime = 0; Uint32 numSamples; struct Packet newPacket; // Allow the system to write to the system registers EALLOW; // Set up the heartbeat gpioCtrlRegisters.GPBDIR.bit.HEARTBEAT = 1; gpioDataRegisters.GPBDAT.bit.HEARTBEAT = 1; // Set up the seven segment display gpioCtrlRegisters.GPADIR.bit.SEVENSEG_A = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_A = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_B = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_B = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_C = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_C = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_D = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_D = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_E = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_E = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_F = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_F = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_G = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_G = 0; gpioCtrlRegisters.GPADIR.bit.SEVENSEG_DIGIT = 1; gpioDataRegisters.GPADAT.bit.SEVENSEG_DIGIT = 1; // Set up timer 0 for use with SPI related timings sysCtrlRegisters.HISPCP.all = 0; // Set the HSPCLK to run at SYSCLK sysCtrlRegisters.LOSPCP.bit.LSPCLK = 0; // Set the LSPCLK to run at SYSCLK timer0Registers.TCR.bit.TSS = 1; // Stop the timer timer0Registers.TPR.bit.TDDR = 0; // Do not prescale the timer timer0Registers.PRD.all = 0xFFFFFFFF; // Set the period register to it's largest possible value timer0Registers.TCR.bit.TIE = false; // Disable timer interrupts timer0Registers.TCR.bit.FREE = 0; // Set the timer to stop when a breakpoint occrs timer0Registers.TCR.bit.SOFT = 0; timer0Registers.TCR.bit.TRB = 1; // Load the period register timer0Registers.TCR.bit.TSS = 0; // Start the timer // Set up the global SPI-related settings IER |= 0x20; // Enable CPU INT6 // Disallow the system to write to the system registers EDIS; interruptStatus = HWI_disable(); numSamples = 0; for(j = 0; j < 1000; j++) { InitializeGlobalVariables(); globals.root.availableAddresses[0].address = 1; globals.root.availableAddresses[0].addressTaken = true; globals.root.availableAddresses[1].address = 2; globals.root.availableAddresses[1].addressTaken = true; globals.root.availableAddresses[2].address = 3; globals.root.availableAddresses[2].addressTaken = true; globals.root.availableAddresses[3].address = 4; globals.root.availableAddresses[3].addressTaken = true; globals.root.availableAddresses[4].address = 5; globals.root.availableAddresses[4].addressTaken = true; globals.root.availableAddresses[5].address = 6; globals.root.availableAddresses[5].addressTaken = true; globals.root.availableAddresses[6].address = 7; globals.root.availableAddresses[6].addressTaken = true; globals.root.availableAddresses[7].address = 8; globals.root.availableAddresses[7].addressTaken = true; globals.protocol.globalNeighborInfo[1][PORTA].nodeAddress = 2; globals.protocol.globalNeighborInfo[1][PORTB].nodeAddress = 3; globals.protocol.globalNeighborInfo[2][PORTA].nodeAddress = 1; globals.protocol.globalNeighborInfo[2][PORTB].nodeAddress = 4; globals.protocol.globalNeighborInfo[3][PORTA].nodeAddress = 1; globals.protocol.globalNeighborInfo[3][PORTB].nodeAddress = 4; globals.protocol.globalNeighborInfo[3][PORTC].nodeAddress = 5; globals.protocol.globalNeighborInfo[4][PORTA].nodeAddress = 2; globals.protocol.globalNeighborInfo[4][PORTB].nodeAddress = 3; globals.protocol.globalNeighborInfo[4][PORTC].nodeAddress = 6; globals.protocol.globalNeighborInfo[5][PORTA].nodeAddress = 3; globals.protocol.globalNeighborInfo[5][PORTB].nodeAddress = 6; globals.protocol.globalNeighborInfo[5][PORTC].nodeAddress = 7; globals.protocol.globalNeighborInfo[6][PORTA].nodeAddress = 4; globals.protocol.globalNeighborInfo[6][PORTB].nodeAddress = 5; globals.protocol.globalNeighborInfo[6][PORTC].nodeAddress = 8; globals.protocol.globalNeighborInfo[7][PORTA].nodeAddress = 5; globals.protocol.globalNeighborInfo[7][PORTB].nodeAddress = 8; globals.protocol.globalNeighborInfo[8][PORTA].nodeAddress = 6; globals.protocol.globalNeighborInfo[8][PORTB].nodeAddress = 7; startTime = timer0Registers.TIM.all; GenerateRoutingTree(); executionTime = TimeDifference(startTime, timer0Registers.TIM.all); genAvgTime = (genAvgTime * numSamples) + executionTime; numSamples++; genAvgTime /= numSamples; if(executionTime < genMinTime) genMinTime = executionTime; else if(executionTime > genMaxTime) genMaxTime = executionTime; } for(i = 2; i <= 8; i++) { numSamples = 0; for(j = 0; j < 1000; j++) { startTime = timer0Registers.TIM.all; GenerateRoutingPath(1, i, &newPacket); executionTime = TimeDifference(startTime, timer0Registers.TIM.all); avgTime[i] = (avgTime[i] * numSamples) + executionTime; numSamples++; avgTime[i] /= numSamples; if(executionTime < minTime[i]) minTime[i] = executionTime; else if(executionTime > maxTime[i]) maxTime[i] = executionTime; } } HWI_restore(interruptStatus); asm(" NOP"); // Set the seed for the random number generator SetRandomSeed(0x175E); // Set up each individual port SetupPort(PORTA); SetupPort(PORTB); SetupPort(PORTC); SetupPort(PORTD); // Create the direct data cleanup follow-up item AddFollowUpItem(&CleanupDirectData,NULL,DIRECT_DATA_CLEANUP_RATE,true); // Create the neighbor check follow-up item #if defined(IS_ROOT) #if TEST != TEST_SPI globals.followUpMonitor.neighborFollowUpIndex = AddFollowUpItem(&NeighborFollowUp,NULL,NEIGHBOR_FOLLOW_UP_RATE,true); #endif SetSevenSegmentDisplay(SEVENSEG_BLANK); globals.processing.sevenSegmentLowerDigit = globals.protocol.address; #elif defined (IS_ROUTER) #if TEST != TEST_SPI globals.followUpMonitor.neighborFollowUpIndex = AddFollowUpItem(&NeighborFollowUp,NULL,NEIGHBOR_FOLLOW_UP_RATE_WITHOUT_ADDRESS,true); #endif SetSevenSegmentDisplay(SEVENSEG_BLANK); // Register the test service RegisterServiceProvider(TEST_SERVICE_TAG,TEST_SERVICE_TASK_PRIORITY,&TestServiceTask,&TestServiceSem); #endif // Let the other threads know that initialization is finished SEM_post(&ProcessInboundFlitsSem); SEM_post(&TestServiceSem); }
void init( ) { int i; double sum, avg; double TimeNow; char TempString[50]; printf("----- Network Simulator Version 2.30 -------- \n\n"); if ( CallingArgc >= 9 ) { MaxMsgsToSimulate = atoi( CallingArgv[1] ); LossProb = atof( CallingArgv[2] ); CorruptProb = atof( CallingArgv[3] ); OutOfOrderProb = atof( CallingArgv[4] ); AveTimeBetweenMsgs = atof( CallingArgv[5] ); TraceLevel = atoi( CallingArgv[6] ); RandomizationRequested = atoi( CallingArgv[7] ); Bidirectional = atoi( CallingArgv[8] ); } else { printf("Enter the number of messages to simulate: "); scanf( "%d", &MaxMsgsToSimulate); printf("Packet loss probability [enter number between 0.0 and 1.0]: "); scanf( "%s", &TempString ); LossProb = atof( TempString ); printf("Packet corruption probability [0.0 for no corruption]: "); scanf( "%s", &TempString ); CorruptProb = atof( TempString ); printf("Packet out-of-order probability [0.0 for no out-of-order]: "); scanf( "%s", &TempString ); OutOfOrderProb = atof( TempString ); printf("Average time between messages from sender's layer5 [ > 0.0]: "); scanf( "%s", &TempString ); AveTimeBetweenMsgs = atof( TempString ); printf("Enter Level of tracing desired: "); scanf( "%d", &TraceLevel); printf("Do you want actions randomized: (1 = yes, 0 = no)? " ); scanf( "%d", &RandomizationRequested); printf("Do you want Bidirectional: (1 = yes, 0 = no)? " ); scanf( "%d", &Bidirectional); } // Do sanity checking on inputs: if ( LossProb < 0 || LossProb> 1.0 || CorruptProb < 0 || CorruptProb > 1.0 || OutOfOrderProb < 0 || OutOfOrderProb > 1.0 || AveTimeBetweenMsgs <= 0.0 ) { printf( "One of your input parameters is out of range\n"); exit(0); } printf( "Input parameters:\n"); printf( "Number of Messages = %d", MaxMsgsToSimulate ); printf( " Lost Packet Prob. = %6.3f\n", LossProb ); printf( "Corrupt Packet Prob. = %6.3f", CorruptProb ); printf( " Out Of Order Prob. = %6.3f\n", OutOfOrderProb ); printf( "Ave. time between messages = %8.2f", AveTimeBetweenMsgs ); printf( " Trace level = %d\n", TraceLevel ); printf( "Randomize = %d", RandomizationRequested ); printf( " Bi-directional = %d\n\n", Bidirectional ); if ( RandomizationRequested == 1 ) { GetTimeNow( &TimeNow ); SetRandomSeed( (long)TimeNow ); } // test random number generator for students // GetRandomNumber() should be uniform in [0,1] sum = 0.0; for (i = 0; i < 1000; i++) sum = sum + GetRandomNumber(); avg = sum/1000.0; if (avg < 0.25 || avg > 0.75) { printf("It is likely that random number generation on your machine\n" ); printf("is different from what this emulator expects. Please look\n"); printf("at the routine GetRandomNumber() in the emulator. Sorry. \n"); exit(0); } NumMsgs4To3 = 0; /* Initialize Counters */ NumMsgsLost = 0; NumMsgsCorrupt = 0; NumSimutaneousMsgs = 0; CurrentSimTime = 0.0; /* initialize time to 0.0 */ GenerateNextArrival(); /* initialize event list */ } /* End of init() */