예제 #1
0
static void *client_thread_main(void *arg){
  /*
   * The *arg is a private copy of the ce. This function must
   * free(ce) it when it is finished, but it must _not_ try to
   * delete anything else from the ce.
   * We used to set the cancellation state to DISABLED and then renabled
   * after the loop in the loop, to avoid cancelling the thread while
   * it holds a mutex locked. But this not appropriate if we let the
   * g.client_queue_read_timeout_ms be a configurable parameter: the user
   * can set this very high, and the thread would not be canceled until
   * that timer expires. [The alternative would be to write a wrapper
   * over connqueue_rcv() that disbales the cancellation and calls
   * connqueue_rcv() with a short (i.e., 1 second) wait time
   * and retries any number of times.]
   *
   * See cleanup().
   */
  /* int cancel_state; */
  /* int status = 0; */
  struct conn_element_st *ce = (struct conn_element_st*)arg;

  pthread_cleanup_push(cleanup, arg);

  while((get_quit_flag() == 0) && (conn_element_get_exit_flag(ce) == 0)){
    pthread_testcancel();

    /*
     * status = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
     */

    periodic(ce);
    loop(ce);

    /*
     * status = pthread_setcancelstate(cancel_state, &cancel_state);
     */
  }

  pthread_cleanup_pop(1);

  return(NULL);
}
예제 #2
0
void Robot::OperatorControl(void)
{
  printf("Operator Mode");

  while(IsOperatorControl() && IsEnabled())
  {
    /* Collect sensor data */
    periodic();
    
    drive->TankDrive(leftStick, rightStick);
    
    if(lstick->GetRawButton(1))
    {
      shifter->Set(DoubleSolenoid::kForward);
    }
    else
    {
      shifter->Set(DoubleSolenoid::kReverse);
    }
    Wait(0.005);	// wait for a motor update time
  }
}
예제 #3
0
void naive_proceed() {
  ++global_clock;

  auto lap = [](Real ar[NX][NY][NZ],int x, int y, int z) {
    auto ret = periodic(ar, x-1, y, z) + periodic(ar, x+1, y, z)
    + periodic(ar, x, y-1, z) + periodic(ar, x, y+1, z)
    + periodic(ar, x, y, z-1) + periodic(ar, x, y, z+1)
    - 6*ar[x][y][z];
    return ret / dx / dx;
  };

#pragma omp parallel for collapse(2)
  for (int x=0;x<NX;++x) {
    for (int y=0;y<NY;++y) {
      for (int z=0;z<NZ;++z) {
        auto u = U[x][y][z],  v = V[x][y][z];
        auto du_dt = -Fe * u*v*v + Fu*(1-u) + Du * lap(U,x,y,z);
        auto dv_dt =  Fe * u*v*v - Fv*v     + Dv * lap(V,x,y,z);
        U_other[x][y][z] = U[x][y][z] + dt*du_dt;
        V_other[x][y][z] = V[x][y][z] + dt*dv_dt;
      }
    }
  }

  for (int x=0;x<NX;++x) {
    for (int y=0;y<NY;++y) {
      for (int z=0;z<NZ;++z) {
        U[x][y][z]=U_other[x][y][z];
      }
    }
  }
  for (int x=0;x<NX;++x) {
    for (int y=0;y<NY;++y) {
      for (int z=0;z<NZ;++z) {
        V[x][y][z]=V_other[x][y][z];
      }
    }
  }
}
예제 #4
0
inline Timers::id_t Timers::periodic(duration_t period, handler_t handler)
{
  return periodic(period, period, handler);
}
예제 #5
0
inline Timers::id_t Timers::oneshot(duration_t when, handler_t handler)
{
  return periodic(when, std::chrono::milliseconds(0), handler);
}
예제 #6
0
파일: res.c 프로젝트: FSchumacher/openlava
int
main(int argc, char **argv)
{
    static char fname[] = "res/main";
    int nready;
    int maxfd;
    int i;
    char *sp;
    char *pathname = NULL;
    int didSomething = 0;
    char exbuf;

    time_t thisPeriodic, lastPeriodic = 0, timeDiff;


    fd_set rm, wm, em;

    int sbdPty = FALSE;
    char *sbdClHost = NULL;
    ushort sbdClPort = 0;
    char **sbdArgv = NULL;
    int selectError = 0;


    _i18n_init(I18N_CAT_RES);

    saveDaemonDir_(argv[0]);



    for (i=1; i<argc; i++) {
      if (strcmp(argv[i], "-d") == 0 && argv[i+1] != NULL) {
         pathname = argv[i+1];
         putEnv("LSF_ENVDIR",pathname);
         break;
      }
    }

    if (pathname == NULL) {
	if ((pathname = getenv("LSF_ENVDIR")) == NULL)
	    pathname = LSETCDIR;
    }


    if (argc > 1) {
        if (!strcmp(argv[1],"-V")) {
            fputs(_LS_VERSION_, stderr);
            exit(0);
        }
    }



    if ((ls_readconfenv(resConfParams, NULL) < 0) ||
        (initenv_(resParams, pathname) < 0) ) {
        if ((sp = getenv("LSF_LOGDIR")) != NULL)
            resParams[LSF_LOGDIR].paramValue = sp;
        ls_openlog("res", resParams[LSF_LOGDIR].paramValue, (debug > 1),
                   resParams[LSF_LOG_MASK].paramValue);
        ls_syslog(LOG_ERR, I18N_FUNC_S_FAIL_MM, fname, "initenv_",
            pathname);
        ls_syslog(LOG_ERR, I18N_Exiting);
        exit(-1);
    }



    restart_argc = argc;
    restart_argv = argv;
    for (i=1; i<argc; i++) {
	if (strcmp(argv[i], "-d") == 0 && argv[i+1] != NULL) {
	    pathname = argv[i+1];
	    i++;
	    continue;
	}

	if (strcmp(argv[i], "-1") == 0) {
	    debug = 1;
	    continue;
	}

	if (strcmp(argv[i], "-2") == 0) {
	    debug = 2;
	    continue;
	}


	if (strcmp(argv[i], "-PTY_FIX") == 0) {
	    printf("PTY_FIX");
	    exit(0);
	}


	if ( (strcmp(argv[i], "-j") == 0) && (argv[i+1] != NULL) ) {
	    lsbJobStarter = argv[++i];
	    continue;
	}

	if (strcmp(argv[i], "-P") == 0) {
	    sbdPty = TRUE;
	    continue;
	}

	if (strcmp(argv[i], "-i") == 0) {
	    sbdFlags |= SBD_FLAG_STDIN;
	    continue;
	}

	if (strcmp(argv[i], "-o") == 0) {
	    sbdFlags |= SBD_FLAG_STDOUT;
	    continue;
	}

	if (strcmp(argv[i], "-e") == 0) {
	    sbdFlags |= SBD_FLAG_STDERR;
	    continue;
	}

	if (strcmp(argv[i], "-m") == 0 && argv[i+1] != NULL) {
	    sbdClHost = argv[i+1];
	    i++;
	    sbdMode = TRUE;
	    continue;
	}

	if (strcmp(argv[i], "-p") == 0 && argv[i+1] != NULL) {
	    sbdClPort = atoi(argv[i+1]);
	    i++;
	    sbdMode = TRUE;
	    continue;
	}


	if (argv[i][0] != '-') {
	    sbdMode = TRUE;
	    sbdArgv = argv + i;
	    break;
	}

        usage(argv[0]);
    }

    if (sbdMode) {

	if (sbdClHost == NULL || sbdArgv == NULL) {
	    usage(argv[0]);
	    exit(-1);
	}
	if (sbdClPort) {
	    sbdFlags |= SBD_FLAG_TERM;
	} else {

	    sbdFlags |= SBD_FLAG_STDIN | SBD_FLAG_STDOUT | SBD_FLAG_STDERR;
	}
    } else {


	if (debug < 2)
	    for (i = sysconf(_SC_OPEN_MAX) ; i >= 0 ; i--)
		close(i);
    }


    if (resParams[LSF_SERVERDIR].paramValue == NULL) {
	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, (debug > 1),
				   resParams[LSF_LOG_MASK].paramValue);
	ls_syslog(LOG_ERR, _i18n_msg_get(ls_catd , NL_SETN, 5001,
	    "LSF_SERVERDIR not defined in %s/lsf.conf: %M; res exiting"), /* catgets 5001 */
	    pathname);
	resExit_(-1);
    }


    if (! debug && resParams[LSF_RES_DEBUG].paramValue != NULL) {
	debug = atoi(resParams[LSF_RES_DEBUG].paramValue);
	if (debug <= 0)
	    debug = 1;
    }


    getLogClass_(resParams[LSF_DEBUG_RES].paramValue,
                 resParams[LSF_TIME_RES].paramValue);


    if (getuid() == 0 && debug) {
        if (sbdMode)  {
	   debug = 0;
	} else {
          ls_openlog("res", resParams[LSF_LOGDIR].paramValue, FALSE,
		   resParams[LSF_LOG_MASK].paramValue);
          ls_syslog(LOG_ERR, I18N(5005,"Root cannot run RES in debug mode ... exiting."));/*catgets 5005 */
	   exit(-1);
	}
    }

    if (debug > 1)
	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, TRUE, "LOG_DEBUG");
    else {
 	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, FALSE,
		   resParams[LSF_LOG_MASK].paramValue);
    }
    if (logclass & (LC_TRACE | LC_HANG))
        ls_syslog(LOG_DEBUG, "%s: logclass=%x", fname, logclass);

    ls_syslog(LOG_DEBUG, "%s: LSF_SERVERDIR=%s", fname, resParams[LSF_SERVERDIR].paramValue);



    init_res();
    initSignals();

    periodic(0);



    if (sbdMode) {
	lsbJobStart(sbdArgv, sbdClPort, sbdClHost, sbdPty);
    }

    maxfd = FD_SETSIZE;


    for (;;) {
        struct timeval *timep;
        struct timeval timeout;
loop:
        didSomething = 0;

        for (i = 0; i < child_cnt; i++) {
            if (children[i]->backClnPtr == NULL
                 && !FD_IS_VALID(conn2NIOS.sock.fd)
                 && children[i]->running == 0) {
                delete_child (children[i]);
            }
        }

	if (logclass & LC_TRACE) {
	    ls_syslog(LOG_DEBUG,"\
%s: %s Res child_res=<%d> child_go=<%d> child_cnt=<%d> client_cnt=<%d>",
		      fname, ((child_res) ? "Application" : "Root") ,
		      child_res, child_go, child_cnt, client_cnt);
            if (child_cnt == 1 && children != NULL && children[0] != NULL) {
                dumpChild(children[0], 1, "in main()");
            }
	}

        if (child_res && child_go && child_cnt == 0 && client_cnt == 0)  {


            if (debug > 1)
		printf (" \n Child <%d> Retired! \n", (int)getpid());

	    if (logclass & LC_TRACE) {
		ls_syslog(LOG_DEBUG,"\
%s: Application Res is exiting.....", fname);
	    }


	    millisleep_(5000);


	    if (sbdMode) {

		close(1);
		close(2);
		exit(lastChildExitStatus);
            }
	    resExit_(EXIT_NO_ERROR);
        }
/** \brief Return a ParameterList filled with all valid parameters,
 *         documentation strings, default values, and validators
 */
RCP< const ParameterList > getValidParameters() 
{
  static RCP< const ParameterList > result;

  if ( result.is_null() )
  {

    // Allocate a new non-const ParameterList
    ParameterList* plist = new ParameterList;

    ////////////////////////////////////////////////////////////////
    // "comm dimensions" parameter applies to MDComm, MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    RCP< EnhancedNumberValidator< int > > axisCommNumber =
      rcp(new EnhancedNumberValidator< int >());
    axisCommNumber->setMin(-1);

    RCP< const EnhancedNumberValidator< int > > constAxisCommNumber =
      rcp_const_cast< EnhancedNumberValidator< int > >(axisCommNumber);

    RCP< const ParameterEntryValidator > axisCommValidator =
      rcp< const ParameterEntryValidator >
      (new ArrayNumberValidator< int >(constAxisCommNumber));

    Array< int > commDims(1);
    commDims[0] = -1;
    plist->set("comm dimensions",
               commDims, 
               "An array of ints that specifies the size of the "
               "MDComm along each axis. If the 'dimensions' parameter is "
               "present, then the length of that parameter determines the "
               "number of dimensions.  If 'dimensions' is not present, then "
               "the length of this parameter determines the number of "
               "dimensions.  If the length of this parameter is shorter than "
               "the number of dimensions, then this parameter is extended with "
               "values of -1.  A negative value tells Domi to fill in a "
               "logical value based on the total number of processors.",
               axisCommValidator);

    ////////////////////////////////////////////////////////////////
    // "periodic" parameter applies to MDComm, MDMap, and MDVector
    ////////////////////////////////////////////////////////////////
    RCP< EnhancedNumberValidator< int > > periodicNumber =
      rcp(new EnhancedNumberValidator< int >());
    periodicNumber->setMin(0);
    periodicNumber->setMax(1);

    RCP< const EnhancedNumberValidator< int > > constPeriodicNumber =
      rcp_const_cast< EnhancedNumberValidator< int > >(periodicNumber);

    RCP< const ParameterEntryValidator > periodicValidator =
      rcp< const ParameterEntryValidator >
      //(new ScalarOrArrayNumberValidator< int >(constPeriodicNumber));
      (new ArrayNumberValidator< int >(constPeriodicNumber));

    //int periodic = 0;
    Array< int > periodic(1);
    periodic[0] = 0;
    plist->set("periodic",
               periodic,
               "A scalar or an array of int flags specifying whether axes are "
               "periodic. If a scalar is given, then all axes share that "
               "periodicity flag.  If an array is given and it is shorter than "
               "the length of commDims array, then the unspecified "
               "entries are given a default value of zero (not "
               "periodic).",
               periodicValidator);

    ////////////////////////////////////////////////////////////////
    // "dimensions" parameter applies to MDComm, MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    RCP< EnhancedNumberValidator< dim_type > > dimensionNumber =
      rcp(new EnhancedNumberValidator< dim_type >());
     dimensionNumber->setMin(0);

    RCP< const EnhancedNumberValidator< dim_type > > constDimensionNumber =
    	rcp_const_cast< EnhancedNumberValidator< dim_type > >(dimensionNumber);

     RCP< const ParameterEntryValidator > dimensionValidator =
     	rcp< const ParameterEntryValidator >
     	(new ArrayNumberValidator< dim_type >(constDimensionNumber));

    Array< dim_type > dimensions(1);
    dimensions[0] = 0;
    plist->set("dimensions",
               dimensions,
               "An array of ordinals specifying the global dimensions of "
               "the MDMap. If present for the MDComm constructor, the length "
               "of this parameter will set the number of dimensions.  If not "
               "present for the MDComm constructor, the number of dimensions "
               "will be set by the length of the 'axis comm szies' parameter.",
               dimensionValidator);

    // Both boundary pad and communication pad use the same number and
    // array validators, so just construct one EnhancedNumberValidator
    // and one ArrayNumberValidator.
    int          pad = 0;
    Array< int > pads;

    RCP< EnhancedNumberValidator< int > > padNumberValidator =
      rcp(new EnhancedNumberValidator< int >());
    padNumberValidator->setMin(0);

    RCP< const EnhancedNumberValidator< int > > constPadNumberValidator =
      rcp_const_cast< EnhancedNumberValidator< int > >(padNumberValidator);

    RCP< const ParameterEntryValidator > padArrayValidator =
      rcp< const ParameterEntryValidator >
      (new ArrayNumberValidator< int >(constPadNumberValidator));

    ////////////////////////////////////////////////////////////////
    // "boundary pad size" parameter applies to MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("boundary pad size",
               pad,
               "An int that specifies the boundary padding size for all axes.",
               padNumberValidator);

    ////////////////////////////////////////////////////////////////
    // "boundary pad sizes" parameter applies to MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("boundary pad sizes",
               pads,
               "An array of ints specifying the size of the boundary padding "
               "along each axis. All unspecified entries take the value of "
               "the 'boundary pad size' parameter, which defaults to zero.",
               padArrayValidator);

    ////////////////////////////////////////////////////////////////
    // "communication pad size" parameter applies to MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("communication pad size",
               pad,
               "An int that specifies the communication padding size for all "
               "axes.",
               padNumberValidator);

    ////////////////////////////////////////////////////////////////
    // "communication pad sizes" parameter applies to MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("communication pad sizes",
               pads,
               "An array of ints specifying the size of the communication "
               "padding along each axis. All unspecified entries take the "
               "value of the 'communication pad size' parameter, which "
               "defaults to zero.",
               padArrayValidator);

    ////////////////////////////////////////////////////////////////
    // "layout" parameter applies to MDMap and MDVector
    ////////////////////////////////////////////////////////////////
    string layout = "Default";

    Array< string >
      layoutOpts(tuple(string("C Order"),
                       string("Fortran Order"),
                       string("Row Major"),
                       string("Column Major"),
                       string("Last Index Fastest"),
                       string("First Index Fastest"),
                       string("Default")));

    Array< string >
      layoutDocs(tuple(string("C storage order (last index varies "
                              "fastest)"),
                       string("Fortran storage order (first index "
                              "varies fastest)"),
                       string("Row major storage order (last index "
                              "varies fastest)"),
                       string("Column major storage order (first "
                              "index varies fastest)"),
                       string("Last index varies fastest"),
                       string("First index varies fastest"),
                       string("Fortran storage order")));

    Array< int > layoutVals(tuple(0, 1, 0, 1, 0, 1, 1));

    RCP< const ParameterEntryValidator > layoutValidator =
      rcp(new StringToIntegralParameterEntryValidator< int >
                   (layoutOpts(),
                    layoutDocs(),
                    layoutVals(),
                    string("Default"),
                    false));

    plist->set("layout",
               layout,
               "A string indicating how the data is laid out in memory. "
               "Default is currently set to Fortran order.",
               layoutValidator);

    ////////////////////////////////////////////////////////////////
    // "leading dimension" parameter applies to MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("leading dimension",
               pad,
               "Use the 'leading dimension' parameter to specify multiple "
               "degrees of freedom at each MDMap index.  This increases the "
               "dimension of the MDVector by one, and the new degrees of "
               "freedom are accessed with the first index.",
               padNumberValidator);

    ////////////////////////////////////////////////////////////////
    // "trailing dimension" parameter applies to MDVector
    ////////////////////////////////////////////////////////////////
    plist->set("trailing dimension",
               pad,
               "Use the 'trailing dimension' parameter to specify multiple "
               "degrees of freedom at each MDMap index.  This increases the "
               "dimension of the MDVector by one, and the new degrees of "
               "freedom are accessed with the last index.",
               padNumberValidator);

    // ParameterList construction is done, so wrap it with an RCP<
    // const ParameterList >
    result.reset(plist);
  }

  return result; 
}
SearchEngine::SearchEngine()
{
	//read book records from book.txt and take in 10 pipe separated fields 
	ifstream book("book.txt");
      while(!getline(book, callNumber,'|').eof())
      {
        getline(book, title,'|');
        getline(book, subjects,'|');
        getline(book, author,'|');
        getline(book, description,'|');
        getline(book, publisher,'|');
        getline(book, city,'|');
        getline(book, year,'|');
        getline(book, series,'|');
        getline(book, notes, '\n');
            Book* objBook = new Book(callNumber, title, subjects, author, description, publisher, city, year, series, notes);
            CardCatalog.push_back(objBook);
      }
      book.close();
      
      //read periodic records from periodic.txt and take in 12 pipe separated fields
      ifstream periodic("periodic.txt");
      while(!getline(periodic, periodic_callNumber,'|').eof())
      {
        getline(periodic, periodic_title,'|');
        getline(periodic, periodic_subjects,'|');
        getline(periodic, periodic_author,'|');
        getline(periodic, periodic_description,'|');
        getline(periodic, periodic_publisher,'|');
        getline(periodic, periodic_publishing_history,'|');
        getline(periodic, periodic_series,'|');
        getline(periodic, periodic_notes,'|');
        getline(periodic, periodic_related_titles,'|');
        getline(periodic, periodic_other_forms_of_title,'|');
        getline(periodic, periodic_govt_doc_number, '\n');
            Periodic* objPeriodic = new Periodic(periodic_callNumber, periodic_title, periodic_subjects, periodic_author, 
            periodic_description, periodic_publisher, periodic_publishing_history, periodic_series, periodic_notes, 
            periodic_related_titles, periodic_other_forms_of_title, periodic_govt_doc_number);
            CardCatalog.push_back(objPeriodic);

      }
      periodic.close();
      
      //read video records from video.txt and take in 8 pipe separated fields
      ifstream video("video.txt");
      while(!getline(video, video_callNumber,'|').eof())
      {
        getline(video, video_title,'|');
        getline(video, video_subjects,'|');
        getline(video, video_description,'|');
        getline(video, video_distributor,'|');
        getline(video, video_notes,'|');
        getline(video, video_series,'|');
        getline(video, video_label, '\n');
            Video* objVideo = new Video(video_callNumber, video_title, video_subjects, video_description, 
            video_distributor, video_notes, video_series, video_label);
            CardCatalog.push_back(objVideo);
	
      }
      video.close();
      
      //read film records from periodic.txt and take in 6 pipe separated fields
      ifstream film("film.txt");
      while(!getline(film, film_callNumber,'|').eof())
      {
        getline(film, film_title,'|');
        getline(film, film_subjects,'|');
        getline(film, film_director,'|');
        getline(film, film_notes,'|');
        getline(film, film_year, '\n');
            Film* objFilm = new Film(film_callNumber, film_title, film_subjects, film_director, film_notes, film_year);
            CardCatalog.push_back(objFilm);

      }
      film.close();
}
예제 #9
0
/*
 * UtilsSuite.cpp
 *
 *  Created on: 29 Sep 2012
 *      Author: Patrick
 */


#include "catch.hpp"

#include "ColourU.h"

TEST_CASE("Utils/ColourPeriodic", "tests the output of the periodic function")
{

    CHECK( periodic(0) == 1.0 );
    CHECK( abs(periodic(0.5)) < 1e-10 );
    CHECK( periodic(1) == 1.0 );

}

TEST_CASE("Utils/ColourRainbow", "tests the colour output")
{

    CHECK(rainbowColour(0) == 46026);
    CHECK(rainbowColour(250) == 16665396);
    CHECK(rainbowColour(500) == 46026);
}
예제 #10
0
void get_solution_at(int t, int x, int y, int z, Real &u, Real &v) {
  if(global_clock > t) fill_initial_condition();
  while(global_clock < t) naive_proceed();
  u = periodic(U,x,y,z);
  v = periodic(V,x,y,z);
}
예제 #11
0
파일: App.cpp 프로젝트: StandardLaw/opentxs
void App::Init_Periodic()
{
    auto storage = storage_;
    auto now = std::time(nullptr);

    Schedule(
        nym_publish_interval_,
        [storage]()-> void{
            NymLambda nymLambda([](const serializedCredentialIndex& nym)->
                void { App::Me().DHT().Insert(nym); });
            storage->MapPublicNyms(nymLambda);
        },
        now);

    Schedule(
        nym_refresh_interval_,
        [storage]()-> void{
            NymLambda nymLambda([](const serializedCredentialIndex& nym)->
            void { App::Me().DHT().GetPublicNym(nym.nymid()); });
            storage->MapPublicNyms(nymLambda);
        },
        (now - nym_refresh_interval_ / 2));

    Schedule(
        server_publish_interval_,
        [storage]()-> void{
            ServerLambda serverLambda([](const proto::ServerContract& server)->
                void { App::Me().DHT().Insert(server); });
            storage->MapServers(serverLambda);
        },
        now);

    Schedule(
        server_refresh_interval_,
        [storage]()-> void{
            ServerLambda serverLambda([](const proto::ServerContract& server)->
                void { App::Me().DHT().GetServerContract(server.id()); });
            storage->MapServers(serverLambda);
        },
        (now - server_refresh_interval_ / 2));

    Schedule(
        unit_publish_interval_,
        [storage]()-> void{
            UnitLambda unitLambda([](const proto::UnitDefinition& unit)->
                void { App::Me().DHT().Insert(unit); });
            storage->MapUnitDefinitions(unitLambda);
        },
        now);

    Schedule(
        unit_refresh_interval_,
        [storage]()-> void{
            UnitLambda unitLambda([](const proto::UnitDefinition& unit)->
                void { App::Me().DHT().GetUnitDefinition(unit.id()); });
            storage->MapUnitDefinitions(unitLambda);
        },
        (now - unit_refresh_interval_ / 2));

    std::thread periodic(&App::Periodic, this);
    periodic.detach();
}
예제 #12
0
void Geometry::MoperatorGeneralBlochFill(Mat A, int b[3][2], int DimPeriod, double k[3], int ih){


	int N[3];
	for(int i=0; i<3; i++) N[i] = gN.x(i);

	double blochbc[3];
	for(int i=0; i<3; i++) blochbc[i] = k[i]*N[i]*h[i];

	int NC = 3, offset = ih*(Nxyzcr()+2);
	int ns, ne;
	double hh;

	int bc[3][2][3]; /* bc[x/y/z direction][lo/hi][Ex/Ey/Ez] */

	dcomp val, magicnum, mucp[2], mulcp[2];
	dcomp cidu_phase, cpidu_phase[2], cpidl_phase[2];



 
  /* set up b ... */
 
	for(int ic=0; ic<3; ic++) for(int j=0; j<2; j++) for(int k=0; k<3; k++)
		bc[ic][j][k] =  b[ic][j]*( k==ic ? -1 :1);

	
	MatGetOwnershipRange(A, &ns, &ne);

for (int itrue = ns; itrue < ne && itrue < 2*Nxyzc(); ++itrue) {

	Point p(itrue, Grid(N, Nc, 2)); p.project(3); int i = p.xyzcr();
	int cp[2], icp[2], cidu, cpidu[2],cpidl[2], cid, cpid[2];
	for(int j=0; j<2;j++){

		cp[j] = (p.c()+1+j) % NC;
		icp[j] = i + (cp[j]-p.c() ) *Nxyz();
		cpidu[j] = cyclic(p, 2-j, N);
		cpidl[j] = cyclic(p, 2-j, N);
		cpid[j] = cyclic(p, 2-j, N);

		cpidu_phase[j] = 1.0;
		cpidl_phase[j] = 1.0;
	}	  
	cidu = cyclic(p, 0, N);
	cid = cyclic(p, 0, N);

	cidu_phase = 1.0;
    
   for(int jr=0; jr<2; jr++) { /* column real/imag parts */
   	int jrd =  (jr-p.r())*NC*Nxyz();            
   	magicnum = (p.r()==jr)*1.0 + (p.r()<jr)*1.0*ComplexI - (p.r()>jr)*1.0* ComplexI; 

//=====================================================================
	Point prow(i, Grid(N,3,2)); prow.project(Nc);
for(int ib=0; ib<2; ib++){


	if(p.x(p.c()) == N[p.c()]-1){
		int per = periodic(p.c(), DimPeriod );
		cidu = per ? (1-N[p.c()])*cid : 0;
		cidu_phase = per? std::exp(ComplexI*blochbc[p.c()]) : bc[p.c()][1][cp[ib]];
	}

	if(p.x(cp[ib]) == 0){
		int per = periodic(cp[ib], DimPeriod );
		cpidl[ib] = per ? (1-N[cp[ib]])*cpid[ib] : 0;
		cpidl_phase[ib] = per ? std::exp(-ComplexI*blochbc[cp[ib]]) : bc[cp[ib]][0][cp[ib]];
	}

        mucp[1-ib] = pmlval(icp[1-ib], N, Npml, h, LowerPML, 1);
      	mulcp[1-ib] = pmlval(icp[1-ib]-cpidl[ib], N, Npml, h, LowerPML, 1);


	double c[4];
        hh = h[p.c()]*h[cp[ib]];
	val = mucp[1-ib] * magicnum /hh; c[1] = val.real();
	val *= cidu_phase; c[0] = -val.real();
	val = cpidl_phase[ib] * mulcp[1-ib] * magicnum/hh; c[3] = -val.real();
	val *= -cidu_phase; c[2] = -val.real();
      

	int dcol[4];
	dcol[0] = cidu; 
	dcol[1] = 0;
	dcol[2] = cidu-cpidl[ib];
	dcol[3] = -cpidl[ib];



	for(int w=0;w<4;w++){
	Point pcol(icp[ib] + jrd+dcol[w], Grid(N,3,2) );
	pcol.project(Nc);	
	if(pcol.c()!=-1) MatSetValue(A, prow.xyzcr()+offset, pcol.xyzcr()+offset, c[w], ADD_VALUES);
	}


	if(p.x(cp[ib]) == N[cp[ib]]-1){
		int per = periodic(cp[ib], DimPeriod );
		cpidu[ib] = per ? (1-N[cp[ib]])*cpid[ib] : 0;
		cpidu_phase[ib] = per? std::exp(ComplexI*blochbc[cp[ib]]) : bc[cp[ib]][1][p.c()];
	}

	if(p.x(cp[ib]) == 0){
		int per = periodic(cp[ib], DimPeriod );
		cpidl[ib] = per ? (1-N[cp[ib]])*cpid[ib] : -cpidu[ib];
		cpidl_phase[ib] = per? std::exp(-ComplexI*blochbc[cp[ib]]) : bc[cp[ib]][0][p.c()];
	}   

     
	hh =  h[cp[ib]]*h[cp[ib]];
	val = -(cpidu_phase[ib] * mucp[1-ib] * magicnum)/hh; c[0] = -val.real();
	val = +( (mucp[1-ib] + mulcp[1-ib]) * magicnum)/hh;c[1] = -val.real();
	val = -(cpidl_phase[ib] * mulcp[1-ib] * magicnum)/hh;c[2] = -val.real();
     
 
	dcol[0] = cpidu[ib]; 
	dcol[1] = 0;
	dcol[2] = -cpidl[ib];

	for(int w=0;w<3;w++){
	Point pcol(i + jrd+dcol[w], Grid(N,3,2) );
	pcol.project(Nc);
	if(pcol.c()!=-1) MatSetValue(A, prow.xyzcr()+offset, pcol.xyzcr()+offset, c[w], ADD_VALUES);
	}

}


    }
  }
}
예제 #13
0
파일: main_m4.cpp 프로젝트: jaycle/pixy
int main(void)
{
	uint16_t major, minor, build;
	char *type;
	int i, res, count, count2;
	volatile uint32_t d;

	// insert a small delay so power supply can stabilize
	for (d=0; d<2500000; d++);

#ifdef KEIL
 	pixyInit(SRAM3_LOC, &LR0[0], sizeof(LR0));
#else
	pixyInit();
#endif

#if 0
	i = 0;
	char *foo;
	while(1)
	{
		foo = new (std::nothrow) char[128];
		if (foo==NULL)
		{
			_DBG("full\n");
			break;
		}
		else
		{
			_DBH32((int)foo); _DBG(" "); _DBH32(i); _DBG("\n");
		}
		i++;
	}
	while(1);
#endif
	// main init of hardware plus a version-dependent number for the parameters that will
	// force a format of parameter between version numbers.  

#ifndef LEGO
	rcs_init();
#endif
	cc_init(g_chirpUsb);
	ser_init();
	exec_init(g_chirpUsb);

#if 0
    exec_addProg(&g_progBlobs);
    ptLoadParams();
    exec_addProg(&g_progPt);
    exec_addProg(&g_progVideo, true);
#if 0
    cam_setMode(CAM_MODE1);
    while(1)
    	periodic();
#endif
#endif

#if 1
	// load programs
	exec_addProg(&g_progBlobs);
#ifndef LEGO
	// need to call this to get the pan/tilt parameters to display.  
	// We can make some properties modal, meaning they are only diaplayed when the program is running.
	// We might want to do this here, but this is good for now.  
	ptLoadParams();	 
	exec_addProg(&g_progPt);
#endif
#if 0
	chaseLoadParams();
	exec_addProg(&g_progChase);
#endif
	exec_addProg(&g_progVideo, true);

#if 1 
	// this code formats if the version has changed
	for (i=0, count=0, count2=0; i<25; i++)
	{
		res = prm_get("fwver", &major, &minor, &build, END);
		if (res>=0 && major==FW_MAJOR_VER && minor==FW_MINOR_VER && build==FW_BUILD_VER)
			count++;
		res = prm_get("fwtype", &type, END);
		if (res>=0 && strcmp(type, FW_TYPE)==0)
			count2++;
	}
	if (count==0 || count2==0)
		prm_format();
#endif

   	// check version
	prm_add("fwver", PRM_FLAG_INTERNAL, "", UINT16(FW_MAJOR_VER), UINT16(FW_MINOR_VER), UINT16(FW_BUILD_VER), END);
	prm_add("fwtype", PRM_FLAG_INTERNAL, "", STRING(FW_TYPE), END);

	exec_loop();
#endif
#if 0
	#define DELAY 1000000
	rcs_setFreq(100);
	rcs_setLimits(0, -200, 200);
	rcs_setLimits(1, -200, 200);
	while(1)
	{
		rcs_setPos(0, 0);
		delayus(DELAY);
		rcs_setPos(0, 500);
		delayus(DELAY);
		rcs_setPos(0, 1000);
		delayus(DELAY);
		rcs_setPos(1, 0);
		delayus(DELAY);
		rcs_setPos(1, 500);
		delayus(DELAY);
		rcs_setPos(1, 1000);
		delayus(DELAY);
	}

#endif
#if 0
	while(1)
	{
		g_chirpUsb->service();
		handleButton();
	}
#endif
}
예제 #14
0
파일: pit_wrap.cpp 프로젝트: iver6/BA
void bx_pit_c::write(Bit32u address, Bit32u dvalue, unsigned io_len)
{
#else
  UNUSED(this_ptr);
#endif  // !BX_USE_PIT_SMF
  Bit8u   value;
  Bit64u my_time_usec = bx_virt_timer.time_usec();
  Bit64u time_passed = my_time_usec-BX_PIT_THIS s.last_usec;
  Bit32u time_passed32 = (Bit32u)time_passed;

  if(time_passed32) {
    periodic(time_passed32);
  }
  BX_PIT_THIS s.last_usec = BX_PIT_THIS s.last_usec + time_passed;

  value = (Bit8u) dvalue;

  BX_DEBUG(("write to port 0x%04x, value = 0x%02x", address, value));

  switch (address) {
    case 0x40: /* timer 0: write count register */
      BX_PIT_THIS s.timer.write(0, value);
      break;

    case 0x41: /* timer 1: write count register */
      BX_PIT_THIS s.timer.write(1, value);
      break;

    case 0x42: /* timer 2: write count register */
      BX_PIT_THIS s.timer.write(2, value);
      break;

    case 0x43: /* timer 0-2 mode control */
      BX_PIT_THIS s.timer.write(3, value);
      break;

    case 0x61:
      BX_PIT_THIS s.speaker_data_on = (value >> 1) & 0x01;
      if (BX_PIT_THIS s.speaker_data_on) {
        DEV_speaker_beep_on((float)(1193180.0 / BX_PIT_THIS get_timer(2)));
      } else {
        DEV_speaker_beep_off();
      }
      /* ??? only on AT+ */
      BX_PIT_THIS s.timer.set_GATE(2, value & 0x01);
      break;

    default:
      BX_PANIC(("unsupported io write to port 0x%04x = 0x%02x", address, value));
  }

  if (time_passed || (BX_PIT_THIS s.last_next_event_time != BX_PIT_THIS s.timer.get_next_event_time())) {
    BX_DEBUG(("RESETting timer"));
    bx_virt_timer.deactivate_timer(BX_PIT_THIS s.timer_handle[0]);
    BX_DEBUG(("deactivated timer"));
    if(BX_PIT_THIS s.timer.get_next_event_time()) {
      bx_virt_timer.activate_timer(BX_PIT_THIS s.timer_handle[0],
                                   (Bit32u)BX_MAX(1,TICKS_TO_USEC(BX_PIT_THIS s.timer.get_next_event_time())),
                                   0);
      BX_DEBUG(("activated timer"));
    }
    BX_PIT_THIS s.last_next_event_time = BX_PIT_THIS s.timer.get_next_event_time();
  }
  BX_DEBUG(("s.last_usec="FMT_LL"d", BX_PIT_THIS s.last_usec));
  BX_DEBUG(("s.timer_id=%d", BX_PIT_THIS s.timer_handle[0]));
  BX_DEBUG(("s.timer.get_next_event_time=%x", BX_PIT_THIS s.timer.get_next_event_time()));
  BX_DEBUG(("s.last_next_event_time=%d", BX_PIT_THIS s.last_next_event_time));

}
예제 #15
0
void system::distribute_data(const bool FLUID, const bool GRADS, const bool NGB)
{
    distribute_data_flag = true;

    ptcl_local.resize(local_n);
    std::vector<vec3> ptcl_pos(local_n);

    // compute integer coordinates for each position
    //
    for (int i = 0; i < (int)local_n; i++)
    {
        ptcl_local[i].local_id = i;
        ptcl_local[i].orig_pos = periodic(ptcl_local[i].orig_pos);
        ptcl_pos[i] = ptcl_local[i].orig_pos;
    }


    // determine domain decomposition
    //
    std::vector<vec3> sample_pos;
    determine_sampling_freq();
    collect_sample_data(sample_pos, ptcl_pos);
    DistributeNew<real, vec3, boundary> distribute(nproc, global_domain);
    if (myproc == 0)
    {
        //			distribute_glb.determine_division(sample_pos);
#if 1
        distribute.determine_division(sample_pos, nproc*32);
#else
        distribute.determine_division(sample_pos, nproc*8);
#endif
    }

    myMPI::Bcast(distribute.tiles, 0, nproc);
    myMPI::Bcast(distribute.procs, 0, nproc);

    compute_proc_domain(distribute.tiles, distribute.procs);

    if (FLUID && GRADS)
        for (int i = 0; i < (int)local_n; i++)
            Wrec_local[i].pos.x = divBi[i];

    int iloc = 0;

    std::vector<Particle> ptcl_send[NMAXPROC];
    std::vector<Particle> ptcl_recv[NMAXPROC];
    std::vector<ParticleFluidStruct> fluid_send[NMAXPROC];
    std::vector<ParticleFluidStruct> fluid_recv[NMAXPROC];
    std::vector<ParticleFluidStructLite> fluidlite_send[NMAXPROC];
    std::vector<ParticleFluidStructLite> fluidlite_recv[NMAXPROC];

#if 0
    std::vector<int> ngb_send[NMAXPROC];
    std::vector<int> ngb_recv[NMAXPROC];
#endif

    std::vector<int> remote_tiles;
    int nremove = 0;
    for (int i = 0; i < (int)local_n; i++)
    {
        remote_tiles.clear();
        proc_tree.root.walk_boundary(boundary(ptcl_pos[i]), remote_tiles, global_domain_size);
        assert(remote_tiles.size() > 0);
        const int proc  = proc_procs[remote_tiles[0]];

        assert(proc >= 0);
        assert(proc < nproc);

        if (proc == myproc && !ptcl_local[i].is_remove())
        {
            std::swap(ptcl_local[i], ptcl_local[iloc]);
            std::swap(ptcl_pos  [i], ptcl_pos  [iloc]);
            if (FLUID)
            {
                std::swap(   U_local[i],    U_local[iloc]);
                std::swap(  dU_local[i],   dU_local[iloc]);
                if (GRADS)
                    std::swap(Wrec_local[i], Wrec_local[iloc]);
            }
            iloc++;
        }
        else if (!ptcl_local[i].is_remove())
        {
            if (FLUID && GRADS)
                fluid_send[proc].push_back(ParticleFluidStruct(ptcl_local[i], U_local[i], dU_local[i], Wrec_local[i]));
            else if (FLUID)
                fluidlite_send[proc].push_back(ParticleFluidStructLite(ptcl_local[i], U_local[i], dU_local[i]));
            else
                ptcl_send[proc].push_back(ptcl_local[i]);
        }
        else
            nremove++;
    }


#if 0
    if (FLUID && GRADS)	myMPI::all2all(fluid_send,     fluid_recv,     myproc, nproc, mpi_debug_flag);
    else if (FLUID    )	myMPI::all2all(fluidlite_send, fluidlite_recv, myproc, nproc, mpi_debug_flag);
    else								myMPI::all2all(ptcl_send,      ptcl_recv,      myproc, nproc, mpi_debug_flag);
#else
    {
        static int nsend[NMAXPROC], nrecv[NMAXPROC];
        if (FLUID && GRADS)	myMPI::all2all<true>(fluid_send,     fluid_recv,     myproc, nproc, 1, nsend, nrecv);
        else if (FLUID    )	myMPI::all2all<true>(fluidlite_send, fluidlite_recv, myproc, nproc, 1, nsend, nrecv);
        else								myMPI::all2all<true>(ptcl_send,      ptcl_recv,      myproc, nproc, 1, nsend, nrecv);
    }
#endif

    int nrecv = 0;
    if (FLUID && GRADS)
        for (int p = 0; p < nproc; p++)
            nrecv += fluid_recv[p].size();
    else if (FLUID)
        for (int p = 0; p < nproc; p++)
            nrecv += fluidlite_recv[p].size();
    else
        for (int p = 0; p < nproc; p++)
            nrecv += ptcl_recv[p].size();

    {
        const int nloc = iloc + nrecv;

        ptcl_local.resize(nloc);
        fit_vec(ptcl_local);
        U_local   .resize(nloc);
        fit_vec(U_local);
        dU_local  .resize(nloc);
        fit_vec(dU_local);
        Wrec_local.resize(nloc);
        fit_vec(Wrec_local);
        divBi    .resize(nloc);
        fit_vec(divBi);
        Wextra_local.resize(nloc);
        fit_vec(Wextra_local);
    }

    for (int p = 0; p < nproc; p++)
        for (size_t q = 0; q < (FLUID ? (GRADS ? fluid_recv[p].size() : fluidlite_recv[p].size()) : ptcl_recv[p].size()); q++)
        {
            assert(p != myproc);

            if (FLUID && GRADS)
            {
                ptcl_local[iloc] = fluid_recv[p][q].p;
                U_local   [iloc] = fluid_recv[p][q].U;
                dU_local  [iloc] = fluid_recv[p][q].dU;
                Wrec_local[iloc] = fluid_recv[p][q].Wrec;
            }
            else if (FLUID)
            {
                ptcl_local[iloc] = fluidlite_recv[p][q].p;
                U_local   [iloc] = fluidlite_recv[p][q].U;
                dU_local  [iloc] = fluidlite_recv[p][q].dU;
            }
            else
                ptcl_local[iloc] = ptcl_recv[p][q];

            assert(!ptcl_local[iloc].is_remove());
            iloc++;
        }

    local_n  = iloc;

    assert(iloc = (int)ptcl_local.size());

    if (FLUID && GRADS)
        for (int i = 0; i < (int)local_n; i++)
        {
            divBi[i] = Wrec_local[i].pos.x;
            Wrec_local[i].pos.x = ptcl_local[i].pos.x;
        }


    unsigned long long nglob, nloc = local_n;
    unsigned long long nvirt_glob;
    virtual_n = nremove;
    MPI_Allreduce(&nloc, &nglob, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);
    MPI_Allreduce(&virtual_n, &nvirt_glob, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);

    unsigned long long local_n_min, local_n_max, local_n_mean;
    MPI_Allreduce(&local_n, &local_n_min,  1, MPI_UNSIGNED_LONG_LONG, MPI_MIN, MPI_COMM_WORLD);
    MPI_Allreduce(&local_n, &local_n_max,  1, MPI_UNSIGNED_LONG_LONG, MPI_MAX, MPI_COMM_WORLD);
    MPI_Allreduce(&local_n, &local_n_mean, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);

    if (myproc == 0)
    {
        fprintf(stderr, "local_n= [min: %llu max: %llu ; mean: %llu ]  global_n= %llu nglob= %llu  remove_n_glob= %llu \n",
                local_n_min, local_n_max, local_n_mean/nproc, global_n, nglob, nvirt_glob);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    assert(nglob == global_n - nvirt_glob);
    global_n = nglob;
    virtual_n = 0;

    sort_local_data();

    // build local tree
    //
    global_domain_size = global_domain.hsize() * 2.0;
    local_tree.clear();
    local_tree.set_domain(
        boundary(
            global_domain.centre() - global_domain.hsize()*1.5,
            global_domain.centre() + global_domain.hsize()*1.5));

    std::vector<Octree::Particle> tree_ptcl(local_n);
    for (int i = 0; i < (int)local_n; i++)
    {
        assert(!ptcl_local[i].is_remove());
        tree_ptcl[i] = Octree::Particle(ptcl_local[i].orig_pos, i);
    }
    local_tree.insert(&tree_ptcl[0], local_n, 0, local_n);

    local_tree.get_leaves();
    local_tree.root.inner_boundary();

    if (NGB)
    {
        if (myproc == 0)
            fprintf(stderr, "---buidling mesh---\n");
        const double t10 = mytimer::get_wtime();
        clear_mesh(false);

        const double t15 = mytimer::get_wtime();
        build_mesh_global();
        double dt_mesh = mytimer::get_wtime() - t15;

        double volume_loc = 0.0;
        {
            std::vector<TREAL> v(local_n);
            for (int i = 0; i < (int)local_n; i++)
            {
                v[i] = cell_local[i].Volume;
                ptcl_local[i].volume_new = v[i];
                ptcl_local[i].local_id = i;
            }
            std::sort(v.begin(), v.end());  // sort volumes from low to high, to avoid roundoff errors
            for (int i = 0; i < (int)local_n; i++)
                volume_loc += v[i];
        }
        extract_ngb_from_mesh();
        clear_mesh(true);
        double dt = mytimer::get_wtime() - t10;

        double volume_glob = 0.0;
        double dt_max = 0.0;
        double dt_mesh_max = 0.0;
        MPI_Allreduce(&volume_loc, &volume_glob,  1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
        MPI_Allreduce(&dt, &dt_max,  1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
        MPI_Allreduce(&dt_mesh, &dt_mesh_max,  1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
        const double volume_exact = global_domain_size.x*global_domain_size.y*global_domain_size.z;
        if (myproc == 0)
        {
            fprintf(stderr, " distribute::build_mesh:[ %g (all %g )  sec ::  %g cells/s/proc/thread ]\n",
                    dt_mesh_max, dt_max,
                    global_n/nproc/dt_mesh_max);
            fprintf(stderr, "   computed_volume= %g  exact_volume= %g diff= %g [ %g ] \n",
                    volume_glob, volume_exact,
                    volume_glob - volume_exact,	(volume_glob - volume_exact)/volume_exact);
        }
    }
}
예제 #16
0
/*!
    wrapping() holds whether it is possible to step the value from the
    highest value to the lowest value and vice versa.

    \sa setWrapping(), QwtDoubleRange::setPeriodic()
    \note The meaning of wrapping is like the wrapping property of QSpinBox,
          but not like it is used in QDial.
*/
bool QwtDial::wrapping() const
{
    return periodic();
}
예제 #17
0
int main (int argc, char **argv)
{
	struct timeval tv;

#ifdef HAVE_LIBKVM
	if (kvm_init()) can_use_kvm = 1;
#endif
	
#ifdef DEBUG
	if (!(debug_file = fopen("debug", "w"))) {
		printf("file debug open error\n");
		exit(0);
	}
#endif
	get_boot_time();
	get_rows_cols(&screen_rows, &screen_cols);
	buf_size = screen_cols + screen_cols/2;
	line_buf = malloc(buf_size);
	if (!line_buf)
		errx(1, "Cannot allocate memory for buffer.");

	curses_init();
	current = &users_list;
	users_init();
	procwin_init();
	subwin_init();
	menu_init();
	signal(SIGINT, int_handler);
	signal(SIGWINCH, winch_handler);  
	//	signal(SIGSEGV, segv_handler);

	print_help();
	update_load();
	current->redraw();
	wnoutrefresh(main_win);
	wnoutrefresh(info_win.wd);
	wnoutrefresh(help_win.wd);
	doupdate();
	
	tv.tv_sec = TIMEOUT;
	tv.tv_usec = 0;
	
	for(;;) {				/* main loop */
#ifndef RETURN_TV_IN_SELECT
		struct timeval before;
		struct timeval after;
#endif
		fd_set rfds;
		int retval;
		
		FD_ZERO(&rfds);
		FD_SET(STDIN_FILENO,&rfds);
#ifdef RETURN_TV_IN_SELECT
		retval = select(1, &rfds, 0, 0, &tv);
		if(retval > 0) {
			int key = read_key();
			key_action(key);
		}
		if (!tv.tv_sec && !tv.tv_usec){
			ticks++;
			periodic();
			tv.tv_sec = TIMEOUT;
		}
#else
		gettimeofday(&before, 0);
		retval = select(1, &rfds, 0, 0, &tv);
		gettimeofday(&after, 0);
		tv.tv_sec -= (after.tv_sec - before.tv_sec);
		if(retval > 0) {
			int key = read_key();
			key_action(key);
		}
		if(tv.tv_sec <= 0) {
			ticks++;
			periodic();
			tv.tv_sec = TIMEOUT;

		}
#endif
		if (size_changed) resize();
	}
}
예제 #18
0
void kern_only_test() {
  // for a simple second test
  // let's just output in a csv our kernels over 2D surfaces
  CovMat<2> eye;
  eye << 1, 0, 
    0, 1;
  
  FeatVec<2> mean;
  mean << 2, 2;

  const std::vector<double> std_params = {1.0, 1.0, 1.0};
  const std::vector<double> lin_params = {-2.0, 1.0, 1.0};

  auto se_kfn = se_generator<2>(std_params);
  auto per_kfn = per_generator<2>(std_params);
  auto lin_kfn = lin_generator<2>(lin_params);
  auto rq_kfn = rq_generator<2>(std_params);

  auto se_x_per = [se_kfn, per_kfn]
    (const FeatVec<2>& a, const FeatVec<2>&b, const CovMat<2>& covar) {
    return se_kfn(a, b, covar) * per_kfn(a, b, covar);
  };
  
  auto se_x_lin = [se_kfn, lin_kfn]
    (const FeatVec<2>& a, const FeatVec<2>&b, const CovMat<2>& covar) {
    return se_kfn(a, b, covar) * lin_kfn(a, b, covar);
  };

  auto per_x_lin = [per_kfn, lin_kfn]
    (const FeatVec<2>& a, const FeatVec<2>&b, const CovMat<2>& covar) {
    return per_kfn(a, b, covar) * lin_kfn(a, b, covar);
  };
  
  auto per_p_lin =  [per_kfn, lin_kfn]
    (const FeatVec<2>& a, const FeatVec<2>&b, const CovMat<2>& covar) {
    return per_kfn(a, b, covar) + lin_kfn(a, b, covar);
  };
  
  auto se_p_per =  [se_kfn, per_kfn]
    (const FeatVec<2>& a, const FeatVec<2>&b, const CovMat<2>& covar) {
    return se_kfn(a, b, covar) + per_kfn(a, b, covar);
  };
  
  
  Kernel<2> squared_exp(se_kfn, mean, eye);
  Kernel<2> periodic(per_kfn, mean, eye);
  Kernel<2> liniar(lin_kfn, mean, eye);
  Kernel<2> rational_quad(rq_kfn, mean, eye);
  Kernel<2> se_times_per(se_x_per, mean, eye);
  Kernel<2> se_times_lin(se_x_lin, mean, eye);
  Kernel<2> per_times_lin(per_x_lin, mean, eye);
  Kernel<2> per_plus_lin(per_p_lin, mean, eye);
  Kernel<2> se_plus_per(se_p_per, mean, eye);

  std::ofstream se_dump("../../data-plots/se.csv");
  std::ofstream per_dump("../../data-plots/per.csv");
  std::ofstream lin_dump("../../data-plots/lin.csv");
  std::ofstream rq_dump("../../data-plots/rq.csv");
  std::ofstream se_x_per_dump("../../data-plots/se_x_per.csv");
  std::ofstream se_x_lin_dump("../../data-plots/se_x_lin.csv");
  std::ofstream per_x_lin_dump("../../data-plots/per_x_lin.csv");
  std::ofstream per_p_lin_dump("../../data-plots/per_p_lin.csv");
  std::ofstream se_p_per_dump("../../data-plots/se_p_per.csv");

    
  test_2d_kernel(squared_exp, se_dump, 100, 4);
  test_2d_kernel(periodic, per_dump, 100, 4);
  test_2d_kernel(liniar, lin_dump, 100, 4);
  test_2d_kernel(rational_quad, rq_dump, 100, 4);
  test_2d_kernel(se_times_per, se_x_per_dump, 100, 4);
  test_2d_kernel(se_times_lin, se_x_lin_dump, 100, 4);
  test_2d_kernel(per_times_lin, per_x_lin_dump, 100, 4);
  test_2d_kernel(per_plus_lin, per_p_lin_dump, 100, 4);
  test_2d_kernel(se_plus_per, se_p_per_dump, 100, 4);

}
예제 #19
0
	void system::read_binary(const char *filename, const int n_files) 
	{
#if 1
		assert(n_files == 1);

		vec3 rmin, rmax;
		if (myproc == 0) 
		{

			FILE *fin; 
			if (!(fin = fopen(filename, "r"))) 
			{
				std::cerr << "Cannot open file " << filename << std::endl;
				exit(-1);
			}

			std::cerr << "proc= " << myproc << " read snapshot: " << filename << std::endl;

			int ival;
			float fval;

#define fload(x) { myfread(&fval, sizeof(float), 1, fin); x = fval; }
#define iload(x) { myfread(&ival, sizeof(int),   1, fin); x = ival;}

			float ftmp;
			int itmp, np0, npx, npy, npz;
			iload(itmp); // 20*4
			assert(itmp == 20*4);
			iload(itmp); // myid
			iload(np0);
			iload(npx);

			union 
			{
				unsigned long long uint_long;
				unsigned int       uint[2];
			} data;
			iload(data.uint[0]);
			iload(data.uint[1]);
			scheduler.tsysU = data.uint_long;

			float courant_No;
			int nglob, nloc, ndim;
			iload(nglob);
			iload(nloc);
			iload(ndim);  
			assert(ndim == 3);
			fload(t_global);
			fload(dt_global);
			iload(iteration);
			fload(courant_No);
			fload(gamma_gas);

			int periodic_on;
			iload(periodic_on);
			assert(periodic_on == -1);
			
			fload(rmin.x);
			fload(rmin.y);
			fload(rmin.z);
			fload(rmax.x);
			fload(rmax.y);
			fload(rmax.z);
			iload(itmp);     // 20*4
			assert(itmp == 20*4);

			ptcl_local.resize(nglob);
			U_local.resize(nglob);
			dU_local.resize(nglob);

			fprintf(stderr, "np =%d   nglob= %d \n", np0, nglob);

			int pc = 0;
			for (int pr = 0; pr < np0; pr++) 
			{
				fprintf(stderr, " p= %d out of %d; nloc= %d\n", pr, np0, nloc);
				for (int i = 0; i < nloc; i++) 
				{
					Particle p;
          p.tend  = t_global;
          p.rung  = 0.0;
          p.new_dt = 0.0;
          p.local_id = i;
					Fluid W(0.0);

					iload(ival);    
					assert(ival == 26*4);
					iload(ival); p.idx = ival;
				
					fload(p.pos.x); 
					fload(p.pos.y);
					fload(p.pos.z);

					p.pos = periodic(p.pos);

					assert(rmin.x <= p.pos.x);
					assert(rmax.x >= p.pos.x);
					assert(rmin.y <= p.pos.y);
					assert(rmax.y >= p.pos.y);
					assert(rmin.z <= p.pos.z);
					assert(rmax.z >= p.pos.z);
          p.orig_pos = p.pos;
          p.pot = 0;


					fload(p.vel.x);
					fload(p.vel.y);
					fload(p.vel.z);
          p.orig_vel = p.vel;
					fload(W[Fluid::DENS]);
					fload(W[Fluid::ETHM]);
					fload(ftmp); // compute_pressure(m.dens, m.ethm));
					fload(p.rmax);     //dump(    (sqr(m.B.x  ) + sqr(m.B.y  ) + sqr(m.B.z  ))*0.5f);
					iload(p.boundary); //				fload(ftmp); //dump(sqrt(sqr(m.vel.x) + sqr(m.vel.y) + sqr(m.vel.z))); 
					fload(W[Fluid::VELX]);
					fload(W[Fluid::VELY]);
					fload(W[Fluid::VELZ]);
					fload(W[Fluid::BX]);
					fload(W[Fluid::BY]);
					fload(W[Fluid::BZ]);
					float h;
					fload(h);
					fload(p.volume);
          p.volume_new = p.volume;
					fload(W[Fluid::PSI]);
					fload(ftmp); //L*divB_i[i]);
					fload(W[Fluid::ENTR]);
					fload(ftmp); // Jx
					fload(ftmp); // Jy
					fload(ftmp); // Jz
					iload(ival); 
					assert(ival == 26*4);

					p.tlast = t_global;

					ptcl_local[pc] = p;
					U_local    [pc] = W;
          dU_local   [pc] = 0.0;
          dU_local   [pc] = 0.0;
					pc++;
				}

				fprintf(stderr, "p= %d  np0= %d size= %d %d\n",
						pr, np0, (int)U_local.size(), (int)ptcl_local.size());
				if (!(pr < np0-1)) break;
				iload(itmp); // 20*4
				assert(itmp == 20*4);
				iload(itmp); // myid
				iload(np0);
				iload(npx);
				iload(npy);
				iload(npz);

				int nglob1;
				iload(nglob1);
				if (nglob != nglob1) {
					fprintf(stderr, "np; npx, npy, npz = %d; %d %d %d \n", 
							np0, npx, npy, npz);
					fprintf(stderr, "nglob= %d  nglob1= %d\n", nglob, nglob1);
				}
				assert(nglob == nglob1);
				iload(nloc);
				iload(ndim);
				fload(t_global);
				fload(dt_global);
				iload(iteration);
				fload(courant_No);
				fload(gamma_gas);

				iload(periodic_on);

				fload(rmin.x);
				fload(rmin.y);
				fload(rmin.z);
				fload(rmax.x);
				fload(rmax.y);
				fload(rmax.z);
				iload(itmp);     // 20*4
			}
			assert(pc == nglob);
			assert(nglob == (int)U_local.size());
			fclose(fin);


			local_n = U_local.size();
		}

		global_n = U_local.size();		      
		local_n = global_n;

		MPI_Bcast(&global_n,   1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD);
		MPI_Bcast(&iteration,  1, MPI_INT, 0, MPI_COMM_WORLD);

		double dt_glob = dt_global;
		double  t_glob =  t_global;
		MPI_Bcast(& t_glob,  1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
		MPI_Bcast(&dt_glob,  1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
		MPI_Bcast(&scheduler.tsysU, 1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD);
		dt_global = dt_glob;
		t_global  =  t_glob;
    scheduler.set_tsys(t_global);
		assert(t_global == scheduler.get_tsys());


//		scheduler.tsysU = (unsigned long long)(t_global / scheduler.dt_tick);
		scheduler.min_rung = 0;

		dt_global = 0.0f;
		
    distribute_data(true, false, true);
	
#if 1	
		fit_vec(ptcl_local);
		fit_vec(U_local);
		fit_vec(dU_local);
		fit_vec(Wrec_local);
#endif

		all_active = true;
		
		MPI_Barrier(MPI_COMM_WORLD);

		for (int i = 0; i < (int)local_n; i++)
		{
			ptcl_local[i].tlast = t_global;
//      ptcl_local[i].volume = cell_local[i].Volume;

      Wrec_local[i] = Fluid_rec(U_local[i]);
      U_local[i] = U_local[i].to_conservative(ptcl_local[i].volume);
      dU_local[i] = 0.0;
		}
    
    MPI_Barrier(MPI_COMM_WORLD);
    if (myproc == 0)
      fprintf(stderr , " pvel ... \n");

    get_active_ptcl(true);

    MPI_Barrier(MPI_COMM_WORLD);
    if (myproc == 0)
      fprintf(stderr , " pvel ... \n");


    cell_list.swap(cell_local);
    ptcl_import.swap(ptcl_local);
    U_import.swap(U_local);
    site_active_list.swap(active_ptcl);

    compute_pvel();
    compute_timesteps(true);

    cell_list.swap(cell_local);
    ptcl_import.swap(ptcl_local);
    U_import.swap(U_local);
    site_active_list.swap(active_ptcl);

    for (int i = 0; i < (int)local_n; i++)
    {
      ptcl_local[i].rung += 1;
      ptcl_local[i].tend  = ptcl_local[i].tlast + scheduler.get_dt(ptcl_local[i].rung);
      ptcl_local[i].orig_vel = ptcl_local[i].vel;
      ptcl_local[i].unset_active();
    }
    all_active = true;
    scheduler.flush_list();
    boundary_n = 0;
    for (int i = 0; i < (int)local_n; i++)
    {
      scheduler.push_particle(i, (int)ptcl_local[i].rung);
      if (ptcl_local[i].is_boundary())
        boundary_n++;
    }

    unsigned long long boundary_glb;
    MPI_Allreduce(&boundary_n, &boundary_glb, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, MPI_COMM_WORLD);

    if (myproc == 0)
      fprintf(stderr, "boundary_glb= %lld\n", boundary_glb);

    clear_mesh(true);

    MPI_Barrier(MPI_COMM_WORLD);
    if (myproc == 0) fprintf(stderr, " proc= %d: complete read_binary \n", myproc);
#endif
  }
예제 #20
0
/* This function computes the local velocity dispersion
 * of each particle (among particles of the same type)
 */
void veldisp(void)
{
  double vsum[3], v2sum[3];
  double h, hinv, hinv3;
  double rho, wk;
  double dx, dy, dz, r, r2, u;
  int    i,j,k,ii,n,count;
  float  *r2list;
  int    *ngblist;
 

  /* only active particles */


  for(i=IndFirstUpdate,count=0; count<NumForceUpdate; i=P[i].ForceFlag, count++)   
    {
      if(P[i].Type>0)
	{
	  rho= vsum[0] = vsum[1] = vsum[2] = v2sum[0] = v2sum[1] = v2sum[2] = 0;
  
	  P[i].HsmlVelDisp= sqrt(ngb_treefind(P[i].PosPred, All.DesNumNgb, 
					      1.1*P[i].HsmlVelDisp, 
					      P[i].Type, &ngblist, &r2list));   
	  
	  h = P[i].HsmlVelDisp;
	  hinv  = 1.0/h;
	  hinv3 = hinv*hinv*hinv;
	  
	  for(n=0; n<All.DesNumNgb; n++)
	    {
	      j  = ngblist[n]+1; 
	  
	      dx = P[i].PosPred[0] - P[j].PosPred[0];
	      dy = P[i].PosPred[1] - P[j].PosPred[1];
	      dz = P[i].PosPred[2] - P[j].PosPred[2];
#ifdef PERIODIC
	      dx= periodic(dx);
	      dy= periodic(dy);
	      dz= periodic(dz);
#endif
	      r2 = dx*dx + dy*dy + dz*dz;
	      
	      r = sqrt(r2);
	      
	      if(r<h)
		{
		  u = r*hinv;
		  
		  ii = (int)(u*KERNEL_TABLE);
		  
		  wk =hinv3*( Kernel[ii]  + (Kernel[ii+1]-Kernel[ii])*(u-KernelRad[ii])*KERNEL_TABLE);
		  
		  rho += P[j].Mass * wk;
		}
	      
	      for(k=0; k<3; k++)
		{
		  vsum[k] +=  P[j].VelPred[k];
		  v2sum[k] += P[j].VelPred[k]*P[j].VelPred[k];
		}
	    }
	  
	  P[i].DensVelDisp = rho;
	  P[i].VelDisp = 0;
	  
	  for(k=0; k<3; k++)
	    {
	      vsum[k] /= All.DesNumNgb;
	      v2sum[k]/= All.DesNumNgb;
	      
	      P[i].VelDisp += v2sum[k] - vsum[k]*vsum[k];
	    }
	  
	  if(P[i].VelDisp > 0)
	    P[i].VelDisp= sqrt(P[i].VelDisp);
	  else
	    P[i].VelDisp= 0;
	}
    }
}
예제 #21
0
bool ButtonMachine::selectProgram(uint8_t progs, uint8_t *selectedProg)
{
	uint32_t bt; 

	if (progs<=1)
		return 0;

	while(1)
	{
		bt = button();
		periodic();

		switch(m_goto)
		{
		case 0:  // wait for nothing
			setTimer(&m_timer);
			m_goto = 1;
			setLED();
			break;

		case 1:	// wait for button down
			if (bt)
			{
				setTimer(&m_timer);
				m_index=0;
				setLED();
				m_goto = 2;
			}
			else if (getTimer(m_timer)>BT_PROG_TIMEOUT)
			{
				m_index = *selectedProg;
				flashLED(4); 
				reset();
				return false;
			}
			break;

		case 2: // cycle through choices, wait for button up
			if (!bt)
			{
				*selectedProg = m_index; // save m_index
				flashLED(4); 
				reset(); // resets m_index
				return true;
			}
			else if (getTimer(m_timer)>BT_INDEX_CYCLE_TIMEOUT)
			{
				setTimer(&m_timer);
				m_index++;
				if (m_index==progs)
					m_index = 0;

				setLED();
			}							   
			break;

		default:
			reset();
		}
	}
}
예제 #22
0
void DistanceToAtom::compute(const QVector<QVector3D> &pointsOriginal, float cutoff)
{
    if(pointsOriginal.size() == 0) {
        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
        return;
    }

    QElapsedTimer timer;
    timer.start();

    float min = 1e90;
    float max = -1e90;
    for(const QVector3D &point : pointsOriginal) {
        min = std::min(min, point[0]);
        min = std::min(min, point[1]);
        min = std::min(min, point[2]);

        max = std::max(max, point[0]);
        max = std::max(max, point[1]);
        max = std::max(max, point[2]);
    }
    max += 1e-5;
    const float systemSize = max - min;

    // Now translate all points
    QVector<QVector3D> points = pointsOriginal;
    for(QVector3D &point : points) {
        point[0] -= min;
        point[1] -= min;
        point[2] -= min;
    }
    float cellSize;
    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    const int numCells = cellList.size(); // Each index should be identical


    m_values.clear();
    m_values.resize(m_numberOfRandomVectors);
    m_randomNumbers.resize(3*m_numberOfRandomVectors);


    for(int i=0; i<3*m_numberOfRandomVectors; i++) {
        m_randomNumbers[i] = floatRandom(0, systemSize);
    }

    const float oneOverCellSize = 1.0/cellSize;

#pragma omp parallel for num_threads(8)
    for(int i=0; i<m_numberOfRandomVectors; i++) {
        const float x = m_randomNumbers[3*i+0];
        const float y = m_randomNumbers[3*i+1];
        const float z = m_randomNumbers[3*i+2];

        const int cx = x * oneOverCellSize;
        const int cy = y * oneOverCellSize;
        const int cz = z * oneOverCellSize;
        float minimumDistanceSquared = 1e10;
        const float minimumDistanceSquared0 = minimumDistanceSquared;

        // Loop through all 27 cells with size=cutoff
        for(int dx=-1; dx<=1; dx++) {
            for(int dy=-1; dy<=1; dy++) {
                for(int dz=-1; dz<=1; dz++) {
                    const vector<QVector3D> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
                    const int numberOfPointsInCell = pointsInCell.size();

                    for(int j=0; j<numberOfPointsInCell; j++) {
                        // const QVector3D &point = points[pointIndex];
                        const QVector3D &point = pointsInCell[j];

                        float dx = x - point[0];
                        float dy = y - point[1];
                        float dz = z - point[2];
                        if(dx < -0.5*systemSize) dx += systemSize;
                        else if(dx > 0.5*systemSize) dx -= systemSize;

                        if(dy < -0.5*systemSize) dy += systemSize;
                        else if(dy > 0.5*systemSize) dy -= systemSize;

                        if(dz < -0.5*systemSize) dz += systemSize;
                        else if(dz > 0.5*systemSize) dz -= systemSize;
                        const float distanceSquared = dx*dx + dy*dy + dz*dz;
                        if(distanceSquared < minimumDistanceSquared) minimumDistanceSquared = distanceSquared;
                    }
                }
            }
        }

        if(minimumDistanceSquared == minimumDistanceSquared0) {
            minimumDistanceSquared = -1;
        }

        m_values[i] = float(minimumDistanceSquared);
    }

    m_randomNumbers.clear();
    points.clear();

    // qDebug() << "DTO finished after " << timer.elapsed() << " ms.";
    m_isValid = true;

    //    if(pointsOriginal.size() == 0) {
    //        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
    //        return;
    //    }

    //    float min = 1e90;
    //    float max = -1e90;
    //    for(const QVector3D &point : pointsOriginal) {
    //        min = std::min(min, point[0]);
    //        min = std::min(min, point[1]);
    //        min = std::min(min, point[2]);

    //        max = std::max(max, point[0]);
    //        max = std::max(max, point[1]);
    //        max = std::max(max, point[2]);
    //    }
    //    max += 1e-5;
    //    const float systemSize = max - min;

    //    // Now translate all points
    //    QVector<QVector3D> points = pointsOriginal;
    //    for(QVector3D &point : points) {
    //        point[0] -= min;
    //        point[1] -= min;
    //        point[2] -= min;
    //    }

    //    float cellSize;
    //    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    //    const int numCells = cellList.size(); // Each index should be identical

    //    const float voxelSize = systemSize / m_size;
    //    for(int i=0; i<m_size; i++) {
    //        for(int j=0; j<m_size; j++) {
    //            for(int k=0; k<m_size; k++) {
    //                const QVector3D voxelCenter((i+0.5)*voxelSize, (j+0.5)*voxelSize, (k+0.5)*voxelSize);
    //                float minimumDistanceSquared0 = 1e10;
    //                float minimumDistanceSquared = 1e10;
    //                // Find the cell list where this position belongs and loop through all cells around
    //                const int cx = voxelCenter[0] / cellSize;
    //                const int cy = voxelCenter[1] / cellSize;
    //                const int cz = voxelCenter[2] / cellSize;

    //                // Loop through all 27 cells with size=cutoff
    //                for(int dx=-1; dx<=1; dx++) {
    //                    for(int dy=-1; dy<=1; dy++) {
    //                        for(int dz=-1; dz<=1; dz++) {
    //                            const vector<int> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
    //                            for(const int &pointIndex : pointsInCell) {
    //                                const QVector3D &point = points[pointIndex];

    //                                const float distanceSquared = periodicDistanceSquared(point, voxelCenter, systemSize);
    //                                minimumDistanceSquared = std::min(minimumDistanceSquared, distanceSquared);
    //                            }
    //                        }
    //                    }
    //                }
    //                if(minimumDistanceSquared == minimumDistanceSquared0) {
    //                    minimumDistanceSquared = -1;
    //                }
    //                setValue(i,j,k,float(minimumDistanceSquared));
    //            }
    //        }
    //    }

    //    m_isValid = true;
}