/***********************************************************************//** * @brief Print event cube information ***************************************************************************/ std::string GCTAEventCube::print(void) const { // Initialise result string std::string result; // Append header result.append("=== GCTAEventCube ==="); result.append("\n"+parformat("Number of events")+str(number())); result.append("\n"+parformat("Number of elements")+str(size())); result.append("\n"+parformat("Number of pixels")+str(npix())); result.append("\n"+parformat("Number of energy bins")+str(ebins())); // Append skymap definition result.append("\n"+m_map.print()); // Append GTI intervals result.append("\n"+parformat("Time interval")); if (gti().size() > 0) { result.append(str(tstart().secs())+" - "+str(tstop().secs())+" sec"); } else { result.append("not defined"); } // Append energy intervals if (ebounds().size() > 0) { result.append("\n"+ebounds().print()); } else { result.append("\n"+parformat("Energy intervals")+"not defined"); } // Return result return result; }
/***********************************************************************//** * @brief Test CTA Npred computation * * Tests the Npred computation for the diffuse source model. This is done * by loading the model from the XML file and by calling the * GCTAObservation::npred method which in turn calls the * GCTAResponse::npred_diffuse method. The test takes a few seconds. ***************************************************************************/ void TestGCTAResponse::test_response_npred_diffuse(void) { // Set reference value double ref = 11212.26274; // Set parameters double src_ra = 201.3651; double src_dec = -43.0191; double roi_rad = 4.0; // Setup ROI centred on Cen A with a radius of 4 deg GCTARoi roi; GCTAInstDir instDir; instDir.radec_deg(src_ra, src_dec); roi.centre(instDir); roi.radius(roi_rad); // Setup pointing on Cen A GSkyDir skyDir; skyDir.radec_deg(src_ra, src_dec); GCTAPointing pnt; pnt.dir(skyDir); // Setup dummy event list GGti gti; GEbounds ebounds; GTime tstart(0.0); GTime tstop(1800.0); GEnergy emin; GEnergy emax; emin.TeV(0.1); emax.TeV(100.0); gti.append(tstart, tstop); ebounds.append(emin, emax); GCTAEventList events; events.roi(roi); events.gti(gti); events.ebounds(ebounds); // Setup dummy CTA observation GCTAObservation obs; obs.ontime(1800.0); obs.livetime(1600.0); obs.deadc(1600.0/1800.0); obs.response(cta_irf, cta_caldb); obs.events(&events); obs.pointing(pnt); // Load models for Npred computation GModels models(cta_rsp_xml); // Perform Npred computation double npred = obs.npred(models, NULL); // Test Npred test_value(npred, ref, 1.0e-5, "Diffuse Npred computation"); // Return return; }
/* * Cleanup from userenter and any passive release that might have occured. * We must reclaim the current-process designation before we can return * to usermode. We also handle both LWKT and USER reschedule requests. */ static __inline void userexit(struct lwp *lp) { struct thread *td = lp->lwp_thread; /* globaldata_t gd = td->td_gd; */ /* * Handle stop requests at kernel priority. Any requests queued * after this loop will generate another AST. */ while (STOPLWP(lp->lwp_proc, lp)) { lwkt_gettoken(&lp->lwp_proc->p_token); tstop(); lwkt_reltoken(&lp->lwp_proc->p_token); } /* * Reduce our priority in preparation for a return to userland. If * our passive release function was still in place, our priority was * never raised and does not need to be reduced. */ lwkt_passive_recover(td); /* WARNING: we may have migrated cpu's */ /* gd = td->td_gd; */ /* * Become the current user scheduled process if we aren't already, * and deal with reschedule requests and other factors. */ lp->lwp_proc->p_usched->acquire_curproc(lp); }
/***********************************************************************//** * @brief Print event cube information * * @param[in] chatter Chattiness. * @return String containing event cube information. ***************************************************************************/ std::string GCTAEventCube::print(const GChatter& chatter) const { // Initialise result string std::string result; // Continue only if chatter is not silent if (chatter != SILENT) { // Append header result.append("=== GCTAEventCube ==="); result.append("\n"+gammalib::parformat("Number of events") + gammalib::str(number())); result.append("\n"+gammalib::parformat("Number of elements") + gammalib::str(size())); result.append("\n"+gammalib::parformat("Number of pixels") + gammalib::str(npix())); result.append("\n"+gammalib::parformat("Number of energy bins") + gammalib::str(ebins())); // Append GTI intervals result.append("\n"+gammalib::parformat("Time interval")); if (gti().size() > 0) { result.append(gammalib::str(tstart().secs()) + " - " + gammalib::str(tstop().secs())+" sec"); } else { result.append("not defined"); } // Append energy intervals if (gammalib::reduce(chatter) > SILENT) { if (ebounds().size() > 0) { result.append("\n"+ebounds().print(gammalib::reduce(chatter))); } else { result.append("\n"+gammalib::parformat("Energy intervals") + "not defined"); } } // Append skymap definition if (gammalib::reduce(chatter) > SILENT) { result.append("\n"+m_map.print(gammalib::reduce(chatter))); } } // endif: chatter was not silent // Return result return result; }
/***********************************************************************//** * @brief Write Good Time Intervals into XML element * * @param[in] xml XML element. * * Writes Good Time Intervals into an XML element. The format of the Good * Time Intervals is * * <parameter name="GoodTimeIntervals" tmin="..." tmax="..."/> * * The units of the @a tmin and @a tmax parameters are seconds. * * The method also writes the time reference as parameter in the @p xml * element. * * This method does nothing if the Good Time Intervals are empty. ***************************************************************************/ void GGti::write(GXmlElement& xml) const { // Continue only if there are GTIs if (!is_empty()) { // Get parameter GXmlElement* par = gammalib::xml_need_par(G_WRITE_XML, xml, "GoodTimeIntervals"); // Write time interval par->attribute("tmin", gammalib::str(tstart().convert(m_reference))); par->attribute("tmax", gammalib::str(tstop().convert(m_reference))); // Write time reference m_reference.write(xml); } // endif: GTIs were not empty // Return return; }
/* afs_osi_TimedSleep * * Arguments: * event - event to sleep on * ams --- max sleep time in milliseconds * aintok - 1 if should sleep interruptibly * * Returns 0 if timeout and EINTR if signalled. */ int afs_osi_TimedSleep(void *event, afs_int32 ams, int aintok) { int code = 0; struct afs_event *evp; struct timestruc_t ticks; struct trb *trb; int rc; ticks.tv_sec = ams / 1000; ticks.tv_nsec = (ams - (ticks.tv_sec * 1000)) * 1000000; evp = afs_getevent(event); trb = talloc(); if (trb == NULL) osi_Panic("talloc returned NULL"); trb->flags = 0; trb->func = AfsWaitHack; trb->eventlist = EVENT_NULL; trb->ipri = INTTIMER; trb->func_data = thread_self(); trb->timeout.it_value = ticks; e_assert_wait(&evp->cond, aintok); AFS_GUNLOCK(); tstart(trb); rc = e_block_thread(); while (tstop(trb)); if (rc == THREAD_INTERRUPTED) code = EINTR; tfree(trb); AFS_GLOCK(); relevent(evp); return code; }
/***********************************************************************//** * @brief Print Good Time Intervals * * @param[in] chatter Chattiness (defaults to NORMAL). * @return String containing Good Time Interval information. ***************************************************************************/ std::string GGti::print(const GChatter& chatter) const { // Initialise result string std::string result; // Continue only if chatter is not silent if (chatter != SILENT) { // Append header result.append("=== GGti ==="); // Append GTI information result.append("\n"+gammalib::parformat("Number of intervals")); result.append(gammalib::str(size())); result.append("\n"+gammalib::parformat("Ontime")); result.append(gammalib::str(ontime())+" sec"); result.append("\n"+gammalib::parformat("Elapsed time")); result.append(gammalib::str(telapse())+" sec"); result.append("\n"+gammalib::parformat("Time range")); result.append(gammalib::str(tstart().convert(m_reference))); result.append(" - "); result.append(gammalib::str(tstop().convert(m_reference))); result.append(" "+reference().timeunit()); result.append(" ("+reference().timesys()+")"); result.append("\n"+gammalib::parformat("Reference MDJ")); result.append(gammalib::str(reference().mjdref())); // EXPLICIT: Append time reference information if (chatter >= EXPLICIT) { result.append("\n"+reference().print(chatter)); } } // endif: chatter was not silent // Return result return result; }
/***********************************************************************//** * @brief Test CTA IRF computation for diffuse source model * * Tests the IRF computation for the diffuse source model. This is done * by calling the GCTAObservation::model method which in turn calls the * GCTAResponse::irf_diffuse method. The test is done for a small counts * map to keep the test executing reasonably fast. ***************************************************************************/ void TestGCTAResponse::test_response_irf_diffuse(void) { // Set reference value double ref = 13803.800313356; // Set parameters double src_ra = 201.3651; double src_dec = -43.0191; int nebins = 5; // Setup pointing on Cen A GSkyDir skyDir; skyDir.radec_deg(src_ra, src_dec); GCTAPointing pnt; pnt.dir(skyDir); // Setup skymap (10 energy layers) GSkymap map("CAR", "CEL", src_ra, src_dec, 0.5, 0.5, 10, 10, nebins); // Setup time interval GGti gti; GTime tstart(0.0); GTime tstop(1800.0); gti.append(tstart, tstop); // Setup energy boundaries GEbounds ebounds; GEnergy emin; GEnergy emax; emin.TeV(0.1); emax.TeV(100.0); ebounds.setlog(emin, emax, nebins); // Setup event cube centered on Cen A GCTAEventCube cube(map, ebounds, gti); // Setup dummy CTA observation GCTAObservation obs; obs.ontime(1800.0); obs.livetime(1600.0); obs.deadc(1600.0/1800.0); obs.response(cta_irf, cta_caldb); obs.events(&cube); obs.pointing(pnt); // Load model for IRF computation GModels models(cta_rsp_xml); // Reset sum double sum = 0.0; // Iterate over all bins in event cube for (int i = 0; i < obs.events()->size(); ++i) { // Get event pointer const GEventBin* bin = (*(static_cast<const GEventCube*>(obs.events())))[i]; // Get model and add to sum double model = obs.model(models, *bin, NULL) * bin->size(); sum += model; } // Test sum test_value(sum, ref, 1.0e-5, "Diffuse IRF computation"); // Return return; }
/* * Handle signals, upcalls, profiling, and other AST's and/or tasks that * must be completed before we can return to or try to return to userland. * * Note that td_sticks is a 64 bit quantity, but there's no point doing 64 * arithmatic on the delta calculation so the absolute tick values are * truncated to an integer. */ static void userret(struct lwp *lp, struct trapframe *frame, int sticks) { struct proc *p = lp->lwp_proc; int sig; int ptok; /* * Charge system time if profiling. Note: times are in microseconds. * This may do a copyout and block, so do it first even though it * means some system time will be charged as user time. */ if (p->p_flags & P_PROFIL) { addupc_task(p, frame->tf_rip, (u_int)((int)lp->lwp_thread->td_sticks - sticks)); } recheck: /* * Specific on-return-to-usermode checks (LWP_MP_WEXIT, * LWP_MP_VNLRU, etc). */ if (lp->lwp_mpflags & LWP_MP_URETMASK) lwpuserret(lp); /* * Block here if we are in a stopped state. */ if (STOPLWP(p, lp)) { lwkt_gettoken(&p->p_token); tstop(); lwkt_reltoken(&p->p_token); goto recheck; } while (dump_stop_usertds) { tsleep(&dump_stop_usertds, 0, "dumpstp", 0); } /* * Post any pending upcalls. If running a virtual kernel be sure * to restore the virtual kernel's vmspace before posting the upcall. */ if (p->p_flags & (P_SIGVTALRM | P_SIGPROF)) { lwkt_gettoken(&p->p_token); if (p->p_flags & P_SIGVTALRM) { p->p_flags &= ~P_SIGVTALRM; ksignal(p, SIGVTALRM); } if (p->p_flags & P_SIGPROF) { p->p_flags &= ~P_SIGPROF; ksignal(p, SIGPROF); } lwkt_reltoken(&p->p_token); goto recheck; } /* * Post any pending signals. If running a virtual kernel be sure * to restore the virtual kernel's vmspace before posting the signal. * * WARNING! postsig() can exit and not return. */ if ((sig = CURSIG_LCK_TRACE(lp, &ptok)) != 0) { postsig(sig, ptok); goto recheck; } /* * block here if we are swapped out, but still process signals * (such as SIGKILL). proc0 (the swapin scheduler) is already * aware of our situation, we do not have to wake it up. */ if (p->p_flags & P_SWAPPEDOUT) { lwkt_gettoken(&p->p_token); p->p_flags |= P_SWAPWAIT; swapin_request(); if (p->p_flags & P_SWAPWAIT) tsleep(p, PCATCH, "SWOUT", 0); p->p_flags &= ~P_SWAPWAIT; lwkt_reltoken(&p->p_token); goto recheck; } /* * In a multi-threaded program it is possible for a thread to change * signal state during a system call which temporarily changes the * signal mask. In this case postsig() might not be run and we * have to restore the mask ourselves. */ if (lp->lwp_flags & LWP_OLDMASK) { lp->lwp_flags &= ~LWP_OLDMASK; lp->lwp_sigmask = lp->lwp_oldsigmask; goto recheck; } }
/***********************************************************************//** * @brief Print spectrum * * @param[in] chatter Chattiness (defaults to NORMAL). * @return String containing spectrum ***************************************************************************/ std::string GMWLSpectrum::print(const GChatter& chatter) const { // Initialise result string std::string result; // Continue only if chatter is not silent if (chatter != SILENT) { // Append header result.append("=== GMWLSpectrum ==="); // Append information result.append("\n"+gammalib::parformat("Telescope")+m_telescope); result.append("\n"+gammalib::parformat("Instrument")+m_instrument); result.append("\n"+gammalib::parformat("Number of points")); result.append(gammalib::str(size())); result.append("\n"+gammalib::parformat("Time interval")); if (m_gti.size() > 0) { result.append(gammalib::str(tstart().secs())+" - "); result.append(gammalib::str(tstop().secs())+" sec"); } else { result.append("not defined"); } result.append("\n"+gammalib::parformat("Energy range")); if (m_ebounds.size() > 0) { result.append(emin().print()+" - "+emax().print()); } else { result.append("not defined"); } // EXPLICIT: Append spectral points if (chatter >= EXPLICIT) { for (int i = 0; i < size(); ++i) { // Build energy string std::string energy = m_data[i].m_eng.print(); if (m_data[i].m_eng_err.MeV() > 0.0) { energy += " +/- "+m_data[i].m_eng_err.print(); } // Build flux string std::string flux = gammalib::str(m_data[i].m_flux); if (m_data[i].m_flux_err > 0.0) { flux += " +/- "+gammalib::str(m_data[i].m_flux_err); } flux += " ph/cm2/s/MeV"; // Append to string result.append("\n"+gammalib::parformat(energy)); result.append(flux); } // endfor: looped over spectral points } // endif: EXPLICIT level } // endif: chatter was not silent // Return result return result; }
/***********************************************************************//** * @brief Print event cube information * * @param[in] chatter Chattiness (defaults to NORMAL). * @return String containing event cube information. ***************************************************************************/ std::string GLATEventCube::print(const GChatter& chatter) const { // Initialise result string std::string result; // Continue only if chatter is not silent if (chatter != SILENT) { // Append header result.append("=== GLATEventCube ==="); // Append information result.append("\n"+gammalib::parformat("Number of elements") + gammalib::str(size())); result.append("\n"+gammalib::parformat("Number of pixels")); result.append(gammalib::str(m_map.nx()) + " x " + gammalib::str(m_map.ny())); result.append("\n"+gammalib::parformat("Number of energy bins") + gammalib::str(ebins())); result.append("\n"+gammalib::parformat("Number of events") + gammalib::str(number())); // Append time interval result.append("\n"+gammalib::parformat("Time interval")); if (gti().size() > 0) { result.append(gammalib::str(tstart().secs()) + " - " + gammalib::str(tstop().secs())+" sec"); } else { result.append("not defined"); } // Append energy range result.append("\n"+gammalib::parformat("Energy range")); if (ebounds().size() > 0) { result.append(emin().print()+" - "+emax().print(chatter)); } else { result.append("not defined"); } // Append detailed information GChatter reduced_chatter = gammalib::reduce(chatter); if (reduced_chatter > SILENT) { // Append sky projection if (m_map.projection() != NULL) { result.append("\n"+m_map.projection()->print(reduced_chatter)); } // Append source maps result.append("\n"+gammalib::parformat("Number of source maps")); result.append(gammalib::str(m_srcmap.size())); for (int i = 0; i < m_srcmap.size(); ++i) { result.append("\n"+gammalib::parformat(" "+m_srcmap_names[i])); result.append(gammalib::str(m_srcmap[i]->nx())); result.append(" x "); result.append(gammalib::str(m_srcmap[i]->ny())); result.append(" x "); result.append(gammalib::str(m_srcmap[i]->nmaps())); } } } // endif: chatter was not silent // Return result return result; }
/***************************************************************************** * * tcase generates code for a case process tptr * *****************************************************************************/ PUBLIC void tcase (treenode * tptr) { /*{{{ save globals */ caseentry *const oldcasetable = casetable; const int olddefaultlab = defaultlab; const int olddefaultjumpdest = defaultjumpdest; const int oldselectortype = selectortype; treenode *const oldselectorexp = selectorexp; /*}}} */ BOOL makedefault = TRUE; treenode *selectionlist = RHSOf (tptr); const int joinlab = newlab (); int maxcase = 0; treenode *defaultp = NULL; /*{{{ initialise globals */ defaultlab = NO_LABEL; defaultjumpdest = FALSE; selectorexp = LHSOf (tptr); selectortype = ntypeof (selectorexp); /* make sure that we don't call memalloc with zero bytes */ casetable = (caseentry *) memalloc (sizeof (caseentry) * casesin (selectionlist) + 1); /*}}} */ /*{{{ evaluate the selector, if neccessary */ tpreexp (selectorexp); simplify (P_EXP, selectorexp); /*}}} */ /*{{{ build up table of selections, and generate jumps into case body */ { treenode *slist; for (slist = selectionlist; !EndOfList (slist); slist = NextItem (slist)) { treenode *thisselection = skipspecifications (ThisItem (slist)); treenode *v = CondGuardOf (thisselection); const int l = newlab (); if (TagOf (v) == S_ELSE) { defaultlab = l; defaultp = ThisItem (slist); makedefault = FALSE; } else /*{{{ set up labels and values */ for (; !EndOfList (v); v = NextItem (v)) { treenode *thisconstant = ThisItem (v); caseentry *caseentryptr = &(casetable[maxcase]); caseentryptr->label = l; caseentryptr->jumpdest = FALSE; caseentryptr->lowvalue = LoValOf (thisconstant); caseentryptr->highvalue = HiValOf (thisconstant); caseentryptr->selectionexp = thisconstant; caseentryptr->selectionp = ThisItem (slist); maxcase++; } /*}}} */ } if (makedefault) defaultlab = newlab (); #if 0 sup_qsort (casetable, maxcase, sizeof (caseentry), fitsinword (selectortype) ? comparecases : doublecomparecases); #else sup_qsort (casetable, maxcase, sizeof (caseentry), (bytesinscalar (selectortype) <= 4) ? comparecases : doublecomparecases); #endif tjumptable (0, maxcase - 1, FALSE); } /*}}} */ /*{{{ generate case body */ { int casesdone = 0; /*{{{ generate default process */ setlab (defaultlab); if (makedefault) { if (NEED_ERRORS) /* bug TS/2071 29/01/93 */ tstop (tptr); } else { if (defaultjumpdest) genstartblock (); tselection (defaultp, joinlab); } /*}}} */ while (casesdone < maxcase) { treenode *thisprocess; int i; BOOL jdest; /* Find a process to generate */ for (i = 0; (i < maxcase) && (casetable[i].selectionp == NULL); i++) /* skip */ ; thisprocess = casetable[i].selectionp; /* Generate thisprocess */ setlab (casetable[i].label); jdest = casetable[i].jumpdest; /*{{{ find and delete other entries for this process */ { int j; for (j = i + 1; j < maxcase; j++) if (casetable[j].selectionp == thisprocess) { /* Delete the process, so we only generate it once */ jdest = jdest | casetable[j].jumpdest; casetable[j].selectionp = NULL; casesdone++; } } /*}}} */ if (jdest) genstartblock (); tselection (thisprocess, joinlab); casetable[i].selectionp = NULL; casesdone++; } setlab (joinlab); genstartblock (); } /*}}} */ /*{{{ restore globals */ memfree (casetable); casetable = oldcasetable; defaultlab = olddefaultlab; defaultjumpdest = olddefaultjumpdest; selectortype = oldselectortype; selectorexp = oldselectorexp; /*}}} */ }
/* * Handle signals, upcalls, profiling, and other AST's and/or tasks that * must be completed before we can return to or try to return to userland. * * Note that td_sticks is a 64 bit quantity, but there's no point doing 64 * arithmatic on the delta calculation so the absolute tick values are * truncated to an integer. */ static void userret(struct lwp *lp, struct trapframe *frame, int sticks) { struct proc *p = lp->lwp_proc; void (*hook)(void); int sig; if (p->p_userret != NULL) { hook = p->p_userret; p->p_userret = NULL; (*hook)(); } /* * Charge system time if profiling. Note: times are in microseconds. * This may do a copyout and block, so do it first even though it * means some system time will be charged as user time. */ if (p->p_flags & P_PROFIL) { addupc_task(p, frame->tf_eip, (u_int)((int)lp->lwp_thread->td_sticks - sticks)); } recheck: /* * If the jungle wants us dead, so be it. */ if (lp->lwp_mpflags & LWP_MP_WEXIT) { lwkt_gettoken(&p->p_token); lwp_exit(0); lwkt_reltoken(&p->p_token); /* NOT REACHED */ } /* * Block here if we are in a stopped state. */ if (p->p_stat == SSTOP || dump_stop_usertds) { lwkt_gettoken(&p->p_token); tstop(); lwkt_reltoken(&p->p_token); goto recheck; } /* * Post any pending upcalls. If running a virtual kernel be sure * to restore the virtual kernel's vmspace before posting the upcall. */ if (p->p_flags & (P_SIGVTALRM | P_SIGPROF | P_UPCALLPEND)) { lwkt_gettoken(&p->p_token); if (p->p_flags & P_SIGVTALRM) { p->p_flags &= ~P_SIGVTALRM; ksignal(p, SIGVTALRM); } if (p->p_flags & P_SIGPROF) { p->p_flags &= ~P_SIGPROF; ksignal(p, SIGPROF); } if (p->p_flags & P_UPCALLPEND) { p->p_flags &= ~P_UPCALLPEND; postupcall(lp); } lwkt_reltoken(&p->p_token); goto recheck; } /* * Post any pending signals. If running a virtual kernel be sure * to restore the virtual kernel's vmspace before posting the signal. * * WARNING! postsig() can exit and not return. */ if ((sig = CURSIG_TRACE(lp)) != 0) { lwkt_gettoken(&p->p_token); postsig(sig); lwkt_reltoken(&p->p_token); goto recheck; } /* * block here if we are swapped out, but still process signals * (such as SIGKILL). proc0 (the swapin scheduler) is already * aware of our situation, we do not have to wake it up. */ if (p->p_flags & P_SWAPPEDOUT) { lwkt_gettoken(&p->p_token); get_mplock(); p->p_flags |= P_SWAPWAIT; swapin_request(); if (p->p_flags & P_SWAPWAIT) tsleep(p, PCATCH, "SWOUT", 0); p->p_flags &= ~P_SWAPWAIT; rel_mplock(); lwkt_reltoken(&p->p_token); goto recheck; } /* * In a multi-threaded program it is possible for a thread to change * signal state during a system call which temporarily changes the * signal mask. In this case postsig() might not be run and we * have to restore the mask ourselves. */ if (lp->lwp_flags & LWP_OLDMASK) { lp->lwp_flags &= ~LWP_OLDMASK; lp->lwp_sigmask = lp->lwp_oldsigmask; goto recheck; } }
int main(int ac, char *av[]) { size_t i, t, f, prnd; struct SshTimeMeasureRec tmit = SSH_TIME_MEASURE_INITIALIZER; #if !defined(HAVE_LIBM) && !defined(HAVE_MATH_H) exit(0); #endif /* Initialize the number of failures. */ f = 0; printf("Running quick tests for sshrand.\n"); if (quick_test_1() == 0) f++, printf(" ** test 1 failed.\n"); if (quick_test_2() == 0) f++, printf(" ** test 2 failed.\n"); printf("Running timing tests for sshrand " "(and for other available generators).\n"); /* Generating a megawords of randomness. */ prnd = 1024 * 1024; #define OK_CRAND 0x01d80000 #define OK_GNURAND 0x3e17b13d #define OK_SSHRAND 0x2405164b tstart(&tmit, "Initialization of C rand."); srand(1001); tstop(&tmit, "C rand initialized."); tstart(&tmit, "Generating %u bytes of prandom data with C rand.", prnd); for (i = 0, t = 0; i < prnd; i++) { t += rand(); } tstop(&tmit, "C rand stopped with checksum %s (%08x)", (t == OK_CRAND) ? "ok" : "failed", t); if (t != OK_CRAND) f++; tstart(&tmit, "Initialization of GNU random."); ssh_rand_seed(1001); tstop(&tmit, "GNU random initialized."); tstart(&tmit, "Generating %u bytes of prandom data with GNU random.", prnd); for (i = 0, t = 0; i < prnd; i++) { t += ssh_rand(); } tstop(&tmit, "GNU random stopped with checksum %s (%08x).", (t == OK_GNURAND) ? "ok" : "failed", t); if (t != OK_GNURAND) f++; tstart(&tmit, "Initialization of SSH rand."); ssh_rand_seed(1001); tstop(&tmit, "SSH random initialized."); tstart(&tmit, "Generating %u bytes of prandom data with SSH rand.", prnd); for (i = 0, t = 0; i < prnd; i++) { t += ssh_rand(); } tstop(&tmit, "SSH rand stopped with checksum %s (%08x).", (t == OK_SSHRAND) ? "ok" : "failed", t); if (t != OK_SSHRAND) f++; printf("%u failures.\n", f); if (f > 0) { printf("" "Caution. This program has detected a failure(s). Any of the following may\n" " be the cause of this failure (more exact indication of error\n" " might have appeared above);\n" " 1. the C rand or GNU random libraries may have generated\n" " checksum that was not verified.\n" " 2. the sshrand library may have generated a checksum that\n" " did not match. This is a fatal error and should be\n" " investigated carefully.\n" " 3. one or more of the quick tests failed. These indicate\n" " statistical weakness in the generator. Such problems can\n" " be due to compilation, platform or even inherent error in\n" " the sshrand library. This is a fatal error and should be\n" " investigated carefully.\n" "\n" " In case of an fatal error you may wish to consult the support at\n" " SFNT Finland Oy.\n"); } ssh_util_uninit(); return f; }
/***********************************************************************//** * @brief Set MC pre-computation cache * * @param[in] tmin Minimum time of time interval. * @param[in] tmax Maximum time of time interval. * * This method sets up an array of indices and the cumulative distribution * function needed for MC simulations. ***************************************************************************/ void GModelTemporalLightCurve::mc_update(const GTime& tmin, const GTime& tmax) const { // Get light curve normalisation value to see whether it has changed double norm = m_norm.value(); // Update the cache only if the time interval or normalisation has changed if (tmin != m_mc_tmin || tmax != m_mc_tmax || norm != m_mc_norm) { // Store new time interval and normalisation value m_mc_tmin = tmin; m_mc_tmax = tmax; m_mc_norm = norm; // Initialise cache m_mc_eff_duration = 0.0; m_mc_cum.clear(); m_mc_slope.clear(); m_mc_offset.clear(); m_mc_time.clear(); m_mc_dt.clear(); // Initialise duration double duration = 0.0; // Continue only if time interval overlaps with temporal file function // and if time interval is valid if (tmax > m_tmin && tmin < m_tmax && tmax > tmin) { // Loop over all intervals between the nodes for (int i = 0; i < m_nodes.size()-1; ++i) { // Get start and stop time of interval GTime tstart(m_nodes[i], m_timeref); GTime tstop(m_nodes[i+1], m_timeref); // Make sure that we only consider the interval that overlaps // with the requested time interval if (tmin > tstart) { tstart = tmin; } if (tmax < tstop) { tstop = tmax; } // If time interval is empty then skip this node if (tstart >= tstop) { continue; } // Evaluate rate at start and stop time double rstart = eval(tstart); double rstop = eval(tstop); // Compute mean normalization for this interval double norm = 0.5 * (rstart + rstop); // Compute integral for this interval double dt = tstop - tstart; double cum = norm * dt; // Compute slope, offset and start time of interval double slope = (rstop - rstart) / dt; double offset = rstart; double renorm = (0.5 * slope * dt + offset) * dt; slope /= renorm; offset /= renorm; // Update effective duration and real duration m_mc_eff_duration += cum; duration += dt; // Put mean normalization and integral on stack m_mc_cum.push_back(cum); m_mc_slope.push_back(slope); m_mc_offset.push_back(offset); m_mc_time.push_back(tstart.convert(m_timeref)); m_mc_dt.push_back(dt); } // endfor: next interval // Build cumulative distribution for (int i = 1; i < m_mc_cum.size(); ++i) { m_mc_cum[i] += m_mc_cum[i-1]; } double norm = m_mc_cum[m_mc_cum.size()-1]; for (int i = 0; i < m_mc_cum.size(); ++i) { m_mc_cum[i] /= norm; } } // endif: time interval overlaps } // endif: Update was required // Return return; }
void feedback(int n, int m, int p, int q, int nb, int output_level, int nn, int input, char *ifn, char *ofn) { dcmplx A[n][n], B[n][m], C[p][n]; dcmplx s[nn], Is[n][n], Is_A[n][n], tmp[p][n], M[p][m]; double a[nn*2], b[nn*p*m*2], *points, *planes, r; int i, j, k, start, nbsols; FILE *ifp, *ofp; timer t_phc; ofp=fopen(ofn, "w"); /*open for writing*/ fprintf(ofp, "n=%d\n", n); fprintf(ofp, "m=%d\n", m); fprintf(ofp, "p=%d\n", p); fprintf(ofp, "q=%d\n", q); if(input == 0) { ifp=fopen(ifn, "r"); /*open for reading*/ skip(ifp); read_dcmatrix0(n, n, A, ifp); printf( "The given matrix A(%d*%d) is:\n", n, n); print_dcmatrix(n, n, A); read_dcmatrix0(n, m, B, ifp); printf("The given matrix B(%d*%d) is:\n", n, m); print_dcmatrix(n, m, B); read_dcmatrix0(p, n, C, ifp); printf("The given matrix C(%d*%d) is:\n", p, n); print_dcmatrix(p, n, C); for(i=0; i<n+q; i++) read_dcmplx0(&s[i], ifp); for(i=n+q; i<nn; i++) /*generate more poles as interpolation points */ { s[i] = create1(cos(rand())); if(s[i].re>0) s[i] = min_dcmplx(s[i]); } fclose(ifp); } if(input == 1) { ifp=fopen(ifn, "r"); /*open for reading*/ skip(ifp); read_dcmatrix2(n, n, A, ifp); printf( "The given matrix A(%d*%d) is:\n", n, n); print_dcmatrix(n, n, A); read_dcmatrix2(n, m, B, ifp); printf("The given matrix B(%d*%d) is:\n", n, m); print_dcmatrix(n, m, B); read_dcmatrix2(p, n, C, ifp); printf("The given matrix C(%d*%d) is:\n", p, n); print_dcmatrix(p, n, C); for(i=0; i<n+q; i++) read_dcmplx1(&s[i], ifp); for(i=n+q; i<nn; i++) /*generate more poles as interpolation points */ { s[i] = create1(cos(rand())); if(s[i].re>0) s[i] = min_dcmplx(s[i]); } fclose(ifp); } if(input==2) { random_dcmatrix ( n, n, A); printf("\nThe random generated matrix A is:\n"); print_dcmatrix(n, n, A); random_dcmatrix ( n, m, B); printf("\nThe random generated matrix B is:\n"); print_dcmatrix(n, m, B); random_dcmatrix ( p, n, C); printf("\nThe random generated matrix C is:\n"); print_dcmatrix(p, n, C); s[0] = create2(-0.23423423423, 0); /* fix one pole for testing realization */ for(i=1; i<nn; i++) { r = rand(); s[i] = create2(cos(r), sin(r)); if(s[i].re>0) s[i] = min_dcmplx(s[i]); s[++i] = conjugate(s[i]); if(i==(nn-2)) { if((nn%2)==0) s[++i] = create1(-1.0); } } printf("\nThe random generated poles are:\n"); for(i=0; i<nn; i++) writeln_dcmplx(s[i]); } if(input==3) { random_dcmatrix0 ( n, n, A); printf("\nThe random generated matrix A is:\n"); print_dcmatrix(n, n, A); random_dcmatrix0 ( n, m, B); printf("\nThe random generated matrix B is:\n"); print_dcmatrix(n, m, B); random_dcmatrix0 ( p, n, C); printf("\nThe random generated matrix C is:\n"); print_dcmatrix(p, n, C); s[0] = create2(-0.23423423423, 0); /* fix one pole for test */ for(i=1; i<nn; i++) { r = rand(); s[i] = create2(cos(r), sin(r)); if(s[i].re>0) s[i] = min_dcmplx(s[i]); s[++i] = conjugate(s[i]); if(i==(nn-2)) { if((nn%2)==0) s[++i] = create1(-1.0); } } printf("\nThe random generated poles are:\n"); for(i=0; i<nn; i++) writeln_dcmplx(s[i]); } if(input == 4) { ifp=fopen(ifn, "r"); /*open for reading*/ skip(ifp); read_dcmatrix0(n, n, A, ifp); printf( "The given matrix A(%d*%d) is:\n", n, n); print_dcmatrix(n, n, A); read_dcmatrix0(n, m, B, ifp); printf("The given matrix B(%d*%d) is:\n", n, m); print_dcmatrix(n, m, B); read_dcmatrix0(p, n, C, ifp); printf("The given matrix C(%d*%d) is:\n", p, n); print_dcmatrix(p, n, C); for(i=0; i<n+q; i++) read_dcmplx1(&s[i], ifp); for(i=n+q; i<nn; i++) /*generate more poles as interpolation points */ { s[i] = create1(cos(rand())); if(s[i].re>0) s[i] = min_dcmplx(s[i]); } fclose(ifp); } /* print the input matrices in matlab format for further study */ fprintf(ofp,"A=[\n"); print_dcmatrix1(n, n, A, ofp); fprintf(ofp,"]\n"); fprintf(ofp,"B=[\n"); print_dcmatrix1(n, m, B, ofp); fprintf(ofp,"]\n"); fprintf(ofp,"C=[\n"); print_dcmatrix1(p, n, C, ofp); fprintf(ofp,"]\n"); fprintf(ofp, "\nPoles=["); for(i=0; i<nn; i++) { write_dcmplx1(s[i], ofp); if(i!=(nn-1)) fprintf(ofp, ","); } fprintf(ofp, "]\n"); /* end of input */ j = 0; for(i=0; i<nn; i++) { a[j++] = s[i].re; a[j++] = s[i].im; } start = 0; for(k=0; k<n+q; k++) { for(i=0; i<n; i++) for(j=0; j<n; j++) { if(i==j) Is[i][j] = s[k]; else Is[i][j] = zero; } sub_dcmatrix(n, n, Is, A, Is_A); dcinverse(n, Is_A); multiply_dcmatrix(p, n, n, C, Is_A, tmp); multiply_dcmatrix(p, n, m, tmp, B, M); c2ada_dc_matrix( p, m, M, nn*p*m*2, b, start); start = start + p*m*2; } /* generate some random planes */ for( i=start ; i<nn*p*m*2; i++ ) { b[i++] = cos(rand()); b[i] = 0.0; } fflush(stdout); fflush(ofp); printf("\nComputing the feedback law with PHC ...\n"); tstart(&t_phc); adainit(); nbsols = _ada_pieri_solver(m, p, q, nb, output_level, a, b, ofn); adafinal(); tstop(&t_phc); /* This subroutine spends almost all the time */ tprint(t_phc); printf("\nSee %s for the realization of the output feedbacks.\n", ofn); fclose(ofp); }