Exemplo n.º 1
0
int main(void)
{
	float value = 0.2;

	value = log(value);

	initialise();

	while (1)
	{
		if (led_updated == 1)
		{
			led_propagate();
			led_updated = 0;
		}
		else
		{
			uart_handle();
		}
	}
}
Exemplo n.º 2
0
CompositorManager::CompositorManager():
	mRectangle(0)
{
	initialise();

	// Loading order (just after materials)
	mLoadOrder = 110.0f;
	// Scripting is supported by this manager
	mScriptPatterns.push_back("*.compositor");
	ResourceGroupManager::getSingleton()._registerScriptLoader(this);

	// Resource type
	mResourceType = "Compositor";

	// Create default thread serializer instance (also non-threaded)
	OGRE_THREAD_POINTER_SET(mSerializer, new CompositorSerializer());

	// Register with resource group manager
	ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this);

}
Exemplo n.º 3
0
Arquivo: main.c Projeto: robinrob/c
int main(void)
{
	char str[] = "My name is Robin Smith!";
	int i;
	stack s;

	printf("The string:     %s\n", str);
	initialise(&s);
	for (i = 0; str[i] != '\0'; ++i) {
		if (!full(&s))
			push(str[i], &s);
	}

	printf("From the stack: ");
	while (!empty(&s)) {
		putchar(pop(&s));
	}
	putchar('\n');

	return 0;
}
QgsBookmarks::QgsBookmarks( QWidget *parent, Qt::WFlags fl )
    : QDialog( parent, fl ),
    mParent( parent )
{
  setupUi( this );

  restorePosition();

  // user database is created at QGIS startup in QgisApp::createDB
  // we just check whether there is our database [MD]
  QFileInfo myFileInfo;
  myFileInfo.setFile( QgsApplication::qgisSettingsDirPath() );
  if ( !myFileInfo.exists( ) )
  {
    QgsDebugMsg( "The qgis.db does not exist" );
  }

  // Note proper queens english on next line
  initialise();

  //
  // Create the zoomto and delete buttons and add them to the
  // toolbar
  //
  QPushButton * btnUpdate = new QPushButton( tr( "&Update" ) );
  QPushButton * btnDelete = new QPushButton( tr( "&Delete" ) );
  QPushButton * btnZoomTo = new QPushButton( tr( "&Zoom to" ) );
  btnZoomTo->setDefault( true );
  buttonBox->addButton( btnUpdate, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnDelete, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnZoomTo, QDialogButtonBox::ActionRole );
  // connect the slot up to catch when a bookmark is updated
  connect( btnUpdate, SIGNAL( clicked() ), this, SLOT( on_btnUpdate_clicked() ) );
  // connect the slot up to catch when a bookmark is deleted
  connect( btnDelete, SIGNAL( clicked() ), this, SLOT( on_btnDelete_clicked() ) );
  // connect the slot up to catch when a bookmark is zoomed to
  connect( btnZoomTo, SIGNAL( clicked() ), this, SLOT( on_btnZoomTo_clicked() ) );
  // connect the slot up to catch when a new bookmark is added
  connect( mParent, SIGNAL( bookmarkAdded() ), this, SLOT( refreshBookmarks() ) );
}
Exemplo n.º 5
0
int main(int argc, char** argv) {
    int human = argc == 2 && argv[1][0] == '-' && argv[1][1] == 'h';
    uint8_t buffer[256];
    int len = fread(buffer, 1, sizeof(buffer), stdin);
    pb_istream_t stream = pb_istream_from_buffer(buffer, len);
    PublicKey pk;
    if (!pb_decode(&stream, PublicKey_fields, &pk)) return 1;
    PublicKeyData pkd;
    stream = pb_istream_from_buffer(pk.publickey_msg.bytes,
            pk.publickey_msg.size);
    if (!pb_decode(&stream, PublicKeyData_fields, &pkd)) return 1;
    for (int i=0; i<pkd.sig_keys_count; i++) {
        if (  pk.sigs_count < i
           || pk.sigs[i].size < crypto_sign_BYTES
           || pkd.sig_keys[i].size < crypto_sign_PUBLICKEYBYTES
           || crypto_sign_detach_open(pk.publickey_msg.bytes,
               pk.publickey_msg.size, pk.sigs[i].bytes, pkd.sig_keys[i].bytes)
           != 0) {
            fprintf(stderr, "Invalid key\n");
            return 2;
        } else {
            initialise(1344, 256, 128);
            char* dgst = digest((char*)pkd.sig_keys[i].bytes,
                    pkd.sig_keys[i].size, 1);
            for (int i=0; i<128/8; i+=2) {
                if (i > 0 && human) {
                    fprintf(stdout, " ");
                    if (i == 8) fprintf(stdout, " ");
                }
                fprintf(stdout, "%X", (dgst[i]&0xF0)>>4);
                fprintf(stdout, "%X", dgst[i]&0x0F);
                fprintf(stdout, "%X", (dgst[i+1]&0xF0)>>4);
                fprintf(stdout, "%X", dgst[i+1]&0x0F);
            }
            if (human) printf("\n");
            else return 1;
            dispose();
        }
    }
}
Exemplo n.º 6
0
//int main(int argc, char *argv[], char *env[])
void main(void)
{
 int i, j;
 mvtype movemade;
 mousex=100;
 mousey=100;
 iconmenu=0;
 set_default_options();
 options=doptions;
 read_options();
 initialise(startbrd);
 initial_displays(current);
 no_more_openings=FALSE;
 quit=game_over=0;
 g_path.move[0].f=0;
 randomize();
 FLAGnewstart=1;
 while(!quit)
 {
   while(game.movenum<maxmoves && !quit)
   {
	 whites=0;
	 blacks=0;
	 if (FLAGnewstart) { starttime=time(NULL); FLAGnewstart=0; }
	 newtime=0;
	 if (!game_over && ((current.mvr=='w' && options.whiteplayer==PROGRAM) || (current.mvr=='b' && options.blackplayer==PROGRAM)))
	      movemade=get_computer_move(current); else
		 movemade=get_player_move(current, game_over);
	 if (kbhit()) { if (getch()==27) { options.whiteplayer=USER; options.blackplayer=USER; } }
	 if (current.mvr=='w') (whites=time(NULL)-starttime); else (blacks=time(NULL)-starttime);
	 if (movemade.t!=0) if (movemade.t<100) makemv(movemade); else {menu_option(movemade.t); game_over=0;}
	 regular_displays(current, movemade);
	 if (!game_over) game_over=over();
	 assert(game.lastmove<maxmoves);
   }
   options.whiteplayer=USER;
   options.blackplayer=USER;
 }
}
Exemplo n.º 7
0
/*************************************************************************
    Application entry point
*************************************************************************/
int CEGuiSample::run()
{
    try
    {
        if (initialise())
            cleanup();
    }
    catch (CEGUI::Exception& exc)
    {
        outputExceptionMessage(exc.getMessage().c_str());
    }
    catch (std::exception& exc)
    {
        outputExceptionMessage(exc.what());
    }
    catch(...)
    {
        outputExceptionMessage("Unknown exception was caught!");
    }

    return 0;
}
Exemplo n.º 8
0
void main(int argc, char **argv) {
    real x[NMAX][NDIM], xdot[NMAX][NDIM], f[NMAX][NDIM],
      /**/fdot[NMAX][NDIM];
    real step[NMAX], tlast[NMAX], m[NMAX], t, dt;
    long int j, i, n, nsteps, noutp, cpu, timenow;
    extern void initialise(), runtime_output(), final_output();
/*     cpu = clock(); */
    time(&cpu);
    srand(cpu);
    assert(argc==4);
    n = atoi(argv[1]); 
    noutp = atoi(argv[2]); 
    dt = atof(argv[3])/(real)noutp; 
    t  = 0;
    /*    printf("\nInitial conditions.\n");*/
    initialise(n, x, xdot, f, fdot, step, tlast, m);
    nsteps=0;
    loop(j, noutp) {
      nsteps += hermite(x, xdot, f, fdot, step, tlast, m, &t, 
			/**/t+dt, n);
      runtime_output(x,t,n);
    }
Exemplo n.º 9
0
int SCIPSolver::solve(){
  DBG("solve!%s\n", "");
  
  if(!has_been_added) initialise();

  if(_verbosity > 0 && _verbosity < 3){
    // Do nothing extra
  } else if(_verbosity >= 3){
    SCIP_CALL_EXC(SCIPprintOrigProblem(_scip, NULL, NULL, FALSE));
    // SCIP_CALL_EXC(SCIPwriteOrigProblem(_scip, "scip.lp", "lp", TRUE));
  } else {
      // disable scip output to stdout
    SCIP_CALL_EXC( SCIPsetMessagehdlr(_scip, NULL) );
  }

  SCIP_CALL_EXC( SCIPsolve(_scip) );
  SCIP_STATUS status = SCIPgetStatus(_scip);
 
  if( status == SCIP_STATUS_OPTIMAL ) return SAT;
  else if( status == SCIP_STATUS_INFEASIBLE ) return UNSAT;
  else return UNKNOWN;
}
Exemplo n.º 10
0
/*************************************************************************
    Application entry point
*************************************************************************/
int SampleBrowserBase::run()
{
    try
    {
        if (initialise("CEGUI.log", CEGUI::String()))
            d_baseApp->run();
        cleanup();
    }
    catch (const std::exception& exc)
    {
        outputExceptionMessage(exc.what());
    }
    catch (const char* exc)
    {
        outputExceptionMessage(exc);
    }
    catch (...)
    {
        outputExceptionMessage("Unknown exception was caught!");
    }
    return 0;
}
Exemplo n.º 11
0
void main()
{
  int gdriver = DETECT, gmode, errorcode;
  initgraph(&gdriver, &gmode, "c:\\tc\\bgi ");
  initialise();
///////////////
  start:
  m=0;
  char b=getch();
  switch(b)
  {
     case 75: if(x!=92) { base(); x-=143;  sr(); }  break;
     case 77: if(x!=378) { base(); x+=143;  sr(); } break;
     case 72:  if(y!=92) { base(); y-=143;  sr(); } break;
     case 80:  if(y!=378) { base(); y+=143;  sr(); } break;
     case 13:  check2();   if(m==0) {move();} break;
     case 27: exit(0); break;
   }
 wincheck();

goto start;
}
Exemplo n.º 12
0
    //==============================================================================
    void prepareToPlay (double newSampleRate, int samplesPerBlockExpected)
    {
        setLatencySamples (0);

        initialise (newSampleRate, samplesPerBlockExpected);

        if (initialised)
        {
            tempBuffer.setSize (jmax (1, outputs.size()), samplesPerBlockExpected);

            // dodgy hack to force some plugins to initialise the sample rate..
            if (getNumParameters() > 0)
            {
                const float old = getParameter (0);
                setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
                setParameter (0, old);
            }

            if (plugin->activate != nullptr)
                plugin->activate (handle);
        }
    }
Exemplo n.º 13
0
AubioOnsetDetector :: AubioOnsetDetector(){
	buffersize = 1024;
	hopsize = 512;
		//aubio related setup
		o = new_aubio_onsetdetection(aubio_onset_complex, buffersize, 1);//initially in complex mode
		pv = (aubio_pvoc_t *)new_aubio_pvoc(buffersize, hopsize, 1);
		parms = new_aubio_peakpicker(threshold);
		vec = (fvec_t *)new_fvec(hopsize,1);
		
		threshold = 1;
		threshold2 = -70.;

	resetValues();
	thresholdRelativeToMedian = 1.3;
	cutoffForRepeatOnsetsMillis = 30;
	medianSpeed = 10;
	pos = 0;
	
	detectionTriggerRatio = 0.5f;
	detectionTriggerThreshold = 10;
    
    initialise();
}
Exemplo n.º 14
0
int main()
{

    int ch;
    initscr();
    noecho();
    cbreak();
    mn *m;
    m = initialise(m);
    printw("\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t\tHello welcome to the editor we support Auto complition! \n");
    printw("\n\t\t\t\t\t\tYou can start writing now\n");
    start_color();          /* Start color          */
    init_pair(1, COLOR_RED, COLOR_BLACK);
    refresh();
    printw("\n\t\t\t\t\t\tPlease choose between following options\n");
    printw("\n\t\t\t\t\t\t1. Enter editor");
    printw("\n\t\t\t\t\t\t2. Enhance Dictionary or tree\n");
    ch = getch();

    switch(ch)
        {
            case 49: clear();
                    refresh();
                    m = start(m);
                    break;
            case 50: menu();
                    break;

        }

  //  m = start(m);
    
    getch();
    endwin();

    return 0;
}
Exemplo n.º 15
0
int main()
{
	int i,valid=1,n;
	char exp[20],t;
	initialise();
	printf("Enter expression ");
	scanf("%s",&exp);
	n=strlen(exp);
	for(i=0;i<n;i++)
	{
		if(exp[i]=='('||exp[i]=='{'||exp[i]=='[')
			push(exp[i]);
		else if(exp[i]==')'||exp[i]=='}'||exp[i]==']')
		{
			if(s.top==-1)
				valid=0;
			else
			{
				t=pop();
				if(exp[i]==')'&&(exp[i]=='{'||exp[i]=='['))
					valid=0;
				else if(exp[i]=='}'&&(exp[i]=='('||exp[i]=='['))
					valid=0;
				else if(exp[i]==']'&&(exp[i]=='('||exp[i]=='{'))
					valid=0;				
			}
		}
	}	
	if(s.top>=0)
		valid=0;
	if(valid==1)
		printf("Expression is valid");
	else
		printf("Expression is not valid");
	getch();
	return 0;
}
void socket_server(char SERVER_IP[], int port)
{
	//Initialise Winsock
	initialise();
	//Create a TCP socket
	SOCKET socket = create_socket();
	//connect to server
	struct sockaddr_in server;
	server.sin_addr.s_addr = inet_addr(SERVER_IP);
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	//Connect to remote server
	if (bind(socket, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("Binding error");
		return;
	}
	if (listen(socket, 10) < 0)
	{
		printf("Listing Error\n");
		return;
	}
	printf("Server Ready to Listen\n");
	struct sockaddr_in sadr;
	int	addr_size = sizeof(SOCKADDR);
	while (1)
	{
		int acceptid = accept(socket, (SOCKADDR*)&sadr, &addr_size);
		if (acceptid == INVALID_SOCKET)
		{
			printf("Error Accepting\n\n");
			return;
		}
		HANDLE thread = CreateThread(NULL, 0, service, acceptid, 0, NULL);
	}
}
Exemplo n.º 17
0
W_EDITBOX::W_EDITBOX(W_EDBINIT const *init)
	: WIDGET(init, WIDG_EDITBOX)
	, FontID(init->FontID)
	, blinkOffset(wzGetTicks())
	, pBoxDisplay(init->pBoxDisplay)
	, pFontDisplay(init->pFontDisplay)
	, HilightAudioID(WidgGetHilightAudioID())
	, ClickedAudioID(WidgGetClickedAudioID())
	, AudioCallback(WidgGetAudioCallback())
{
	char const *text = init->pText;
	if (!text)
	{
		text = "";
	}
	aText = QString::fromUtf8(text);

	if (display == NULL)
	{
		display = editBoxDisplay;
	}

	initialise();
}
// update the state of the sensor
void AP_Proximity_LightWareSF40C::update(void)
{
    if (uart == nullptr) {
        return;
    }

    // initialise sensor if necessary
    bool initialised = initialise();

    // process incoming messages
    check_for_reply();

    // request new data from sensor
    if (initialised) {
        request_new_data();
    }

    // check for timeout and set health status
    if ((_last_distance_received_ms == 0) || (AP_HAL::millis() - _last_distance_received_ms > PROXIMITY_SF40C_TIMEOUT_MS)) {
        set_status(AP_Proximity::Proximity_NoData);
    } else {
        set_status(AP_Proximity::Proximity_Good);
    }
}
Exemplo n.º 19
0
GameManager::GameManager () :
	_currentGameDescription(0), _enginePath(GlobalRegistry().get(RKEY_ENGINE_PATH)), _cleanedEnginePath(
			DirectoryCleaned(_enginePath)), _emptyString("")
{
	GlobalRegistry().addKeyObserver(this, RKEY_ENGINE_PATH);

	// greebo: Register this class in the preference system so that the constructPreferencePage() gets called.
	GlobalPreferenceSystem().addConstructor(this);

	// TODO Remove this and read the game.xml data from the xmlregistry, too
	std::string strGameFilename = Environment::Instance().getAppPath() + "game.xml";

	xmlDocPtr pDoc = xmlParseFile(strGameFilename.c_str());
	if (pDoc) {
		_currentGameDescription = new GameDescription(pDoc, strGameFilename);
		// Import this information into the registry
		//GlobalRegistry().importFromFile(strGameFilename, "");
		xmlFreeDoc(pDoc);
	} else {
		gtkutil::errorDialog(_("XML parser failed to parse game.xml"));
	}

	initialise();
}
Exemplo n.º 20
0
int main(int argc, char **argv)
{
	srand((time)NULL);
	
	
	printf("Taille structure = %u\n", sizeof(Tableau)); // (taille du tableau * taille int) + (taille du champs 'taille') = 100*4 + 1 = 404
	

/*	int a = 0; // On initialise arbitrairement la variable a
	printf("%d\n", alea(a));	
*/
	
	Tableau T = initialise(T);
	
	affiche(T);
	printf("Elément minimum du tableau : %d\n", minimum(T));
	if (produit(T) < 0) printf("Produit trop grand"); // Evite d'afficher un produit négatif sur des entiers non signés
	else printf("Produit des éléments du tableau : %d\n", produit(T));
	
	
	// Décalage //
	T = decalage(T); 
	putchar('\n'); 
	printf("Tableau après décalage : \n"); 
	affiche(T);	
	printf("Taille du tableau après le décalage = %d\n\n", T.taille);
	
	
	// Trie //
	printf("Après trie du tableau : \n");
	T = trie(T);
	affiche(T);	
	
	
	return 0;
}
Exemplo n.º 21
0
//==============================================================================
bool JUCEApplication::initialiseApp (const String& commandLine)
{
    commandLineParameters = commandLine.trim();

   #if ! (JUCE_IOS || JUCE_ANDROID)
    jassert (appLock == nullptr); // initialiseApp must only be called once!

    if (! moreThanOneInstanceAllowed())
    {
        appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());

        if (! appLock->enter(0))
        {
            appLock = nullptr;
            MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);

            DBG ("Another instance is running - quitting...");
            return false;
        }
    }
   #endif

    // let the app do its setting-up..
    initialise (commandLineParameters);

   #if JUCE_MAC
    juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
   #endif

   #if ! (JUCE_IOS || JUCE_ANDROID)
    broadcastCallback = new AppBroadcastCallback();
   #endif

    stillInitialising = false;
    return true;
}
Exemplo n.º 22
0
Foam::regionModels::singleLayerRegion::singleLayerRegion
(
    const fvMesh& mesh,
    const word& regionType,
    const word& modelName,
    bool readFields
)
:
    regionModel(mesh, regionType, modelName, false),
    nHatPtr_(NULL),
    magSfPtr_(NULL),
    passivePatchIDs_()
{
    if (active_)
    {
        constructMeshObjects();
        initialise();

        if (readFields)
        {
            read();
        }
    }
}
//______________________________________________________________________________
shutterInterface::shutterInterface( const bool* show_messages_ptr, const bool * show_debug_messages_ptr )
: configReader( show_messages_ptr, show_debug_messages_ptr  ), interface( show_messages_ptr, show_debug_messages_ptr  )
{
    initialise();
}
Exemplo n.º 24
0
ComediDigitalInput::ComediDigitalInput(const char *deviceFile, uint inputSubdevice,
					uint readChannel)
        : ComediDigitalIO(deviceFile, inputSubdevice, &readChannel, 1)
{
        initialise();
}
//  __  ___  __   __    /  __  ___  __   __
// /  `  |  /  \ |__)  /  |  \  |  /  \ |__)
// \__,  |  \__/ |  \ /   |__/  |  \__/ |  \
//
shutterInterface::shutterInterface( const std::string & configFileLocation, const bool* show_messages_ptr, const  bool * show_debug_messages_ptr )
: configReader( configFileLocation, show_messages_ptr, show_debug_messages_ptr ), interface( show_messages_ptr, show_debug_messages_ptr )
{
    initialise();
}
Exemplo n.º 26
0
ComediDigitalOutput::ComediDigitalOutput(const char *deviceFile, uint outputSubdevice,
					uint writeChannel)
        : ComediDigitalIO(deviceFile, outputSubdevice, &writeChannel, 1)
{
        initialise();
}
Exemplo n.º 27
0
static int
qags (const gsl_function * f,
      const double a, const double b,
      const double epsabs, const double epsrel,
      const size_t limit,
      gsl_integration_workspace * workspace,
      double *result, double *abserr,
      gsl_integration_rule * q)
{
  double area, errsum;
  double res_ext, err_ext;
  double result0, abserr0, resabs0, resasc0;
  double tolerance;

  double ertest = 0;
  double error_over_large_intervals = 0;
  double reseps = 0, abseps = 0, correc = 0;
  size_t ktmin = 0;
  int roundoff_type1 = 0, roundoff_type2 = 0, roundoff_type3 = 0;
  int error_type = 0, error_type2 = 0;

  size_t iteration = 0;

  int positive_integrand = 0;
  int extrapolate = 0;
  int disallow_extrapolation = 0;

  struct extrapolation_table table;

  /* Initialize results */

  initialise (workspace, a, b);

  *result = 0;
  *abserr = 0;

  if (limit > workspace->limit)
    {
      GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
    }

  /* Test on accuracy */

  if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
    {
      GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel",
                 GSL_EBADTOL);
    }

  /* Perform the first integration */

  q (f, a, b, &result0, &abserr0, &resabs0, &resasc0);

  set_initial_result (workspace, result0, abserr0);

  tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));

  if (abserr0 <= 100 * GSL_DBL_EPSILON * resabs0 && abserr0 > tolerance)
    {
      *result = result0;
      *abserr = abserr0;

      GSL_ERROR ("cannot reach tolerance because of roundoff error"
                 "on first attempt", GSL_EROUND);
    }
  else if ((abserr0 <= tolerance && abserr0 != resasc0) || abserr0 == 0.0)
    {
      *result = result0;
      *abserr = abserr0;

      return GSL_SUCCESS;
    }
  else if (limit == 1)
    {
      *result = result0;
      *abserr = abserr0;

      GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER);
    }

  /* Initialization */

  initialise_table (&table);
  append_table (&table, result0);

  area = result0;
  errsum = abserr0;

  res_ext = result0;
  err_ext = GSL_DBL_MAX;

  positive_integrand = test_positivity (result0, resabs0);

  iteration = 1;

  do
    {
      size_t current_level;
      double a1, b1, a2, b2;
      double a_i, b_i, r_i, e_i;
      double area1 = 0, area2 = 0, area12 = 0;
      double error1 = 0, error2 = 0, error12 = 0;
      double resasc1, resasc2;
      double resabs1, resabs2;
      double last_e_i;

      /* Bisect the subinterval with the largest error estimate */

      retrieve (workspace, &a_i, &b_i, &r_i, &e_i);

      current_level = workspace->level[workspace->i] + 1;

      a1 = a_i;
      b1 = 0.5 * (a_i + b_i);
      a2 = b1;
      b2 = b_i;

      iteration++;

      q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);
      q (f, a2, b2, &area2, &error2, &resabs2, &resasc2);

      area12 = area1 + area2;
      error12 = error1 + error2;
      last_e_i = e_i;

      /* Improve previous approximations to the integral and test for
         accuracy.

         We write these expressions in the same way as the original
         QUADPACK code so that the rounding errors are the same, which
         makes testing easier. */

      errsum = errsum + error12 - e_i;
      area = area + area12 - r_i;

      tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));

      if (resasc1 != error1 && resasc2 != error2)
        {
          double delta = r_i - area12;

          if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)
            {
              if (!extrapolate)
                {
                  roundoff_type1++;
                }
              else
                {
                  roundoff_type2++;
                }
            }
          if (iteration > 10 && error12 > e_i)
            {
              roundoff_type3++;
            }
        }

      /* Test for roundoff and eventually set error flag */

      if (roundoff_type1 + roundoff_type2 >= 10 || roundoff_type3 >= 20)
        {
          error_type = 2;       /* round off error */
        }

      if (roundoff_type2 >= 5)
        {
          error_type2 = 1;
        }

      /* set error flag in the case of bad integrand behaviour at
         a point of the integration range */

      if (subinterval_too_small (a1, a2, b2))
        {
          error_type = 4;
        }

      /* append the newly-created intervals to the list */

      update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);

      if (errsum <= tolerance)
        {
          goto compute_result;
        }

      if (error_type)
        {
          break;
        }

      if (iteration >= limit - 1)
        {
          error_type = 1;
          break;
        }

      if (iteration == 2)       /* set up variables on first iteration */
        {
          error_over_large_intervals = errsum;
          ertest = tolerance;
          append_table (&table, area);
          continue;
        }

      if (disallow_extrapolation)
        {
          continue;
        }

      error_over_large_intervals += -last_e_i;

      if (current_level < workspace->maximum_level)
        {
          error_over_large_intervals += error12;
        }

      if (!extrapolate)
        {
          /* test whether the interval to be bisected next is the
             smallest interval. */

          if (large_interval (workspace))
            continue;

          extrapolate = 1;
          workspace->nrmax = 1;
        }

      if (!error_type2 && error_over_large_intervals > ertest)
        {
          if (increase_nrmax (workspace))
            continue;
        }

      /* Perform extrapolation */

      append_table (&table, area);

      qelg (&table, &reseps, &abseps);

      ktmin++;

      if (ktmin > 5 && err_ext < 0.001 * errsum)
        {
          error_type = 5;
        }

      if (abseps < err_ext)
        {
          ktmin = 0;
          err_ext = abseps;
          res_ext = reseps;
          correc = error_over_large_intervals;
          ertest = GSL_MAX_DBL (epsabs, epsrel * fabs (reseps));
          if (err_ext <= ertest)
            break;
        }

      /* Prepare bisection of the smallest interval. */

      if (table.n == 1)
        {
          disallow_extrapolation = 1;
        }

      if (error_type == 5)
        {
          break;
        }

      /* work on interval with largest error */

      reset_nrmax (workspace);
      extrapolate = 0;
      error_over_large_intervals = errsum;

    }
  while (iteration < limit);

  *result = res_ext;
  *abserr = err_ext;

  if (err_ext == GSL_DBL_MAX)
    goto compute_result;

  if (error_type || error_type2)
    {
      if (error_type2)
        {
          err_ext += correc;
        }

      if (error_type == 0)
        error_type = 3;

      if (res_ext != 0.0 && area != 0.0)
        {
          if (err_ext / fabs (res_ext) > errsum / fabs (area))
            goto compute_result;
        }
      else if (err_ext > errsum)
        {
          goto compute_result;
        }
      else if (area == 0.0)
        {
          goto return_error;
        }
    }

  /*  Test on divergence. */

  {
    double max_area = GSL_MAX_DBL (fabs (res_ext), fabs (area));

    if (!positive_integrand && max_area < 0.01 * resabs0)
      goto return_error;
  }

  {
    double ratio = res_ext / area;

    if (ratio < 0.01 || ratio > 100.0 || errsum > fabs (area))
      error_type = 6;
  }

  goto return_error;

compute_result:

  *result = sum_results (workspace);
  *abserr = errsum;

return_error:

  if (error_type > 2)
    error_type--;



  if (error_type == 0) 
    {
      return GSL_SUCCESS;
    }
  else if (error_type == 1)
    {
      GSL_ERROR ("number of iterations was insufficient", GSL_EMAXITER);
    }
  else if (error_type == 2)
    {
      GSL_ERROR ("cannot reach tolerance because of roundoff error",
                 GSL_EROUND);
    }
  else if (error_type == 3)
    {
      GSL_ERROR ("bad integrand behavior found in the integration interval",
                 GSL_ESING);
    }
  else if (error_type == 4)
    {
      GSL_ERROR ("roundoff error detected in the extrapolation table",
                 GSL_EROUND);
    }
  else if (error_type == 5)
    {
      GSL_ERROR ("integral is divergent, or slowly convergent",
                 GSL_EDIVERGE);
    }
  else
    {
      GSL_ERROR ("could not integrate function", GSL_EFAILED);
    }

}
Exemplo n.º 28
0
/*
** main program:
** initialise, timestep loop, finalise
*/
int main(int argc, char* argv[])
{
    char * final_state_file = NULL;
    char * av_vels_file = NULL;
    char * param_file = NULL;

    accel_area_t accel_area;

    param_t  params;              /* struct to hold parameter values */
    speed_t* cells     = NULL;    /* grid containing fluid densities */
    speed_t* tmp_cells = NULL;    /* scratch space */
    int*     obstacles = NULL;    /* grid indicating which cells are blocked */
    double*  av_vels   = NULL;    /* a record of the av. velocity computed for each timestep */

    int    ii;                    /*  generic counter */
    struct timeval timstr;        /* structure to hold elapsed time */
    struct rusage ru;             /* structure to hold CPU time--system and user */
    double tic,toc;               /* floating point numbers to calculate elapsed wallclock time */
    double usrtim;                /* floating point number to record elapsed user CPU time */
    double systim;                /* floating point number to record elapsed system CPU time */

    parse_args(argc, argv, &final_state_file, &av_vels_file, &param_file);

    initialise(param_file, &accel_area, &params, &cells, &tmp_cells, &obstacles, &av_vels);

    /* iterate for max_iters timesteps */
    gettimeofday(&timstr,NULL);
    tic=timstr.tv_sec+(timstr.tv_usec/1000000.0);

    for (ii = 0; ii < params.max_iters; ii++)
    {
      /** timestep(params, accel_area, cells, tmp_cells, obstacles);
        av_vels[ii] = av_velocity(params, cells, obstacles);*/

        av_vels[ii] = timestep(params, accel_area, cells, tmp_cells, obstacles);

        #ifdef DEBUG
        printf("==timestep: %d==\n", ii);
        printf("av velocity: %.12E\n", av_vels[ii]);
        printf("tot density: %.12E\n", total_density(params, cells));
        #endif
    }

    gettimeofday(&timstr,NULL);
    toc=timstr.tv_sec+(timstr.tv_usec/1000000.0);
    getrusage(RUSAGE_SELF, &ru);
    timstr=ru.ru_utime;
    usrtim=timstr.tv_sec+(timstr.tv_usec/1000000.0);
    timstr=ru.ru_stime;
    systim=timstr.tv_sec+(timstr.tv_usec/1000000.0);

    printf("==done==\n");
    printf("Reynolds number:\t\t%.12E\n", calc_reynolds(params,cells,obstacles));
    printf("Elapsed time:\t\t\t%.6f (s)\n", toc-tic);
    printf("Elapsed user CPU time:\t\t%.6f (s)\n", usrtim);
    printf("Elapsed system CPU time:\t%.6f (s)\n", systim);

    write_values(final_state_file, av_vels_file, params, cells, obstacles, av_vels);
    finalise(&cells, &tmp_cells, &obstacles, &av_vels);

    return EXIT_SUCCESS;
}
Exemplo n.º 29
0
MD_MIDIFile::MD_MIDIFile(void) 
{ 
	initialise();
}
Exemplo n.º 30
0
static int
qag (const gsl_function * f,
     const double a, const double b,
     const double epsabs, const double epsrel,
     const size_t limit,
     gsl_integration_workspace * workspace,
     double *result, double *abserr,
     gsl_integration_rule * q)
{
  double area, errsum;
  double result0, abserr0, resabs0, resasc0;
  double tolerance;
  size_t iteration = 0;
  int roundoff_type1 = 0, roundoff_type2 = 0, error_type = 0;

  double round_off;     

  /* Initialize results */

  initialise (workspace, a, b);

  *result = 0;
  *abserr = 0;

  if (limit > workspace->limit)
    {
      GSL_ERROR ("iteration limit exceeds available workspace", GSL_EINVAL) ;
    }

  if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
    {
      GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel",
                 GSL_EBADTOL);
    }

  /* perform the first integration */

  q (f, a, b, &result0, &abserr0, &resabs0, &resasc0);

  set_initial_result (workspace, result0, abserr0);

  /* Test on accuracy */

  tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));

  /* need IEEE rounding here to match original quadpack behavior */

  round_off = GSL_COERCE_DBL (50 * GSL_DBL_EPSILON * resabs0);

  if (abserr0 <= round_off && abserr0 > tolerance)
    {
      *result = result0;
      *abserr = abserr0;

      GSL_ERROR ("cannot reach tolerance because of roundoff error "
                 "on first attempt", GSL_EROUND);
    }
  else if ((abserr0 <= tolerance && abserr0 != resasc0) || abserr0 == 0.0)
    {
      *result = result0;
      *abserr = abserr0;

      return GSL_SUCCESS;
    }
  else if (limit == 1)
    {
      *result = result0;
      *abserr = abserr0;

      GSL_ERROR ("a maximum of one iteration was insufficient", GSL_EMAXITER);
    }

  area = result0;
  errsum = abserr0;

  iteration = 1;

  do
    {
      double a1, b1, a2, b2;
      double a_i, b_i, r_i, e_i;
      double area1 = 0, area2 = 0, area12 = 0;
      double error1 = 0, error2 = 0, error12 = 0;
      double resasc1, resasc2;
      double resabs1, resabs2;

      /* Bisect the subinterval with the largest error estimate */

      retrieve (workspace, &a_i, &b_i, &r_i, &e_i);

      a1 = a_i; 
      b1 = 0.5 * (a_i + b_i);
      a2 = b1;
      b2 = b_i;

      q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);
      q (f, a2, b2, &area2, &error2, &resabs2, &resasc2);

      area12 = area1 + area2;
      error12 = error1 + error2;

      errsum += (error12 - e_i);
      area += area12 - r_i;

      if (resasc1 != error1 && resasc2 != error2)
        {
          double delta = r_i - area12;

          if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)
            {
              roundoff_type1++;
            }
          if (iteration >= 10 && error12 > e_i)
            {
              roundoff_type2++;
            }
        }

      tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));

      if (errsum > tolerance)
        {
          if (roundoff_type1 >= 6 || roundoff_type2 >= 20)
            {
              error_type = 2;   /* round off error */
            }

          /* set error flag in the case of bad integrand behaviour at
             a point of the integration range */

          if (subinterval_too_small (a1, a2, b2))
            {
              error_type = 3;
            }
        }

      update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);

      retrieve (workspace, &a_i, &b_i, &r_i, &e_i);

      iteration++;

    }
  while (iteration < limit && !error_type && errsum > tolerance);

  *result = sum_results (workspace);
  *abserr = errsum;

  if (errsum <= tolerance)
    {
      return GSL_SUCCESS;
    }
  else if (error_type == 2)
    {
      GSL_ERROR ("roundoff error prevents tolerance from being achieved",
                 GSL_EROUND);
    }
  else if (error_type == 3)
    {
      GSL_ERROR ("bad integrand behavior found in the integration interval",
                 GSL_ESING);
    }
  else if (iteration == limit)
    {
      GSL_ERROR ("maximum number of subdivisions reached", GSL_EMAXITER);
    }
  else
    {
      GSL_ERROR ("could not integrate function", GSL_EFAILED);
    }
}